|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Ctypes wrapper module for Vector CAN Interface on win32/win64 systems |
| 4 | +Authors: Julien Grave <grave.jul@gmail.com>, Christian Sandberg |
| 5 | +""" |
| 6 | +# Import Standard Python Modules |
| 7 | +# ============================== |
| 8 | +import ctypes |
| 9 | +import logging |
| 10 | +import sys |
| 11 | +import time |
| 12 | + |
| 13 | +# Import Modules |
| 14 | +# ============== |
| 15 | +from can import BusABC, Message |
| 16 | +from .exceptions import VectorError |
| 17 | + |
| 18 | +# Define Module Logger |
| 19 | +# ==================== |
| 20 | +LOG = logging.getLogger(__name__) |
| 21 | + |
| 22 | +# Import safely Vector API module for Travis tests |
| 23 | +vxlapi = None |
| 24 | +try: |
| 25 | + from . import vxlapi |
| 26 | +except Exception as exc: |
| 27 | + LOG.warning('Could not import vxlapi: %s', exc) |
| 28 | + |
| 29 | + |
| 30 | +class VectorBus(BusABC): |
| 31 | + """The CAN Bus implemented for the Vector interface.""" |
| 32 | + |
| 33 | + def __init__(self, channel, can_filters=None, poll_interval=0.01, |
| 34 | + bitrate=None, rx_queue_size=256, app_name="CANalyzer", **config): |
| 35 | + """ |
| 36 | + :param list channel: |
| 37 | + The channel indexes to create this bus with. |
| 38 | + Can also be a single integer or a comma separated string. |
| 39 | + :param float poll_interval: |
| 40 | + Poll interval in seconds. |
| 41 | + :param int bitrate: |
| 42 | + Bitrate in bits/s. |
| 43 | + :param int rx_queue_size: |
| 44 | + Number of messages in receive queue. |
| 45 | + :param str app_name: |
| 46 | + Name of application in Hardware Config. |
| 47 | + """ |
| 48 | + if vxlapi is None: |
| 49 | + raise ImportError("The Vector API has not been loaded") |
| 50 | + self.poll_interval = poll_interval |
| 51 | + if isinstance(channel, (list, tuple)): |
| 52 | + self.channels = channel |
| 53 | + elif isinstance(channel, int): |
| 54 | + self.channels = [channel] |
| 55 | + else: |
| 56 | + # Assume comma separated string of channels |
| 57 | + self.channels = [int(ch.strip()) for ch in channel.split(',')] |
| 58 | + self._app_name = app_name.encode() |
| 59 | + self.channel_info = 'Application %s: %s' % ( |
| 60 | + app_name, ', '.join('CAN %d' % (ch + 1) for ch in self.channels)) |
| 61 | + |
| 62 | + vxlapi.xlOpenDriver() |
| 63 | + self.port_handle = vxlapi.XLportHandle(vxlapi.XL_INVALID_PORTHANDLE) |
| 64 | + self.mask = 0 |
| 65 | + # Get channels masks |
| 66 | + for channel in self.channels: |
| 67 | + hw_type = ctypes.c_uint(0) |
| 68 | + hw_index = ctypes.c_uint(0) |
| 69 | + hw_channel = ctypes.c_uint(0) |
| 70 | + vxlapi.xlGetApplConfig(self._app_name, channel, hw_type, hw_index, |
| 71 | + hw_channel, vxlapi.XL_BUS_TYPE_CAN) |
| 72 | + LOG.debug('Channel index %d found', channel) |
| 73 | + mask = vxlapi.xlGetChannelMask(hw_type.value, hw_index.value, |
| 74 | + hw_channel.value) |
| 75 | + LOG.debug('Channel %d, Type: %d, Mask: %d', |
| 76 | + hw_channel.value, hw_type.value, mask) |
| 77 | + self.mask |= mask |
| 78 | + permission_mask = vxlapi.XLaccess() |
| 79 | + vxlapi.xlOpenPort(self.port_handle, self._app_name, self.mask, |
| 80 | + permission_mask, rx_queue_size, |
| 81 | + vxlapi.XL_INTERFACE_VERSION, vxlapi.XL_BUS_TYPE_CAN) |
| 82 | + LOG.debug( |
| 83 | + 'Open Port: PortHandle: %d, PermissionMask: 0x%X', |
| 84 | + self.port_handle.value, permission_mask.value) |
| 85 | + if bitrate: |
| 86 | + if permission_mask.value != self.mask: |
| 87 | + LOG.warning('Can not set bitrate since no init access') |
| 88 | + vxlapi.xlCanSetChannelBitrate(self.port_handle, permission_mask, bitrate) |
| 89 | + self.set_filters(can_filters) |
| 90 | + try: |
| 91 | + vxlapi.xlActivateChannel(self.port_handle, self.mask, |
| 92 | + vxlapi.XL_BUS_TYPE_CAN, 0) |
| 93 | + except VectorError: |
| 94 | + self.shutdown() |
| 95 | + raise |
| 96 | + # Calculate time offset for absolute timestamps |
| 97 | + offset = vxlapi.XLuint64() |
| 98 | + vxlapi.xlGetSyncTime(self.port_handle, offset) |
| 99 | + self._time_offset = time.time() - offset.value / 1000000000.0 |
| 100 | + super(VectorBus, self).__init__() |
| 101 | + |
| 102 | + def set_filters(self, can_filters=None): |
| 103 | + if can_filters: |
| 104 | + # Only one filter per ID type allowed |
| 105 | + if len(can_filters) == 1 or ( |
| 106 | + len(can_filters) == 2 and |
| 107 | + can_filters[0].get("extended") != can_filters[1].get("extended")): |
| 108 | + for can_filter in can_filters: |
| 109 | + try: |
| 110 | + vxlapi.xlCanSetChannelAcceptance( |
| 111 | + self.port_handle, self.mask, |
| 112 | + can_filter["can_id"], can_filter["can_mask"], |
| 113 | + vxlapi.XL_CAN_EXT if can_filter.get("extended") else vxlapi.XL_CAN_STD) |
| 114 | + except VectorError as exc: |
| 115 | + LOG.warning("Could not set filters: %s", exc) |
| 116 | + else: |
| 117 | + LOG.warning("Only one filter per extended or standard ID allowed") |
| 118 | + |
| 119 | + def recv(self, timeout=None): |
| 120 | + end_time = time.time() + timeout if timeout is not None else None |
| 121 | + event = vxlapi.XLevent(0) |
| 122 | + while True: |
| 123 | + event_count = ctypes.c_uint(1) |
| 124 | + try: |
| 125 | + vxlapi.xlReceive(self.port_handle, event_count, event) |
| 126 | + except VectorError as exc: |
| 127 | + if exc.error_code != vxlapi.XL_ERR_QUEUE_IS_EMPTY: |
| 128 | + raise |
| 129 | + else: |
| 130 | + if event.tag == vxlapi.XL_RECEIVE_MSG: |
| 131 | + msg_id = event.tagData.msg.id |
| 132 | + dlc = event.tagData.msg.dlc |
| 133 | + flags = event.tagData.msg.flags |
| 134 | + timestamp = event.timeStamp / 1000000000.0 |
| 135 | + msg = Message( |
| 136 | + timestamp=timestamp + self._time_offset, |
| 137 | + arbitration_id=msg_id & 0x1FFFFFFF, |
| 138 | + extended_id=bool(msg_id & vxlapi.XL_CAN_EXT_MSG_ID), |
| 139 | + is_remote_frame=bool(flags & vxlapi.XL_CAN_MSG_FLAG_REMOTE_FRAME), |
| 140 | + is_error_frame=bool(flags & vxlapi.XL_CAN_MSG_FLAG_ERROR_FRAME), |
| 141 | + dlc=dlc, |
| 142 | + data=event.tagData.msg.data[:dlc]) |
| 143 | + msg.channel = event.chanIndex |
| 144 | + return msg |
| 145 | + if end_time is not None and time.time() > end_time: |
| 146 | + return None |
| 147 | + time.sleep(self.poll_interval) |
| 148 | + |
| 149 | + def send(self, msg, timeout=None): |
| 150 | + message_count = ctypes.c_uint(1) |
| 151 | + msg_id = msg.arbitration_id |
| 152 | + if msg.id_type: |
| 153 | + msg_id |= vxlapi.XL_CAN_EXT_MSG_ID |
| 154 | + flags = 0 |
| 155 | + if msg.is_remote_frame: |
| 156 | + flags |= vxlapi.XL_CAN_MSG_FLAG_REMOTE_FRAME |
| 157 | + xl_event = vxlapi.XLevent() |
| 158 | + xl_event.tag = vxlapi.XL_TRANSMIT_MSG |
| 159 | + xl_event.tagData.msg.id = msg_id |
| 160 | + xl_event.tagData.msg.dlc = msg.dlc |
| 161 | + xl_event.tagData.msg.flags = flags |
| 162 | + for idx, value in enumerate(msg.data): |
| 163 | + xl_event.tagData.msg.data[idx] = value |
| 164 | + vxlapi.xlCanTransmit(self.port_handle, self.mask, message_count, xl_event) |
| 165 | + |
| 166 | + def flush_tx_buffer(self): |
| 167 | + vxlapi.xlCanFlushTransmitQueue(self.port_handle, self.mask) |
| 168 | + |
| 169 | + def shutdown(self): |
| 170 | + vxlapi.xlDeactivateChannel(self.port_handle, self.mask) |
| 171 | + vxlapi.xlClosePort(self.port_handle) |
| 172 | + vxlapi.xlCloseDriver() |
0 commit comments