Webserver only w/o any other functions, single thread. Running on STM32F013+W5500

Dependencies:   NTPClient W5500Interface Watchdog device_configuration eeprom_flash mbed-rpc-nucleo mbed-rtos mbed

Fork of F103-Serial-to-Ethernet by Chau Vo

main.cpp

Committer:
olympux
Date:
2014-10-04
Revision:
17:88ef7a078095
Parent:
16:84a5bf7285d0
Child:
18:ca499a2e7da6

File content as of revision 17:88ef7a078095:

/*
*
*  Alarm and Monitoring application

*/
#include "mbed.h"
#include "eeprom.h"
#include "EthernetInterface.h"
#include "NTPClient.h"
#include "rtos.h"

#include "my_eeprom_funcs.h"


//Debug is disabled by default
#if 1
//Enable debug
#include <cstdio>
#define DBG(x, ...) std::printf("[main : DBG]"x"\r\n", ##__VA_ARGS__); 
#define WARN(x, ...) std::printf("[main : WARN]"x"\r\n", ##__VA_ARGS__); 
#define ERR(x, ...) std::printf("[main : ERR]"x"\r\n", ##__VA_ARGS__); 

#else
//Disable debug
#define DBG(x, ...) 
#define WARN(x, ...)
#define ERR(x, ...) 

#endif


/*
* Hardware defines
*/
#define ST_NUCLEO // hardware pin mapping

#ifdef ST_NUCLEO
// Ethernet
SPI spi(PA_7, PA_6, PA_5); // mosi, miso, sclk
EthernetInterface eth(&spi, PA_4, PC_9); // spi, cs, reset
#endif

// Serial
Serial uart(USBTX,USBRX);

// Digital inputs
DigitalIn din0(PB_14);
DigitalIn din1(PB_12);
DigitalIn din2(PB_10);
DigitalIn din3(PB_1);
DigitalIn din4(PB_15);
DigitalIn din5(PB_13);
DigitalIn din6(PB_11);
DigitalIn din7(PB_2);
// Digital outputs
DigitalOut dout0(PB_3);
DigitalOut dout1(PB_5);
DigitalOut dout2(PB_7);
DigitalOut dout3(PB_9);
DigitalOut dout4(PD_2);
DigitalOut dout5(PB_4);
DigitalOut dout6(PB_6);
DigitalOut dout7(PB_8);
// Analog inputs
AnalogIn ain0(PC_0);
AnalogIn ain1(PC_1);
// Analog outputs
//AnalogOut ano0(PA_8);
//AnalogOut ano1(PA_15);

void update_digital_outputs(char* buf);
void update_sending_frame(char* buf);



/*
* EEPROM section
*/
// Virtual address defined by the user: 0xFFFF value is prohibited
uint16_t VirtAddVarTab[NumbOfVar] = {0x1212, 0x1313, 0x1414, 0x1515, // IP_Addr
                                     0x2212, 0x2313, 0x2414, 0x2515, // IP_Subnet
                                     0x3212, 0x3313, 0x3414, 0x3515, // IP_Gateway
                                     0x4212, // TCP server port, not used
                                     0x5212, // UDP server port, not used
                                     0x8888, // 1st run? 0xA5A5 = configured
                                     0x6212, 0x6313, 0x6414, // MAC
                                     
                                     // this section is for the TCP server that this device connects to in TCP client mode
                                     0x7212, 0x7313, // 0xA5 = auto transmit status, time period
                                     0x8212, 0x8313,0x8414, 0x8515, // TCP server IP address
                                     0x9212, // TCP server port
                                     
                                     // this section is for selecting protocol
                                     0xA212, // 0xA5A5 = enable TCP server
                                     0xA313, // 0xA5A5 = eanble TCP client
                                     0xA414  // 0xA5A5 = enable UDP client
                                     };

/*
* Network configuration
*/
#define TCP_SERVER
#define TCP_CLIENT
#define UDP_SERVER
//#define UDP_CLIENT
#define NTP

