Teach you to use Python to make the Internet of things. It's so awesome that beginners can understand it

There are many ways to build a complete Internet of things system. Recently, we have been building a set of simplest Internet of things system with python + Alibaba cloud, which can transfer the data on the single chip computer to the PC through Alibaba cloud.

Note: many people will encounter all kinds of problems in the process of learning python. No one can easily give up. For this reason, I have built a python full stack for free answer. Skirt: seven clothes, 977 bars and five (homophony of numbers) can be found under conversion. The problems that I don't understand are solved by the old driver and the latest Python practical course. We can supervise each other and make progress together!

1, Basic structure

First look at the architecture

Frame.png

2, Device end access

Internet of things terminal is ESP32, which is a singlechip with Bluetooth and Wifi. It can be directly connected to the Internet without other modules. Of course, you can connect the popular NB IOT module to the Internet, but you need to write your own driver. The module I bought supports the development of micro python, which can be found on Taobao and is very convenient to use. When I have time, I will fill in the preliminary course of this section.

 

 
ESP32 module.jpg

Micropyron is a python that can run on low-end hardware. It can use Python language to directly operate IO and MCU peripherals such as UART and I2C. It is very convenient to use. It is not necessary to build a complex development environment or learn register configuration. As a hardware engineer familiar with traditional MCU development, it feels very simple to operate. At present, micropython has supported a lot of hardware, and should be supported with a relatively wide range of STM32 part series. Micropython also supports many common libraries, such as Bluetooth, telnet, mqtt, etc. The following link is the Chinese Forum of micropython.
http://www.micropython.org.cn/bbs/forum.php

ESP32 connects to the Internet through wifi, uses mqtt protocol to access alicloud, and uploads temperature data to alicloud. In the cloud, you can directly view the temperature information through message subscription. Use python on the PC side to call mqtt protocol and connect to alicloud. However, the PC and ESP32 are two different devices on Alibaba cloud. They need to forward information through Alibaba cloud, so that the PC can get the data uploaded by ESP32.

The code on ESP32 is as follows:

from umqtt.simple import MQTTClient
import usocket as socket
import time
import wifi

wifi.connect()

#Demo_01
ProductKey = "*********"#Use your own
ClientId = "1234|securemode=3,signmethod=hmacsha1|"
DeviceName = "Demo_01"
DeviceSecret = "*******************************"#Use your own

strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
Brokerport = 1883

user_name = "Demo_01&*********"#Use your own
user_password = "**********************************************"#Use your own

print("clientid:",ClientId,"\n","Broker:",strBroker,"\n","User Name:",user_name,"\n","Password:",user_password,"\n")


def connect():
    client = MQTTClient(client_id = ClientId,server= strBroker,port=Brokerport,user=user_name, password=user_password,keepalive=60) 
    #please make sure keepalive value is not 0
    
    client.connect()

    temperature =25.00
    while temperature < 30:
        temperature += 0.5      
    
        send_mseg = '{"params": {"IndoorTemperature": %s},"method": "thing.event.property.post"}' % (temperature)
        client.publish(topic="/sys/*************/Demo_01/thing/event/property/post", msg=send_mseg,qos=1, retain=False)#*product id at No
        
        time.sleep(3)

    while True:
        pass

    #client.disconnect()

There are several points to explain:
1. The wifi.connect() function in the code needs to be written by yourself. Similar functions can be found on the Internet. You can also reward the source code I want for private letters.
2. The access of Alibaba cloud Internet of things platform requires triple authentication. The login name and password will be generated according to certain rules. This online information is relatively comprehensive.
3. The format of publishing messages to Alibaba cloud Internet of things platform must be in accordance with the code. There are many codes on the Internet, but the description of this block is not clear.

  1. For the umqtt.simple library used by Micropython, you must set the keepalive time, otherwise you cannot connect. I groped for this point for a long time, and finally found the problem by looking at the source code of the library.

3, Cloud settings

Build an advanced product in the cloud and create two devices for ESP32 and PC connectivity.

 

 
device.JPG

 

You need to define the function in the product.

 

 
device_define.JPG


After the cloud and device are established, you can view the running status of the device and see the data upload

 
Cloud data view.JPG

 

This is the result of looking at the data record

 

 
Cloud data logging.JPG


When you see the right data, it means that you have successfully connected to the Internet of things and uploaded the data.
Next is the most important part - the setting is to use the rule engine to forward the data from the device demo 01 to demo 02. The grammar of this step is very important. Although there are detailed tutorials on the official website, it took a long time to get it right.

Rule query statement:
SELECT items.IndoorTemperature.value as IndoorTemperature FROM "/sys/use-your-productkey-here/Demo_01/thing/event/property/post" WHERE items.IndoorTemperature.value > 0

4, PC access

The PC uses python to simulate MQTT devices to log in to alicloud to subscribe to messages. As long as python is installed, it can be implemented quickly. There are many codes on the Internet. A large part of the code is doing triple authentication, which can be slightly modified to calculate the required ESP 32 login
The python code of PC is as follows:

# coding=utf-8
import datetime
import time
import hmac
import hashlib
import math

try:
    import paho.mqtt.client as mqtt
except ImportError:
    print("MQTT client not find. Please install as follow:")
    print("pip install paho-mqtt")

# Set up connection information

#Demo_02
ProductKey = "*********"#Use your own
ClientId = "2234"  # Custom clientId
DeviceName = "Demo_02"
DeviceSecret ="************************************8**"#Use your own

# Get timestamp (current time in milliseconds)
us = math.modf(time.time())[0]
ms = int(round(us * 1000))
timestamp = str(ms)

# Calculate password (signature value)
def calculation_sign(signmethod):
    data = "".join(("clientId", ClientId, "deviceName", DeviceName,
                    "productKey", ProductKey, "timestamp", timestamp))

    if "hmacsha1" == signmethod:
        # ret = hmac.new(bytes(DeviceSecret),
        #                bytes(data), hashlib.sha1).hexdigest()
        ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
                       bytes(data, encoding="utf-8"),
                       hashlib.sha1).hexdigest()
    elif "hmacmd5" == signmethod:
        # ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
        #                bytes(data, encoding="utf-8"), hashlib.md5).hexdigest()
        ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
                       bytes(data, encoding="utf-8"),
                       hashlib.md5).hexdigest()
    else:
        raise ValueError
    return ret


# ======================================================

strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
port = 1883

client_id = "".join((ClientId,
                     "|securemode=3",
                     ",signmethod=", "hmacsha1",
                     ",timestamp=", timestamp,
                     "|"))
username = "".join((DeviceName, "&", ProductKey))
password = calculation_sign("hmacsha1")

print("="*60)
print(strBroker)
print("client_id:", client_id)
print("username:", username)
print("password:", password)
print("="*60)


# Operation after successful connection
def on_connect(client, userdata, flags, rc):
    print("OnConnetc, rc: " + str(rc))


# Operation to publish message successfully
def on_publish(client, msg, rc):
    if rc == 0:
        print("publish success, msg = " 

Tags: Python encoding SHA1 PHP

Posted on Fri, 20 Mar 2020 02:52:52 -0700 by visonardo