×
Community Blog Temperature Monitoring with Raspberry Pi and Alibaba Cloud IoT Platform

Temperature Monitoring with Raspberry Pi and Alibaba Cloud IoT Platform

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,

  1. Monitor temperature of a home aquarium.
  2. Detect and receive safety alerts such as gas leakage, fire, and unauthorized entry.
  3. Monitor humidity and receive notification of rain drops.
  4. 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.


1
Figure 1 Data Flowchart

Prerequisites

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

  1. Python programming language
  2. Electronic circuit build using breadboard
  3. 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.

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

2
Figure 2 Circuit Diagram

Set Up Raspberry Environment

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

    3
    Figure 3 Raspberry Pi 1-Wire Configuration


  2. 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

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

    4
    Figure 4 Product Setup


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

    5
    Figure 5 Device Setup


  4. Create Rule with data type as JSON and then configure below options by clicking manage button
  5. Write sql expression to select temperature attribute value which is available in JSON data published from Raspberry

    6
    Figure 6 SQL Query Expression


  6. 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.

    7
    Figure 7 Data Forwarding Rule


Python Application Walkthrough

  1. Download/clone sample python code from github repository
    https://github.com/itexpertshire/AlibabaIoTCloudDemo
  2. 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

  3. 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>'

  4. For publishing message, IoT cloud setups default topic as /${productKey}/${deviceName}/update. So, prepare publishing topic name string as below.
    topicName = '/'+productKey+'/'+deviceName+'/update'

  5. 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.

  6. Initialise the temperature sensor method before reading the temperature from the sensor
    sensor = W1ThermSensor()

  7. 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,


8
Figure 8 Raspberry Pi Output

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

9
Figure 9 Table Store Data

Troubleshooting

  1. Python code returning below error

    w1thermsensor.errors.NoSensorFoundError: No Unknown temperature sensor with id '' found

    Run below commands to see if you can cat w1_slave

    cd /sys/bus/w1/devices
    ls
    cd 28-XXXXXXXXXXXX (change the X's to your own address)
    cat w1_slave

    if you can't see any devices starting with 28, then either the DS18B20 incorrectly connected, faulty wiring or sensor is faulty. For connection, exactly follow the diagram given above.

  2. Messages are not stored in Table Store

    Verify the messages are received and pushed to table store in Device Log section.

    10
    Figure 10 Device Log


1 1 1
Share on

Alibaba Clouder

2,599 posts | 763 followers

You may also like

Comments

Raja_KT February 8, 2019 at 5:02 pm

It goes to show that we can do monitor our home,houses , while in office or elsewhere. Many ready-made codes are available.