1. 程式人生 > >From sensor to the Cloud in just 15 lines of Python

From sensor to the Cloud in just 15 lines of Python

The world of IoT is all about moving data to the cloud and then back to the devices. That process may sound simple, but once you start doing it, you realize it has its complications.

Let’s be honest, all the technicalities behind correctly programming a device, in order to connect it to the internet and send data in a secure way, are still a daunting task.

So, after we were done with all the technical issues and the winding road of tests, and demonstrations, we wanted to make sure that everyone else had a clear “how-to” guide to sending sensor data to the cloud, in an easy,  secure, cost-effective and robust way.

Isn’t that every embedded developer’s dream?

For everyone that’s new to Zerynth tools, here’s a brief summary. Zerynth software tools simplify IoT development, providing an easy and efficient way to program the most popular 32-bit microcontrollers in Python and connect them to the top Cloud infrastructures like Microsoft Azure, Amazon Web Services, IBM Bluemix, and Google Cloud IoT.

Zerynth has been listed as a Trusted IoT Platform Partner by Microchip in their partner program designed to recognize and recommend companies that are deemed as a genuine security expert on Microchip technologies. Zerynth has also formed numerous partnerships with companies like Espressif Systems, NXP, Amazon Web Services, Google Cloud Platform, RS Components, Mouser Electronics, XinaBox, Eseye and more.

Reusable Python code, and a vast collection of libraries

We worked to make sure other IoT developers can focus on the actual value in the project – the data. That is why we have created the Zerynth Toolchain. More precisely, our tools make all those daunting tasks become an easy routine.

How did we accomplish this?

On one hand, we made reading the sensors a simple task, with the numerous Python libraries that take care of all the complexities, leaving you with what really matters, the data.

On the other hand, a robust TCP/IP stack, a wifi driver and a state of the art TLS library allow connecting any supported 32-bit microcontroller to AWS MQTT endpoints (or to the other supported Cloud services ) and stream data to your database.  And if this wasn’t enough, the resulting Python code is 99% reusable on a different hardware, in case you decide to use a different board later.

Let’s take a look at the code:

Python
12345678910111213141516171819202122232425262728293031323334353637 # import wireless and iot modulesfromwireless importwififromespressif.esp32net importesp32wifi aswifi_driverfromaws.iot importiot# import the sensor modulefrombosch.bme280 importbme280# import some utilitiesimportstreamsimportjsonimporthelpers# load device credentialsnew_resource('private.key')new_resource('certificate')new_resource('config')streams.serial()# connect to wifiwifi_driver.auto_init()wifi.link("SSID",wifi.WIFI_WPA2,"PASSWORD")# configure the AWS devicepkey,cert=helpers.load_key_cert('private.key','certificate')thing_conf=helpers.load_thing_conf()thing=iot.Thing(thing_conf['endpoint'],thing_conf['mqttid'],cert,pkey,thingname=thing_conf['thingname'])# start the MQTT clientthing.mqtt.connect()thing.mqtt.loop()# send data!sensor=bme280.BME280(I2C0)whileTrue:thing.mqtt.publish("data/sink",{'temp':sensor.get_temp()})sleep(1000)

We start by importing the wireless and IoT modules. Once configured with the appropriate credentials, the device can connect first to the local wifi and then authenticate itself to the AWS IoT Core.

The last lines perform the actual work: initializing the sensor and keep reading and streaming data.

As you can see from the example, every single line except line 3 is hardware independent. By changing the wireless driver from ESP32 by Espressif Systems  (if you’re using a XinaBox CW02 ) to let’s say WINC1500 Module by Microchip, the code works the same thanks to the power of the Zerynth Virtual Machine.

The same occurs also if you want or need to change the Cloud: the resulting Python code is almost completely reusable. Take a look at these two examples for a comparison:

Boosting secure IoT connections using Python

With connecting to the WiFi, and Cloud authentication covered, we can move on to the next section of this tutorial – how to make your projects more secure in just a few lines of code.

As cool as it can be, the previous example is not that “professional”. For example (and you probably already know this), it’s a bad practice to store the credentials of the device (private key and certificate) in the firmware itself, or in any part of the device that can be easily accessed and tampered with. This method of work is insecure and forces the generation of different firmware for each device.

For these reasons, we have released the support for Microchip crypto elements, tiny integrated circuits that can generate and securely store all the credentials of a device.

Now take a look at the modified code:

Python
12345678910111213141516171819202122232425262728293031323334353637383940 # import wireless and iot modulesfromwireless importwififromespressif.esp32net importesp32wifi aswifi_driver fromaws.iot importiotfrombosch.bme280 importbme280# import some utilitiesimportstreamsimportjsonimporthelpers# import microchip ateccx08a module for its hw crypto element interfacefrommicrochip.ateccx08a importateccx08a# load device credentialsnew_resource('certificate')new_resource('config')streams.serial()# connect to wifiwifi_driver.auto_init()wifi.link("SSID",wifi.WIFI_WPA2,"PASSWORD")# start hardware crypto interfaceateccx08a.hwcrypto_init(I2C0,0)# configure the AWS devicecert=helpers.load_cert('certificate')thing_conf=helpers.load_thing_conf()thing=iot.Thing(thing_conf['endpoint'],thing_conf['mqttid'],cert,'',thingname=thing_conf['thingname'])# start the MQTT clientthing.mqtt.connect()thing.mqtt.loop()# send data!sensor=bme280.BME280(I2C0)whileTrue:thing.mqtt.publish("sensors",{'temp':sensor.get_temp()})sleep(1000)

And that’s it! Only a few lines changed, and now the private key is generated by the crypto element and the secure connection library directly interacts with the element to perform hardware accelerated cryptography!

The solution can be made even more secure by following all the guidelines that come with the crypto element. For more info, take a look at this tutorial: “Zero Touch Secure Provisioning for AWS IoT using Python, our Python version of the popular Microchip’s demo. Thanks to this porting, Zerynth has recently been listed as a “Trusted IoT Platform Partner” by Microchip. More info here.

Send data to the cloud in 15 lines of Python

Still, the code can be simplified even further. With the last update, it’s now possible to send data to the cloud in just 15 lines of Python.

Take a look at the code:

Python
123456789101112131415 fromwireless importwififromespressif.esp32net importesp32wifi aswifi_driverfrombosch.bme280 importbme280fromaws.iot importiot,default_credentialswifi_driver.auto_init()wifi.link("SSID",wifi.WIFI_WPA2,"PSW")endpoint,mqttid,clicert,pkey=default_credentials.load()thing=iot.Thing(endpoint,mqttid,clicert,pkey)thing.mqtt.connect()thing.mqtt.loop()sensor=bme280.BME280(I2C0)whileTrue:thing.mqtt.publish("sensors",{'temp':sensor.get_temp()})sleep(1000)

We cut the amount of code in half, and now it’s possible to send temperature data to the Cloud in minutes. All that in a secure way with the generated private key.

Get started with Zerynth on XinaBox xChips

The XK12 IoT Starter Kit is a Zerynth programmable toolset intended for fast evaluating and prototyping. Since the Zerynth license is already onboard this IoT kit is a great combination of XinaBox’s modular electronics and our easy-to-use software tools.

Now it’s your turn. Get your XinaBox kit “powered by Zerynth” and pick these xChips:

  • 1 x SW01 – Advanced Weather Sensor (BME280)
  • 1 x CW02 – Wi-Fi & Bluetooth Core (based on ESP-WROOM-32 by our partner Espressif Systems)
  • 1 x AH01 – SHA-256 Hardware Encryption (ATECC508A)
  • 1 x IP01 – USB Programming Interface (FT232R)

Follow the getting started, and you’ll be finished in no time. Just to recap, you have to:

  1. Clone a ready-made example. You can start with the “Hello Zerynth” and then go with “Cloud15Lines” (in this case, of course, you need also to set up your accounts and things on Cloud platforms)
  2. Enjoy!

We hope that you found this tutorial helpful and that you are already making a mental list of sensors you would like to use. Our main goal was to show you how easy it is to send data to the Cloud with Zerynth Studio, and why it shouldn’t be thought of as difficult or complex.