#define TCP_SERVER_WAIT_CLIENT_TIMEOUT     200
#define TCP_SERVER_RECEIVE_TIMEOUT         3000
#define UDP_SERVER_RECEIVE_TIMEOUT         200


// TCP server function
TCPSocketServer tcp_server;
TCPSocketConnection tcp_client;
// TCP client function
TCPSocketConnection tcp_sock;
// UDP server
UDPSocket udp_server;
Endpoint ep_udp_client;
// NTP
NTPClient ntp;



/*
* Variables for network configuration, server
*/
uint8_t u8mac[6], u8ip_addr[4];// keep mac and ip address in 8-bits
uint16_t u16mac_addr[3], u16ip_addr[4], u16ip_subnet[4], u16ip_gateway[4]; // 16-bits, directly loaded from eeprom
char   str_ip_addr[16], str_ip_subnet[16], str_ip_gateway[16]; // for printf, converted from 16-bits u16ip_xxx
uint16_t first_run = 0;  // first run flag

const uint16_t tcp_server_local_port = 10000; // fixed
const uint16_t udp_server_local_port = 11000; // fixed

// TCP client: this section is used for the TCP server that this device connects to in TCP client mode
// this device will transmit status every transmit_time_period
uint16_t auto_transmit_flag = 0, transmit_time_period = 1000; // auto transmit status, time period = 1s
uint16_t u16server_ip_addr[4]; // directly loaded from eeprom
uint8_t u8server_ip_addr[4]; // server ip address in 8-bits
char str_server_ip_addr[16];// for printf, converted from 16-bits u16server_ip_addr
uint16_t u16tcp_server_port; // directly loaded from eeprom

char tcp_client_buffer[256]; // socket buffer
char udp_server_buffer[256];
char tcp_server_buffer[256];


/*
* Protocol
*/
// Commands
#define DEVICE_ID                           "NNIO"

#define RECEIVING_PROTOCOL_LENGTH           58
#define SENDING_PROTOCOL_LENGTH             39
#define QUERY_CMD_LENGTH                    6
#define SET_NETWORK_CONFIG_CMD_LENGTH       19
#define UPDATE_TCP_SERVER_INFO_CMD_LENGTH   12

#define QUERY_DISCOVERY_CMD                 "NNIODS"
#define QUERY_IP_CMD                        "NNIOIP"
#define QUERY_SUBNET_CMD                    "NNIOSN"
#define QUERY_GATEWAY_CMD                   "NNIOGW"
#define QUERY_MAC_CMD                       "NNIOMC"
#define QUERY_UDP_PORT_CMD                  "NNIOUP"
#define QUERY_TCP_PORT_CMD                  "NNIOTP"
#define QUERY_UPDATE_TIME_CMD               "NNIOTM"
#define RECEIVING_PROTOCOL_ENABLE_OUTPUT    'O'
#define QUERY_STATUS_COMMAND                'Q'
#define DIGITAL_HIGH                        'H'
#define DIGITAL_LOW                         'L'


// Positions
#define RECEIVING_PROTOCOL_ID_POS           0
#define RECEIVING_PROTOCOL_OP_POS           4
#define RECEIVING_PROTOCOL_EN_DO_POS        RECEIVING_PROTOCOL_OP_POS + 0
#define RECEIVING_PROTOCOL_EN_A0O_POS       RECEIVING_PROTOCOL_OP_POS + 1
#define RECEIVING_PROTOCOL_EN_A1O_POS       RECEIVING_PROTOCOL_OP_POS + 2
#define RECEIVING_PROTOCOL_EN_UART_POS      RECEIVING_PROTOCOL_OP_POS + 3
#define RECEIVING_PROTOCOL_COMMAND_POS      RECEIVING_PROTOCOL_OP_POS + 4

#define RECEIVING_PROTOCOL_IP_POS           9
#define RECEIVING_PROTOCOL_DO_POS           13
#define RECEIVING_PROTOCOL_A0O_POS          21
#define RECEIVING_PROTOCOL_A01_POS          23
#define RECEIVING_PROTOCOL_UART_POS         25


