/*
 * Copyright (C) 2022 EXOLIGENT (www.exoligent.com)
 * Author: Maxime Coroyer <maxime.coroyer@exoligent.com>
 */

#include <string.h>     // memset()

#include "gw.h"

void gw_display_update(struct gateway *gw)
{
    int i, j, str_len;
    char value_str[50];

    printf("%c[;H%c[2J",27,27);
    mbus_display_update(gw);
    fip_display_update(gw);
    printf("I/O mapping:\n");
    printf("  [FIP]    \t\t\t [MODBUS]\t\t\t[DATA]\n");
    printf("  **PROD** \t\t\t **HOLDING REGISTERS**\n");

    for (i = 0; i < gw->fip.prod_varcnt; ++i) {
        memset(value_str, '\0', 50 * sizeof(char));
        str_len = 0;
        for (j = 0; j < gw->fip.prod_varlist[i]->bsz; ++j)
            str_len += sprintf(value_str + str_len, "%02x ",
                gw->fip.prod_varlist[i]->buffer[j]);

        printf("    [%03d] ID=0x%04x LEN=%03d "
               " <==>  ADDR=%04d REG_CNT=%03d "
               " ===>  %s\n", i,
            gw->fip.prod_varlist[i]->id, gw->fip.prod_varlist[i]->bsz,
            gw->mbus.prod_varlist[i].addr, gw->mbus.prod_varlist[i].nb,
            value_str);
    }
    printf("\n  **CONS** \t\t\t **INPUT REGISTERS**\n");

    for (i = 0; i < gw->fip.cons_varcnt; ++i) {
        memset(value_str, '\0', 50 * sizeof(char));
        str_len = 0;
        for (j = 0; j < gw->fip.cons_varlist[i]->bsz; ++j)
            str_len += sprintf(value_str + str_len, "%02x ",
                gw->fip.cons_varlist[i]->buffer[j]);

        printf("    [%03d] ID=0x%04x LEN=%03d "
               " <==>  ADDR=%04d REG_CNT=%03d "
               " ===>  %s\n", i,
            gw->fip.cons_varlist[i]->id, gw->fip.cons_varlist[i]->bsz,
            gw->mbus.cons_varlist[i].addr, gw->mbus.cons_varlist[i].nb,
            value_str);
    }
}