Connect devices to IoT
Trimble IoT manages device communication through a message broker. Devices publish messages to a message broker and also subscribe to messages that the message broker publishes.
Prerequisites:
- Activate device in IoT, refer to Activate Devices.
Information needed to connect to Trimble IoT and manage device communication
- Host Address: Broker endpoint. This host address can be found in the Groups API response
- Port: MQTT listens on 8883
- Protocol: MQTT
- CA: Server certificate of the Broker endpoint. Click here to download the Server Certificate.
- Key: Private Key of the Device Certificate.
- Cert: Device Certificate of the device (PEM formatted).
- ClientId: Unique identifier for a device. It can be found in the device activate response. For more details refer to the Devices API.
Code sample
Section titled “Code sample”import paho.mqtt.client as pahoimport osimport socketimport sslfrom time import sleepfrom random import uniformimport json
import logginglogging.basicConfig(level=logging.DEBUG)
# Refactored original source - https://github.com/mariocannistra/python-paho-mqtt-for-aws-iot
class PubSub(object):
def __init__(self, listener = False, topic = "default"): self.connect = False self.listener = listener self.topic = topic self.logger = logging.getLogger(repr(self))
def on_connect(self, client, userdata, flags, rc): print("Device connected with result code: " + str(rc)) self.mqttc.subscribe("<cloud to device message topic>", qos=1)
def __on_message(self, client, userdata, msg): self.logger.info("{0}, {1} - {2}".format(userdata, msg.topic, msg.payload))
def __on_log(self, client, userdata, level, buf): self.logger.debug("{0}, {1}, {2}, {3}".format(client, userdata, level, buf))
def on_disconnect(self, client, userdata, rc): print("Device disconnected with result code: " + str(rc))
def on_publish(self,client,userdata, mid): print("Device sent message")
def on_subscribe(self,client, userdata, mid, granted_qos): print("Client Subscribed")
def bootstrap_mqtt(self):
self.mqttc = paho.Client(client_id="<ClientId>") self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.__on_message self.mqttc.on_publish= self.on_publish self.mqttc.on_subscribe = self.on_subscribe self.mqttc.on_log = self.__on_log self.mqttc.on_disconnect = self.on_disconnect
azurehost = "<Group BrokerEndpoint>" azureport = 8883
caPath = "<Server CA path>" certPath = "<Operational Certificate Path>" keyPath = "<Operational Private key Path>"
self.mqttc.tls_set(ca_certs=caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
self.mqttc.username_pw_set(username='<Device Username>') result_of_connection = self.mqttc.connect(azurehost, azureport, keepalive=120)
if result_of_connection == 0: self.connect = True
return self
def start(self): self.mqttc.loop_start()
while True: sleep(2) if self.connect == True: print('Waiting for disconnect') self.mqttc.publish('<D2C Topic>', json.dumps({'data':'test'}), qos=1) else: self.logger.debug("Attempting to connect.")
if __name__ == '__main__': PubSub(listener = True).bootstrap_mqtt().start()