我有一個Beaglebone黑色連接到CAN總線設備:電池。如何在龍捲風中使用多個ioloop並在ioloop(s)之間共享數據?
作爲GUI在Beaglebone Black上運行的龍捲風網頁。
CAN總線讀取循環不斷從CAN總線讀取數據更新電池例如
的狀態,但我怎樣才能使兩個IOLOOP攜手共進,共享電池組的實例?
龍捲風網絡:
class Battery(object):
status = {}
class API_Handler(web.RequestHandler):
def get(self, dev, cmd):
if cmd == 'data':
self.write(self.application.battery0.status)
class Application(web.Application):
def __init__(self):
self.battery0 = Battery('bat0')
routing = [
(r'/api/battery/(data|)', API_Handler),
]
settings = {
'template_path': os.path.join(os.path.dirname(__file__), "templates"),
'static_path': os.path.join(os.path.dirname(__file__), "static"),
}
web.Application.__init__(self, routing, debug=True, **settings)
if __name__ == "__main__":
import tornado
app = Application()
app.listen(address='0.0.0.0', port=8888)
tornado.ioloop.IOLoop.instance().start()
CAN總線讀取循環,代碼:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import errno
import functools
import tornado.ioloop
import socket
import struct
can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)
def build_can_frame(can_id, data):
can_dlc = len(data)
data = data.ljust(8, b'\x00')
return struct.pack(can_frame_fmt, can_id, can_dlc, data)
def dissect_can_frame(frame):
can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
return (can_id, can_dlc, data[:can_dlc])
def connection_ready(sock, fd, events):
while True:
try:
cf, addr = sock.recvfrom(can_frame_size)
except socket.error as e:
if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
raise
return
dissect_can_frame(cf)
if __name__ == '__main__':
sock = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
sock.bind(('can0',))
sock.setblocking(0)
io_loop = tornado.ioloop.IOLoop.current()
callback = functools.partial(connection_ready, sock)
io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
io_loop.start()
如果您使用龍捲風,這是能夠[WebSockets的(https://en.wikipedia.org/wiki/WebSocket),爲什麼用戶發送一個獲得狀態的命令?您只需啓動一個線程,以指定的頻率讀取電池狀態,並通過websocket連接自動更新瀏覽器。 – yegorich
@yegorich我知道你的關心。但這只是cmd的一個例子。我還有很多其他的cmd。另一個原因是內部數據變化頻繁得多,但GUI不需要更新爲相同的頻率。第三個原因是這允許其他模塊使用相同的API以自己的頻率請求數據。 –