def __init__(self, ui_queue, db_queue=None, enable_ems=False): threading.Thread.__init__(self) bic0 = Bic('bic0') battery0 = Battery('battery0') pv0 = PV('pv0') rm0 = RM('rm0') self.dev = { 'bic' : (bic0,), 'battery': (battery0,), 'pv' : (pv0,), 'rm' : (rm0,), } self.rtc = RTC(dev=self.dev, enable_ems=enable_ems) self.rtc.ui_queue = ui_queue self.api = Application(dev=self.dev, rtc=self.rtc) self.api.listen(address='0.0.0.0', port=8888) for category, devs in self.dev.items(): for dev in devs: dev.ui_queue = ui_queue dev.db_queue = db_queue
class MainThread(threading.Thread): def __init__(self, ui_queue, db_queue=None, enable_ems=False): threading.Thread.__init__(self) bic0 = Bic('bic0') battery0 = Battery('battery0') pv0 = PV('pv0') rm0 = RM('rm0') self.dev = { 'bic' : (bic0,), 'battery': (battery0,), 'pv' : (pv0,), 'rm' : (rm0,), } self.rtc = RTC(dev=self.dev, enable_ems=enable_ems) self.rtc.ui_queue = ui_queue self.api = Application(dev=self.dev, rtc=self.rtc) self.api.listen(address='0.0.0.0', port=8888) for category, devs in self.dev.items(): for dev in devs: dev.ui_queue = ui_queue dev.db_queue = db_queue def run(self): import errno import functools import tornado.ioloop import socket import struct io_loop = tornado.ioloop.IOLoop.current() 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) can_message = CAN_Message() # parse the message can_message.data0.bytes.b0 = data[0] can_message.data0.bytes.b1 = data[1] can_message.data1.bytes.b0 = data[2] can_message.data1.bytes.b1 = data[3] can_message.data2.bytes.b0 = data[4] can_message.data2.bytes.b1 = data[5] can_message.index = data[6] if can_id == self.api.dev['rm'][0].can_id_dev: self.dev['rm'][0].update_regs_from_CANbus_message(can_message) elif can_id == self.api.dev['bic'][0].can_id_dev: self.dev['bic'][0].update_regs_from_CANbus_message(can_message) elif can_id == self.api.dev['battery'][0].can_id_dev: self.dev['battery'][0].update_regs_from_CANbus_message(can_message) elif can_id == self.api.dev['pv'][0].can_id_dev: self.dev['pv'][0].update_regs_from_CANbus_message(can_message) 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 'Linux' in platform(): sock = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW) if 'arm' in platform(): sock.bind(('can0',)) else: sock.bind(('vcan0',)) sock.setblocking(0) callback = functools.partial(connection_ready, sock) io_loop.add_handler(sock.fileno(), callback, io_loop.READ) io_loop.start()