
python+巴法云+DHT11+开关灯配合APP Inventor或智能音箱使用
import time
from machine import Timer
import socket
import dht
import machine
from machine import Pin
led=Pin(23,Pin.OUT)
d = dht.DHT11(machine.Pin(22))
b=""
# 需要修改的地方
wifiName = "****" # wifi 名称,不支持5G wifi
wifiPassword = "88888888" # wifi 密码
clientID = "a0e57392252d478986297b2671d1fb83" # Client ID ,密钥,巴法云控制台获取
myTopic = "wsd" # 需要订阅的主题值,巴法TCP控制台创建
myTopic2 = "led002" # 需要订阅的主题值,巴法TCP控制台创建
# 默认设置
serverIP = "bemfa.com" # mqtt 服务器地址
port = 8344
# WIFI 连接函数
def do_connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print("连接网络....")
sta_if.active(True)
sta_if.connect(wifiName, wifiPassword)
while not sta_if.isconnected():
pass
print("已经连接到WIFI")
# tcp 客户端初始化
def connect_and_subscribe():
addr_info = socket.getaddrinfo(serverIP, port)
addr = addr_info[0][-1]
client = socket.socket(
socket.AF_INET, socket.SOCK_STREAM
) # 创建TCP的套接字,也可以不给定参数。默认为TCP通讯方式
client.connect(addr) # 设置要连接的服务器端的IP和端口,并连接
substr = "cmd=3&uid=" + clientID + "&topic=" + myTopic + "\r\n"
substr2 = "cmd=3&uid=" + clientID + "&topic=" + myTopic2 + "\r\n"
client.send(substr.encode("utf-8"))
client.send(substr2.encode("utf-8"))
print("连接到 %s" % serverIP)
return client
# 发送数据
def send_data():
d.measure()#读取DHT11数据
t = str(d.temperature()) # 温度(°C)
s = str(d.humidity()) # 湿度(% RH)
substr = (
"cmd=2&uid="
+ clientID
+ "&topic="
+ myTopic
+ "&msg=#"
+ t
+ "#"
+ s
+ "#"
+b
+ "#"
+ "\r\n"
)
client.send(substr.encode("utf-8"))
# 心跳
def Ping(self):
# 发送心跳
try:
keeplive = "ping\r\n"
client.send(keeplive.encode("utf-8"))
send_data()
except:
restart_and_reconnect()
# 重新连接
def restart_and_reconnect():
print("未能连接到TCP代理。重新连接...")
time.sleep(10)
machine.reset()
# 开始连接WIFI
do_connect()
# 开始连接TCP
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
# 开启定时器,定时发送心跳
tim = Timer(-1)
tim.init(period=3000, mode=Timer.PERIODIC, callback=Ping)
while True:
try:
data = client.recv(256) # 从服务器端套接字中读取1024字节数据
if len(data) != 0: # 如果接收数据为0字节时,关闭套接字
data = data.decode("utf-8")
if "on" in data:
b="on"
led.value(1) #控制灯
if "off" in data:
b="off"
led.value(0)
print(data.strip()) # 去掉尾部回车换行符,并打印接收到的字符
except OSError as e: # 如果出错就重新启动
print("未能连接到TCP代理。重新连接... ...")
restart_and_reconnect()
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)