#define SENDING_PROTOCOL_ID_POS             0
#define SENDING_PROTOCOL_MAC_POS            4
#define SENDING_PROTOCOL_IP_POS             10
#define SENDING_PROTOCOL_DI_POS             14
#define SENDING_PROTOCOL_DO_POS             22
#define SENDING_PROTOCOL_AI0_POS            30
#define SENDING_PROTOCOL_AI1_POS            32
#define SENDING_PROTOCOL_AO0_POS            34
#define SENDING_PROTOCOL_AO1_POS            36
#define SENDING_PROTOCOL_CR_POS             38


/*
* RTOS
*/
struct message_t {
    int len;
    char *msg;
};
Queue<message_t, 16> uart_queue;
Queue<bool, 1> auto_update_queue;

Mutex uart_mutex;


/*
* Threads
*/
void uart_thread(void const *args) {
    message_t *p_message;
    
    while (true) {
        osEvent evt = uart_queue.get();
        if (evt.status == osEventMessage) {
            p_message = (message_t*)evt.value.p;
            uart_mutex.lock(); // mutex for stdio is not neccessary
            //DBG("len=%d\n", p_message->len);
            DBG("%s\n", p_message->msg);
            uart_mutex.unlock();
        }
    }
}


// Timer thread for auto update
void auto_update_timer_thread(void const* args) {
    bool update_flag;
    
    Thread::wait(500);
    while(true) {
        update_flag = true;
        auto_update_queue.put(&update_flag);
        Thread::wait(1000*transmit_time_period);
    }
}


/*
* Ethernet init
*/
int ethernet_init(void) {
    DBG("Start initialising ethernet\n");
    int ret = eth.init(u8mac, str_ip_addr, str_ip_subnet, str_ip_gateway); // static

    if (!ret) {
        DBG("Initialized, MAC: %s\n", eth.getMACAddress());
    } else {
        ERR("Error eth.init() - ret = %d\n", ret);
        return -1;
    }

    ret = eth.connect();
    if (!ret) {
        DBG("IP: %s, MASK: %s, GW: %s\n", eth.getIPAddress(), eth.getNetworkMask(), eth.getGateway());
    } else {
        ERR("Error eth.connect() - ret = %d\n", ret);
        return -1;
    }
    
    return 0;
}





