CuPID Brew System : Industrial Monitoring with CuPID UPS and RS485 Mote

TL;DR

Here’s a few pics of the final product. We’ll get you some more close-ups of the CuPID, but you can see it elsewhere as well:

Networked control panel : The CuPID way.
Networked control panel : The CuPID way.

We’ll get you a little final UI here, but here’s a taste:

Our first revision UI for our control panels. Yummy stuff.
Our first revision UI for our control panels. Yummy stuff.

Introduction

We’re building our networked industrial panel solution. We’ve got all the pieces:

We’ve got our RS485 enabled mote reading data from our temperature controllers. See here (post for remote node coming):

http://www.cupidcontrols.com/2015/10/software-serial-modbus-master-over-rs485-transceiver/

We’re passing that into our UPS-enabled CuPID through our gateway RF node:

http://www.cupidcontrols.com/2015/10/cupid-ups-rf-gateway-uninterrupted-control-for-industrial-applications/

This logs the serial messages on controller status as they are received. It also takes queued messages and sends them to our gateway as available. We use this interface to send and debug:

http://www.cupidcontrols.com/2015/03/rf-mote-web-ui-program-all-the-rf-things/

We’ve also talked about our general web-based UI strategies:

http://www.cupidcontrols.com/2014/09/cupid-remote-read-database-logging-and-ui/

We have a few more elements to wrap up:

Command response

Command response is an important feature. When we send a message, we need confirmation that it was received and acknowledged. Ideally, we receive a status that indicates whether there was an error or not. This is especially important when we have multiple links in the command sequence. In the case below, for example, we queue a message that is sent over serial from the Pi in the CuPID to the Moteino. This command is received and sent to node 2, where it is then interpreted as a setpoint change request to Controller 1. Once the command is successfully processed, the remote node returns the data to the CuPID node, which sends it to the Pi and it is again databased. This is shown below:

Command chain for sending and receiving acknowledgement for a command to a remote controller.
Command chain for sending and receiving acknowledgement for a command to a remote controller.

So on our UI, we double-check our response comes through:

Testing out command and response on our mote interface. We sent our setpoint command out and receive a command acknowledgement response.
Testing out command and response on our mote interface. We sent our setpoint command out and receive a command acknowledgement response.

Linking up setpoint commands and remotes

So the tricky part here is sending commands to the controllers at the proper times. We have to take actions on the UI and immediately translate them into serial commands to send to the motes and then controllers, and then ensure the commands are acknowledged (later). The reason this is tough is that some channels are local, i.e. the CuPID is actually running a control algorithm and controlling outputs, and in some cases we have a mote channel that is controlled remotely. For the former case, the setpoint is a simple value change in the database. For the latter, we need to change the value, mark the setpoint change as a pending setpoint change, and insert the command into the serial queue for processing.  To accomplish this differentiation, we add a ‘type’ field for channels, as well as a ‘pending’ field in which we can put values that we are in the process of updating. The other nice part about this type field is that we can use it to determine which data to display. Some fields just don’t make sense for remote channels, e.g. control inputs on a remote channel.

So now each time a setpoint (or other parameter) is changed, we simply add the name of the field to the ‘pending’ channel entry. Then, when picontrol (the control algorithm script) iterates over a local channel, it will clear this field, and for remote channels, when we receive a message indicating the value has been updated, accepted or rejected, we will also clear this field. The question is: where do we write to the pending field? Do we do this from the UI, i.e. add an additional action to the widget? Or do we do it server-side, perhaps in the wsgi script, where if the value to set matches a list of values, it also sets the pending field? Or perhaps we can enforce it into the database with a value change trigger. All are possible. In the end, we put into into wsgi, for a few reasons. First of all, we like the way our js value updater works, and really didn’t want to mess with it. Second, we have logging capability in our wsgi that makes debug and keeping track of things easy. Lastly, it will make integration of pending setpoints for things like recipes quite easy, if we factor them properly. In other words, if we have a ‘setvalue’ function, and when ‘database’ = ‘systemdatabase’ and ‘table’=’channels’ and ‘value’=’setpoint’, we set ‘pending’=’setpoint’, this is a behavior that can be used universally.

