In this tutorial we will demonstrate how to establish a 1-way communication of message delivery from end devices to the cloud using Alibaba Cloud IoT Platform.

By Amit Maity, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

Overview

Alibaba Cloud IoT Platform allows you to easily and securely connect, manage, and ingest data from various types of electronic devices located globally. By using IoT Platform in combination with other cloud services (i.e. ApsaraDB, Quick BI, and Message Queue), you can build complete solution for collecting, processing, analyzing, and visualizing IoT data in real time to support improved operational efficiency.

There are two different types of communication channels, which you can setup between end devices and IoT cloud. A 2-way communication will allow you to send and receive data using the same data channel, whereas a 1-way communication will enable you to either send or receive data from IoT devices to IoT platform. Below are the few example projects, which can be implemented using 1-way communication channel,



Monitor temperature of a home aquarium. Detect and receive safety alerts such as gas leakage, fire, and unauthorized entry. Monitor humidity and receive notification of rain drops. Monitor electrical appliances and electronic gadgets statuses.

These projects can be further extended to control the monitoring parameters using 2-way communication. Best example would be soil moisture controller of garden. You can monitor soil humidity and if the humidity drops below certain threshold, you can send a signal to IoT device to switch on the water sprinkler so that humidity comes back to acceptable level.

However, in this tutorial I'll only demonstrate 1-way communication of sending messages from end devices to IoT cloud. Raspberry PI will measure the temperature using temperature sensors in every 60 seconds and publish the temperature data to Alibaba IoT cloud as a JSON serialized string in the below form:

{ 'temperature': 12 }

where 12 is the temperature measured by the sensor.

Published temperature readings are then stored into a table setup in an Alibaba Cloud Table Store instance.

The following diagram gives a simplified illustration how data flows through the example system. Note that all of the events in the diagram occur asynchronously.





Figure 1 Data Flowchart

Prerequisites

This tutorial can easily be understood and followed if you are familiar with the below technologies,



Python programming language Electronic circuit build using breadboard Alibaba Cloud Environment

Hardware and Software Prerequisites

Before you start working on this project, please ensure you have built the electronic circuit as per below circuit diagram and it's working correctly. Also, please download the below libraries into your raspberry pi environment.



w1thermsensor python library (https://pypi.org/project/w1thermsensor/ ) Example python code (https://github.com/itexpertshire/AlibabaIoTCloudDemo )



Figure 2 Circuit Diagram

Set Up Raspberry Environment

Login to Raspberry Pi and enable 1-Wire interface in Raspberry Pi configuration.

Figure 3 Raspberry Pi 1-Wire Configuration

Open shell terminal in Raspberry pi and install the following libraries sudo pip install aliyun-python-sdk-core sudo pip install aliyun-python-sdk-iot sudo pip install w1thermsensor

Configure IoT device in Alibaba Cloud

Log in to the IoT Platform console and select region China (Shanghai) region Create Basic Version Product with node type as Device

Figure 4 Product Setup

Add device under product created in previous step. Ensure device state is enabled as shown below

Figure 5 Device Setup

Create Rule with data type as JSON and then configure below options by clicking manage button

Write sql expression to select temperature attribute value which is available in JSON data published from Raspberry

Figure 6 SQL Query Expression

Define data forwarding rule. Extracted data from IoT message is stored in table named myIOT created in Alibaba Table Store instance. Table Store table will have minimum 1 primary key. Current time is included in the JSON message to use it for primary key.

To retrieve the time value from the published message you'll have to use below syntax ${JSON message attribute} for example ${time}

Remaining JSON attributes will automatically be stored as separate attributes in Table Store table.

Figure 7 Data Forwarding Rule



Python Application Walkthrough

Download/clone sample python code from github repository

https://github.com/itexpertshire/AlibabaIoTCloudDemo

Import the IoT python SDK, W1TermSensor and base64 libraries from aliyunsdkcore import client from aliyunsdkiot.request.v20170420 import RegistDeviceRequest from aliyunsdkiot.request.v20170420 import PubRequest import time import base64 from w1thermsensor import W1ThermSensor Initialise following variables with your cloud account credentials and IoT device keys, accessKeyId='<This will be found in your account security management page>' accessKeySecret='<This will be found in account security management page>' clt = client.AcsClient(accessKeyId, accessKeySecret, '<IoT Region>') productKey ='< This is available in ProductKey field of the product configured >' deviceName = '<Name of the device created>' For publishing message, IoT cloud setups default topic as /${productKey}/${deviceName}/update. So, prepare publishing topic name string as below. topicName = '/'+productKey+'/'+deviceName+'/update' Initialise the message object "request" with the topic name and product key request = PubRequest.PubRequest() request.set_accept_format('json') # Set the response format as json. request.set_ProductKey(productKey) request.set_TopicFullName(topicName) #Full name of the topic to which the messages are sent. Initialise the temperature sensor method before reading the temperature from the sensor sensor = W1ThermSensor() In an infinite loop, read the temperature using sensor.get_temperature and publish the message to IoT device using clt.do_action_with_exception function in every 60 seconds while True: temperature = sensor.get_temperature() timevalue = time.time() print("The temperature is %s celsius" % temperature) message = "{ 'temperature': %s, 'time': %s }" % (temperature,timevalue) print (base64.urlsafe_b64encode(message)) request.set_MessageContent(base64.urlsafe_b64encode(message)) #JSON message in Base64 String request.set_Qos(0) result = clt.do_action_with_exception(request) print 'result : ' + result time.sleep(60)

Run and Test

Now let's execute the python code. Make sure the sensor is connected to Raspberry GPIO pins correctly.

In the Raspberry Unix terminal, navigate to the directory of the application code and execute the code using python command,

pi@raspberrypi:~/iot/AlibabaIoTCloudDemo $ python tempMonitor.py

You'll see bellow messages in the terminal as output,





Figure 8 Raspberry Pi Output

Temperature readings will be available in Table Store table as below,



Figure 9 Table Store Data

Troubleshooting