缘由:因为带钥匙实在麻烦,市面上的智能锁虽好,但是有点小贵,于是我们就想着能不能自己做一个用手机语音助手加上自己搭的客户端和服务端加上电机,做一个简易版低成本的智能门锁。
功能及应用流程介绍:用户只需要用手机语音助手下达开关门指令(需要在手机端设置命令),门锁服务端接收到移动客户端发送的指令,发送指令给门锁客户端并发送网页反馈,门锁客户端接收服务端命令并驱动电机执行开关门。
话不多说,我们来看一下门锁服务端代码实现吧~
import os,sys
import socket,time
def order(data):
datalist = data.split("\n")
for i in datalist:
if(i=='Upgrade-Insecure-Requests: 1\r'):
print("open the door for master")
msg = 'open'
door_sock.send(msg.encode('gbk'))
http_response = """\
HTTP/1.1 200 OK
Hello, World!
"""
sock.sendall(http_response.encode("utf-8"))
sock.close()
break
if(i=='close'):
print("close the door for master")
break
HOST,PORT ='',4000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(5)
m = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
m.bind((HOST, 5000))
m.listen(5)
while True:
try:
print('Waiting for door_client connection...')
door_sock,door_addr = m.accept()
except:
continue
while True:
try:
recv_data = door_sock.recv(1024)
if recv_data:
print('Waiting for connection...')
datalist = [ ]
sock,addr = s.accept()
print('Accept new connection from client')
while True:
data = sock.recv(1024).decode()
order(data)
break
else:
door_sock.close()
break
except:
door_sock.close()
break
sock.close()
door_sock.close()
print('Connection from %s:%s closed.' % addr)
注意:门锁客户端需要一直给服务端发送信息以检测是否掉线,同时也需要一直接收客户端发送过来的指令,于是需要用到多线程。
简易门锁客户端搭建:
import socket
import threading
def send_date(socket_tcp_client):
while True:
server_date = 'connected'
socket_tcp_client.send(server_date.encode("gbk"))
socket_tcp_client.close()
def recv_date(socket_tcp_client):
while True:
recv_date = socket_tcp_client.recv(1024)
print("接收到的数据为:", recv_date.decode("gbk"))
def main():
socket_tcp_client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_ip= '10.161.42.184'
server_port = 5000
server_addr=(server_ip,server_port)
socket_tcp_client.connect(server_addr)
send_tcp_date=threading.Thread(target=send_date,args=(socket_tcp_client,))
recv_tcp_date=threading.Thread(target=recv_date,args=(socket_tcp_client,))
send_tcp_date.start()
recv_tcp_date.start()
if __name__ =='__main__':
main()
移动端可用浏览器模拟
看一下运行效果: 大概就是这样的。 小白入门在代码书写上可能还不够简洁、不够优美,还需要继续努力…
|