Sample code

Sample code

We supply a .zip file with the X509 certificate for authentication, alongside a sample Python script (referenced below) that illustrates how to connect to the API and obtain information.

Please modify it as necessary (such as changing the certificate name or using your site’s API key).

You might need a root CA that can be found here : https://www.amazontrust.com/repository/AmazonRootCA1.pem

The code requires the installation of two packages, msgpack and paho-mqtt. Use the pip package manager(recommended) to install. These packages can be found at https://pypi.org/project/paho-mqtt and https://pypi.org/project/msgpack/.

Version 1.6.1 of paho-mqtt is needed. If you are using version 2, please make the following modifications to the given code:

  • When creating the client, add “paho.CallbackAPIVersion.VERSION2” as an argument, like so:
    self.mqttc = paho.Client(paho.CallbackAPIVersion.VERSION2)
  • Modify the on_connect and on_subscribe functions to include the properties parameter:
    def on_connect(self, client, userdata, flags, rc, properties):
    def on_subscribe(self, client, userdata, mid, granted_qos, properties):
 If you encounter any issues, please do not hesitate to contact our support team.
1import os
2import ssl
3import msgpack
4import paho.mqtt.client as paho
5 
6MQTT_ENDPOINT = "iot.nao-cloud.com"
7MQTT_PORT = 8883
8 
9MQTT_CERT_PATH = os.path.join(os.path.dirname(__file__), "certificate-xxxx.pem")
10MQTT_PRIVATE_KEY_PATH = os.path.join(os.path.dirname(__file__), "private-xxxx.pem")
11 
12class MQTTLocationClient:
13    """
14        Get locations for tags of a given site
15    """
16 
17    def __init__(self, api_key, topic_prefix='prod'):
18        self.topic = "{}/{}/locs/#".format(topic_prefix, api_key) #change "locs" for "alerts" or "monitoring" depending your needs
19        self.mqttc = paho.Client()
20        self.mqttc.on_connect = self.on_connect
21        self.mqttc.on_disconnect = self.on_disconnect
22        self.mqttc.on_subscribe = self.on_subscribe
23        self.mqttc.on_message = self.on_message
24        # self.mqttc.on_log = self.on_log
25        if not os.path.exists(MQTT_CERT_PATH):
26            raise Exception("MQTT certificate not found at " + MQTT_CERT_PATH)
27 
28        if not os.path.exists(MQTT_PRIVATE_KEY_PATH):
29            raise Exception("MQTT certificate's private key not found at " + MQTT_KEY_PATH)
30        self.mqttc.tls_set(None, certfile=MQTT_CERT_PATH, keyfile=MQTT_PRIVATE_KEY_PATH, cert_reqs=ssl.CERT_REQUIRED,
31                      tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
32 
33    def start(self):
34        self.mqttc.connect(MQTT_ENDPOINT, MQTT_PORT, keepalive=60)
35        self.mqttc.loop_forever()
36 
37    def on_connect(self, client, userdata, flags, rc):
38        if rc == 0:
39            print("Connected. Subscribing to topic {}".format(self.topic))
40            self.mqttc.subscribe(self.topic, qos=1)
41        else:
42            raise Exception("MQTT Connection refused with code: " + str(rc))
43 
44    def on_disconnect(self, client, userdata, rc):
45        raise Exception("MQTT Connection refused with code: " + str(rc) + ". Please check your credentials.")
46 
47    def on_subscribe(self, client, userdata, mid, granted_qos):
48        print('Subscribed!')
49 
50    def on_message(self, client, userdata, msg):
51        data = msgpack.unpackb(msg.payload, encoding='utf-8')
52        print("topic={} data-len={} data={}".format(msg.topic, len(msg.payload), data))
53 
54    def on_log(self, client, userdata, level, buf):
55        print("MQTT: {}".format(buf))
56 
57 
58if __name__ == '__main__':
59    locationClient = MQTTLocationClient(api_key='9NqWWUa0uvYLOJWiWme7b')
60    locationClient.start()

    • Related Articles

    • Sample code

      The following code shows an example of how to infer the floor information from the altitude of a location update, and convert the (lat, lon) coordinates to pixel (x, y) to ease display on an image map. 1 import matplotlib.pyplot as plt 2 import ...
    • Sample code

      The following code shows an example of how to infer the floor information from the altitude of a location update, and convert the (lat, lon) coordinates to pixel (x, y) to ease display on an image map. 1 import matplotlib.pyplot as plt 2 import ...
    • Background related guidelines

      Your app behavior should be adapted depending on the background permissions you asked for in the app plist, and on the ones granted by your users. Refer to https://docs.nao-cloud.com/docs/mobile-sdk/ios-sdk/configure-your-xcode-project/ for more ...
    • Flutter

      NAOSDK Flutter Plugin In the context of helping our customers and partners who want to develop their application with Flutter and use NAOSDK indoor location-based use cases, we have developed a version of a flutter plugin that makes it easy to embed ...
    • Integration workflow and recommendations

      This page gives useful information for the project management aspect of the integration of the MQTT API. Planning and effort estimation for the integration: Coding effort: from 1 to 2 staff days, integration support : 1 staff day; Testing effort: 1 ...