int main()
{
    message_t message;
    int n, ret;
    
    Thread::wait(2000); // turn on delay
    
    /*
    * Configure
    */
    uart.baud(115200);
    DBG("\r\nStarting...\r\n");
  
    /*
    * UI threads
    */
    Thread t1(uart_thread);
    Thread t2(auto_update_timer_thread);
    
    //// send to uart
    //buffer[n] = '\0';
    //message.len = n;
    //message.msg = buffer;
    //uart_queue.put(&message);
    
    
    /*
    * FLASH
    */
    load_eeprom_network();
    load_eeprom_tcpserver();
        
    /*
    * Ethernet
    */
    ret = ethernet_init();
    if (ret) {
        ERR("Ethernet initialisation failed. App halted\r\n");
        while (true) {};
    }
    

/*
* TCP/UDP setup
*/
#ifdef TCP_SERVER
    tcp_server.bind(tcp_server_local_port);
    tcp_server.listen();
    DBG("TCP server started...\r\n");
    tcp_server.set_blocking(false, TCP_SERVER_WAIT_CLIENT_TIMEOUT);
#endif

#ifdef TCP_CLIENT
    //RtosTimer tcp_client_auto_update_timer(tcp_client_auto_update, osTimerPeriodic, NULL);
#endif
    
#ifdef UDP_SERVER
    ret = udp_server.bind(udp_server_local_port);
    DBG("UDP started (sock.bind = %d)\r\n", ret);
    udp_server.set_blocking(false, UDP_SERVER_RECEIVE_TIMEOUT);
#endif


    /*
    * Network processor
    */
    while (true) {
#ifdef TCP_CLIENT
    // FOR AUTO TRANSMIT DEVICE STATUS
    if (auto_transmit_flag == 0xA5A5) {
        // connect to TCP server if required
        if (!tcp_sock.is_connected()) {
            ret = tcp_sock.connect(str_server_ip_addr, u16tcp_server_port);
            if (ret > -1) {
                DBG("Successfully connected to %s on port %d\r\n", str_server_ip_addr, u16tcp_server_port);
            }
            else {
                ERR("Unable to connect to %s on port %d\r\n", str_server_ip_addr, u16tcp_server_port);
            }
        }
        
        // transmit data if connected
        if (tcp_sock.is_connected()) {
            osEvent evt = auto_update_queue.get(1); // timeout after 1ms
            if (evt.status == osEventMessage) {
                DBG("Updating...\r\n");
                update_sending_frame(tcp_client_buffer);
                tcp_sock.send_all(tcp_client_buffer, SENDING_PROTOCOL_LENGTH);
            }
        }
    } // auto transmit
#endif


// FOR INTERFACING
#ifdef TCP_SERVER
        // no tcp client connected
        if (!tcp_client.is_connected())
        {
            // wait for client within timeout
            ret = tcp_server.accept(tcp_client);
            
            // tcp client connected
            if (ret > -1) {
                DBG("Connection from: %s\r\n", tcp_client.get_address());
                
                // loop waiting and receiving data within timeout
                tcp_client.set_blocking(false, TCP_SERVER_RECEIVE_TIMEOUT); // Timeout after x seconds
                while (true) {
                    n = tcp_client.receive(tcp_server_buffer, sizeof(tcp_server_buffer));
                    if (n <= 0) break;
                    
                    // got some data, test it
                    DBG("TCP server received: %s\r\n", tcp_server_buffer);
                    // process received data
                    switch (n) {
                        // length 58-bytes, Receiving protocol
                        case RECEIVING_PROTOCOL_LENGTH: {
                            DBG("Checking device ID...");
                            // check device id
                            char* id = strstr(tcp_server_buffer, DEVICE_ID);
                            if (id == NULL)
                                break;
                            else if ((id - tcp_server_buffer) > 0)
                                break;
                            DBG("Correct.\r\n");
                            
                            // firstly, update outputs if required
                            // digital outputs
                            if (tcp_server_buffer[RECEIVING_PROTOCOL_EN_DO_POS] == RECEIVING_PROTOCOL_ENABLE_OUTPUT) {
                                DBG("Update digital outputs\r\n");
                                char str_dout[9];
                                memcpy(str_dout, &tcp_server_buffer[RECEIVING_PROTOCOL_DO_POS], 8);
                                str_dout[8] = '\0';
                                update_digital_outputs(str_dout);
                            }
                            // analog output 0
                            if (tcp_server_buffer[RECEIVING_PROTOCOL_EN_A0O_POS] == RECEIVING_PROTOCOL_ENABLE_OUTPUT) {
                                DBG("Update analog output 0\r\n");
                            }
                            // analog output 1
                            if (tcp_server_buffer[RECEIVING_PROTOCOL_EN_A1O_POS] == RECEIVING_PROTOCOL_ENABLE_OUTPUT) {
                                DBG("Update analog output 1\r\n");
                            }
                            // UART
                            if (tcp_server_buffer[RECEIVING_PROTOCOL_EN_UART_POS] == RECEIVING_PROTOCOL_ENABLE_OUTPUT) {
                                DBG("UART data: ");
                                char str_uart[33];
                                memcpy(str_uart, &tcp_server_buffer[RECEIVING_PROTOCOL_UART_POS], 32);
                                str_uart[32] = '\0';
                                printf("%s\r\n", str_uart);
                            }
                            
                            // then, check query status command and sending protocol if required
                            if (tcp_server_buffer[RECEIVING_PROTOCOL_COMMAND_POS] == QUERY_STATUS_COMMAND) {
                                DBG("Sent device status through TCP\r\n");
                                // sending protocol
                                update_sending_frame(tcp_server_buffer);
                                tcp_client.send_all(tcp_server_buffer, SENDING_PROTOCOL_LENGTH);
                            }
                            
                            break;
                        }
                        default:
                            break;
                    }
                } // end loop if no data received within timeout
                tcp_client.close();
            } // if client connected
        } // if no client connected
#endif
    
    
    
// ONLY FOR CONFIGRATION
#ifdef UDP_SERVER
        // wait for udp packet within timeout
        n = udp_server.receiveFrom(ep_udp_client, udp_server_buffer, sizeof(udp_server_buffer));
        if (n <= 0) continue;

        // got some data, test it
        DBG("UDP received (%s) from (%s) and port (%d)\r\n", udp_server_buffer, ep_udp_client.get_address(), ep_udp_client.get_port());
        // process received data
        switch (n) {
            // length = 6, a QUERY command (discovery command, TCP port, or UDP port)
            // Format: NNIODS, NNIOTP, NNIOUP, NNIOTM
            case QUERY_CMD_LENGTH:
                // discovery command
                if (strstr(udp_server_buffer, QUERY_DISCOVERY_CMD) != NULL) {
                    char str[30];
                    sprintf(str, "%s%s", DEVICE_ID, eth.getIPAddress());
                    udp_server.sendTo(ep_udp_client, str, strlen(str));
                } // NNIODS
                else if (strstr(udp_server_buffer, QUERY_IP_CMD) != NULL) {
                    udp_server.sendTo(ep_udp_client, eth.getIPAddress(), strlen(eth.getIPAddress()));
                } // NNIOIP
                else if (strstr(udp_server_buffer, QUERY_SUBNET_CMD) != NULL) {
                    udp_server.sendTo(ep_udp_client, eth.getNetworkMask(), strlen(eth.getNetworkMask()));
                } // NNIOSN
                else if (strstr(udp_server_buffer, QUERY_GATEWAY_CMD) != NULL) {
                    udp_server.sendTo(ep_udp_client, eth.getGateway(), strlen(eth.getGateway()));
                } // NNIOGW
                else if (strstr(udp_server_buffer, QUERY_MAC_CMD) != NULL) {
                    udp_server.sendTo(ep_udp_client, eth.getMACAddress(), strlen(eth.getMACAddress()));
                } // NNIOMC
                // ask for TCP server port
                else if (strstr(udp_server_buffer, QUERY_TCP_PORT_CMD) != NULL) {
                    char port[5];
                    sprintf(port, "%5d", tcp_server_local_port);
                    udp_server.sendTo(ep_udp_client, port, strlen(port));
                } // NNIOTP
                // ask for UDP server port
                else if (strstr(udp_server_buffer, QUERY_UDP_PORT_CMD) != NULL) {
                    char port[5];
                    sprintf(port, "%5d", udp_server_local_port);
                    udp_server.sendTo(ep_udp_client, port, strlen(port));
                } // NNIOUP
                else if (strstr(udp_server_buffer, QUERY_UPDATE_TIME_CMD) != NULL) {
#ifdef NTP
                    char str_time[50];
                    
                    DBG("Trying to update time...\r\n");
                    if (ntp.setTime("0.pool.ntp.org") == 0) {
                        DBG("Set time successfully\r\n");
                        time_t ctTime;
                        ctTime = time(NULL);
                        
                        DBG("Time is set to (UTC): %s\r\n", ctime(&ctTime));
                        sprintf(str_time, "%s", ctime(&ctTime));
                        udp_server.sendTo(ep_udp_client, str_time, strlen(str_time));
                    }
                    else {
                        WARN("Error\r\n");
                        sprintf(str_time, "ERR");
                        udp_server.sendTo(ep_udp_client, str_time, strlen(str_time));
                    }
#elif
                    WARN("NTP disabled\r\n");
                    sprintf(str_time, "DIS");
                    udp_server.sendTo(ep_udp_client, str_time, strlen(str_time));
#endif
                } // NNIOTM

                break;
            // length = 19, SET NETWORK CONFIGURATION
            // Format: 4E 4E 49 4F      C0 A8 00 78        FF FF FF 00            C0 A8 00 01      00 00 01
            //        (NNIO;            IP: 192.168.0.120; Subnet: 255.255.255.0; GW: 192.168.0.1; MAC: 0 0 1)
            case SET_NETWORK_CONFIG_CMD_LENGTH: {
                // check device id
                char* id = strstr(udp_server_buffer, DEVICE_ID);
                if (id == NULL)
                    break;
                else if ((id - udp_server_buffer) > 0)
                    break;

                DBG("Received user configuration\r\n");
                write_eeprom_network(&udp_server_buffer[strlen(DEVICE_ID)]); // parameters from 5th char, 15-bytes
                break;
            }
            // length = 12, SET TCP SERVER CONFIGURATION
            // auto update & its time period, TCP server configuration (IP & port)
            // Format: 4E 4E 49 4F   'Y'     01   C0 A8 00 09   E0 2E (LSB MSB)
            //         NNIO          Auto   1s   192.168.0.9   12000
            case UPDATE_TCP_SERVER_INFO_CMD_LENGTH: {
                char* id = strstr(udp_server_buffer, DEVICE_ID);
                if (id == NULL)
                    break;
                else if ((id - udp_server_buffer) > 0)
                    break;
                
                DBG("Received TCP server configuration\r\n");
                write_eeprom_tcpserver(&udp_server_buffer[strlen(DEVICE_ID)]); // parameters from 5th char
                break;
            }
            default:
                break;
        }
#endif
    } // network processor
}

