基于websocket的跨平台通信——iPhone/iPad/Mac控制树莓派
思路/接口说明
根据后端定义的…等等python的json库不是通过类来解析json数据的…
所以我们要时刻牢记数据类型,或者直接封装一个函数:
import json
def getMsg(toPlatform, msgType, text):
msg = dict(type = 1, toPlatform = toPlatform, msgType = msgType, msg = text)
return json.dumps(msg)
WebSocket
这里我们使用的是python的websocket库:
pip3 install websocket
pip3 install websocket-client
然后封装一个websocket的类方便使用:
class WmSocket:
wsAddress = 'ws://localhost:8880/websocket/MacTerminal'
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_open(ws):
print('### opened ###')
def on_close(ws):
print("### closed ###")
ws = websocket.WebSocketApp(wsAddress,
on_message=on_message,
on_close=on_close,
on_error=on_error,
on_open=on_open)
on_open,on_mseeage都是老面孔了,看名字就知道作用是干什么的;把url和那几个函数传入websocket.WebSocketApp()就可以建立一个websocket链接。
不过需要说明的是,python的websocket非常不友好;
首先线程必须停留在on_open()函数中,不能跳出这个函数,否则websocket连接的生命周期会结束,断开连接;
然后就是发送函数;发送数据是ws.send没错,但是必需是调用on_open()那几个函数的参数ws.open(),不能调用作为WebSocketApp类的ws.open(),也就是说我们要定义一堆全局变量。
数据类
同样的,在python脚本中我也定义了一个Device的父类:
class Device:
sendTime = 3
def get(self):
return(dict(msg = "empty"))
def send(self, ws):
ws.send(self.get())
网络延迟类
# NetDelay.py
import time
import json
import Device
class NetworkDelay(Device):
deviceName = 'NetworkDelay' # 设备名称,暂时用不上
sendTime = 2 # 默认n秒发送一次
def get(self):
_text = str((round(time.time() * 1000)) % 100000)
msg = dict(type = 1, toPlatform = ["WMBP"], msgType = "NetDelay", msg = _text)
return json.dumps(msg)
# 全局变量
netDelay = NetworkDelay()
然后我们在WmSocket类中的on_open中填上:
from NetworkDelay import netDelay
def on_open(ws):
while True:
ws.send(netDelay.get())
time.sleep(netDelay.sendTime)
在主函数中适时初始化websocket:
from WmSocket import WmSocket
if __name__ == '__main__':
# ...
wmsocket = WmSocket()
wmsocket.ws.runforever() # 这一句是阻塞式的
这样一个十分简单的iPhone接收树莓派的网络延迟就完成了。