So something like this works great as an add-on to the existing setvalue function:

def setsinglecontrolvalue(database, table, valuename, value, condition=None):
    if table == 'channels':
        if valuename in ['setpointvalue']:
            # get existing pending entry
            pendingvaluelist = []

            pendingentry = getsinglevalue(database, table, 'pending', condition)
            if pendingentry:
                try:
                    pendingvaluelist = pendingentry.split(',')
                except:
                    pendingvaluelist = []

            if valuename in pendingvaluelist:
                pass
            else:
                pendingvaluelist.append(valuename)

            pendinglistentry = ','.join(pendingvaluelist)

            setsinglevalue(database, table, 'pending', pendinglistentry, condition)

    # carry out original query no matter what
    response = setsinglevalue(database, table, valuename, value, condition=None)
    return response


def setsinglevalue(database, table, valuename, value, condition=None):
    query = makesinglevaluequery(table, valuename, value, condition)
    response = sqlitequery(database, query)
    return response

Now we need to get the message to the Gateway CuPID Mote so that it can actually send the set message to the controller. We want to do this as expediently as possible, so we don’t want to wait for picontrol to get to it. It may only be polling every 15s or so, and we want the system to be as responsive as possible. So we insert a conditional that will execute if this is a remote channel:

# Get the channel data
channeldata = readonedbrow(controldatabase, 'channels', condition=condition)[0]

if channeldata['type'] == 'remote' and channeldata['enabled']:
    # Process setpointvalue send for remote here to make it as fast as possible.
    # First we need to identify the node and channel by retrieving the interface

    channelname = channeldata['name']
    
    # Then go to the interfaces table to get the node and channel addresses
    address = getsinglevalue(controldatabase, 'interfaces', 'address', "name='" + channelname + "'")

    node = address.split(':')[0]
    channel = address.split(':')[1]

    # If it's local, we send the command to the controller directly
    if int(node) == 1:
        message = '~setsv;' + channel + ';' + str(value)

    # If not, first insert the sendmsg command to send it to the remote node
    else:
        message = '~sendmsg;' + node + ';~setsv;' + channel + ';' + str(value)

    # Then queue up the message for dispatch
    sqliteinsertsingle(motesdatabase, 'queuedmessages', [gettimestring(), message])

And that does the trick nicely. The best part about this: we have to change NOTHING about any of our UI code. All of our existing setvalue functions (the ‘setvalue’ action in our wsgiactions script) is now mapped, simply by changing ‘setvalue’ to ‘setcontrolvalue’ in the function call!

So let’s give this a shot. We’ll change a setpoint value on our UI and ensure that:

  • A serial message is queued
  • The ‘pending’ status is added to the remote channel.

So we slide away on our UI slider and see what happens.

Our message send test sequence.
Our message send test sequence.

Verifying commands : acknowledgement

The last step is closing the loop on the command, in case something goes awry along the way. We do have the mote set up to receive command acknowledgement from the controllers, and this message will be passed to the gateway. We can use this message as a command acknowledgement, and if we don’t receive it after some time, we will assume our setpoint command went into a black hole and try sending it again. So in the same way that we turned the setpoint command into a serial message, we will take the acknowledge message and deconstruct to remove the pending status from our channel. We return a message in json like:

~nodeid:1;chan:03;svcmd:100.0

For now, we’re not going to worry about the value on the command. Later, we can worry about this, but for now let’s just get back to the channel and zero out the pending status. So we jam out node and channel ids together to get an address of 1:3, and search our interfaces for a MOTE interface of type channel with an address 1:3. We return an entry with a name, which we can match with our channel. Piece of cake. In fact, we already do this in our updateio.py script to insert our remotes data into our channels. All we have to do now is add an entry that:

  • Removes ‘svcmd’ from the node data stored in ‘remotes’ in the ‘data’ field (a json field that stores whatever data we happen to accumulate about a node)
  • Update the channel with this modified data without the ‘svcmd’ keyword
  • Clear out the pending setpointvalue status

