IoT Quick Tip: Connecting an IoT device to IBM Cloud with Python
Many developers have great ideas about their IoT projects, but often stuck on some basics before getting to the heart of their development. In this tutorial, we show a simple code in MicroPython that connects a certain device (or e.g. a Linux PC emulating an actual device) to a well known service such as IBM Cloud.
First and foremost, let´s create a file with the proper credentials for the device to log on to the service, let's say "ibmcloud_credentials.py":
def client_id():
from mqtt import MQTTClient
client = MQTTClient("d:IBM_Cloud_id:Device_type:Device_id",
"IBM_Cloud_id.messaging.internetofthings.ibmcloud.com",
user="use-token-auth",
password="IBM_Cloud_device_token",
port=1883)
return client
Secondly, let's create the main program "main.py":
# Import needed libraries from Micropython
from mqtt import MQTTClient
import ujson
import machine
import time
from time import sleep
def settimeout(duration):
pass
# Import IoT device credentials
import ibmcloud_credentials
client = ibmcloud_credentials.client_id()
# Log in device to IBM Cloud using the given credentials
client.settimeout = 5
client.connect()
print("Connected to IBM Cloud IoT Platform.\n")
# Defining JSON pack with dummy sensor data. To be replaced with actual data collected by the sensor.
def message_pack():
sensor_pack = {'temperature':35, # in degC.
'humidity' :65, # in %RH.
}
return sensor_pack
# Main loop
def send_sensor_data():
while (True):
messagepack = message_pack()
client.publish(topic="iot-2/evt/status/fmt/json", msg=ujson.dumps(messagepack))
sleep(10)
# Execute main loop
send_sensor_data()
The above code will, in short, connect to IBM Cloud and send through MQTT messaging formatted JSON at every 10 seconds, emulated temperature and humidity data, respectively 35C and 65%.
The "main.py" program from above assumes that the device is already connected to the internet in some manner. This is typically done by a code in another file, named "boot.py". On a future article, I will approach the connection through WiFi and Sigfox.