#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#include "modbus.h"

#define SLAVE_1         0x01
#define DEFAULT_BAUD    57600L
#define TOTAL_COILS     32

int main(int argc, char* argv[])
{
    int ret, i;
    int start;
    int ncoils;
    unsigned long coil_word, temp_coil_word;
    uint8_t coils[TOTAL_COILS];

    char buff[32];
    modbus_param_t mb_param;
    long baud;

    if ( argc < 5)
    {
        printf("Usage: fcoil_mult port start ncoils coil_word [baud]\n");
        printf("Default baud is %ld\n\n", DEFAULT_BAUD);
        printf("Examples:\n");
        printf("./fcoil_mult ttyS0 0 8 0xAA       #for Linux\n");
        printf("./fcoil_mult com1  0 8 0xAA       #for Cygwin\n");
        printf("\n");
        printf("./fcoil_mult ttyS0 0 8 0xAA 38400 #for Linux with non default baud\n");
        return -1;
    }

    /* set device name */
    sprintf(buff, "/dev/%s", argv[1]);

    /* set coil state */
    start = atoi(argv[2]);

    /* set coil address */
    ncoils = atoi(argv[3]);

    if ( ncoils > TOTAL_COILS )
    {
        printf("ERROR exceed max coils of %d\n", TOTAL_COILS);
        exit(1);
    }

    /* get the coil word */
    coil_word = strtoul(argv[4], NULL, 16);
    
    baud = DEFAULT_BAUD;
    if ( argc == 6 )
    {
        baud = atol(argv[4]);
        switch ( baud )
        {
            case 9600:   break;
            case 19200:  break;
            case 38400:  break;
            case 57600:  break;
            case 115200: break;
            default: 
                printf("Invalid baud: %ld\n", baud);
                printf("Supported bauds: 9600, 19200, 38400, 57600, 115200\n");
                return -1;
        }
    }

    modbus_init_rtu(&mb_param, buff, baud, "none", 8, 1);

    if (modbus_connect(&mb_param) == -1) 
    {
        printf("ERROR Connection failed\n");
        exit(1);
    }

    temp_coil_word = coil_word;
    for (i = 0; i < ncoils; ++i)
    {
        coils[i] = temp_coil_word & 0x00000001;
        printf("COIL %02d = %d\n", (i + start), (int)coils[i]);
        
        /* shift to next coild word bit */
        temp_coil_word >>= 1;
    }
    
    printf("force_multiple_coils(ID 0x01, START %d, NCOILS %d, COIL_WORD 0x%08X): ", 
           start, ncoils, coil_word);
    
    ret = force_multiple_coils(&mb_param, SLAVE_1, start, ncoils, coils);

    if ( ret != ncoils ) 
    {
        printf("FAILED\n");
        exit(1);
    }
        
    printf("OK\n");

 
    return 0;
}
