//------------------------------------------------------------------------------
// send a data request packet to from master to slave
//------------------------------------------------------------------------------
static gboolean
send_packet_timeout(gpointer data)
{
    static gchar *func_name = "send_packet_timer";
    u_char buff[256];
    int len, ret;

    mbus_frame *frame;
    
    frame = mbus_frame_new(MBUS_FRAME_TYPE_SHORT);
    
    frame->control  = MBUS_CONTROL_MASK_SND_NKE | MBUS_CONTROL_MASK_DIR_M2S; // data request from master to slave
    frame->address  = addr; // address

    //if ((ret = mbus_frame_print(frame)) < 0)
    //{
    //    printf("%s: mbus_frame_print -> %d\n", __PRETTY_FUNCTION__, ret);
    //    return -1;
    //}
   
    if ((len = mbus_frame_pack(frame, buff, sizeof(buff))) == -1)
    {
        printf("%s: mbus_frame_pack -> %d\n", __PRETTY_FUNCTION__, ret);
        mbus_frame_free(frame);
        return -1;
    }    

    if (fs_net_send(gio_server, buff, len) < len)
    { 
        g_message("%s: failed to write data to server", func_name);
    }    
	
    mbus_frame_free(frame);
    return FALSE; 
}
//------------------------------------------------------------------------------
// Scan for devices using secondary addressing.
//------------------------------------------------------------------------------
int
main(int argc, char **argv)
{
    mbus_frame *frame, reply;
    mbus_frame_data reply_data;
    mbus_handle *handle = NULL;

    char *device, *addr_str, *xml_result;
    int address, baudrate = 9600;
 
    memset((void *)&reply, 0, sizeof(mbus_frame));
    memset((void *)&reply_data, 0, sizeof(mbus_frame_data));
     
    if (argc == 3)
    {
        device   = argv[1];   
        addr_str = argv[2];
    }
    else if (argc == 4 && strcmp(argv[1], "-d") == 0)
    {
        device   = argv[2];   
        addr_str = argv[3];
        debug = 1;
    }
    else if (argc == 5 && strcmp(argv[1], "-b") == 0)
    {
        baudrate = atoi(argv[2]);
        device   = argv[3];   
        addr_str = argv[4];
    }
    else if (argc == 6 && strcmp(argv[1], "-d") == 0 && strcmp(argv[2], "-b") == 0)
    {
        baudrate = atoi(argv[3]);
        device   = argv[4];   
        addr_str = argv[5];
        debug = 1;
    }
    else 
    {
        fprintf(stderr, "usage: %s [-d] [-b BAUDRATE] device mbus-address\n", argv[0]);
        fprintf(stderr, "    optional flag -d for debug printout\n");
        fprintf(stderr, "    optional flag -b for selecting baudrate\n");
        return 0;
    }
    
    if (debug)
    {
        mbus_register_send_event(&mbus_dump_send_event);
        mbus_register_recv_event(&mbus_dump_recv_event);
    }
 
    if ((handle = mbus_context_serial(device)) == NULL)
    {
        fprintf(stderr, "Could not initialize M-Bus context: %s\n",  mbus_error_str());
        return 1;
    }

    if (mbus_connect(handle) == -1)
    {
        printf("Failed to setup connection to M-bus gateway\n");
        return 1;
    }

    if (mbus_serial_set_baudrate(handle, baudrate) == -1)
    {
        printf("Failed to set baud rate.\n");
        return 1;
    }
    
    //
    // init slave to get really the beginning of the records
    //
    
    frame = mbus_frame_new(MBUS_FRAME_TYPE_SHORT);
    
    if (frame == NULL)
    {
        fprintf(stderr, "Failed to allocate mbus frame.\n");
        return 1;
    }
    
    frame->control = MBUS_CONTROL_MASK_SND_NKE | MBUS_CONTROL_MASK_DIR_M2S;
    frame->address = MBUS_ADDRESS_NETWORK_LAYER;
    
    if (debug)
        printf("%s: debug: sending init frame #1\n", __PRETTY_FUNCTION__);
    
    if (mbus_send_frame(handle, frame) == -1)
    {
        fprintf(stderr, "Failed to send mbus frame.\n");
        mbus_frame_free(frame);
        return 1;
    }
    
    mbus_purge_frames(handle);
    
    //
    // resend SND_NKE, maybe the first get lost
    //
    
    frame->control = MBUS_CONTROL_MASK_SND_NKE | MBUS_CONTROL_MASK_DIR_M2S;
    frame->address = MBUS_ADDRESS_NETWORK_LAYER;

    if (debug)
        printf("%s: debug: sending init frame #2\n", __PRETTY_FUNCTION__);

    if (mbus_send_frame(handle, frame) == -1)
    {
        fprintf(stderr, "Failed to send mbus frame.\n");
        mbus_frame_free(frame);
        return 1;
    }

    mbus_purge_frames(handle);

    if (strlen(addr_str) == 16)
    {
        // secondary addressing

        int ret;

        ret = mbus_select_secondary_address(handle, addr_str);

        if (ret == MBUS_PROBE_COLLISION)
        {
            fprintf(stderr, "%s: Error: The address mask [%s] matches more than one device.\n", __PRETTY_FUNCTION__, addr_str);
            return 1;
        }
        else if (ret == MBUS_PROBE_NOTHING)
        {
            fprintf(stderr, "%s: Error: The selected secondary address does not match any device [%s].\n", __PRETTY_FUNCTION__, addr_str);
            return 1;
        }
        else if (ret == MBUS_PROBE_ERROR)
        {
            fprintf(stderr, "%s: Error: Failed to select secondary address [%s].\n", __PRETTY_FUNCTION__, addr_str);
            return 1;    
        }
        // else MBUS_PROBE_SINGLE

        address = 253;
    } 
    else
    {
        // primary addressing
        address = atoi(addr_str);
    }   
    
    // instead of the send and recv, use this sendrecv function that 
    // takes care of the possibility of multi-telegram replies (limit = 16 frames)
    if (mbus_sendrecv_request(handle, address, &reply, 16) != 0)
    {
        fprintf(stderr, "Failed to send/receive M-Bus request.\n");
        return 1;
    }

    //
    // dump hex data if debug is true
    //
    if (debug)
    {
        mbus_frame_print(&reply);
    }

    //
    // generate XML and print to standard output
    //
    if ((xml_result = mbus_frame_xml(&reply)) == NULL)
    {
        fprintf(stderr, "Failed to generate XML representation of MBUS frames: %s\n", mbus_error_str());
        return 1;
    }
    
    printf("%s", xml_result);
    free(xml_result);

    mbus_disconnect(handle);
    mbus_context_free(handle);
    return 0;
}
//------------------------------------------------------------------------------
// client_io:
//
//------------------------------------------------------------------------------
static gboolean
server_io(GIOChannel *gio, GIOCondition condition, gpointer data)
{
    static gchar *func_name = "server_io";
    gchar buff[PACKET_BUFF_SIZE];
    gint len, len_tot = 0;
    int fd;
    FsNetBuffer *nbdata;

    bzero((void *)buff, sizeof(buff));

    mbus_frame *frame;
    mbus_frame_data frame_data;

    //
    // init
    //

    if ((fd = g_io_channel_unix_get_fd(gio)) < 0)
    {
       g_warning("%s: Failed to aquire socket fd.", func_name);
       return FALSE;
    }

    if (condition & (G_IO_HUP|G_IO_NVAL|G_IO_ERR))
    {
        exit(0);
    }

    if ((nbdata  = fs_net_buffer_get(gio)) == NULL)
    {
        g_warning("%s: Serious error, couldn't retrieve data buffer for GIO Channel.", func_name);
        return FALSE;
    }

    //
    // start reading data
    //
    frame = mbus_frame_new(MBUS_FRAME_TYPE_ANY);
    len_tot = 1;
    
    while (len > 0)
    {
        if ((len = fs_net_read_data_nonblocking(gio, nbdata, len_tot)) < 0)
        {
            if (len == -2 && nbdata->offset == 0)
            {
                // Return value -2 is a special return value that we use to indicate
                // that the read operation was interrupted due to unavailability of 
                // data (so we got an try-again error, preventing a blocking read).
                //
                // Restart the read operation later.
                mbus_frame_free(frame);
                return TRUE;
            }        
	
	        if (len == -1)
	        {
                fs_net_buffer_free(gio);
	            fs_net_socket_close(fd);
                exit(0);
            }
        }
        
        nbdata->offset = len_tot; // start next read at the correct offset
        len = mbus_parse(frame, nbdata->buff, len_tot);
       	len_tot += len;
    }
  
    if (len == -1)
    {
        mbus_frame_free(frame);
        return TRUE;
    }
  
    //
    // parse data and print in XML format
    //
    mbus_frame_data_parse(frame, &frame_data);
    printf("%s", mbus_frame_data_xml(&frame_data));
    
        
    //
    // Free and exit
    //
    
    mbus_frame_free(frame);
    exit(0);	

    return TRUE;
}
//------------------------------------------------------------------------------
// Scan for devices using secondary addressing.
//------------------------------------------------------------------------------
int
main(int argc, char **argv)
{
    char *device, *addr_mask = NULL;
    long baudrate = 9600;
    mbus_handle *handle = NULL;
    mbus_frame *frame = NULL, reply;

    memset((void *)&reply, 0, sizeof(mbus_frame));

    if (argc == 2)
    {
        device = argv[1];
        addr_mask = strdup("FFFFFFFFFFFFFFFF");
    }
    else if (argc == 3 && strcmp(argv[1], "-d") == 0)
    {
        device = argv[2];
        addr_mask = strdup("FFFFFFFFFFFFFFFF");
        debug = 1;
    }
    else if (argc == 3)
    {
        device = argv[1];
        addr_mask = strdup(argv[2]);
    }
    else if (argc == 4 && strcmp(argv[1], "-d") == 0)
    {
        device = argv[2];
        addr_mask = strdup(argv[3]);
        debug = 1;
    }
    else if (argc == 4 && strcmp(argv[1], "-b") == 0)
    {
        baudrate = atol(argv[2]);
        device = argv[3];
        addr_mask = strdup("FFFFFFFFFFFFFFFF");
    }
    else if (argc == 5 && strcmp(argv[1], "-d") == 0 && strcmp(argv[2], "-b") == 0)
    {
        baudrate = atol(argv[3]);
        device = argv[4];
        addr_mask = strdup("FFFFFFFFFFFFFFFF");
        debug = 1;
    }
    else if (argc == 5 && strcmp(argv[1], "-b") == 0)
    {
        baudrate = atol(argv[2]);
        device = argv[3];
        addr_mask = strdup(argv[4]);
    }
    else if (argc == 6 && strcmp(argv[1], "-d") == 0)
    {
        baudrate = atol(argv[3]);
        device = argv[4];
        addr_mask = strdup(argv[5]);
        debug = 1;
    }
    else
    {
        fprintf(stderr, "usage: %s [-d] [-b BAUDRATE] device [address-mask]\n", argv[0]);
        fprintf(stderr, "\toptional flag -d for debug printout\n");
        fprintf(stderr, "\toptional flag -b for selecting baudrate\n");
        fprintf(stderr, "\trestrict the search by supplying an optional address mask on the form\n");
        fprintf(stderr, "\t'FFFFFFFFFFFFFFFF' where F is a wildcard character\n");
        return 0;
    }

    if (addr_mask == NULL)
    {
        fprintf(stderr, "Failed to allocate address mask.\n");
        return 1;
    }

    if (mbus_is_secondary_address(addr_mask) == 0)
    {
        fprintf(stderr, "Misformatted secondary address mask. Must be 16 character HEX number.\n");
        free(addr_mask);
        return 1;
    }

    if ((handle = mbus_context_serial(device)) == NULL)
    {
        fprintf(stderr, "Could not initialize M-Bus context: %s\n",  mbus_error_str());
        free(addr_mask);
        return 1;
    }
    
    if (debug)
    {
        mbus_register_send_event(handle, &mbus_dump_send_event);
        mbus_register_recv_event(handle, &mbus_dump_recv_event);
    }

    if (mbus_connect(handle) == -1)
    {
        fprintf(stderr,"Failed to setup connection to M-bus gateway\n");
        free(addr_mask);
        return 1;
    }

    if (mbus_serial_set_baudrate(handle, baudrate) == -1)
    {
        fprintf(stderr, "Failed to set baud rate.\n");
        free(addr_mask);
        return 1;
    }


    frame = mbus_frame_new(MBUS_FRAME_TYPE_SHORT);

    if (frame == NULL)
    {
        fprintf(stderr, "Failed to allocate mbus frame.\n");
        free(addr_mask);
        return 1;
    }

    if (init_slaves(handle) == 0)
    {
        free(addr_mask);
        return 1;
    }

    mbus_scan_2nd_address_range(handle, 0, addr_mask);

    mbus_disconnect(handle);
    mbus_context_free(handle);
    //printf("Summary: Tried %ld address masks and found %d devices.\n", probe_count, match_count);

    free(addr_mask);

    return 0;
}