Last active
April 16, 2018 05:43
-
-
Save zhanglongqi/3a1ddf90d3168c6275c2 to your computer and use it in GitHub Desktop.
Get socketcan message using tornado IOloop which uses epoll (Linux) or kqueue (BSD and Mac OS X) if they are available, or else fall back on select().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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): | |
| try: | |
| cf, addr = sock.recvfrom(can_frame_size) | |
| except BlockingIOError: | |
| self.logger.debug('Captured no data, socket in non-blocking mode.') | |
| return None | |
| except socket.timeout: | |
| self.logger.debug('Captured no data, socket read timed out.') | |
| return None | |
| 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment