Python can.Message() Examples
The following are 30
code examples of can.Message().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
can
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: funcTest_Uds_withConfigTool.py From python-uds with MIT License | 6 votes |
def callback_onReceive_multiFrameResponse_noBs(msg): global payload # print("Received Id: " + str(msg.arbitration_id)) # print("Data: " + str(msg.data)) N_PCI = ((msg.data[0] & 0xf0) >> 4) outMsg = can.Message() outMsg.arbitration_id = 0x650 if(N_PCI == 0): outMsg.data = [0x10, 19] + test2Response[0:6] bus1.send(outMsg) time.sleep(0.01) if(N_PCI == 3): outMsg.data = [0x21] + test2Response[6:13] bus1.send(outMsg) time.sleep(0.01) outMsg.data = [0x22] + test2Response[13:19] + [0] bus1.send(outMsg) time.sleep(0.01)
Example #2
Source File: electronic_control_unit.py From j1939 with MIT License | 6 votes |
def send_message(self, can_id, data): """Send a raw CAN message to the bus. This method may be overridden in a subclass if you need to integrate this library with a custom backend. It is safe to call this from multiple threads. :param int can_id: CAN-ID of the message (always 29-bit) :param data: Data to be transmitted (anything that can be converted to bytes) :raises can.CanError: When the message fails to be transmitted """ if not self._bus: raise RuntimeError("Not connected to CAN bus") msg = can.Message(extended_id=True, arbitration_id=can_id, data=data ) with self._send_lock: self._bus.send(msg) # TODO: check error receivement
Example #3
Source File: CANData.py From CANalyzat0r with GNU General Public License v3.0 | 6 votes |
def readPacketAsync(self): """ Read a packet from the queue using the SocketCAN interface **and a timeout**. :return: A packet as can.Message object or None of no packet was received """ # If no packet is received within timeout second --> break # this is used to be able to stop sniffing processes which will then # use nonblocking recv-calls # self.iface.socket.settimeout(self.timeout) # If no packet is received withing the timeout # return no data try: p = self.iface.recv(timeout=self.timeout) return p except TimeoutException: return None
Example #4
Source File: functest_uds.py From python-uds with MIT License | 6 votes |
def singleFrameResponse_target(): global bus working = True startTime = time() canMsg = can.Message(arbitration_id=0x650) clearReceiveBuffer() while working: currTime = time() if (currTime - startTime) > 5: working = False recvMsg = getNextReceivedMessage() if recvMsg is not None: canMsg.data = [0x04, 0x62, 0xF1, 0x8C, 0x01] bus.send(canMsg) working = False
Example #5
Source File: network.py From canopen with MIT License | 6 votes |
def __init__(self, can_id, data, period, bus, remote=False): """ :param int can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param float period: Seconds between each message :param can.BusABC bus: python-can bus to use for transmission """ self.bus = bus self.period = period self.msg = can.Message(is_extended_id=can_id > 0x7FF, arbitration_id=can_id, data=data, is_remote_frame=remote) self._task = None self._start()
Example #6
Source File: can_actions.py From caringcaribou with GNU General Public License v3.0 | 6 votes |
def send(self, data, arb_id=None, is_extended=None, is_error=False, is_remote=False): if len(data) > 8: raise IndexError("Invalid CAN message length: {0}".format(len(data))) # Fallback to default arbitration ID (self.arb_id) if no other ID is specified if arb_id is None: if self.arb_id is None: raise ValueError("Arbitration ID must be set through either 'arb_id' argument or self.arb_id") arb_id = self.arb_id # Force extended flag if it is unspecified and arbitration ID is larger than the standard format allows if is_extended is None: is_extended = arb_id > ARBITRATION_ID_MAX msg = can.Message(arbitration_id=arb_id, data=data, is_extended_id=is_extended, is_error_frame=is_error, is_remote_frame=is_remote) self.bus.send(msg)
Example #7
Source File: test_tester.py From cantools with MIT License | 6 votes |
def test_flush_input(self): """Test the flush_input method. """ tester, can_bus = setup_tester('Node1') tester.start() can_bus.input_message(can.Message(arbitration_id=0x101, data=b'\x00\x00')) can_bus.input_message(can.Message(arbitration_id=0x102, data=b'\x00\x00\x00')) time.sleep(0.1) self.assertIsNone(tester.flush_input()) message = tester.expect('Message1', timeout=0.0) self.assertIsNone(message) tester.stop()
Example #8
Source File: tester.py From cantools with MIT License | 6 votes |
def __init__(self, database, can_bus, input_list, input_queue, decode_choices, scaling, padding): super(Message, self).__init__() self.database = database self._can_bus = can_bus self._input_queue = input_queue self.decode_choices = decode_choices self.scaling = scaling self.padding = padding self._input_list = input_list self.enabled = True self._can_message = None self._periodic_task = None self.update({signal.name: 0 for signal in database.signals})
Example #9
Source File: can_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
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
Example #10
Source File: bootload.py From cyflash with BSD 2-Clause "Simplified" License | 6 votes |
def make_session(args, checksum_type): if args.serial: import serial ser = serial.Serial(args.serial, args.serial_baudrate, timeout=args.timeout) ser.flushInput() # need to clear any garbage off the serial port ser.flushOutput() transport = protocol.SerialTransport(ser, args.verbose) elif args.canbus: import can # Remaining configuration options should follow python-can practices canbus = can.interface.Bus(bustype=args.canbus, channel=args.canbus_channel, bitrate=args.canbus_baudrate) # Wants timeout in ms, we have it in s transport = protocol.CANbusTransport(canbus, args.canbus_id, int(args.timeout * 1000), args.canbus_echo, args.canbus_wait) transport.MESSAGE_CLASS = can.Message else: raise BootloaderError("No valid interface specified") try: checksum_func = checksum_types[checksum_type] except KeyError: raise BootloaderError("Invalid checksum type: %d" % (checksum_type,)) return protocol.BootloaderSession(transport, checksum_func)
Example #11
Source File: test_can_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_rpc_with_hex_data_in_params(self): self._create_connector("rpc.json") config = self.config["devices"][1]["serverSideRpc"][0] hex_data = "1234 abcd" self.assertNotEqual(hex_data, config["dataInHex"]) self.connector.server_side_rpc_handler({"device": self.config["devices"][1]["name"], "data": { "id": 1, "method": config["method"], "params": { "dataInHex": hex_data } }}) actual_message = self.bus.recv(1) self.assertTrue(actual_message.equals(Message(arbitration_id=config["nodeId"], is_fd=config["isFd"], bitrate_switch=config["bitrateSwitch"], data=bytearray.fromhex(hex_data), timestamp=actual_message.timestamp, channel=actual_message.channel)))
Example #12
Source File: test_can_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_rpc_with_hex_data_in_config(self): self._create_connector("rpc.json") config = self.config["devices"][0]["serverSideRpc"][0] self.connector.server_side_rpc_handler({"device": self.config["devices"][0]["name"], "data": { "id": 1, "method": config["method"] }}) actual_message = self.bus.recv(1) self.assertTrue(actual_message.equals(Message(arbitration_id=config["nodeId"], is_fd=config["isFd"], bitrate_switch=config["bitrateSwitch"], data=bytearray.fromhex(config["dataInHex"]), timestamp=actual_message.timestamp, channel=actual_message.channel)))
Example #13
Source File: test_can_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_string_attribute_and_custom_device_type(self): self._create_connector("ts_and_attr.json") device_name = self.config["devices"][0]["name"] config = self.config["devices"][0]["attributes"][0] value_matches = re.search(self.connector.VALUE_REGEX, config["value"]) string_value = ''.join(choice(ascii_lowercase) for _ in range(int(value_matches.group(2)))) can_data = list(config["command"]["value"].to_bytes(config["command"]["length"], config["command"]["byteorder"])) can_data.extend(string_value.encode(value_matches.group(5))) message_count = 5 for _ in range(message_count): self.bus.send(Message(arbitration_id=config["nodeId"], is_fd=config["isFd"], data=can_data)) sleep(1) # Wait while connector process CAN message self.assertEqual(self.gateway.send_to_storage.call_count, message_count) self.gateway.send_to_storage.assert_called_with(self.connector.get_name(), {"deviceName": device_name, "deviceType": self.config["devices"][0]["type"], "attributes": [{"serialNumber": string_value}], "telemetry": []})
Example #14
Source File: test_can_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def test_send_only_on_change_and_default_device_type(self): self._create_connector("ts_and_attr.json") config = self.config["devices"][1]["timeseries"][0] value_matches = re.search(self.connector.VALUE_REGEX, config["value"]) value = randint(0, pow(2, int(value_matches.group(2)))) can_data = list(bytearray.fromhex("0" * 2 * int(value_matches.group(1)))) can_data.extend(value.to_bytes(int(value_matches.group(2)), value_matches.group(3) if value_matches.group( 3) else self.connector.DEFAULT_BYTEORDER)) for _ in range(5): self.bus.send(Message(arbitration_id=config["nodeId"], data=can_data)) sleep(1) self.gateway.send_to_storage.assert_called_once_with(self.connector.get_name(), {"deviceName": self.config["devices"][1]["name"], "deviceType": self.connector._CanConnector__connector_type, "attributes": [], "telemetry": [{config["key"]: value}]})
Example #15
Source File: ItemAdderThread.py From CANalyzat0r with GNU General Public License v3.0 | 5 votes |
def frameToRow(self, frame): """ Converts a can.Message object to a raw value list. This list will be emitted using the signal ``appendRow`` along with the table data and rawData list. :param frame: can.Message CAN frame """ # Extract the data to be displayed id = str(hex(frame.arbitration_id)).replace("0x", "").upper() if len(id) <= 3: neededLength = 3 else: neededLength = 8 while len(id) < neededLength: id = "0" + id # cut "0x" and always use an additional leading zero if needed data = "".join(hex(value)[2:].zfill(2) for value in frame.data).upper() length = frame.dlc timestamp = str(frame.timestamp) if frame.timestamp is not None else "" values = [id, data, length] if self.useTimestamp: values.append(timestamp) self.appendRow.emit(values)
Example #16
Source File: funcTest_Uds_withConfigTool.py From python-uds with MIT License | 5 votes |
def callback_onReceive_singleFrame(msg): #print("Received Id: " + str(msg.arbitration_id)) #print("Data: " + str(msg.data)) response = [0x04, 0x62, 0xF1, 0x8C, 0x01, 0x00, 0x00, 0x00] outMsg = can.Message() outMsg.arbitration_id = 0x650 outMsg.data = response bus1.send(outMsg) time.sleep(1)
Example #17
Source File: python_can.py From pyxcp with GNU General Public License v2.0 | 5 votes |
def transmit(self, payload): frame = Message( arbitration_id = self.parent.can_id_slave.id, is_extended_id = True if self.parent.can_id_slave.is_extended else False, data = payload ) self.bus.send(frame)
Example #18
Source File: functest_uds.py From python-uds with MIT License | 5 votes |
def multiFrameResponse_target(): global bus working = True startTime = time() canMsg = can.Message(arbitration_id=0x650) clearReceiveBuffer() index = 0 response = False while working: currTime = time() if (currTime - startTime) > 50: working = False recvMsg = getNextReceivedMessage() if recvMsg is not None: response = True if response: if index == 0: sleep(0.002) canMsg.data = [0x10, 0x13, 0x62, 0xF1, 0x8C, 0x30, 0x30, 0x30] index = 1 elif index == 1: canMsg.data = [0x21, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30] index = 2 elif index == 2: canMsg.data = [0x22, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00] working = False bus.send(canMsg) sleep(0.020)
Example #19
Source File: funcTest_Uds_withConfigTool.py From python-uds with MIT License | 5 votes |
def callback_onReceive_multiFrameWithWait(msg): print("Received Id: " + str(msg.arbitration_id)) print("Data: " + str(unpack('BBBBBBBB', msg.data))) response = msg.data N_PCI = (response[0] & 0xF0) >> 4 responsePayload = [] outMsg = can.Message() outMsg.arbitration_id = 0x650 if(N_PCI == 1): #print("First frame received, responding CTS") responsePayload = [0x30, 5, 20, 00, 00, 00, 00, 00] outMsg.data = responsePayload bus1.send(outMsg) elif(N_PCI == 2): #print("Consecutive frame received") if( (msg.data[7] == 40) | (msg.data[7] == 75) | (msg.data[7] == 145) | (msg.data[7] == 180) ): #print("End of block, sending CTS") responsePayload = [0x30, 10, 10, 00, 00, 00, 00, 00] outMsg.data = responsePayload bus1.send(outMsg) elif( msg.data[7] == 110 ): #print("End of block, producing a Wait") responsePayload = [0x31, 0, 0, 0, 0, 0, 0, 0] outMsg.data = responsePayload bus1.send(outMsg) time.sleep(0.7) responsePayload = [0x30, 10, 10, 00, 00, 00, 00, 00] outMsg.data = responsePayload bus1.send(outMsg)
Example #20
Source File: funcTest_Uds_withConfigTool.py From python-uds with MIT License | 5 votes |
def callback_onReceive_multiFrameSend(msg): global startTime, lastTime startTime = time.time() #print("Separation time: " + str(startTime - lastTime)) # print("Received Id: " + str(msg.arbitration_id)) #print("Data: " + str(msg.data)) response = msg.data N_PCI = (response[0] & 0xF0) >> 4 responsePayload = [] outMsg = can.Message() outMsg.arbitration_id = 0x650 if(N_PCI == 1): #print("First frame received, responding CTS") responsePayload = [0x30, 5, 5, 00, 00, 00, 00, 00] outMsg.data = responsePayload bus1.send(outMsg) elif(N_PCI == 2): #print("Consecutive frame received") if( (msg.data[7] == 40) | (msg.data[7] == 110) | (msg.data[7] == 180) ): #print("End of block, sending CTS") responsePayload = [0x30, 10, 10, 00, 00, 00, 00, 00] outMsg.data = responsePayload bus1.send(outMsg) lastTime = startTime
Example #21
Source File: obdii_logger.py From PiCAN-Python-examples with MIT License | 5 votes |
def can_tx_task(): # Transmit thread while True: GPIO.output(led,True) # Sent a Engine coolant temperature request msg = can.Message(arbitration_id=PID_REQUEST,data=[0x02,0x01,ENGINE_COOLANT_TEMP,0x00,0x00,0x00,0x00,0x00],extended_id=False) bus.send(msg) time.sleep(0.05) # Sent a Engine RPM request msg = can.Message(arbitration_id=PID_REQUEST,data=[0x02,0x01,ENGINE_RPM,0x00,0x00,0x00,0x00,0x00],extended_id=False) bus.send(msg) time.sleep(0.05) # Sent a Vehicle speed request msg = can.Message(arbitration_id=PID_REQUEST,data=[0x02,0x01,VEHICLE_SPEED,0x00,0x00,0x00,0x00,0x00],extended_id=False) bus.send(msg) time.sleep(0.05) # Sent a Throttle position request msg = can.Message(arbitration_id=PID_REQUEST,data=[0x02,0x01,THROTTLE,0x00,0x00,0x00,0x00,0x00],extended_id=False) bus.send(msg) time.sleep(0.05) GPIO.output(led,False) time.sleep(0.1)
Example #22
Source File: CANData.py From CANalyzat0r with GNU General Public License v3.0 | 5 votes |
def __init__(self, ifaceName, bitrate=500000, fdBitrate=2000000, isFD=False): """ This method initializes the can.Message CAN interface using the passed parameters and the start() method. Please note the active-flag which protects the object from being deleted while being in use. :param ifaceName: Name of the interface as displayed by ``ifconfig -a`` :param bitrate: Desired bitrate of the interface """ self.ifaceName = ifaceName self.VCAN = self.checkVCAN() self.bitrate = bitrate if not self.VCAN else -1 self.fdBitrate = fdBitrate if not self.VCAN else -1 self.isFD = isFD self.iface = can.Bus( interface="socketcan", channel=self.ifaceName, receive_own_messages=False, fd=isFD) self.updateBitrate(bitrate, fdBitrate, fd=isFD) #: 100 ms read timeout for async reads (see :func:`readPacketAsync`) self.timeout = 0.1 self.active = False
Example #23
Source File: CANData.py From CANalyzat0r with GNU General Public License v3.0 | 5 votes |
def sendPacket(self, packet): """ Sends a packet using the SocketCAN interface. :param packet: A packet as can.Message oject (see :func:`tryBuildPacket`) """ assert self.iface is not None try: self.iface.send(packet) except Exception as e: if not self.isFD and len(packet.data) > 8: CANData.logger.info(Strings.CANDataNeedFD) else: raise e
Example #24
Source File: CANData.py From CANalyzat0r with GNU General Public License v3.0 | 5 votes |
def readPacket(self): """ Read a packet from the queue using the SocketCAN interface. Note: This blocks as long as no packet is being received. You can use :func:`readPacketAsync` to read packets with a timeout. :return: A packet as can.Message object """ self.iface.socket.settimeout(0) return self.iface.recv()
Example #25
Source File: test_connection.py From python-udsoncan with MIT License | 5 votes |
def test_receive(self): self.vcan0_bus.send(can.Message(arbitration_id = self.stack_rxid, data = b"\x03\x01\x02\x03", extended_id = False)) frame = self.conn.wait_frame(timeout=1) self.assertEqual(frame, b"\x01\x02\x03")
Example #26
Source File: test_connection.py From python-udsoncan with MIT License | 5 votes |
def test_reopen(self): self.conn.send(b"\x0A\x0B\x0C\x0D") self.vcan0_bus.send(can.Message(arbitration_id = self.stack_rxid, data = b"\x03\x01\x02\x03", extended_id = False)) self.conn.close() self.vcan0_bus.shutdown() self.vcan0_bus = self.make_bus() self.conn.open(bus=self.vcan0_bus) with self.assertRaises(TimeoutException): self.conn.wait_frame(timeout=0.05, exception=True) self.assertIsNone(self.vcan0_bus.recv(0))
Example #27
Source File: network.py From canopen with MIT License | 5 votes |
def send_message(self, can_id, data, remote=False): """Send a raw CAN message to the network. This method may be overridden in a subclass if you need to integrate this library with a custom backend. It is safe to call this from multiple threads. :param int can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param bool remote: Set to True to send remote frame :raises can.CanError: When the message fails to be transmitted """ if not self.bus: raise RuntimeError("Not connected to CAN bus") msg = can.Message(is_extended_id=can_id > 0x7FF, arbitration_id=can_id, data=data, is_remote_frame=remote) with self.send_lock: self.bus.send(msg) self.check()
Example #28
Source File: can_actions.py From caringcaribou with GNU General Public License v3.0 | 5 votes |
def bruteforce_arbitration_id(self, data, callback, min_id, max_id, callback_end=None): # Set limits if min_id is None: min_id = ARBITRATION_ID_MIN if max_id is None: if min_id <= ARBITRATION_ID_MAX: max_id = ARBITRATION_ID_MAX else: # If min_id is extended, use an extended default max_id as well max_id = ARBITRATION_ID_MAX_EXTENDED # Sanity checks if min_id > max_id: if callback_end: callback_end("Invalid range: min > max") return # Start bruteforce self.bruteforce_running = True for arb_id in range(min_id, max_id + 1): self.notifier.listeners = [callback(arb_id)] # Use standard addressing (11 bits arbitration ID) instead of extended (29 bits) when possible extended = False if arb_id > ARBITRATION_ID_MAX: extended = True msg = can.Message(arbitration_id=arb_id, data=data, is_extended_id=extended) self.bus.send(msg) time.sleep(MESSAGE_DELAY) # Return if stopped by calling module if not self.bruteforce_running: self.clear_listeners() return # Callback if bruteforce finished without being stopped if callback_end: self.clear_listeners() callback_end("Bruteforce of range 0x{0:x}-0x{1:x} completed".format(min_id, max_id))
Example #29
Source File: iso15765_2.py From caringcaribou with GNU General Public License v3.0 | 5 votes |
def send_message(self, data, arbitration_id, force_extended=False): """ Transmits a message using 'arbitration_id' and 'data' on 'self.bus' :param data: Data to send :param arbitration_id: Arbitration ID to use :param force_extended: Force extended arbitration ID :return: None """ is_extended = force_extended or arbitration_id > ARBITRATION_ID_MAX msg = can.Message(arbitration_id=arbitration_id, data=data, is_extended_id=is_extended) self.bus.send(msg)
Example #30
Source File: stm32.py From can-prog with MIT License | 5 votes |
def _send_data(self, cmd, data=[]): self._send(can.Message(arbitration_id=cmd, data=data, extended_id=False))