Overview

Skill Level: Beginner

Basic knowledge of Micropython is required with familiarity of Pycom hardware.

Pycom devices integration with Watson IoT platform using MicroPython and MQTT clients connecting over WiFi

Ingredients

 

Hardwares :

1 x PyCom device (LoPy or WiPy or SiPy)

1 x Expansion board (Expansion 1.0 or 2.0 or Pytrack or Pysense) 

1 x Micro USB cable

 

Softwares : 

- Filezilla

- Putty

 

Other :

- WiFi Connection with WPA Security

- Bluemix Account with Internet of Things Platform service added.

 

Step-by-step

  1. Setup Bluemix by registering the Pycom device

    Log onto Bluemix console and navigate to Internet of Things Platform from the Dashboard – 

     GoToIoTPlatform

    Launch Watson IoT Service platform –

     LaunchWIoT

    Go to Security settings –

     SecuritySettings

    Edit Security Policy –

    EditSecurityPolicy

    Confirm that the Security Level is set to ‘TLS Optional’. This is important as we would be using the MQTT port 1883 for this communication – 

    TLSOptional

     

    Go to devices list –

    GoToDevices

    Click on ‘Add Device’ button – 

    AddDevice

    From the add devices dialog click on the ‘Create device type’ –

     CreateDeviceType

     Click on ‘Create device type’ from this screen – 

    CreateDeviceType2

    Fill in the required fields (Name and Description) and click on ‘Next’ – 

    CreateDeviceType3

    Select the fields as desired to add attributes to this device type and click on ‘Next’ –

    CreateDeviceType4

    Enter the default values for the attributes and click on ‘Next’ – 

    CreateDeviceType5

    For this recipe this Metadata field is not used hence can be left blank. Click on ‘Create’ – 

    CreateDeviceType6

    With the device type selected to ‘Pycom’ as created in the steps above, click on ‘Next’ to begin registering a Pycom device –

    RegisterPycomDevice

    Fill in the form with values as appropriate. Below is an example. Then click on ‘Next’ – 

    RegisterPycomDevice1

    Leave the metadata section blank and click on ‘Next’ to proceed – 

    RegisterPycomDevice2

    Provide a suitable device authentication token and click ‘Next’ –

    RegisterPycomDevice4

    Confirm the values as entered in the previous steps here and click on ‘Next’ – 

    RegisterPycomDevice4-1

    The device is now registered and the unique authentication details are shown in this screen. Take a note of these values especially the authentication token as it would not be visible aymore in the site –

    RegisterPycomDevice5

    Registered device can now be seen on the Devices view in Internet of Things Platform. Note the exclamation icon before the Device ID, indicating the device is not connected yet –

    RegisteredPycomDevice

  2. Setup Pycom device for sketch upload

    Place the the deveopment board module on the Expansion Board. Setup the module and the Expansion board by installing required drivers and update to latest firmware version. Instructions are available in the pycom website – 

     

    Expansion Board FTDI driver and Firmware Tool for Pycom modules: 

    https://docs.pycom.io/chapter/gettingstarted/installation/firmwaretool.html

    Expansion board USB Serial driver : 

    https://docs.pycom.io/chapter/pytrackpysense/installation/drivers.html

    Expansion board Firmware :

    https://docs.pycom.io/chapter/pytrackpysense/installation/firmware.html

     

    Optional :

    Pymakr Plugin and Atom installation – 

    https://docs.pycom.io/chapter/gettingstarted/installation/pymakr.html

  3. Write the Sketch and update with appropriate values

    Save the following skech in bold in a file named ‘main.py’

    This sketch is an adoption of the Pycom documentation under the link – 

    https://docs.pycom.io/chapter/tutorials/all/mqtt.html

    Update the sections in italics (including the angle brackets) in the sketch with appropriate values. Note the MQTT publish URL. This is the standard value for sending status update messages for devices registered in Watson IoT. The MQTT client Id is with a specific syntax that must be followed otherwise Watson IoT would not allow the conection. The connection communicates via the MQTT port 1883

    ################################################################################

    from network import WLAN
    from mqtt import MQTTClient
    import machine
    import time

    wlan = WLAN(mode=WLAN.STA)
    wlan.connect(“<WiFi SSID>“, auth=(WLAN.WPA2, “<WiFi Password>“), timeout=5000)

    print(“Waiting to get connected to Wifi…\n”)
    while not wlan.isconnected():
         machine.idle()
    print(“Connected to Wifi!\n”)

    client = MQTTClient(“d:<ORG Id>:<Device Type>:<Device Id>“, “<ORG Id>.messaging.internetofthings.ibmcloud.com”,user=”use-token-auth”, password=”<TOKEN>“, port=1883)

    client.connect()
    print(“Connected to Watson IoT!\n”)

    while True:
         print(“Sending ON”)
         client.publish(topic=”iot-2/evt/status/fmt/json”, msg=”{\”d\”:\”ON\”}”)
         time.sleep(10)
         print(“Sending OFF”)
         client.publish(topic=”iot-2/evt/status/fmt/json”, msg=”{\”d\”:\”OFF\”}”)
         time.sleep(10)

    ################################################################################

    Download the mqtt.py file which would be put under the lib folder on the Pycom device – 

    https://github.com/pycom/pycom-libraries/blob/master/lib/mqtt/mqtt.py

     

    Purpose of this sketch is to send toggling ‘ON’ and ‘OFF’ string values in json format every 10 seconds to the Watson IoT platform as device status message.

  4. Upload sketch and run

    Disclaimer : The actions here attempts to transfer the sketch created in the previous step to the Pycom module. This, as Pycom suggests, can also be done using Pymakr plugin with Atom or other suitable IDE. This is the process I follow to perform the transfer. Also the following screensots cater to the use of a LoPy unit together with a Pytrack expansion board. Other Pycom modules and Expansion boards would work in the same fashion as described here.

    Please note that the following steps assme that a Windows PC is used with preinstalled Putty and File zilla applications. 

    Connect the Pycom module to a PC using the micro USB cable. Note the COM port from Windows Device Manager. Open a Putty Terminal and connect using correct Serial COM port with Baud rate of 115200.

    PuttySerial

    Execute the following commands (after changing the WiFi credentials in italics) in order to connect the Pycom module to the local WiFi Network – 

    from network import WLAN
    wlan = WLAN() 
    wlan.init(mode=WLAN.STA)
    wlan.connect(‘<WiFi SSID>’, auth=(WLAN.WPA2, ‘<WiFi Password>’), timeout=10000)

    Wait 5 seconds and run the following command to check the assigned IP address.

    wlan.ifconfig()

    WiFiConnect

    This would print out the IP address along with the subnet mask and router IP for the local WiFi. Take a note of the assigned IP address.

    Launch FileZilla and go to File -> Site Manager. Click on the ‘New Site’ Button and add the configuration – 

    FileZilla1

    Update Host IP (XX.XX.XX.XX) as obtained running the wlan.ifconfig() command previously. User Id to be used is ‘micro‘. Password is not needed to be entered now, only when the connection is initiated FileZilla would prompt for password. Note that Pycom devices only support passive FTP hence in the Transfer Settings section configure the following –

    FileZilla2

    Pycom devices only support 1 Simultaneous connection, hence the checkbox needs to be selected. Once finished, click on the ‘Connect’ button to initiate the connection. FileZilla now asks for Password. Enter the default password for FTP for Pycom device, which is ‘python‘ and click ‘OK’ –

    FileZilla3

    FileZilla shows connection progress trace – 

    FileZillaConnected

    The file system of the Pycom module can now be seen – 

    FlashFileSystem

    Sync the following files to device along with the updated main.py

    boot.py

    main.py

    lib/mqtt.py

    Reboot the device via the reset button on the Pycom module or simply plug-out the USB cable and plug back in. Allow a few seconds before the WiFi connection suceeds and MQTT connection is established. The serial console displays the following messages – 

    Pycom-Watson-IoT

    As per the sketch the device will send status ‘ON’ or ‘OFF’ string value wrapped in a JSON envelope, toggling every 10 seconds.

  5. Check Device connectivity from Watson IoT platform

    Go to the Devices view on the Internet of Things platform. The icon before the Device ID is now changed to indicate that the device is nw connected to Watson IoT –

    ConnectedPycomDevice

     

    Click on the row to open the device details and scroll down to the Sensor Information section – 

    DataReceivedonWatsonIoT

     

    This concludes the basic recipe to connect a Pycom device to Watson IoT platform using MicroPython with data publish only. This can further be extended to extract and send sensor data from Pysense or Pyrack or other connected sensors with Pycom devices. 

    Happy IoTing!

Join The Discussion