AWS IoT Device Client UDS sensor example

2 minute read
Content level: Intermediate
0

In this article we demonstrate how to create a virtual sensor that communicates with the AWS IoT Device Client over a Unix Domain Socket (UDS).

The AWS IoT Device Client is a free, open-source, modular software written in C++ that customers compile and install on Embedded Linux based IoT devices to access AWS IoT Core, AWS IoT Device Management, and AWS IoT Device Defender features. The Sensor Publish feature allows customers to publish sensor data captured on their device to the cloud over MQTT.

The diagram below represents a device client with the Sensor Publish feature enabled. To send data to the device client, a local server on the device serves sensor data over an UDS in streaming mode. The device client connects to the local server and parses the stream into messages that are then buffered on the device client using the configurable size and time limits and published as a single batch to AWS IoT Core over MQTT.

Sensor publish diagram

The code sample below is a Python script that creates and binds a socket and then publishes a test message every 5 seconds. The server_address must match the addr value specified in the sensor-publish section of the device client configuration file. For more details on configuring the sensor publish feature of the device client, please see the AWS IoT Device client documentation.

# imports
import socket
import os
import time
 
# set socket location
server_address = '/tmp/sensors/my-sensor-server'  
 
# check for previous socket and clean up
try:
    os.unlink(server_address)
except OSError:
    if os.path.exists(server_address):
        print ("socket already exists")

# create socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)       
print ("socket successfully created")
 
# bind to the socket
s.bind(server_address)        
print ("binding complete")
 
# start listening mode
s.listen(5)    
print ("socket is listening")           
 
# forever loop
while True:
 
# establish connection with client
  c, addr = s.accept()    
  print ('got connection')
  
  while True:
    message = '{\"message\":\"UDS test message\"}\r\n'
    print('sending message:')
    print(message)
    c.sendall(message.encode('utf-8'))
    time.sleep(5)
AWS
EXPERT
published 9 months ago593 views