简短说明一下吧
这个都是我做过的试验写的代码,使用的芯片是ESP32,ESP32连接了WIFI后,其他中断通过TCP消息,来控制ESP连接的LED灯,当然,这个灯,带了继电器后,是可以用在别的地方的。
Python以后再嵌入式会大有作为,我有时也练习一下C语言的嵌入式,总体感觉C语言的太繁琐了。
#导入Pin模块
from machine import Pin
import time
import network
import socket
import _thread
import utime
#路由器WIFI账号和密码
ssid="Longhu"
password="***********"
#存储客户端地址字符串
conn_list = []
#存储连接
conn_dic = {}
#引入上一次有效通信时间的字典,如果超过10s没有通信,就主动关掉
conn_last_time_dic={}
led1=Pin(2,Pin.OUT)
#WIFI连接
def wifi_connect():
wlan=network.WLAN(network.STA_IF) #STA模式
wlan.ifconfig(('192.168.100.201', '255.255.255.0', '192.168.100.1', '192.168.100.1'))
wlan.active(True) #激活
start_time=time.time() #记录时间做超时判断
if not wlan.isconnected():
wlan.connect(ssid,password) #输入WIFI账号和密码
while not wlan.isconnected():
#超时判断,5 秒没连接成功判定为超时
if time.time()-start_time>5:
print("WIFI Connect Timeout!")
break
return False
else:
print("network information:", wlan.ifconfig())
return True
#启动网络
def start_tcp_server():
listenSocket = socket.socket()
listenSocket.bind(("192.168.100.201", 7799))
listenSocket.listen(5)
listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return listenSocket
#监视线程,长时间不用时主动断开
def tcp_online(sock,addr):
while True:
datetime_now_unix_second=utime.mktime(utime.localtime())
#如果10秒没有接收消息就主动断开,减少系统压力
#print("now:",datetime_now_unix_second)
#print("last:",conn_last_time_dic[addr])
if datetime_now_unix_second-conn_last_time_dic[addr]>10:
sock.close()
print(addr,'offline')
_index = conn_list.index(addr)
conn_dic.pop(addr)
conn_last_time_dic.pop[addr]
conn_list.pop(_index)
break
time.sleep(1)
def tcp_link(sock,addr):
while True:
try:
#此处是阻塞的
recv_data_str=sock.recv(1024).decode('utf-8')
#print(recvdata, addr)
#处理接收的数据
if recv_data_str == "led on":
#print("这里是要灯亮的代码...")
led1.value(1)
sock.send(str(led1.value()))
conn_last_time_dic[addr]=utime.mktime(utime.localtime())
elif recv_data_str == "led off":
#print("这里是要灯灭的代码...")
led1.value(0)
sock.send(str(led1.value()))
conn_last_time_dic[addr]=utime.mktime(utime.localtime())
except:
sock.close()
print(addr,'offline')
_index = conn_list.index(addr)
conn_dic.pop(addr)
conn_last_time_dic.pop[addr]
conn_list.pop(_index)
break
#程序入口
if __name__=="__main__":
wifi_connect()
time.sleep(5)
led1.value(1)
tcp_socket = start_tcp_server()
#接收网络数据
while True:
conn, addr = tcp_socket.accept()
#多于3个连接时候,直接不让连接
#if len(conn_list)>3:
# conn.close()
# continue
if addr not in conn_list:
conn_list.append(addr)
conn_dic[addr] = conn
conn_last_time_dic[addr]=utime.mktime(utime.localtime())
t=_thread.start_new_thread(tcp_link,(conn,addr))
t2=_thread.start_new_thread(tcp_online,(conn,addr))
time.sleep(0.05)