本文整理汇总了Python中can.Message方法的典型用法代码示例。如果您正苦于以下问题:Python can.Message方法的具体用法?Python can.Message怎么用?Python can.Message使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类can
的用法示例。
在下文中一共展示了can.Message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_string_attribute_and_custom_device_type
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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": []})
示例2: test_send_only_on_change_and_default_device_type
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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}]})
示例3: test_rpc_with_hex_data_in_config
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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)))
示例4: test_rpc_with_hex_data_in_params
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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)))
示例5: send_data_to_bus
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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
示例6: __init__
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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})
示例7: test_flush_input
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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()
示例8: callback_onReceive_multiFrameResponse_noBs
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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)
示例9: singleFrameResponse_target
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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
示例10: readPacketAsync
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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
示例11: send_message
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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
示例12: __init__
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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()
示例13: send
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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)
示例14: make_session
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
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)
示例15: send_msg
# 需要导入模块: import can [as 别名]
# 或者: from can import Message [as 别名]
def send_msg(self, msg):
try:
self.bus.send(msg)
print("Message sent on {}".format(self.bus.channel_info))
except can.CanError:
print("Message NOT sent")