Connect devices to IoT
Trimble IoT manages device communication through a message broker. Devices publish messages to the message broker and also subscribe to messages that the message broker publishes.
Prerequisites:
- Activate a device in Trimble IoT using the Devices API.
You need the following details to connect to Trimble IoT and manage device communication:
-
Host Address: Broker endpoint of the region. This host address can be found in the Group API response when you create a group with Trimble IoT API.
-
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 your Device Certificate
-
Cert: Device Certificate of your device (PEM formatted)
-
ClientId: Unique identifier for a device.The ClientId is available in the device activate response. For more details, refer to the Device 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("<Outbound 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
awshost= "<Group BrokerEndpoint>" awsport= 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)
result_of_connection = self.mqttc.connect(awshost, awsport, 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('<Inbound Topic>', json.dumps({'data':'test'}), qos=1) else: self.logger.debug("Attempting to connect.")
if __name__ == '__main__': PubSub(listener = True).bootstrap_mqtt().start()