/*
* Update digital outputs following receiving frame from TCP client
*/
void update_digital_outputs(char* buf) {
    DBG("Digital outputs: %s\n", buf);
    
    dout0 = (buf[0] == DIGITAL_HIGH)? 1 : 0;
    dout1 = (buf[1] == DIGITAL_HIGH)? 1 : 0;
    dout2 = (buf[2] == DIGITAL_HIGH)? 1 : 0;
    dout3 = (buf[3] == DIGITAL_HIGH)? 1 : 0;
    dout4 = (buf[4] == DIGITAL_HIGH)? 1 : 0;
    dout5 = (buf[5] == DIGITAL_HIGH)? 1 : 0;
    dout6 = (buf[6] == DIGITAL_HIGH)? 1 : 0;
    dout7 = (buf[7] == DIGITAL_HIGH)? 1 : 0;
}

void update_sending_frame(char* buf) {
    memcpy(&buf[SENDING_PROTOCOL_ID_POS], DEVICE_ID, 4); // device id
    memcpy(&buf[SENDING_PROTOCOL_MAC_POS], &u8mac, 6);
    memcpy(&buf[SENDING_PROTOCOL_IP_POS], &u8ip_addr, 4);
    
    buf[SENDING_PROTOCOL_DI_POS+0] = (din0 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+1] = (din1 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+2] = (din2 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+3] = (din3 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+4] = (din4 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+5] = (din5 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+6] = (din6 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DI_POS+7] = (din7 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    
    buf[SENDING_PROTOCOL_DO_POS+0] = (dout0 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+1] = (dout1 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+2] = (dout2 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+3] = (dout3 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+4] = (dout4 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+5] = (dout5 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+6] = (dout6 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    buf[SENDING_PROTOCOL_DO_POS+7] = (dout7 == 1) ? DIGITAL_HIGH : DIGITAL_LOW;
    
    uint16_t val = ain0.read_u16(); // 16-bits normalised
    memcpy(&buf[SENDING_PROTOCOL_AI0_POS], &val, 2); // LSB MSB
    val = ain1.read_u16(); // 16-bits normalised
    memcpy(&buf[SENDING_PROTOCOL_AI1_POS], &val, 2); // LSB MSB
    val = 0x0180;
    memcpy(&buf[SENDING_PROTOCOL_AO0_POS], &val, 2); // LSB MSB
    val = 0x0180;
    memcpy(&buf[SENDING_PROTOCOL_AO1_POS], &val, 2); // LSB MSB
    buf[SENDING_PROTOCOL_CR_POS] = 0x0D;
    buf[SENDING_PROTOCOL_CR_POS+1] = '\0';
}