开发设备控制和消息订阅服务(Python SDK)

更新时间:2024-06-20 06:23:47

本文介绍如何基于涂鸦云开发开放的能力和 SDK,开发一个控制 Powered by Tuya 的智能设备的程序。

前提条件

操作步骤

第一步:配置开发环境

本步骤基于 Tuya-connector-Python SDK。Tuya-connector 集成了开发者在涂鸦云云对接(OpenAPI 或者消息订阅)项目过程中的云端连接和处理过程,可以让开发者如同本地开发一样,聚焦于自身的业务逻辑。

  1. Tuya-connector-Python 获取 SDK 项目地址。

    开发设备控制和消息订阅服务(Python SDK)

  2. Projects > Get from VCS > URL,输入 SDK 项目地址,单击 Clone
    开发设备控制和消息订阅服务(Python SDK)

  3. 独立项目开发)导入 Python 依赖包

    说明: GitHub 托管平台包含了 SDK 源码,本文使用的接口调用为 SDK 项目内的源码,若开发者开发独立项目,可使用 PIP 工具,导入 Python 依赖包。

    导入代码: pip3 install tuya-connector-python

第二步:编辑配置文件

在您的 py 文件中配置环境变量。

开发设备控制和消息订阅服务(Python SDK)

  • ACCESS_ID 和 ACCESS_KEY:云应用密钥 Access ID 和 Access Key,获取方法参见 查询项目信息。-

  • API_ENDPOINT: API 请求 数据中心地址,参考 tuya-connector-python/tuya_connector/tuya_enums.py 文件。

  • MQ_ENDPOINT: 消息订阅 请求地址,参考 tuya-connector-python/tuya_connector/tuya_enums.py 文件。

    地域 API_ENDPOINT MQ_ENDPOINT
    中国区 https://openapi.tuyacn.com wss://mqe.tuyacn.com:8285/
    美国区 https://openapi.tuyaus.com wss://mqe.tuyaus.com:8285/
    欧洲区 https://openapi.tuyaeu.com wss://mqe.tuyaeu.com:8285/
    印度区 https://openapi.tuyain.com wss://mqe.tuyain.com:8285/

示例如下

ACCESS_ID = "xtu7m*****48ufod"
ACCESS_KEY = "479bcba6d*******d9c4e080f7"
API_ENDPOINT = "https://openapi.tuyacn.com"
MQ_ENDPOINT = "wss://mqe.tuyacn.com:8285/"

第三步:控制设备实践

编辑项目配置参数后,您可以开始代码开发。最常见的功能类型为设备控制。
以下为云项目的 授权密钥鉴权查询设备详情获取设备指令集下发指令集查询设备状态 的代码示例,供您参考。

开发设备控制和消息订阅服务(Python SDK)

设备查询、下发指令代码示例:device_control.py

import logging
from tuya_connector import TuyaOpenAPI, TUYA_LOGGER

ACCESS_ID = "xtu7m*****48ufod"
ACCESS_KEY = "479bcba6d*******d9c4e080f7"
API_ENDPOINT = "https://openapi.tuyacn.com"


# Enable debug log
TUYA_LOGGER.setLevel(logging.DEBUG)

# Init openapi and connect
openapi = TuyaOpenAPI(API_ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect()

# set up device_id
DEVICE_ID ="vdevo********74966"

# Call API from Tuya
#Get the device information
response = openapi.get("/v1.0/iot-03/devices/{}".format(DEVICE_ID))

#Get the instruction set of the device
response = openapi.get("/v1.0/iot-03/devices/{}/functions".format(DEVICE_ID))

#Send commands
commands = {'commands': [{'code': 'switch_led', 'value': False}]}
openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)

#Get the status of a single device
response = openapi.get("/v1.0/iot-03/devices/{}/status".format(DEVICE_ID))

返回结果示例:

/Users/even/Documents/SDK/Python/ttuya-connector-python1/venv/bin/python /Users/even/Documents/SDK/Python/ttuya-connector-python/example/device_control.py
[2021-08-24 16:27:21,832] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/token,params = {'grant_type': 1},body = None,t = 1629793641832
[2021-08-24 16:27:22,007] [tuya-openapi] Response: {
  "result": {
    "access_token": "***",
    "expire_time": 6147,
    "refresh_token": "***",
    "uid": "***"
  },
  "success": true,
  "t": 1629793642090
}
[2021-08-24 16:27:22,007] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966,params = None,body = None,t = 1629793642007
[2021-08-24 16:27:22,183] [tuya-openapi] Response: {
  "result": {
    "active_time": 1629792940,
    "asset_id": "14178********2832",
    "category": "dj",
    "category_name": "Light Source",
    "create_time": 1629792940,
    "gateway_id": "",
    "icon": "smart/icon/bay161786******240908156830dd.png",
    "id": "vdevo********74966",
    "ip": "***",
    "lat": "***",
    "local_key": "***",
    "lon": "***",
    "model": "",
    "name": "可调白光灯(C)_SIG-vdevo",
    "online": true,
    "product_id": "ppg6apfp",
    "product_name": "可调白光灯(C)_SIG",
    "sub": false,
    "time_zone": "+08:00",
    "update_time": 1629793223,
    "uuid": "vdevo********74966"
  },
  "success": true,
  "t": 1629793642263
}
[2021-08-24 16:27:22,183] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966/functions,params = None,body = None,t = 1629793642183
[2021-08-24 16:27:22,256] [tuya-openapi] Response: {
  "result": {
    "category": "dj",
    "functions": [
      {
        "code": "switch_led",
        "desc": "switch led",
        "name": "switch led",
        "type": "Boolean",
        "values": "{}"
      },
      {
        "code": "work_mode",
        "desc": "work mode",
        "name": "work mode",
        "type": "Enum",
        "values": "{\"range\":[\"white\",\"colour\",\"scene\",\"music\"]}"
      },
      {
        "code": "bright_value_v2",
        "desc": "bright value v2",
        "name": "bright value v2",
        "type": "Integer",
        "values": "{\"min\":10,\"max\":1000,\"scale\":0,\"step\":1}"
      },
      {
        "code": "scene_data_v2",
        "desc": "scene data v2",
        "name": "scene data v2",
        "type": "Json",
        "values": "{\"scene_num\":{\"min\":1,\"scale\":0,\"max\":8,\"step\":1},\"scene_units\": {\"unit_change_mode\":{\"range\":[\"static\",\"jump\",\"gradient\"]},\"unit_switch_duration\":{\"min\":0,\"scale\":0,\"max\":100,\"step\":1},\"unit_gradient_duration\":{\"min\":0,\"scale\":0,\"max\":100,\"step\":1},\"bright\":{\"min\":0,\"scale\":0,\"max\":1000,\"step\":1},\"temperature\":{\"min\":0,\"scale\":0,\"max\":1000,\"step\":1},\"h\":{\"min\":0,\"scale\":0,\"unit\":\"\",\"max\":360,\"step\":1},\"s\":{\"min\":0,\"scale\":0,\"unit\":\"\",\"max\":1000,\"step\":1},\"v\":{\"min\":0,\"scale\":0,\"unit\":\"\",\"max\":1000,\"step\":1}}}"
      },
      {
        "code": "countdown_1",
        "desc": "countdown 1",
        "name": "countdown 1",
        "type": "Integer",
        "values": "{\"unit\":\"s\",\"min\":0,\"max\":86400,\"scale\":0,\"step\":1}"
      }
    ]
  },
  "success": true,
  "t": 1629793642338
}
[2021-08-24 16:27:22,256] [tuya-openapi] Request: method = POST,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966/commands,params = None,body = {'commands': [{'code': 'switch_led', 'value': False}]},t = 1629793642256
[2021-08-24 16:27:22,386] [tuya-openapi] Response: {
  "result": true,
  "success": true,
  "t": 1629793642470
}
[2021-08-24 16:27:22,386] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966/status,params = None,body = None,t = 1629793642386
[2021-08-24 16:27:22,461] [tuya-openapi] Response: {
  "result": [
    {
      "code": "switch_led",
      "value": false
    },
    {
      "code": "work_mode",
      "value": "white"
    },
    {
      "code": "bright_value_v2",
      "value": 10
    },
    {
      "code": "scene_data_v2",
      "value": ""
    },
    {
      "code": "countdown_1",
      "value": 0
    }
  ],
  "success": true,
  "t": 1629793642546
}

Process finished with exit code 0

登陆鉴权

# Init openapi and connect
openapi = TuyaOpenAPI(API_ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect()

查询设备详情

response = openapi.get("/v1.0/iot-03/devices/{}".format(DEVICE_ID))

获取设备指令集

response = openapi.get("/v1.0/iot-03/devices/{}/functions".format(DEVICE_ID))

下发指令

commands = {'commands': [{'code': 'switch_led', 'value': true}]}
openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)

查询设备状态

response = openapi.get("/v1.0/iot-03/devices/{}/status".format(DEVICE_ID))

第四步:监听设备状态

本代码实现了消息订阅的转发功能,包含了设备在线、离线、状态上报等。

该功能需要开通 消息订阅 服务,开通方式参见 管理消息订阅

开发设备控制和消息订阅服务(Python SDK)

消息订阅代码示例:Mq.py

import logging
from tuya_connector import TUYA_LOGGER, TuyaOpenPulsar, TuyaCloudPulsarTopic

ACCESS_ID = "xtu7m*****48ufod"
ACCESS_KEY = "479bcba6d*******d9c4e080f7"
MQ_ENDPOINT = "wss://mqe.tuyacn.com:8285/"


# Enable debug log
TUYA_LOGGER.setLevel(logging.DEBUG)

# Init Message Queue
open_pulsar = TuyaOpenPulsar(
    ACCESS_ID, ACCESS_KEY, MQ_ENDPOINT, TuyaCloudPulsarTopic.PROD
)
# Add Message Queue listener
open_pulsar.add_message_listener(lambda msg: print(f"---\nexample receive: {msg}"))

# Start Message Queue
open_pulsar.start()

input()
# Stop Message Queue
open_pulsar.stop()

返回结果示例:

/Users/even/Documents/SDK/Python/ttuya-connector-python1/venv/bin/python /Users/even/Documents/SDK/Python/ttuya-connector-python/example/Mq.py
[2021-08-24 16:44:56,274] [tuya-openpulsar] start
[2021-08-24 16:44:56,274] [tuya-openpulsar] ws-client connect status is not ok.
                     trying to reconnect for the  1 time
[2021-08-24 16:44:56,274] [tuya-openpulsar] ---
ws-client connecting...
[2021-08-24 16:45:16,198] [tuya-openpulsar] received message origin payload: {"data":"hBfzoXBHP4H5S44R41JYQ6SoW2dYdwIBh/OVljw/BWnHceQwrrF0vuCyPhPmcgsLzQtf9wFhkSQ6IBE2P3yYPvavGWoPpl0r3fkcooWquX8JfG8gnY2R7wUL3Xn4MP48poM3HepgaRZOkpsSKmAqgdxobOPC7kNpk92hmXjB0PEOZ2Du4MbP4NSN49QcJ4MPl9NsbN/2CZpBNFtIusOL74T+aj0XxXAkcYXc/URNLpxRJ3xeyrLXEwM+0nBc+60qvhnd5XA0Y7aFpHh02iIbzZfTbGzf9gmaQTRbSLrDi+/NOqojg8fRo3AW+Cq6m/AtpGIRH8fwQo+FZ9RzGrk+V7bzGsXu3MK7mEqvJpca8eT7C2ZAat2eM9LwAcsDgOoQaWYWiLcqj04ZYzJqLETUGyRFs3pL4aNsWiTEGuQkMHNV0yTN7Nw/PmMonsmdM3aYSaAwQM37T2HC7gqa2exumamfEL7hh+lWoqymRU/hApq0SeBffyniddW2Daw8AUet","protocol":4,"pv":"2.0","sign":"0e523e66fea32a3873b122152fc04c84","t":1629794716261}
[2021-08-24 16:45:16,198] [tuya-openpulsar] received message descripted: {"dataId":"9aa9d3c4-04b7-11ec-8396-02425b0322e7","devId":"vdevo********74966","productKey":"ppg6apfp","status":[{"1":"true","code":"switch_led","t":1629794716199,"value":true},{"2":"white","code":"work_mode","t":1629794716199,"value":"white"},{"3":"10","code":"bright_value_v2","t":1629794716199,"value":10},{"code":"countdown_1","t":1629794716199,"7":"0","value":0}]}
---
example receive: {"dataId":"9aa9d3c4-04b7-11ec-8396-02425b0322e7","devId":"vdevo********74966","productKey":"ppg6apfp","status":[{"1":"true","code":"switch_led","t":1629794716199,"value":true},{"2":"white","code":"work_mode","t":1629794716199,"value":"white"},{"3":"10","code":"bright_value_v2","t":1629794716199,"value":10},{"code":"countdown_1","t":1629794716199,"7":"0","value":0}]}

小结

本文介绍了如何使用 Python SDK 基于涂鸦云开发,调用设备相关 API 控制一个智能设备和监听设备信息。基于 Powered by Tuya 设备体系严格的统一性,您可以将这个控制方式拓展到所有 Powered by Tuya 设备中。让您无需担心设备差异性,快速基于智能设备开发 SaaS 应用。