The popularity of Artificial intelligence and machine learning has brought the popularity of Python to a new height. The Python classes that are frequently picked up on wechat moments have even made many non-technical students doubt that they are modern even if they don’t know Python. There is plenty of information on the web about the basics of Python, and there are plenty of resources available for anyone interested. In this article, I mainly start from some readers’ concerns, such as the popularity of various IoT intelligent devices today, how to use Python to control intelligent hardware, to achieve some function demonstration? For example, we can use Python to control light bulb switches, brightness adjustments, color changes, and so on.

In fact, the ability to control hardware devices does not require you to completely develop your own programs. Through ready-made platforms and simple Python code programming, you can realize the control and interaction of intelligent devices, which really enables you to master the integration of software and hardware capabilities.

Below, I will use the Doodle Cloud development platform to show you how to use the platform and control a smart device by calling the relevant API in Python. Using the Doodle Cloud development platform, you can obtain the call permission of the OpenAPI of the Doodle IoT platform. Powered By Tuya smart devices can be easily controlled with simple code programming.

bom

Hardware: A smart hardware device, any Powered By Tuya device, you can also go to doodle Smart selection platform to purchase samples.

Software: A Python IDE, such as PyCharm, VS Code, IDLE, etc

steps

Step 1: Create a cloud development project

To use the Doodle API, you need to create a project on the Doodle Cloud development platform.

Once created, you can obtain the authorization key (a combination of Access ID and Access Secret) on the project details page. Please copy it for safekeeping. You will need the authorization key when calling the API.

Step 2: Associate devices with the project

Doodle OpenAPI is primarily used to control smart devices, so we need to associate devices with cloud development projects first.

Device Association Mode

Doodle provides four dimensions of device context:

The first three methods require you to develop intelligent hardware products or mobile applications. In order to quickly experience the IoT application construction process, this article uses the fourth method of device association.

  • Recommended method 1: Use the Doodle Smart App to add smart devices
  • Recommended method 2: Add virtual devices

If you do not have a Powered By Tuya device available, you can also debug By adding virtual devices.

  • Devices under associated products: Associate intelligent devices developed by you with product Pids.
  • Associate devices added to the wechat applets network: Associate devices under the applets you developed by App Schema.
  • Associating devices added to the App configuration network: Associate devices under your App using the App Schema.
  • Associated devices under App Accounts: Use the Doodle Smart App to associate devices with the Internet in your IoT account.
  1. Install a Doodle Smart App or smart Life App on your phone.

  2. Connect the smart device to the App.

  3. The cloud development device association page is displayed.

  4. Select the device TAB under the associated App account.

  5. All devices under the account can be authorized to cloud development projects by scanning the code using the Doodle Smart App.

  6. After an intelligent device is associated with a cloud development project, you can choose Device Management > Device List to view the devices that are associated in various ways.

  7. After the device ID is added, copy the device ID for later use. Assume that the obtained device ID is 6C7ASA9B55FS632C12ZcwY.

  8. The cloud development virtual device page is displayed.

  9. Select Add virtual device.

  10. Select a product and choose Add Virtual Device > Associate with Doodle App account.

  11. The virtual device under the account can be authorized to the cloud development project by scanning the code using the Doodle Smart App. Virtual devices are placed separately on the Device Management > Virtual Devices page.

  12. After the virtual device IS added, copy the device ID for later use. Assume that the obtained virtual device ID is vdevo160544422718591.

Step 3: Apply for API call permission

Graffiti IoT Platform OpenAPI is disabled by default. You need to apply for OPENING API in groups to use it. If you call an API that is not enabled, you will get an underprivileged call error.

In this document, you need to apply for authorization management, device management, and device control apis on the cloud development API group page.

Now that you’ve done your homework on the Doodle Cloud development platform, choose any Python IDE for your programming practice.

Step 4: Invoke the API control device

All Python code involved in this step has been packaged as PYTHon_iot_code_sample. py, which you can download and use in advance.

4.1 get access_token

Graffiti IoT uses HMAC-SHA256 to create a summary. According to different application scenarios, the cloud development platform provides two sets of signature algorithms. The algorithm of the token management interface (obtaining and refreshing tokens) is as follows:

sign = HMAC-SHA256(client_id + t, secret).toUpperCase()

Here is the corresponding Python application code logic:

# from cloud development project authorization keys client_id = '3 meqtq4x9wr22a90lee4' secret = '7 b121dd8196043f3b6944250fa3ad4ab # the interface using the parties according to their own area, please call the corresponding interface. China # https://openapi.tuyacn.com # # # https://openapi.tuyaus.com americas Europe https://openapi.tuyaeu.com India area # https://openapi.tuyain.com base = 'https://openapi.tuyacn.com' signature algorithm function def calc_sign (MSG, key) : import hmac import hashlib sign = hmac.new(msg=bytes(msg, 'latin-1'),key = bytes(key, 'latin-1'), digestmod = hashlib.sha256).hexdigest().upper() return sign import time import requests t = str(int(time.time()*1000)) r Request. Get (base+'/v1.0/token? Grant_type =1', headers={'client_id':client_id, 'sign':calc_sign(client_id+t, secret), 'secret':secret, 't':t, 'sign_method':'HMAC-SHA256', }) res = r.json()['result'] print(res)Copy the code

4.2 Writing generic request functions

All service apis require public parameters. To avoid repetitive and tedious operations, you are advised to write GET and POST requests for subsequent use. Meanwhile, the signature algorithm of the service interface is different from that used to obtain the Token in the previous step. The algorithm is as follows:

sign = HMAC-SHA256(client_id + access_token + t, secret).toUpperCase()

Here is the corresponding Python application code logic:

Def get (url, headers={}): t = str(int(time.time()*1000)) default_par={ 'client_id':client_id, 'access_token':res['access_token'], 'sign':calc_sign(client_id+res['access_token']+t, secret), 't':t, 'sign_method':'HMAC-SHA256', } r = requests.get(base + url, headers=dict(default_par,**headers)) r = json.dumps(r.json(), indent=2, Return r # def post (url, headers={}, body={}): import json t = str(int(time.time()*1000)) default_par={ 'client_id':client_id, 'access_token':res['access_token'], 'sign':calc_sign(client_id+res['access_token']+t, secret), 't':t, 'sign_method':'HMAC-SHA256', } r = requests.post(base + url, headers=dict(default_par,**headers), data=json.dumps(body)) r = json.dumps(r.json(), Indent =2, ensure_ASCII =FalseCopy the code

4.3 Bidirectional control equipment

You can obtain the latest device status through the API. You need to invoke the API with the device ID as the parameter.

Here is the corresponding Python application code logic:

Device_id = '65057368c44f3380cc4b' r = GET(URL =f'/v1.0/devices/{device_id}/status') print(r)Copy the code

The following is an example of the returned result. For more details, refer to the intelligent device instruction set:

{
  "result": [
    {
      "code": "switch",
      "value": true
    },
    {
      "code": "countdown_1",
      "value": 0
    },
    {
      "code": "cur_current",
      "value": 68
    },
    {
      "code": "cur_power",
      "value": 3
    },
    {
      "code": "cur_voltage",
      "value": 2125
    }
  ],
  "success": true,
  "t": 1606880360840
}
Copy the code

Sometimes you don’t know what instructions you can issue to control an unknown device until you control it. In this case, you can use the API to get all the available control instructions for the device, and then issue specific instructions to control the device.

R = the GET (url = f '/ v1.0 / devices / {device_id} / functions provides') print (r)Copy the code

Using a smart socket as an example, the following is an example:

{" result ": {" category" : "cz", "functions provides" : [{" code ":" switch ", "desc" : "[the] socket switch", "name" : "switch", "type" : "Boolean" and "values", "{}"}, {" code ":" countdown_1 ", "desc" : "switch 1 countdown", "name" : "switch 1 countdown", "type" : "Integer", "values" : "{\"unit\":\"s\",\"min\":0,\"max\":86400,\"scale\":0,\"step\":1}" } ] }, "success": true, "t": 1606880309547 }Copy the code

After obtaining the device instruction set, you can invoke the DEVICE instruction API to control the intelligent device.

D = {"code":"switch","value":True},]} r = POST(url=f'/v1.0/devices/{device_id}/commands',  body=d) print(r)Copy the code

Example return result:

{
  "result": true,
  "success": true,
  "t": 1606880463013
}
Copy the code

Details: Python IoT Development Practices based on the Doodle Cloud Development Platform (tuya.com)

summary

This article showed you how to control an intelligent device using Python based on the Doodle Cloud development platform by calling basic apis. Due to the strict uniformity of the Powered By Tuya device architecture, you can extend this control mode to all Powered By Tuya devices. Enables you to quickly build IoT applications and services without considering device heterogeneity.