Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: NaturalTinyShell_ice libmDot-12Sept mbed-rtos mbed
Fork of ICE by
src/ModbusMaster/ModbusMaster.cpp
- Committer:
- jmarkel44
- Date:
- 2016-09-16
- Revision:
- 67:49f266601d83
- Parent:
- 57:5f18ae91c7c7
- Child:
- 81:d45bfa16953a
File content as of revision 67:49f266601d83:
/******************************************************************************
 *
 * File:                ModbusMaster.cpp
 * Desciption:          source for the ICE Modbus Master
 *
 *****************************************************************************/
#include "global.h"
#include <stdio.h>
#include "MTSLog.h"
#include "BLEDataHandler.h"
#include "ModbusMaster.h"
#include "MbedJSONValue.h"
/*****************************************************************************
 * Function:             ModbusMaster
 * Description:          entry point for the Modbus Master
 *
 * @param                (IN) args (user-defined arguments)
 * @return               none
 *****************************************************************************/
char ModbusMasterScratchBuf[1024];
void ModbusMaster(void const *args)
{
    logInfo("%s ModbusMaster has started...", __func__);
    bool status;
    MbedJSONValue json_value;
    
    modbus_init(MB_BAUD_RATE);
    DigitalOut flu_power(PA_11);
    flu_power = 0; // provide power to the modbus
    printf("\r\nMODBUS INITIALIZED\r\n");
    
    while( true ) {
        logInfo("Top Of Modbus Master Loop");
        // configure modbus registers based in all files that start with "input"
        std::vector<mDot::mdot_file> file_list = GLOBAL_mdot->listUserFiles();
        for (std::vector<mDot::mdot_file>::iterator i = file_list.begin(); i != file_list.end(); ++i) {
            if( strncmp( i->name, "input", (strlen("input")-1)) == 0 ) {
                logInfo("(%d)FOUND INPUT FILE: %s", __LINE__, i->name);
                status = GLOBAL_mdot->readUserFile(i->name, ModbusMasterScratchBuf, 1024);
                if( status != true ) {
                    logInfo("(%d)read file failed, status=%d", __LINE__, status);
                } else {
                    logInfo("(%d)Read File SUCCESS: %s", __LINE__, ModbusMasterScratchBuf );
                }
                
                parse( json_value, ModbusMasterScratchBuf );
                std::string id = json_value["id"].get<std::string>().c_str();
                ModbusRegisterMap[id].name = json_value["name"].get<std::string>().c_str();
                ModbusRegisterMap[id].units = json_value["units"].get<std::string>().c_str();
                ModbusRegisterMap[id].min = atof(json_value["min"].get<std::string>().c_str());
                ModbusRegisterMap[id].max = atof(json_value["max"].get<std::string>().c_str());
                ModbusRegisterMap[id].node = atoi(json_value["node"].get<std::string>().c_str());
                ModbusRegisterMap[id].reg = atoi(json_value["reg"].get<std::string>().c_str());
                ModbusRegisterMap[id].rtype = atoi(json_value["rtype"].get<std::string>().c_str());
                ModbusRegisterMap[id].type = atoi(json_value["type"].get<std::string>().c_str());
                ModbusRegisterMap[id].size = atoi(json_value["size"].get<std::string>().c_str());
                ModbusRegisterMap[id].order = atoi(json_value["order"].get<std::string>().c_str());
                ModbusRegisterMap[id].fmt = json_value["fmt"].get<std::string>().c_str();
                ModbusRegisterMap[id].rfreq = atoi(json_value["rfreq"].get<std::string>().c_str());
            }
        }
        // read modbus registers that have been configured.
        while ( true ) {
            std::map<std::string, ModbusRegister>::iterator iter;
            for (iter = ModbusRegisterMap.begin(); iter != ModbusRegisterMap.end(); ++iter) {
                logInfo("Reading node=%d, reg=%d, size=%d, order=%d", iter->second.node, iter->second.reg, iter->second.size, iter->second.order );
                SendModbusCommand(iter->second.node, iter->second.reg, iter->second.size);
                Thread::wait(30);
                switch( iter->second.type ) {
                    case TYPE_32BIT_FLOAT:
                        float float_value;
                        status = ReadModbus_32bit_float( &float_value, iter->second.order );
                        if( status == true ) {
                            ModbusRegisterMap[iter->first].float_value = float_value;
                            logInfo("Modbus Tag:%s value=%2.2f", iter->first.c_str(), float_value );
                        }
                        else
                        {
                            logInfo("Modbus Read Failed, tag=%s", iter->first.c_str() );
                        }
                        break;
                    case TYPE_32BIT_INT:
                        break;
                    case TYPE_32BIT_UINT:
                        break;
                    case TYPE_16BIT_INT:
                        break;
                    case TYPE_16BIT_UINT:
                        break;
                    default:
                        break;
                }
            }
            logInfo("Checking for MAIL");
            osEvent evt = ModbusMasterMailBox.get(50);
            if (evt.status == osEventMail) {
                Message_t *mail = (Message_t*)evt.value.p;
                logInfo("Mail Received: Action: %d, New Input File: %s", mail->action, mail->controlFile);
                ModbusMasterMailBox.free(mail);
                ModbusRegisterMap.clear();
                break;
            } else {
                logInfo("No Mail");
            }
            Thread::wait(5000);
        }
    }
}
volatile char       modbus_buffer_char;
volatile bool       modbus_interrupt_complete = false;
uint8_t             modbus_input_buffer[SIZE_MB_BUFFER];// 1byte address + 1 byte function +1 byte number of regs + 12 bytes of data + 2 bytes for crc response frame from slave
volatile uint8_t    modbus_input_buffer_counter = 0;
//Frame crc calucation
uint16_t modbus_crc(uint8_t* buf, int len)
{
    uint16_t crc = 0xFFFF;
    for (int pos = 0; pos < len; pos++) {
        crc ^= (uint16_t)buf[pos];          // XOR byte into least sig. byte of crc
        for (int i = 8; i != 0; i--) {
            // Loop over each bit
            if ((crc & 0x0001) != 0) {
                // If the LSB is set
                crc >>= 1;                    // Shift right and XOR 0xA001
                crc ^= 0xA001;
            } else                          // Else LSB is not set
                crc >>= 1;                    // Just shift right
        }
    }
    // Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
    return crc;
}
RawSerial modbus(PA_2, PA_3);
DigitalOut mod_de(PB_0);
DigitalOut mod_re(PB_1);
void modbus_init( uint16_t baudRate )
{
    modbus.baud(baudRate);
    modbus.attach(&modbus_recv, RawSerial::RxIrq);
}
//call back when character goes into RX buffer for RS485 modbus
void modbus_recv()
{
    if (modbus.readable()) {
        modbus_buffer_char = modbus.getc();
        if (modbus_input_buffer_counter == 0 && modbus_buffer_char == 0x00) {
            modbus_input_buffer_counter = 0;
        } else {
            modbus_input_buffer[modbus_input_buffer_counter] = modbus_buffer_char;
            modbus_input_buffer_counter++;
        }
    }
    if (modbus_input_buffer_counter > modbus_input_buffer[2] + 4) {
        modbus_interrupt_complete = true;
        modbus_input_buffer_counter = 0;
    }
}
// Read modbus master frame
void SendModbusCommand(uint8_t slave_address, uint16_t firstReg, uint16_t noRegs)
{
    uint8_t L1V[8] = {slave_address, 0x04, 0x00, 0x02, 0x00, 0x02, 0xD1, 0x16};
    L1V[2] = (firstReg >> 8) & 0xFF;
    L1V[3] = firstReg & 0xFF;
    L1V[4] = (noRegs >> 8) & 0xFF;
    L1V[5] = noRegs & 0xFF;
    L1V[6] = modbus_crc(L1V,6) & 0xFF;
    L1V[7] = (modbus_crc(L1V,6)>>8) & 0xFF;
    mod_de = 1;
    mod_re = 1;
    Thread::wait(1);
    for (uint8_t i = 0; i < 8; i++)
        modbus.putc(L1V[i]);
    Thread::wait(2);
    mod_de = 0;
    mod_re = 0;
}
bool mbInterruptComplete()
{
    if (modbus_interrupt_complete) {
        modbus_interrupt_complete = false;
        return true;
    } else {
        return false;
    }
}
bool ReadModbus_32bit_float( float *float_value, int order )
{
    MR_REGISTER_32_BIT_FLOAT value;
    if (mbInterruptComplete() != true ) {
        return false;
    }
    switch( order ) {
        case BigEndian:
            value.b.lo_lo = modbus_input_buffer[6];
            value.b.lo_hi = modbus_input_buffer[5];
            value.b.hi_lo = modbus_input_buffer[4];
            value.b.hi_hi = modbus_input_buffer[3];
            break;
        case BigEndianReverseWord:
            value.b.lo_lo = modbus_input_buffer[4];
            value.b.lo_hi = modbus_input_buffer[3];
            value.b.hi_lo = modbus_input_buffer[6];
            value.b.hi_hi = modbus_input_buffer[5];
            break;
        default:
            return false;
    }
    *float_value = value.f;
    return true;
}
            
    