We won’t bore you with the code here. It’s all in the git repo in updateio. It works.

Linking up the panel UI

So we need to get all of the data out of our remote entries and into our channel entries. The way we do this is pretty simple and we talked about it elsewhere and referenced it above.: we create an interface. This can be done manually via phpliteadmin (what we did at the time of writing this), or via the web UI (a work in progress). The key fields in the entry are Interface, type and Address. the Interface value needs to be set to MOTE, type to channel, and address to nodeid:channel. Here, nodeid is the id of the RF node (1 for the gateway in the main panel), and channel is the id of the controller on the Modbus network. So in the main panel, we have 1:1, 1:2, and 1:3 for the Kettle, MLT, and HLT controllers, respectively. We also need to give the channels unique names.

Once we have the above entries in place, the updatio script will go grab the setpoint value, process value, and the remainder of the data from the most recent mote entry in the remotes table. It will take ‘sv’ and ‘pv’ and insert these values into the channel entry, and the entire data entry will be stored in the channel ‘data’ field, so any additional data can be accessed by parsing out the data that exists there in json format.

Now, we need to link everything up for display in our brew panel interface. As it turns out, this is already done, so we’re just left to do a little sprucing up to make our UI a bit more application-specific.

Working on it!

 

Two-way error-free RF messaging : avoiding concurrent retry failure

Introduction

So we have our RF nodes happily talking to one another, and most often we have one talking, one listening. This is very easy, and facilitated even in poor reception by our built in SendWithRetry function (we’re speaking of the RFM69 library here, of course). This is what a unidirectional communication structure often looks lke:

A typical RF (or otherwise) communication structure. One talks, one listens

The Problem : The Retry Loop

The problem arises when we want to have two nodes talk to each other that sometimes have other stuff to do. The following situation arises, which results in failure of at least one of the communication attempts. Essentially, they get stuck in a a retry loop:

The retry loop. The boon of two-way communication.

The Solution : The State Machine

The solution is rather simple: tell one node to stop retrying until it’s had a chance to listen. In pseudocode, this looks like this:

The state machine: savior of two-way retry communication.

In Real Life

In real life, this is pretty easily coded using a switch statement, with a delay afterwards to allow enough time for radio messages to show up and complete. 100ms is more than sufficient.

CuPID UPS RF Gateway : Uninterrupted control for industrial applications

Introduction

So we have been using our CuPID RF Controller all over the place. We use it at home, for automation and monitoring, at the shop for keeping an eye on things and connecting everybody, and most recently in industrial control panels. One issue that keeps coming up is reliability, and a few related sub-issues. As a result, we have decided to incorporate a battery and power management solution into our standard controller. This addresses these main issues:

Reliability

One thing guaranteed to eventually corrupt the operating system of a Raspberry Pi (and most OS, for that matter), is memory corruption. A great way to corrupt the memory on the OS is to remove power, have it fluctuate above or below the recommended voltage (nominally 4.75-5.2V on Raspberry Pi), or otherwise halt operations in an unknown state. Unfortunately, even AC power fluctations can cause problems. The Pi is notoriously picky about power supplies and their ability to maintain voltage under load. And, sometimes, you accidentally knock the power supply, something upstream fails … you get the picture. You can’t always choose when power is removed/changed, and you certainly don’t get to pick when it corrupts your OS. And when it does … you get to rebuild. Even if this just means writing an existing image, it’s still a pain, especially in a mission-critical embedded system.

Continuous operation during brief power outages

During commissioning of systems, testing power supplies, or for things as simple as moving your sensor gateway across the house, it is VERY convenient to be able to handle a brief power outage while the Pi still chugs away. And if you lose power for too long? it shuts itself down. For example, our control panels automatically cut all power to the system when the front door is closed. If we didn’t have some sort of UPS, we’d have to shutdown and reboot our CuPID every time we opened the door! Obviously this doesn’t work. What about if you blow a fuse or breaker? No problem.

Power Conditioning

