We love the mightyboost. We’ve raved about it here and here. Aside from plug and play, however, it has become a bit difficult for us to use. We had some features we wanted to add and things we wanted to tweak, so when we did that we decided to just redo it entirely.
We use jqplot. A lot. Exclusively. It is a great lightweight library for producing pretty, mobile-friendly plots.
One issue we have discovered, however, is that when updating plots frequently (as we nearly always do), memory tends to leak. On larger plots, long periods, or frequent updates, this can spiral out of control and crash a browser. This tends to be especially problematic in Firefox.
The Problem
In a typical jqplot call, we generate a plot in a div with a command like:
As it turns out, memory is allocated and never released here. Watching a system resource monitor reveals that the browser continues to increase memory usage.
The Solution
To solve this problem, we do two simple things:
Put the plot into a global variable so it can be accessed at any time.
Destroy the plot before recreating it.
In the section of our body (using jquerymobile, where all our js lives in the body), put our plot into our globaldata container:
var globodata = {netplot:''};
Now, each time we create the plot, in addition to emptying out our container div, we also use the destroy() method to release the memory.
Previously, we showed how to read a LabJack over Modbus TCP/IP, and showed a couple examples. This is super convenient for networked devices. Having a LAN handy (or the U9, the only LabJack with an ethernet port) isn’t always the situation, however, and in these cases, communicating over USB is the standard method with a LabJack. Further, the flexibility of the API allows us to abstract the functions of the LabJack much more easily with built-in functions. This is of course possible by wrapping up functions with a modbus map available, but here we don’t have to reinvent the wheel, as the functions are already wrapped for us. There are some clear drawbacks and shortcomings with the API (as will be discussed), but there are ways to deal with them.
The Setup
Here, we’ll be using a typical Raspberry Pi-based CuPID, with a LabJack U6 connected on USB. We are using a recently release of Raspbian as a part of our standard install. This particular system involves two devices connected to the LabJack, where the LabJack is put near the devices and some distance away from the CuPID. For this reason, we use USB over Cat5 adapters, which allow extension of the USB far beyond what is the typical spec of 5m. Here is what they look like:
RJ45 USB extenders
For this particular device, we need to read an analog input with a max output of 10mV, and a counter.
The Python API
The LabJack python API is available here. The main disadvantage … and a huge disadvantage it is … is that you MUST maintain and close your sessions to the device religiously. There is no way to reattach, and no method to close_all(), as you would expect (AHEM!). So, don’t abuse your connection (read, handle errors in all called functions religiously), and close it. Otherwise you will be rebooting. This can be enormously painful if you are trying to do it all remotely.
To use this in a modular fashion, we include it as an interface type in our updateio.py reader script:
elif interface['type'] in ['U6', 'U3', 'U9', 'U12']:
utility.log(pilib.dirs.logs.io, 'Interface type is LabJack of type: ' + interface['type'], 3, pilib.loglevels.io)
valueentries = processlabjackinterface(interface, previnputs)
if valueentries:
control_db.queue_queries(valueentries)
We call our processlabjackinterface function to process the interface entry. Any number of options can be entered into the interface options field and be processed, e.g. resolution, gain, etc.
Examples
For our case of U6 entries, we create the following interface entry:
interface
type
address
id
name
USB
U6
first
USB_U6_first
U6 on USB
We then create entries in our LabJack table. Here, we are reading an analog input (with suitable options), and a counter. The addresses correspond to input addresses. See the processlabjackinterface function for more detail.
interfaceid
address
mode
options
USB_U6_first
2
AIN
differential:false,resolution:12,gain:3
USB_U6_first
0
CNT
And, when updateio is run, inputs entries with appropriate values are automagically created.
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:
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.
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.
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.
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.
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.
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
With a Moteino on top:
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.
Here, we added in a shutdown jumper to GPIO20, power from the MightyBoost output, and a 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:
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.
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.
Here’s 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.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:
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:
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:
So you are using logmein Hamachi, the awesome, easily configured VPN solution that runs networks in gateway and mesh configurations, and lets you see anything from anywhere. You have the desktop app, where you can see your devices easily in a window. You also have it set up on your phone, which allows you to log in to your Hamachi network so you can access your devices.
Problem: You can’t find the Hamachi IPs (or device status) easily when you’re on mobile.
When you’re running the desktop app, to get the Hamachi IP (the special IP that lets you access the device as if it were on your local network), you can see it, and just right click and ‘copy address’. This is not the case, however, when you’re on mobile. So .. you can either:
Memorize that silly IP address and hope that it’s online
Use your desktop app to get the IP (defeating the purpose)
Set a bookmark (not an awful solution)
Find a more elegant solution.
We (obviously) went with 4.
Step 1 : Get and parse the Hamachi data
So this is nothing new (although we did improve it to parse out networks recently). Inside our netfun.py lib, we have a set of functions that will parse the text output from the ‘hamachi list’ command. So hamachi list will output something like this:
* [187-XXX-002]HomeWork capacity: 2/32, [10.40.1.120/24] subscription type: Standard, owner: xxx@gmail.com
* 175-XXX-053 innovate 10.40.1.101 alias: not set direct UDP 192.168.1.101:43381
* [283-XXX-722]CuPID Network capacity: 11/32, subscription type: Standard, owner: xxx@gmail.com
* 136-XXX-383 XXXX2 25.XXX.78.58 alias: not set 2620:9b::xxxx:4e3a via relay TCP
! 176-XXX-808 linaro 25.0.0.0 alias: not set This address is a lso used by another peer
179-XXX-373 cupid-xxxx 25.0.0.0 alias: not set
179-XXX-060 Colin Phone 25.0.0.0 alias: not set
179-XXX-134 cupid-stevevorres 25.0.0.0 alias: not set
* 179-XXX-052 MYBOT 25.XXX.112.71 alias: not set 2620:xx::xxxx:7047 direct UDP 192.168.1.140:49240
181-XXX-742 colin-home 25.0.0.0 alias: not set
182-XXX-757 iispace 25.0.0.0 alias: not set
We take this raw data and spit it out into two lists: one containing network dictionaries with their metadata, and another containing a list of client dictionaries with each client’s metadata (online status, etc.). Easy peasy. The function is called gethamachidata(), and is in the netfun lib. It will output something nice:
… and so you have a list of networks, and then the clients attached to each of the networks.
Step 2 : Squirt data into webpage
The next part is also pretty easy. We write a little function that runs the above and formats it into a pretty little page. It is in the script hamachidaemon.py, available in the github here. We’d paste it here, but formatting the HTML is a bit of a pain, plus the code will get stale anyway. We do some pretty basic stuff, using jQuerymobile, which we really like, and we get pretty. We add some links too. Typing is for the birds.
Our Hamachi interface. Pretty, with links and networks.
Step 3 : Cron it
As you may guess from the name of the aforementioned script, we run it every so often. We also use this script to double-check that Hamachi is online. So set it up in your cron, and you’ll not only keep yourself online, but also keep your page updated, with links to your hamachi devices! Piece of cake.
Deploying a bunch of remote nodes and a gateway into the wild presents a number of issues. What does each do? What is connected to it? How often should it tell me what’s up?
Typically wrapping up a group of remote sensors requires a unique program for each node, programming and debugging each node locally with a serial interface, and programming a gateway/data aggregator to understand each individually. This can be a bit of a nightmare, and we really wanted a solution where we would never have to get out our FTDI cable to program a micro directly!
We’ve addressed all of these issues with our UniMote code and our gateway UI for messaging remote nodes. Read on.
UniMote for universal code and remote config
One thing we all loathe is repeating ourselves. Another is constant maintenance of multiple instances of code, even if they are quite similar (and often even more so if they are). For this reason, we’ve built a UniMote sketch that does, well, everything. It works on a battery-powered mote as well as it does on a sensor gateway. You can configure it over serial or RF with simple commands. You can read about that here and here.
Gateway SerialHandler to dispatch and process
On a gateway, we have a mote connected by serial, often to a Raspberry Pi, for example on our Pi HAT. On our gateway, we need to both listen for incoming messages from our mote, as well as send messages when necessary.
To facilitate this, we set up a pretty simple serial message handler. It continuously listens, and dispatches messages as they show up in a queue set up in a database, This database houses received messages, queued messages, as well as those that have been sent, time-stamped of course. It’s in python, uses pyserial, and is pretty darned straightforward. In the form you’ll find it, it does use our pilib, but you can easily cut and paste if you want a standalone version.
Our serial handler does nothing except process commands put into a queue, so all we need to do with a UI is to present a way of inserting messages into it. This is pretty easy, and based on things we have talked about previously. We create a UI that executes a simply wsgi function to insert entries in the serial queue. We add some css, and we get the UI below:
Terminal UI for entering sending messages to our motes.
We can pretty easily see the messages as they go out and are received. Simple stuff.
Mote Control Panel
Now, on top of this basic goodness, we’re going to build something that resembles a control panel, where we can view each node’s vitals, update data, and view what the status of all the IO are. We do it using the same basic methods above, combined with the databased data retrieval we’ve talked about here and here. The end result is a browser-determined data retrieval sequencing that complements the node-side code that is set up to deliver data when the node feels like it. This will be the bedrock that our remote thermostat/PLC code rests firmly on. Here are a couple videos with an explanation and demo of the control panel interface:
In our last UniMote installment, we outlined our UniMote program. A one-size fits all sketch for our avr-based, RF-enabled microcontrollers, our sketch has the following main features:
Numbered, sequential access to all available IO on R4 and Moteino Mega microcontrollers
8 channels with configurable positive/negative feedback and deadband
Configurable IO and channel status reporting
Remote command for RF send
Daisy-chainable commands, e.g. send command to mote to send command to mote to send command, etc.
Support for low power sleep modes
Configurable program control
Remote (RF) and local (serial) modification of all control parameters
What we wanted to add, however, were a few more features.
RF parameter readout: While we already had local parameter readout (with the listparams command), we didn’t have a readout feature for communication over RF. For devices that don’t sleep, it’s very useful to poll parameters when necessary. So with the previous feature set, we have configurable bidirectional communication. We can confirm commands, read out all setpoints, process values, io/channel statuses, and program configuration. This is great for a status UI.
Command response with status: Like an ACK with useful information, all commands to the remote will now receive a response both acknowledging the command as well as a status response. This will alert us to errors with our command, should we try to set a parameter incorrectly.
Code cleanup:
In addition to the above, there was a lot of code cleanup and optimization to be done. We removed all string objects and replaced them with character arrays to save space and avoid seg faults. We also employed a great library that stores strings (where necessary) in flash memory, to avoid the RAM usage that results in unpredictable behavior when collisions occur. It saves a ton of memory, especially compared to sprintf. Best of all, we fit all of the above into the memory space of at ATMega328P. With no further ado, let’s introduce the features.
Gateway/Mote Universality
Another thing we didn’t like was that we had to have unique gateway and mote sketches. We’ve done away with that. A gateway and a mote are the same. Just change the NODEID and sleep parameters, if you wish.
RF Parameter Readout
In the previous version of UniMote, we had a listparams command that would list all the Mote parameters. It looked something like this:
This worked well, but this didn’t work for reporting over RF, as each message is only 61 characters long. OOPS. So we broke the reporting into a number of “modes” that determined what would be reported in each chunk. This makes it more efficient anyway: we don’t always need all of the data. In fact, we rarely do. We made all of these functions work for both local and radio readout. So a listparams command has the following format:
~listparams;iovals;0
This would list the first chunk of io values to the Serial display:
If we change the third parameter to something non-zero, the data will also be sent to that node number over RF. Simple as that. Each chunk is formatted to be 61 characters or less, and is listed in the table below. It’s all json-encoded, too, which makes it easy to extract with our gateway serial handler.
Since we’ve built the UniMote to receive commands from a remote, it’s very useful to receive a reply with two key pieces of information:
An echo of the command sent to confirm that it was received as sent
A status to indicate success, failure, and an error description of the sent command
So, when a command is sent, we get a short reply indicating the command, and the status. So, for example, if we want to change the loopperiod of the mote, we would see the following:
Issued command:
~sendmsg;10;;~lp;cfg;1
This command to the gateway (NODEID=1), sends a message to node 10 with the content “~lp;cnf;1”. When the node receives the command, it will send listparams configuration to node 1 (back to the gateway). On the remote node 10, we see on serial output:
BEGIN RECEIVED
nodeid:1, ~lp;cfg;1, RX_RSSI:-26
END RECEIVED
SENDING TO 1
cmd:lp,node:10,gw:1,nw:10,loop:1000,slpmd:0,slpdly:1000
SEND COMPLETE
Response from the mote:
And, sure enough, back on the gateway, we get the response:
BEGIN RECEIVED
nodeid:10, cmd:lp,node:10,gw:1,nw:10,loop:1000,slpmd:0,slpdly:1000,RX_RSSI:-23
END RECEIVED
Now let’s try a set command, where we expect a status response
Issued command:
~sendmsg;10;;~modparam;loopperiod;10
This command to the gateway (NODEID=1), sends a message to node 10 requesting that the loopperiod be changed to 1s (100ms increments). Sure enough, we receive the command, it is executed, and a reply message is sent that confirms the action:
BEGIN RECEIVED
nodeid:1,~modparam;loopperiod;10,RX_RSSI:-23
END RECEIVED
cmd:mp,param:loopperiod,setvalue:10,status:0
Sending message to replynode: 1
And back on the sending node, we receive the reply:
BEGIN RECEIVED
nodeid:10,cmd:mp,param:loopperiod,setvalue:10,status:0,RX_RSSI:-34
END RECEIVED
Our node has received confirmation! Logic ensues.
Now, let’s test a parameter set command that would receive an error. Let’s try to set the iomode to 9:
~sendmsg;10;;~modparam;iomode;0;9
The response from the node is:
cmd:mp,param:iomode,ionum:0,iomode:9status:1,error:moderange
Sending message to replynode: 1
Our sending note receives the status of 1, with an error of moderange. Enough said!
Cleanup Notes
Important things we did to optimize memory and to clean things up:
Elimination of all String objects: All strings objects have been converted to character arrays (people often refer to these as strings). This has helped RAM tremendously, avoided segfault issues with overruns that result in restart of the micro.
Use of FLASH library to take strings out of RAM: RAM is a precious resource (we report it locally after each command), and overrun of available RAM is a really easy way to get very unpredictable behavior, such as variable gibberish and sporadic reboots. Use of the native FLASH library string write and copy functions saves immensely on the tiny bit (2k) of ram available on an ATMega328P
Reuse of code for local (serial) output and for Radio commands: All code is built around the same output for local and remote programming. This not only saves loads of code space, but also makes the output the same for both methods.
Reference
The above makes use of the open source libraries available on github: