基本知识

以下为官网描述:
In order to subscribe to RPC commands from the server, send SUBSCRIBE message to the following topic:
为了订阅来自服务器端的RPC命令,设备需要订阅下边的topic

  1. v1/devices/me/rpc/request/+

Once subscribed, the client will receive individual commands as a PUBLISH message to the corresponding topic:
一旦订阅之后,客户端设备将接收单个命令作为到相应主题的 PUBLISH 消息:

  1. v1/devices/me/rpc/request/$request_id

where $request_id is an integer request identifier.
The client should publish the response to the following topic:
其中$request_id是整数请求标识符。
客户端应发布对以下主题的响应: 也就是下边的topic用作响应,id的值等于上边服务器返回来的id值。

v1/devices/me/rpc/response/$request_id

用例

下面以一个例子说明 如何使用服务器端RPC。用例说明:
服务器端远程写数据到设备端(或者远程控制开关,原理一致)。
流程说明:
创建设备(略)
创建控制组件
设备端订阅主题—-服务器返回—-设备端回复
新建仪表板
image.png
image.png
结果

image.png
编写测试软件,当写法的开关量是true的时候UI变为绿色,是false的时候变为红色。
image.png
image.png
之下是全部的代码;

import json
import paho.mqtt.client as mqtt
import tkinter as tk

borker = 'www.vincentisme.com'
port = 1883
access = "TRU09Sr72OWYQv0DMmZN"

def on_connect(client, userdata, flags, rc):
    print("rc code:", rc)
    if rc:
        return
    print("链接成功")
    client.subscribe('v1/devices/me/rpc/request/+')    #订阅主题


def on_message(client, userdata, msg):
    print('Topic: ' + msg.topic + '\nMessage: ' + str(msg.payload))
    request_id = msg.topic.split('/')[-1]   #获取返回来的id
    print(request_id)
    method = json.loads(msg.payload)['method']
    try:
        data = json.loads(msg.payload)['params']
        if method == 'setValue':
            print("收到数据:", data)
            client.publish('v1/devices/me/rpc/response/' + request_id, json.dumps({"response": request_id}), 1)
            #响应
        if method == 'setIO':
            print("收到开关量:", data)
            set_config(data)   #修改界面
            client.publish('v1/devices/me/rpc/response/' + request_id, json.dumps({"response": request_id}), 1)
            #响应
    except Exception as e:
        print(e)
        pass

def set_config(value):
    if value:
        l.configure(bg="green", text='开')
    else:
        l.configure(bg="red", text='关')

window = tk.Tk()
window.title(u'测试tb下发的开关量')
window.geometry('400x200')
l = tk.Label(window, text='开', bg='green', font=('Arial', 12), width=30, height=12)
l.pack()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(access)
client.connect(borker, port, keepalive=60)
try:
    client.loop_start()
except KeyboardInterrupt:
    client.disconnect()


window.mainloop()