This follows from the above, but line voltage is not always guaranteed. Our first warehouse space monitoring CuPID was continually going offline. The culprit? The neighbor was running high power equipment and pulling our line voltage below where our AC/DC converter could handle it on short intervals. Our battery and boost converter ensure that momentary drops below where our AC/DC converter is comfortable will not give our gateway problems.

External, Field-serviceable power control

One necessary feature of a deployed device is the ability to treat and diagnose. Worse comes to worse, sometimes you need to reset. A great feature of the UPS-enabled CuPID is the ability to reboot, shutdown, and hard reset. Ideally, this is not necessary, but things happen. The MightyBoost gives us a functional button, programmable actions, and an LED to give us status of our CuPID gateway.

Real-time power monitoring

The least important (but still cool) feature of the CuPID UPS gateway is the ability to monitor voltage in real time. You can see just how bad your power supply or building power is, or when things got bad.

The Hardware

The hardware here is quite simple: we take our standard CuPID HAT build and put a MightyBoost on top. Luckily the MightyBoost has the same footprint for the Moteino, so it’s a pretty easy fit. Here is a very abbreviated assembly procedure:

The board with EEPROM, DS2483 and a few passives installed:

CuPID Pi HAT Board
CuPID Pi HAT Board

With a Moteino on top:

Mounting the Moteino on the CuPDI HAT board + Moteino is a piece of cake.
Mounting the Moteino on the CuPDI HAT board + Moteino is a piece of cake.

Mightboost loaded up on the Moteino headers:

CuPID UPS RF with an RS485, loaded into an enclosure.
CuPID UPS RF with an RS485, loaded into an enclosure.

Here, we added in a shutdown jumper to GPIO20, power from the MightyBoost output, and a battery:

CuPID + Moteino + Mightyboost + battery
CuPID + Moteino + Mightyboost + battery

With a few more components, the stack fits nicely into an enclosure. Here, we’ve also added an RS485 board:

fab6

And finally, the CuPID lives in its native environment with On/Off switch, IO connected, and 5V supply in from a DIN mount AC/DC converter.

fab7

Software Serial Modbus Master over RS485 transceiver

The Problem

We like cheap, well-made temperature controllers. Sure, we can make our own, but for a modest sum we can get a nice NEMA-rated package capable of reasonably complex logic with a communications interface. The Love 4C and 16C controllers can both be had for <$100 fit this description and make dependable control and higher-level monitoring possible.

The downside is that the interface is modbus over RS485, which requires a driver chip such as the Maxim RS485 which will translate to serial for control over a UART or other serial interface. This is not a killer, as you can get a nicely laid out RS485 chip from Sparkfun for $10, or make your own.

The reason for this piece is that all RS485 code I could find was designed for use with the hardware serial UART on microcontrollers such as Arduino or clones such as the Moteino. Because I typically use the UART for communication to a Pi or to a debug console, and the 328P I typically use has only one, this was not an option. To make it work over a few digital pins, it is actually quite easy to use the SoftwareSerial library to make this happen.

The Hardware

Here’s the basic board from SparkFun, a bargain at $10:

SparkFun Adafruit board.
SparkFun Adafruit board.

 

Here’s our desktop prototyping setup:

Our desktop prototyping setup.
Our desktop prototyping setup.

 

We’ve mounted this a bunch of ways, but here are a couple of examples:

An RS485 board mounted on a CuPID RF module with MightyBoost. A pretty typical configuration.
An RS485 board mounted on a CuPID RF module with MightyBoost. A pretty typical configuration.
Another mounting configuration on a CuPID RF with RF and MightyBoost. This one is wired.
Another mounting configuration on a CuPID RF with RF and MightyBoost. This one is wired.

Talking Modbus

The modbus protocol is actually quite simple. A frame is created with a bit of metadata that describes the data and then either transmits or waits for it. Because we are using 2-wire modbus rather than 4-wire, communication is not duplex, and we need to instruct the RS485 driver to enter transmit mode. We do this by pulling a digital pin high. This pin is typically referred to as RTS (Ready To Send). When we are done, we set RTS low and the transceiver again waits to receive data.

The data frame contains where who we are, where we are sending/receiving the data to/from, how much there is, and a CRC data integrity check. For more information, SimplyModbus is a great source for bit-by-bit breakdown. Note that ASCII and RTU also differ in the CRC format: RTU uses a two-byte CRC (CRC16),  while ASCII uses a two-character LRC.

An RTU read modbus message:

byte 0 1 2 3 4 5 6 7
value node FC register high register low # registers high # registers low CRC high CRC low

A modbus RTU command modbus message:

byte 0 1 2 3 4 5 6 7
value node FC register high register low set value high set value low CRC high CRC low

There are two types of Modbus typically used: ASCII and RTU. RTU is the binary data that comprises a frame (typically 8 bytes for a request), and ASCII is the byte-by-byte equivalent of the message in ASCII characters. So each hex byte character is translated to an ASCII character, doubling the message size (and adding a byte for a ‘:’ delimiter). Clearly, RTU is much more efficient, but ASCII as usual offers human-readability.

Although the manual for the 4C and 16C list ASCII as the type, the units have an RTU option, accessible in the communications menu.

The Code

The code for the master is quite simple, and operates on a simple state machine. This example is written for a series of 5 controllers with sequential addresses, but the number and addresses of devices polled can be easily configured by the initialization arrays. Registers polled are hard-coded, but could easily be parameterized or customized.

The sequence below sends and receives three basic commands, and rotates through them for each device. It utilizes a helper function to calculate and append CRC on the fly, as well as our serial/radio transmit functions on message receive:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(14, 15, 0); // RX, TX
byte RTSPIN = 16;
int xmitdelay = 0;
unsigned long rxstart;
unsigned long rxwait = 1000;
float sv;
float pv;
byte rtuaddress=0;

// message : node, FC, register start high byte, register start low byte, number of registers, CRC, CRC
byte pvsvmessage[] = {0x01, 0x03, 0x47, 0x00, 0x00, 0x02, 0x00, 0x00 };
byte outputmessage[] = {0x01, 0x03, 0x47, 0x14, 0x00, 0x02, 0x00, 0x00 };
byte modemessage[] = {0x01, 0x03, 0x47, 0x18, 0x00, 0x02, 0x00, 0x00 };

switch ( mbstate ) {
case 0: // This is the transmit stage
  message[0] = rtuaddresses[rtuindex];
  for (byte i=1; i<6; i++) {
    switch (mbmessagetype) {
    case 0:
      message[i] = pvsvmessage[i];
      break;
    case 1:
      message[i] = outputmessage[i];
      break;
    case 2:
      message[i] = modemessage[i];
      break; 
    }
  }
  addcrc(message,6);
  if (DEBUG) {
    Serial.print("sending to controller: ");
    Serial.println(rtuaddresses[rtuindex]);
    Serial.print(message[0],HEX);
    Serial.print(" ");
    Serial.print(message[1],HEX);
    Serial.print(" ");
    Serial.print(message[2],HEX);
    Serial.print(" ");
    Serial.print(message[3],HEX);
    Serial.print(" ");
    Serial.print(message[4],HEX);
    Serial.print(" ");
    Serial.print(message[5],HEX);
    Serial.print(" ");
    Serial.print(message[6],HEX);
    Serial.print(" ");
    Serial.println(message[7],HEX);
  }
 
  pinMode(RTSPIN, OUTPUT);
  digitalWrite(RTSPIN,HIGH);
  delay(xmitdelay);

  mySerial.write(message, sizeof(message));
  delay(xmitdelay);
  digitalWrite(RTSPIN,LOW);
  mbstate = 1;
  rxstart = millis();
  break; 
case 1: // wait for response
  if (mySerial.available() > 0)
  {
    Blink(LED,5);
    cmdlength = mySerial.readBytes(buff, 60);
    if (DEBUG) {
      Serial.print("Received message of length ");
      Serial.println(cmdlength);

      for (i=0; i<cmdlength;i++){
        Serial.print(buff[i], HEX);
        Serial.print(" ");
      }
      Serial.println();
    }
 
    if (buff[1]==3) {
      if (mbmessagetype == 0){
        pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255))/10;
        sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255))/10;
        if (DEBUG) {
          Serial.println("values");
 
          Serial.print("nodeid:");
          Serial.print(NODEID);
          Serial.print(",controller:"); 
          Serial.print(rtuindex);
          Serial.print(",pv:"); 
          Serial.print(pv);
          Serial.print(",sv:");
          Serial.println(sv);
        }
      }
      else if (mbmessagetype == 1) {
        pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255));
        sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255));
        if (DEBUG) {
          Serial.print("Proportional offset: ");
          Serial.println(pv);
          Serial.print("Regulation value");
          Serial.println(sv);
        }
      }
      else if (mbmessagetype == 2) {
        pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255));
        sv = (float(buff[5] & 255) * 256 + float(buff[6] & 255));
        if (DEBUG) {
          Serial.print("Heating/cooling");
          Serial.println(pv);
          Serial.print("Run/Stop");
          Serial.println(sv);
        }
      }
      Blink(SENDLED,5);
      sendControllerMessage(rtuaddresses[rtuindex], pv, sv, mbmessagetype);
    }
    else {
      if (DEBUG) {
        Serial.println("bad response");
      }
    } 
    if (millis() - rxstart > rxwait) {
      if (mbmessagetype >= 2) {
        mbmessagetype = 0;
        if (rtuindex >= sizeof(rtuaddresses)-1) {
          rtuindex = 0;
        }
        else {
          rtuindex ++;
        }
      }
      else {
        mbmessagetype ++;
      }
      mbstate=0;
    }
    break;
  } // switch
}

