转载请保留原地址. http://www.cnblogs.com/lsqandzy
最近买了几个智能插座玩,插座安装在家里,连接好wifi,不管你人在哪里,通过手机,一键开启或关闭插座电源,想象一下,马上要下班了,天好热,先把空调打开,等回到家已经凉飕飕的。哈~
闲暇时间用python3写了 局域网内一键扫描和控制插座开关的代码。
一键扫描:
import socket import threading,time class UdpServer: def __init__(self): self.DeviceList={} self.thread_server=threading.Thread(target=self.start) self.thread_server.start() def start(self): address = ('', 48899) self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.bind(address) try: while True: data, addr = self.s.recvfrom(1024) if not data: print("exist") break data=str(data) d_list=data.replace("b'","").replace("'","").split(',') if str(addr[0]) in d_list[0]: temp_device={} temp_device['IP']=d_list[0] temp_device['MAC']=d_list[1] temp_device['SN']=d_list[2] temp_device['RES']=d_list[3] temp_device['STATUS']=d_list[4] self.DeviceList[addr[0]]=temp_device self.s.close() except: self.s.close() print("Thread Wrong") def stop(self): self.s.close() del self.thread_server def getDevice(self): return self.DeviceList try: ss=UdpServer() address = ('192.168.1.255', 48899) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) msg = b"""YZ-RECOSCAN""" s.sendto(msg, address) s.close() time.sleep(1) DeviceList=ss.getDevice() ss.stop() for item in DeviceList: print(DeviceList[item]) except: print("wrong") del ss
贴图:
接了3个插座,ip分别是 128、123、121
Status表示开关状态 0关闭 1开启
Mac是网卡mac不解释
Res是插座的工作状态 0异常(正在启动、正在恢复、等等) 1正常
Sn是插座的序列号
一键控制:
from socket import * HOST='192.168.1.121' PORT=8899 tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect((HOST,PORT)) data2 =b"""AT+YZSWITCH=1,ON,201604151533""" tcpCliSock.send(data2) data1 = tcpCliSock.recv(1024) print (data1)
控制121插座开启
操作成功!
以上是在局域网内控制的代码。