Turn Serial Devices Into IoT-Connected Devices

Mariano Goluboff

June 5, 2014

4 Min Read
Turn Serial Devices Into IoT-Connected Devices

We've all heard about how the Internet of Things will revolutionize our lives and businesses by having every asset connected to the cloud and data instantly available for analysis and display. The first step is to get those devices connected so that they can send data. The second step is for the device to know when it needs to send that data. That means that both connectivity and intelligence needs to be added to every device.

With so many devices that have a serial connection, there's a solution available that makes it easy to configure and enable delivery of end device data to Google Analytics, 2lemetry, or any other cloud provider that has an open API such as HTTP or MQTT. The solution uses the Lantronix PremierWave family of devices to connect an end device via a serial port like RS-232/485, or Ethernet, intelligently extract useful data, and send it to Google Analytics and 2lemetry. The tools available with Google Analytics make it easy to create custom dashboards to present the data in the format that helps drive business processes and provides end users with meaningful insights.

Google Analytics allows this data to be combined with data from other business processes. With 2lemetry you have an easy publish/subscription process for machine-to-machine communication. This lets data easily flow from one end device to another, as well as be displayed to end users via standard web tools.

The family includes a device for Ethernet or serial to cellular connectivity, one that provides Ethernet or serial to WiFi connectivity, and a third, a system-on-module that can be embedded into a custom device. The parts can natively execute Python code and support the Python Standard Library. This makes it easy to handle both the intelligence at the edge device, as well as use Python packages to connect to Cloud services that have open protocols.

In a demo of the system at the recent Embedded World 2014 trade show, we sent live data from the floor. With an enabled device, the user could quickly post data to the cloud service of their choice, using open standards and an easy-to-develop programming language like Python.

The demo consisted of a scale with an RS-232 output connected to a PremierWave part. The Python script running on the PremierWave device parsed the data from the scale and sent the weight received to both Google Analytics and 2lemetry services in parallel.

The Python program uses the Pyserial module to parse this data. Theserial port is easily initialized with Pyserial:class ser349klx:# setup the serial port. Pass the device as '/dev/ttyS1' or # '/dev/ttyS2' for# serial port 1 and 2 (respectively) in PremierWave EN or XC HSPA+def __init__(self, device, weight, c2l, ga):while True:try:serstat = Trueser = serial.Serial(device,2400, interCharTimeout=0.2, timeout=1)except Exception:serstat = Falseif serstat:breakself.ser = serself.weight = weightself.c2l = c2lself.ga = ga
The scale used constantly sends the current weight via the RS-232 port, witheach value separated by a carriage return:def receive_line(self):buffer = ''while True:buffer = buffer + self.ser.read(self.ser.inWaiting())if '\r' in buffer:lines = buffer.split('\r')return lines[-2]
The code that finds a new weight is called from a loop, which then waits forten equal non-zero values to wait for the weight to settle before sending it toGoogle Analytics and 2lemetry, as shown below:# This runs a continuous loop listening for lines coming from the# serial port and processing them.def getData(self):count = 0prev = 0.0while True:time.sleep(0.1)try:val = self.receive_line()weight.value=float(val[-5:])*0.166if (prev == weight.value):count += 1if (count == 10) and (str(prev) != '0.0'):self.ga.send("{:.2f}".format(prev))if supportMqtt:  self.c2l.send("{:.2f}".format(prev))else:count = 0prev = weight.valueexcept Exception:pass
Since the Google Analytics Measurement Protocol uses standardHTTP requests to send data from devices other than web browsers, the ga.send method iseasily implemented using the Python urllib and urllib2 modules, as seen below: class gaConnect:            def __init__(self, tracking, mac):                            self.tracking = tracking                            self.mac = mac                                        def send(self, data):                            values = { 'v' : '1',                                            'tid' : self.tracking,                                            'cid' : self.mac,                                            't' : 'event',                                            'ec' : 'scale',                                            'ea' : 'weight',                                            'el' : data }                                                            res = urllib2.urlopen(urllib2.Request                 ("http://www.google-analytics.com/collect",urllib.urlencode(values)))

The last piece is to initialize a Google Analytics connect object to connect to the user's Analytics account:

ga = gaConnect("UA-XXXX-Y", dev.mac)

The device's MAC address sends unique information from each device.

The 2lemetry system uses the MQTT protocol. This can be easily implemented by using the Mosquitto package:

class connection2lemetry:def __init__(self, dev):self.client = mosquitto.Mosquitto('things/'+dev.mac)self.client.username_pw_set("username", password="password")self.id = dev.macdef send(self, value):self.client.connect("q.m2m.io")self.client.loop()self.client.publish('domain/things/'+self.id,'{                               "report":{"test":{"weight":"'+value+'"}}}',1)self.client.loop()self.client.disconnect()def disconnect(self):self.client.disconnect()

So there it is -- you can see that when Python is used, you can easily transform serial devices into IoT-connected devices.

Mariano Goluboff is a principal field applications engineer with Lantronix. He holds a Bachelor of Science in Electrical and Computer Engineering from the University of Colorado at Boulder. Previously to the Field Application Engineer work, Goluboff spent 10 years as a hardware/firmware engineer and later an engineering manager designing microprocessor based systems and embedded software for data acquisition and industrial automation.

Sign up for the Design News Daily newsletter.

You May Also Like