We use a controller message function and CRC as here:

void sendControllerMessage(byte controller, float pv, float sv, byte messagetype) {
 
  // Initialize send string

  int sendlength = 61; // default
  int wholepv = pv;
  int fractpv = (pv - wholepv) * 1000;
  int wholesv = sv;
  int fractsv = (sv - wholesv) * 1000;
 
  if (messagetype == 0) {
    if (NODEID == 1) {
      sendlength = 39; 
      sprintf(buff, "nodeid:1,chan:%02d,sv:%03d.%03d,pv:%03d.%03d", controller, wholesv, fractsv, wholepv, fractpv);
      Serial.println(buff);
    }
    else {
      sendlength = 30; 
      sprintf(buff, "chan:%02d,sv:%03d.%03d,pv:%03d.%03d", controller, wholesv, fractsv, wholepv, fractpv);
      sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); 
    }
 }
 else if (messagetype == 1) {
   if (NODEID == 1) {
     sendlength = 37; 
     sprintf(buff, "nodeid:1,chan:%02d,prop:%03d,treg:%03d.%01d", controller,wholepv, wholesv, fractpv);
     Serial.println(buff);
   }
   else {
     sendlength = 28; 
     sprintf(buff, "chan:%02d,prop:%03d,treg:%03d.%01d", controller,wholepv, wholesv, fractsv);
 sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); 
     }
   }
   else if (messagetype == 2) {
     if (NODEID == 1) {
     sendlength = 31; 
     sprintf(buff, "nodeid:1,chan:%02d,htcool:%01d,run:%01d", controller,wholepv,wholesv);
     Serial.println(buff);
   }
   else {
     sendlength = 22; 
     sprintf(buff, "chan:%02d,htcool:%01d,run:%01d", controller,wholepv, wholesv);
     sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); 
   }
 }
}
void addcrc(byte* message, int len) {
  mycrc = ModRTU_CRC(message, len);

  long byte1 = mycrc & 255;
  long byte2 = (mycrc & long(255*256))>>8;
  if (DEBUG) {
    Serial.print(byte1,HEX);
    Serial.print(",");
    Serial.println(byte2,HEX);
  }
  message[len] = byte1;
  message[len + 1] = byte2;
}

In debug mode, we get something like what’s shown below:

sending to controller: 1
1 3 47 0 0 2 D0 BF
Received message of length 9
1 3 4 2 FFFFFFCE 3 FFFFFFE8 FFFFFF9A FFFFFFCA 
values
nodeid:2,controller:0,pv:71.80,sv:100.00

