def try_run(self): watchdog1 = Message(arbitration_id=CANID_BM_WATCHDOG, data=bytearray(MESSAGE_BM_WATCHDOG1.bytes)) watchdog2 = Message(arbitration_id=CANID_BM_WATCHDOG, data=bytearray(MESSAGE_BM_WATCHDOG2.bytes)) start_time = time.time() while self.should_run: self.bus.send(self.bm_channel) time.sleep(0.2) seconds = "0x{:02d}{:02d}487800000000".format( self.track_position // 60, self.track_position % 60) self.bus.send( Message(arbitration_id=CANID_BM_TRACK_TIME, data=bytearray(ba(hex=seconds).bytes))) time.sleep(0.05) self.bus.send(watchdog1) time.sleep(0.02) self.bus.send(watchdog2) if self.bt_is_playing: self.track_position += 1 time.sleep(1.0 - ((time.time() - start_time) % 1.0))
def openFile(self): """ Opens a CAN-D Trace file and loads its data. """ self.controller.open_file_path = QFileDialog.getOpenFileName( self, 'Open File', './', filter= "CAN-D Trace Files(*.cand);;All Files(*.*);;Text Files(*.txt)")[0] if self.controller.open_file_path is not '': try: file = open(self.controller.open_file_path, "r") lines = file.readlines() for l in lines: frame_id, payload = parse_line(l) msg = Message() msg.arbitration_id = frame_id msg.dlc = len(payload) msg.data = bytes(payload) self.insertTrace(msg) except: popup = QtWidgets.QMessageBox.critical( self, "Error", "Failed to open CAN-D trace file. \n\nFile must be of type .cand or .txt" ) return
def test_general(self): messages = [ Message(timestamp=50.0), Message(timestamp=50.0), Message(timestamp=50.0 + 0.05), Message(timestamp=50.0 + 0.05 + 0.08), Message(timestamp=50.0), # back in time ] sync = MessageSync(messages, gap=0.0) start = time() collected = [] timings = [] for message in sync: collected.append(message) now = time() timings.append(now - start) start = now self.assertMessagesEqual(messages, collected) self.assertEqual(len(timings), len(messages), "programming error in test code") self.assertTrue(0.0 <= timings[0] < inc(0.005), str(timings[0])) self.assertTrue(0.0 <= timings[1] < inc(0.005), str(timings[1])) self.assertTrue(0.045 <= timings[2] < inc(0.055), str(timings[2])) self.assertTrue(0.075 <= timings[3] < inc(0.085), str(timings[3])) self.assertTrue(0.0 <= timings[4] < inc(0.005), str(timings[4]))
def _ics_msg_to_message(self, ics_msg): is_fd = ics_msg.Protocol == ics.SPY_PROTOCOL_CANFD if is_fd: if ics_msg.ExtraDataPtrEnabled: data = ics_msg.ExtraDataPtr[:ics_msg.NumberBytesData] else: data = ics_msg.Data[:ics_msg.NumberBytesData] return Message( timestamp=self._get_timestamp_for_msg(ics_msg), arbitration_id=ics_msg.ArbIDOrHeader, data=data, dlc=ics_msg.NumberBytesData, is_extended_id=bool(ics_msg.StatusBitField & ics.SPY_STATUS_XTD_FRAME), is_fd=is_fd, is_remote_frame=bool(ics_msg.StatusBitField & ics.SPY_STATUS_REMOTE_FRAME), error_state_indicator=bool(ics_msg.StatusBitField3 & ics.SPY_STATUS3_CANFD_ESI), bitrate_switch=bool(ics_msg.StatusBitField3 & ics.SPY_STATUS3_CANFD_BRS), channel=ics_msg.NetworkID) else: return Message(timestamp=self._get_timestamp_for_msg(ics_msg), arbitration_id=ics_msg.ArbIDOrHeader, data=ics_msg.Data[:ics_msg.NumberBytesData], dlc=ics_msg.NumberBytesData, is_extended_id=bool(ics_msg.StatusBitField & ics.SPY_STATUS_XTD_FRAME), is_fd=is_fd, is_remote_frame=bool(ics_msg.StatusBitField & ics.SPY_STATUS_REMOTE_FRAME), channel=ics_msg.NetworkID)
def transmitMessage(self, transmit_message): """ Transmits the message to the CAN device and populates the transmit table. Arguments: transmit_message {[Message]} -- A message object containing the CAN data. """ # Build the Message object message = Message() message.arbitration_id = int(transmit_message.can_id, 16) message.dlc = transmit_message.dlc try: message.data = bytes.fromhex(transmit_message.data) except: return "Data field is not in valid hexadecimal form." # If there is a task for a given can_id, cancel that task if transmit_message.can_id in self.tasks: self.tasks[transmit_message.can_id].cancel() loop = asyncio.get_event_loop() if transmit_message.cycle_time is "" or transmit_message.cycle_time is None: loop.create_task( self.transmit_and_append(message, transmit_message)) else: # Calculate the cycle time for transmitting messages in ms cycle_time = int(transmit_message.cycle_time) / 1000 # Create a task, which is re-scheduled every cycle_time ms self.tasks[transmit_message.can_id] = loop.create_task( do_stuff_every_x_seconds( cycle_time, lambda: self.transmit_and_append( message, transmit_message)))
def connect(self): """Connect to the device""" msg = Message(arbitration_id=self._tx_id, is_extended_id=self._extended_id, data=bytes(8)) msg.data[0] = XCPCommands.CONNECT.value msg.data[1] = self._conn_mode # spec, p138 if self._conn_mode == 0: timeout_s = xcp_timeout_s( 1) # some bootloader require fast startup else: timeout_s = self._timeout_s(7) while True: self._drain_bus() try: self._bus.send(msg) response = self._wait_for_rx(timeout_s) except CanError as e: if not XCPFlash._is_can_device_tx_queue_full(e): raise e response = None time.sleep(self._timeout_s(7)) if None is response: continue if response.data[0] == XCPResponses.ERROR.value: raise ConnectionAbortedError(response.data[1]) break self._pgm = (response.data[1] & 0b00010000) != 0 self._stm = (response.data[1] & 0b00001000) != 0 self._daq = (response.data[1] & 0b00000100) != 0 self._cal_pag = (response.data[1] & 0b00000001) != 0 if not self._pgm: raise ConnectionError( "Flash programming not supported by the connected device") self._max_data = response.data[4] << 8 self._max_data += response.data[5] self._byte_order = response.data[2] & 1 if not self._ag_override: self._ag = 1 << ((response.data[2] >> 1) & 0x3) if self._byte_order == self.sys_byte_order(): self._swap16 = lambda x: x & 0xffff self._swap32 = lambda x: x & 0xffffffff else: self._swap16 = self.swap16 self._swap32 = self.swap32
def simple_send_periodic(bus): """ Sends a message every 20ms with no explicit timeout Sleeps for 2 seconds then stops the task. """ print("Try to Starting to send a message periodic every 200ms for 10s...") msg = Message(arbitration_id=0x0cf02200, data=[0, 1, 3, 1, 4, 1], extended_id=False) task = bus.send_periodic(msg, 0.20, store_task=False) assert isinstance(task, can.CyclicSendTaskABC) time.sleep(2) # second print("Trying to change data") msg.data[0] = 99 task.modify_data(msg) time.sleep(2) task.stop() print("stop cyclic send!") time.sleep(1) task.start() print('starting again') time.sleep(1) print("done") time.sleep(5) task.stop()
def _recv_internal(self, timeout=None): """ Read a message from kvaser device and return whether filtering has taken place. """ arb_id = ctypes.c_long(0) data = ctypes.create_string_buffer(64) dlc = ctypes.c_uint(0) flags = ctypes.c_uint(0) timestamp = ctypes.c_ulong(0) if timeout is None: # Set infinite timeout # http://www.kvaser.com/canlib-webhelp/group___c_a_n.html#ga2edd785a87cc16b49ece8969cad71e5b timeout = 0xFFFFFFFF else: timeout = int(timeout * 1000) log.log( 9, 'Reading for %d ms on handle: %s' % (timeout, self._read_handle)) status = canReadWait( self._read_handle, ctypes.byref(arb_id), ctypes.byref(data), ctypes.byref(dlc), ctypes.byref(flags), ctypes.byref(timestamp), timeout # This is an X ms blocking read ) if status == canstat.canOK: #log.debug('read complete -> status OK') data_array = data.raw flags = flags.value is_extended = bool(flags & canstat.canMSG_EXT) is_remote_frame = bool(flags & canstat.canMSG_RTR) is_error_frame = bool(flags & canstat.canMSG_ERROR_FRAME) is_fd = bool(flags & canstat.canFDMSG_FDF) bitrate_switch = bool(flags & canstat.canFDMSG_BRS) error_state_indicator = bool(flags & canstat.canFDMSG_ESI) msg_timestamp = timestamp.value * TIMESTAMP_FACTOR rx_msg = Message(arbitration_id=arb_id.value, data=data_array[:dlc.value], dlc=dlc.value, extended_id=is_extended, is_error_frame=is_error_frame, is_remote_frame=is_remote_frame, is_fd=is_fd, bitrate_switch=bitrate_switch, error_state_indicator=error_state_indicator, channel=self.channel, timestamp=msg_timestamp + self._timestamp_offset) rx_msg.flags = flags rx_msg.raw_timestamp = msg_timestamp #log.debug('Got message: %s' % rx_msg) return rx_msg, self._is_filtered else: #log.debug('read complete -> status not okay') return None, self._is_filtered
def program_start(self): msg = Message(arbitration_id=self._tx_id, is_extended_id=self._extended_id, data=bytes(8)) msg.data[0] = XCPCommands.PROGRAM_START.value timeout_s = self._timeout_s(1) count = 0 while True: self._drain_bus() self._bus.send(msg) response = self._wait_for_rx(timeout_s) if None is response: if count >= 3: raise ConnectionError(f'PROGRAM_START failed timeout') else: self._sync_or_die() count += 1 continue if response.data[0] == XCPResponses.ERROR.value: if response.data[1] == XCPErrors.ERR_CMD_BUSY: timeout_s = self._timeout_s(7) count = 0 continue else: raise ConnectionError( f'PROGRAM_START failed with error code: 0x{response.data[1]:02x}' ) break prog_comm_mode = response.data[2] # if prog_comm_mode != self._conn_mode: # if self._initial_comm_mode != self._conn_mode: # # prevent a ring around the rosy situation # raise ConnectionError(f'communication mode already switch once from {self._initial_comm_mode} to {self._conn_mode} with new request for {prog_comm_mode}') # self._conn_mode = prog_comm_mode # # fix me: do this automatically # raise ConnectionError(f'device requires comm mode 0x{prog_comm_mode:02x} for programming') self._max_block_size = response.data[4] self._max_cto = response.data[3] if self._max_cto == 0 or self._max_cto % self._ag: raise ConnectionError( f'inconsistent device params: MAX_CTO_PGM={self._max_cto}, ADDRESS_GRANULARITY={self._ag}' ) self._queue_size = response.data[6] self._min_separation_time_us = 100 * response.data[5] if not self._master_block_mode_supported_override: self._master_block_mode_supported = (response.data[2] & 1) == 1
def ship_frame(self, id, addr, value): valuebytes = struct.pack(">i", value) data = bytearray([0x00, 0xFA, addr[0], addr[1]]) data = data + valuebytes frame = Message(extended_id=False, data=data) frame.arbitration_id = id frame.timestamp = time.time() frame.dlc = 8 return frame
async def _send_data(self, log_path, message_sleep_time=0.00): with open(log_path, "r") as log_file: for log_line in log_file.readlines(): frame_id, payload = parse_line(log_line) msg = Message() msg.arbitration_id = frame_id msg.dlc = len(payload) msg.data = bytes(payload) self.data_queue.put_nowait(msg) await asyncio.sleep(message_sleep_time)
def send(self): """The loop for sending.""" print("Start to send messages") start_time = time.time() while not self.stop_send.is_set(): msg = Message(arbitration_id=self.send_id, data=self.cmd_data) msg.timestamp = time.time() - start_time self.bus.send(msg) # print(f"tx: {msg}") time.sleep(0.001) print("Stopped sending messages")
def test_update_ecu(can, logger): logger.info("Testing update_ecu...") test1 = Message(arbitration_id=12, data=[0, 128, 255, 0, 0]) can._update_ecu(test1) assert can.ecus["throttle"].get_state("ThrottlePos") == 128 assert can.ecus["throttle"].get_state("BotsSense") == 255 test2 = Message(arbitration_id=12, data=[0, 255, 0, 0, 0]) can._update_ecu(test2) assert can.ecus["throttle"].get_state("ThrottlePos") == 255
def test_send(channel): bus = ZL_motor_control(channel, 115200, 115200, {1}) bus.open_bus() bus.bus.ser.setDTR(False) msg = Message(extended_id=False) msg.arbitration_id = 0x01 msg.dlc = 8 msg.data = [0x00, 0xfa, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0f] bus.send(msg) bus.logger.debug("send finished!") bus.close_bus() bus.logger.debug("\n\n")
def recv(self, timeout=None): """ Read a message from kvaser device. """ arb_id = ctypes.c_long(0) data = ctypes.create_string_buffer(8) dlc = ctypes.c_uint(0) flags = ctypes.c_uint(0) timestamp = ctypes.c_ulong(0) if timeout is None: # Set infinite timeout # http://www.kvaser.com/canlib-webhelp/group___c_a_n.html#ga2edd785a87cc16b49ece8969cad71e5b timeout = 0xFFFFFFFF else: timeout = int(timeout * 1000) log.log( 9, 'Reading for %d ms on handle: %s' % (timeout, self._read_handle)) status = canReadWait( self._read_handle, ctypes.byref(arb_id), ctypes.byref(data), ctypes.byref(dlc), ctypes.byref(flags), ctypes.byref(timestamp), timeout # This is an X ms blocking read ) if status == canstat.canOK: #log.debug('read complete -> status OK') data_array = data.raw flags = flags.value is_extended = bool(flags & canstat.canMSG_EXT) is_remote_frame = bool(flags & canstat.canMSG_RTR) is_error_frame = bool(flags & canstat.canMSG_ERROR_FRAME) msg_timestamp = self.__convert_timestamp(timestamp.value) rx_msg = Message(arbitration_id=arb_id.value, data=data_array[:dlc.value], dlc=dlc.value, extended_id=is_extended, is_error_frame=is_error_frame, is_remote_frame=is_remote_frame, timestamp=msg_timestamp) rx_msg.flags = flags rx_msg.raw_timestamp = timestamp.value / (1000000.0 / TIMESTAMP_RESOLUTION) #log.debug('Got message: %s' % rx_msg) return rx_msg else: #log.debug('read complete -> status not okay') return None
def execute(self, command, **kwargs): """Execute a command Builds the can-message to execute the given command and sends it to the device. :param command: The xcp-command to be executed :param kwargs: Needed arguments for the command. :command SET_MTA: 'addr_ext' and 'addr' :command PROGRAM_CLEAR: 'range' :command PROGRAM: 'size' and 'data' :return: response of the command if waited for """ msg = Message(arbitration_id=self._tx_id, is_extended_id=False, data=bytes(8)) msg.data[0] = command.value if command == XCPCommands.CONNECT: msg.data[1] = self._conn_mode response = self.send_can_msg(msg) self._max_data = response.data[4] << 8 self._max_data += response.data[5] return response if command == XCPCommands.DISCONNECT: return self.send_can_msg(msg) if command == XCPCommands.SET_MTA: msg.data[3] = kwargs.get('addr_ext', 0) for i in range(4, 8): msg.data[i] = (kwargs['addr'] & (0xFF000000 >> (8 * (i - 4)))) >> (8 * (7 - i)) return self.send_can_msg(msg) if command == XCPCommands.PROGRAM_START: response = self.send_can_msg(msg) max_dto_prg = response.data[3] max_bs = response.data[4] self._data_len = (max_dto_prg - 2) * max_bs self._max_data_prg = max_dto_prg - 2 return response if command == XCPCommands.PROGRAM_CLEAR: for i in range(4, 8): msg.data[i] = (kwargs['range'] & (0xFF000000 >> (8 * (i - 4)))) >> (8 * (7 - i)) return self.send_can_msg(msg) if command == XCPCommands.PROGRAM or command == XCPCommands.PROGRAM_NEXT: msg.data[1] = kwargs["size"] position = 2 for data in kwargs["data"]: msg.data[position] = data position += 1 return self.send_can_msg(msg, kwargs['size'] <= self._max_data_prg) if command == XCPCommands.PROGRAM_RESET: return self.send_can_msg(msg)
def encode_instpanel(self, message, is_menu): bitstring = self.encode_string(message).ljust(96, '0') if is_menu: line1 = self.instpanel_menu_prefix1 + bitstring[:48] line2 = self.instpanel_menu_prefix2 + bitstring[48:] else: line1 = self.instpanel_text_prefix1 + bitstring[:48] line2 = self.instpanel_text_prefix2 + bitstring[48:] can1 = Message(arbitration_id=CANID_BM_TEXT_MESSAGE, data=self.bitstring_to_bytes(line1)) can2 = Message(arbitration_id=CANID_BM_TEXT_MESSAGE, data=self.bitstring_to_bytes(line2)) return can1, can2
def test_recv(channel, id_list): bus = ZL_motor_control(channel, 115200, 115200, id_list) bus.open_bus() bus.bus.ser.setDTR(False) msg = Message(extended_id=False) msg.arbitration_id = 0x01 msg.dlc = 8 msg.data = [0x00, 0xfa, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0f] bus.send(msg) recv_msg = bus.recv() bus.logger.debug("test_recv收到的消息是") bus.logger.debug(recv_msg) bus.close_bus() bus.logger.debug("\n")
def _sync_or_die(self): msg = Message(arbitration_id=self._tx_id, is_extended_id=self._extended_id, data=bytes(8)) msg.data[0] = XCPCommands.SYNCH.value self._drain_bus() self._bus.send(msg) response = self._wait_for_rx(self._timeout_s(7)) if None is response: raise ConnectionError("timeout SYNCH") if response.data[0] == XCPResponses.ERROR.value: if response.data[1] != XCPErrors.ERR_CMD_SYNCH: raise ConnectionAbortedError(response.data[1])
def _process_cts(self, msg): logger.debug("_process_cts") logger.debug("MIL8: cts message is: %s" % msg) logger.debug("MIL8: len(pdu-send-buffer) = %d" % len(self._incomplete_transmitted_pdus[0][23])) if msg.arbitration_id.pgn.pdu_specific in self._incomplete_transmitted_pdus: if msg.arbitration_id.source_address in self._incomplete_transmitted_pdus[ msg.arbitration_id.pgn.pdu_specific]: # Next packet number in CTS message (Packet numbers start at 1 not 0) start_index = msg.data[2] - 1 # Using total number of packets in CTS message end_index = start_index + msg.data[1] for _msg in self._incomplete_transmitted_pdus[ msg.arbitration_id.pgn.pdu_specific][ msg.arbitration_id. source_address][start_index:end_index]: logger.debug("MIL8: msg=%s" % (_msg)) # TODO: Needs to be pacing if we get this working... try: # Shouldent send a J1939 PDU as a CAN Message unless we are careful canMessage = Message( arbitration_id=_msg.arbitration_id, data=_msg.data) self.can_bus.send(canMessage) except CanError: if self._ignore_can_send_error: pass raise logger.debug("MIL8: _process_cts complete")
def sender(event: threading.Event) -> None: event.wait() sender_socket = create_socket() bind_socket(sender_socket, "vcan0") msg = Message(arbitration_id=0x01, data=b"\x01\x02\x03") sender_socket.send(build_can_frame(msg)) print("Sender sent a message.")
def _recv_internal(self, timeout): if timeout != self.serialPortOrig.timeout: self.serialPortOrig.timeout = timeout canId = None remote = False extended = False frame = [] # First read what is already in the receive buffer while (self.serialPortOrig.in_waiting and self.LINE_TERMINATOR not in self._buffer): self._buffer += self.serialPortOrig.read(1) # If we still don't have a complete message, do a blocking read if self.LINE_TERMINATOR not in self._buffer: self._buffer += self.serialPortOrig.read_until(self.LINE_TERMINATOR) if self.LINE_TERMINATOR not in self._buffer: # Timed out return None, False readStr = self._buffer.decode() del self._buffer[:] if not readStr: pass elif readStr[0] == 'T': # extended frame canId = int(readStr[1:9], 16) dlc = int(readStr[9]) extended = True for i in range(0, dlc): frame.append(int(readStr[10 + i * 2:12 + i * 2], 16)) elif readStr[0] == 't': # normal frame canId = int(readStr[1:4], 16) dlc = int(readStr[4]) for i in range(0, dlc): frame.append(int(readStr[5 + i * 2:7 + i * 2], 16)) elif readStr[0] == 'r': # remote frame canId = int(readStr[1:4], 16) dlc = int(readStr[4]) remote = True elif readStr[0] == 'R': # remote extended frame canId = int(readStr[1:9], 16) dlc = int(readStr[9]) extended = True remote = True if canId is not None: msg = Message(arbitration_id=canId, is_extended_id=extended, timestamp=time.time(), # Better than nothing... is_remote_frame=remote, dlc=dlc, data=frame) return msg, False return None, False
def _recv_can(self) -> Optional[Message]: xl_event = xlclass.XLevent() event_count = ctypes.c_uint(1) self.xldriver.xlReceive(self.port_handle, event_count, xl_event) if xl_event.tag != xldefine.XL_EventTags.XL_RECEIVE_MSG: self.handle_can_event(xl_event) return None msg_id = xl_event.tagData.msg.id dlc = xl_event.tagData.msg.dlc flags = xl_event.tagData.msg.flags timestamp = xl_event.timeStamp * 1e-9 channel = self.index_to_channel.get(xl_event.chanIndex) return Message( timestamp=timestamp + self._time_offset, arbitration_id=msg_id & 0x1FFFFFFF, is_extended_id=bool( msg_id & xldefine.XL_MessageFlagsExtended.XL_CAN_EXT_MSG_ID), is_remote_frame=bool( flags & xldefine.XL_MessageFlags.XL_CAN_MSG_FLAG_REMOTE_FRAME), is_error_frame=bool( flags & xldefine.XL_MessageFlags.XL_CAN_MSG_FLAG_ERROR_FRAME), is_rx=not bool( flags & xldefine.XL_MessageFlags.XL_CAN_MSG_FLAG_TX_COMPLETED), is_fd=False, dlc=dlc, data=xl_event.tagData.msg.data[:dlc], channel=channel, )
def recv(self, timeout=0.3): timepass = 0 timestamp = time.time() while (timepass < timeout): try: rx_byte = self.bus.ser.read() # print('rx_byte is :',ord(rx_byte)) except: # print("rx_byte is None") return None if len(rx_byte) and ord(rx_byte) == 0xAA: # print("begin to get details") s = bytearray(self.bus.ser.read()) # print("extended_id",s) extended_id = struct.unpack('?', s) s = bytearray(self.bus.ser.read()) remote_frame = struct.unpack('?', s) dlc = ord(self.bus.ser.read()) s = bytearray(self.bus.ser.read(4)) arb_id = (struct.unpack('>I', s))[0] data = self.bus.ser.read(dlc) return Message(timestamp=timestamp / 1000, arbitration_id=arb_id, dlc=dlc, data=data, extended_id=extended_id) timepass = time.time() - timestamp print(" read failed!") return False
def send_data_to_bus(self, data, config, data_check=True, raise_exception=False): try: self.__bus.send( Message(arbitration_id=config["nodeId"], is_extended_id=config.get( "isExtendedId", self.DEFAULT_EXTENDED_ID_FLAG), is_fd=config.get("isFd", self.DEFAULT_FD_FLAG), bitrate_switch=config.get( "bitrateSwitch", self.DEFAULT_BITRATE_SWITCH_FLAG), data=data, check=data_check)) return True except (ValueError, TypeError) as e: log.error("[%s] Wrong CAN message data: %s", self.get_name(), str(e)) except CanError as e: log.error("[%s] Failed to send CAN message: %s", self.get_name(), str(e)) if raise_exception: raise e else: self.__on_bus_error(e) return False
def send_data(): with open("output.CAN", "rb") as canfile: messages = iter(partial(canfile.read, 16), b'') ids = set() # print(header.hex(), decode2(header)) time = 1 prev_time_in_ms = 0 for chunk in islice(messages, 99999999999999999): is_service, time_in_minutes, time_in_milliseconds, message_id, message = decode2( chunk) dt = time_in_milliseconds - prev_time_in_ms # time.sleep(new_time - dt) if (dt) < 0: dt = 1 time += dt delta = datetime.timedelta(milliseconds=time) prev_time_in_ms = time_in_milliseconds date = str(delta)[:-3] if len(date) < 8: continue result = "%s %s %s %s\r\n" % (date, "N" if is_service else "R", message_id, " ".join( chunks(message, 2))) msg = Message(arbitration_id=int(message_id, 16), data=list( map(lambda x: int(x, 16), chunks(message, 2))), extended_id=True) bus.send(msg) print(msg) sleep(dt / 1000)
def generate_message(arbitration_id): """ Generates a new message with the given ID, some random data and a non-extended ID. """ data = bytearray([random.randrange(0, 2**8 - 1) for _ in range(8)]) return Message(arbitration_id=arbitration_id, data=data, extended_id=False)
def _recv_internal(self, timeout): raw_msg = MessageExStruct() end_time = time.time() + timeout if timeout is not None else None while True: try: iscan.isCAN_ReceiveMessageEx(self.channel, ctypes.byref(raw_msg)) except IscanError as e: if e.error_code != 8: # An error occurred raise if end_time is not None and time.time() > end_time: # No message within timeout return None, False # Sleep a short time to avoid hammering time.sleep(self.poll_interval) else: # A message was received break msg = Message(arbitration_id=raw_msg.message_id, extended_id=bool(raw_msg.is_extended), timestamp=time.time(), # Better than nothing... is_remote_frame=bool(raw_msg.remote_req), dlc=raw_msg.data_len, data=raw_msg.data[:raw_msg.data_len], channel=self.channel.value) return msg, False
def sender(event): event.wait() sender_socket = create_socket() bind_socket(sender_socket, 'vcan0') msg = Message(arbitration_id=0x01, data=b'\x01\x02\x03') sender_socket.send(build_can_frame(msg)) print("Sender sent a message.")
def _recv_internal(self, timeout): try: if len(self._rx_queue) == 0: fr = self.__session_receive.frames.read(4, timeout=0) for f in fr: self._rx_queue.append(f) can_frame = self._rx_queue.pop(0) # Timestamp should be converted from raw frame format(100ns increment from(12:00 a.m. January 1 1601 Coordinated # Universal Time (UTC)) to epoch time(number of seconds from January 1, 1970 (midnight UTC/GMT)) msg = Message( timestamp=can_frame.timestamp / 10000000.0 - 11644473600, channel=self.channel, is_remote_frame=can_frame.type == constants.FrameType.CAN_REMOTE, is_error_frame=can_frame.type == constants.FrameType.CAN_BUS_ERROR, is_fd=( can_frame.type == constants.FrameType.CANFD_DATA or can_frame.type == constants.FrameType.CANFDBRS_DATA ), bitrate_switch=can_frame.type == constants.FrameType.CANFDBRS_DATA, is_extended_id=can_frame.identifier.extended, # Get identifier from CanIdentifier structure arbitration_id=can_frame.identifier.identifier, dlc=len(can_frame.payload), data=can_frame.payload, ) return msg, self._filters is None except Exception as e: # print('Error: ', e) return None, self._filters is None