python 与小米网关通讯的三块内容:
以下内容的理解需要配合《绿米网关局域网通讯协议》使用
1、监听网关发出的组播信息:(有网关及连接设备的生命信号,事件信息)
2、读取需要获得的信息
3、控制连接设备(涉及了token加密部分)
1、upd广播监听小米网关的组播信息
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import socket 5 6 def get_gateway_heart(): 7 SENDERIP = "0.0.0.0" 8 MYPORT = 9898 9 MYGROUP = '224.0.0.50' 10 11 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) 12 #allow multiple sockets to use the same PORT number 13 sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 14 #Bind to the port that we know will receive multicast data 15 sock.bind((SENDERIP,MYPORT)) 16 #tell the kernel that we are a multicast socket 17 #sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255) 18 #Tell the kernel that we want to add ourselves to a multicast group 19 #The address for the multicast group is the third param 20 status = sock.setsockopt(socket.IPPROTO_IP, 21 socket.IP_ADD_MEMBERSHIP, 22 socket.inet_aton(MYGROUP) + socket.inet_aton(SENDERIP)); 23 24 #sock.setblocking(0) 25 #ts = time.time() 26 data, addr = sock.recvfrom(1024) 27 data_str=str(data,encoding='utf-8') 28 # sock.close() 29 return data_str 30 31 32 if __name__=='__main__': 33 while True: 34 tmp=get_gateway_heart() 35 print(tmp)