SENDING TO 1
chan:01,sv:100.000,pv:071.800
SEND COMPLETE

sending to controller: 1
1 3 47 14 0 2 90 BB
Received message of length 9
1 3 4 0 0 0 0 FFFFFFFA 33 
Proportional offset: 0.00
Regulation value0.00

SENDING TO 1
chan:01,prop:000,treg:000.0
SEND COMPLETE

sending to controller: 1
1 3 47 18 0 2 50 B8
Received message of length 9
1 3 4 0 0 0 1 3B FFFFFFF3 
Heating/cooling0.00
Run/Stop1.00 

SENDING TO 1
chan:01,htcool:0,run:1
SEND COMPLETE

When we’re not in debug, only the messages between the “SENDING” and “SEND COMPLETE” are sent, which our CuPID gateway picks up and logs.

Writing Values

In MODBUS, writing values is as simple as changing the function code. The message format is as above. We need function code 6, and to format our values. We borrow some command processing code, so we can issue setpoint value commands over serial.

The other piece is value conversion, which we glossed over earlier. We have to convert back and forth between our float values. The values in this particular case are stored in tenths of. i.e. a setpoint or process value of 123.4 will be stored as 1234. In hex, this is 04 D2.

So we use the following to go from bytes to value:

pv = (float(buff[3] & 255) * 256 + float(buff[4] & 255))/10;

And this to go from value to bytes:

int highbyte = (sv * 10) / 256;
int lowbyte = int(sv * 10) & 255;

And what we end up with is a routine to send our messages nicely:

void sendsvmessage(int node, float sv) {
  message[0] = node;
  for (byte i=1; i<6; i++) {
    message[i] = setmessage[i];
  }
  Serial.print("received setpoint:");
  Serial.println(sv);
  int highbyte = (sv * 10) / 256;
  int lowbyte = int(sv * 10) & 255;

  message[4] = highbyte;
  message[5] = lowbyte;
  
  addcrc(message,6);
 
  pinMode(RTSPIN, OUTPUT);
  digitalWrite(RTSPIN,HIGH);
  delay(xmitdelay);

  mySerial.write(message, sizeof(message));

  delay(xmitdelay);
  digitalWrite(RTSPIN,LOW);
 
  rxstart = millis();
  mbstate = 1;
}

Finally, it would be nice to confirm that the command was received, and return a command to the serial or radio interface so that the gateway or user can confirm that it was accepted (without looking at the device. So we write in a handler for the message reader:

else if (buff[1]==6) {
 
  sv = (float(buff[4] & 255) * 256 + float(buff[5] & 255))/10;
  if (DEBUG) {
    Serial.print("Command acknowledged for node:");
    Serial.println(buff[0]);
    Serial.print("Setpoint: ");
    Serial.println(sv);
  }
  sendCmdResponseMessage(buff[0], sv);
}
void sendCmdResponseMessage(byte controller, float sv) {
  // Initialize send string

  int sendlength = 61; // default
  int wholesv = sv;
  long fractsv = ((long)(sv*1000))%1000;
 
  if (NODEID == 1) {
    sendlength = 31; 
    sprintf(buff, "nodeid:1,chan:%02d,svcmd:%03d.%03d", controller, wholesv, fractsv);
 Serial.println(buff);
  }
  else {
    sendlength = 23; 
    sprintf(buff, "chan:%02d,svcmd:%03d.%03d", controller, wholesv, fractsv);
    sendWithSerialNotify(GATEWAYID, buff, sendlength, 1); 
  }
}

And we get what we expect on the way out:

SENDING SV CMD
sending to controller: 1
1 6 47 1 1 C9 D 78
Received message of length 8
1 6 47 1 1 FFFFFFC9 D 78 
Command acknowledged for node:
Setpoint: 45.70

SENDING TO 1
chan:01,svcmd:045.700
SEND COMPLETE

This code can be located on the git repo here:

https://github.com/iinnovations/iicontrollibs/tree/master/mote/brew/brewmotewrite