问题描述:
from aLiYun import aLiYun
import ujson
from machine import Pin
import utime
import checkNet
from machine import Timer
PRODUCT_KEY = 'a1lLrpffrHe'
PRODUCT_SECRET = None
DEVICE_NAME = 'device4'
DEVICE_SECRET = '165073e93c1484cfc525f8fec259d03d'
*_NAME = "QuecPython_AliYin_example"
*_VERSION = "1.0.0"
checknet = checkNet.CheckNetwork(*_NAME, *_VERSION)
aLiY = aLiYun(PRODUCT_KEY, PRODUCT_SECRET, DEVICE_NAME, DEVICE_SECRET)
gpio1 = Pin(Pin.GPIO15, Pin.OUT, Pin.PULL_DISABLE, 0)
timer1 = Timer(Timer.Timer1)
state = 1
# 设备下发命令的set主题
ALINK_TOPIC_PROP_SET = b"/sys/" + PRODUCT_KEY + "/" + DEVICE_NAME + "/thing/service/property/set"
# 设备上传数据的post主题
ALINK_TOPIC_PROP_POST = b"/sys/" + PRODUCT_KEY + "/" + DEVICE_NAME + "/thing/*nt/property/post"
# 设备post上传数据要用到一个json字符串, 这个是拼接postJson用到的一个字符串
ALINK_METHOD_PROP_POST = "thing.*nt.property.post"
# 回调函数
def sub_cb(topic, msg):
print("进入回到")
print(topic)
if topic == ALINK_TOPIC_PROP_POST:
print("进入回到1")
print("上报成功! Subscribe Recv: Topic={},Msg={}".format(
topic.decode(), msg.decode()))
elif topic == ALINK_TOPIC_PROP_SET:
print("进入回到2")
print("下发成功! Subscribe Recv: Topic={},Msg={}".format(
topic.decode(), msg.decode()))
params = ujson.loads(msg.decode())['params']
global time
time = params["time"] #时间
print(gpio1)
gpio1.write(1) # 设置 gpio1 输出高电平
# utime.sleep(8)
# gpio1.write(1) # 设置 gpio1 输出高电平
utime.sleep_ms(time)
gpio1.write(0) # 设置 gpio1 输出高电平
val = gpio1.read() # 获取 gpio1 的当前高低状态
print('val = {}'.format(val))
def send_msg_to_AliY(args):
print("进入www3")
# 要上传的数据
data_dict = {
"status": 0
}
# 上传数据格式
msg_dict = {
"id": 1,
"version": 1.0,
"method": "thing.*nt.property.post",
"params": data_dict
}
aLiY.publish(ALINK_TOPIC_PROP_POST, ujson.dumps(msg_dict))
if __name__ == '__main__':
stagecode, subcode = checknet.wait_network_connected(60)
print('stagecode = {}, subcode = {}'.format(stagecode, subcode))
if stagecode == 3 and subcode == 1:
clientID = "device4"
aLiY.setMqtt(clientID, clean_session=False, keepAlive=60)
aLiY.setCallback(sub_cb)
aLiY.subscribe(ALINK_TOPIC_PROP_SET) # 订阅上传数据主题
print("进入回到3")
timer1.start(period=10000, mode=Timer.PERIODIC, callback=send_msg_to_AliY)
aLiY.start()
while True:
if state:
pass
else:
aLiY.disconnect()
break