Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions can/interfaces/kvaser/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,11 @@ def __init__(self, channel, can_filters=None, **config):
:param bool single_handle:
Use one Kvaser CANLIB bus handle for both reading and writing.
This can be set if reading and/or writing is done from one thread.
:param bool receive_own_messages:
If messages transmitted should also be received back.
Only works if single_handle is also False.
If you want to receive messages from other applications on the same
computer, set this to True or set single_handle to True.
"""
log.info("CAN Filters: {}".format(can_filters))
log.info("Got configuration of: {}".format(config))
Expand All @@ -319,6 +324,7 @@ def __init__(self, channel, can_filters=None, **config):
no_samp = config.get('no_samp', 0)
driver_mode = config.get('driver_mode', DRIVER_MODE_NORMAL)
single_handle = config.get('single_handle', False)
receive_own_messages = config.get('receive_own_messages', False)

try:
channel = int(channel)
Expand Down Expand Up @@ -350,6 +356,15 @@ def __init__(self, channel, can_filters=None, **config):
4)
canSetBusParams(self._read_handle, bitrate, tseg1, tseg2, sjw, no_samp, 0)

# By default, use local echo if single handle is used (see #160)
local_echo = single_handle or receive_own_messages
if receive_own_messages and single_handle:
log.warning("receive_own_messages only works if single_handle is False")
canIoCtl(self._read_handle,
canstat.canIOCTL_SET_LOCAL_TXECHO,
ctypes.byref(ctypes.c_byte(local_echo)),
1)

if self.single_handle:
log.debug("We don't require separate handles to the bus")
self._write_handle = self._read_handle
Expand Down
1 change: 1 addition & 0 deletions can/interfaces/kvaser/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ def CANSTATUS_SUCCESS(status):
canIOCTL_SET_USB_THROTTLE = 28
canIOCTL_GET_USB_THROTTLE = 29
canIOCTL_SET_BUSON_TIME_AUTO_RESET = 30
canIOCTL_SET_LOCAL_TXECHO = 32
canIOCTL_PREFER_EXT = 1
canIOCTL_PREFER_STD = 2
canIOCTL_CLEAR_ERROR_COUNTERS = 5
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/socketcan/socketcan_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ def pack_filters(can_filters=None):
if can_filter.get('extended'):
can_id |= CAN_EFF_FLAG
filter_data.append(can_id)
filter_data.append(can_filter['can_mask'])
filter_data.append(can_filter['can_mask'] | CAN_EFF_FLAG)
return struct.pack(can_filter_fmt, *filter_data)
11 changes: 9 additions & 2 deletions can/interfaces/socketcan/socketcan_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,12 +370,13 @@ def capturePacket(sock):
class SocketcanNative_Bus(BusABC):
channel_info = "native socketcan channel"

def __init__(self, channel, **kwargs):
def __init__(self, channel, receive_own_messages=False, **kwargs):
"""
:param str channel:
The can interface name with which to create this bus. An example channel
would be 'vcan0'.

:param bool receive_own_messages:
If messages transmitted should also be received back.
:param list can_filters:
A list of dictionaries, each containing a "can_id" and a "can_mask".
"""
Expand All @@ -386,6 +387,12 @@ def __init__(self, channel, **kwargs):
if 'can_filters' in kwargs and len(kwargs['can_filters']) > 0:
log.debug("Creating a filtered can bus")
self.set_filters(kwargs['can_filters'])
try:
self.socket.setsockopt(socket.SOL_CAN_RAW,
socket.CAN_RAW_RECV_OWN_MSGS,
struct.pack('i', receive_own_messages))
except Exception as e:
log.error("Could not receive own messages (%s)", e)

bindSocket(self.socket, channel)
super(SocketcanNative_Bus, self).__init__()
Expand Down
9 changes: 5 additions & 4 deletions can/interfaces/virtual.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
virtual CAN interface for testing purposes.

Any VirtualBus instances connecting to the same channel
will get the same messages. Sent messages will also be
echoed back to the same bus.
will get the same messages.
"""

import logging
Expand All @@ -29,8 +28,9 @@
class VirtualBus(BusABC):
"""Virtual CAN bus using an internal message queue for testing."""

def __init__(self, channel=None, **config):
def __init__(self, channel=None, receive_own_messages=False, **config):
self.channel_info = 'Virtual bus channel %s' % channel
self.receive_own_messages = receive_own_messages

# Create a new channel if one does not exist
if channel not in channels:
Expand All @@ -53,7 +53,8 @@ def send(self, msg, timeout=None):
msg.timestamp = time.time()
# Add message to all listening on this channel
for bus_queue in self.channel:
bus_queue.put(msg)
if bus_queue != self.queue or self.receive_own_messages:
bus_queue.put(msg)
logger.log(9, 'Transmitted message:\n%s', msg)

def shutdown(self):
Expand Down
2 changes: 1 addition & 1 deletion can/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def main():
can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG
can_filters.append({"can_id": can_id, "can_mask": can_mask})

config = {"can_filters": can_filters}
config = {"can_filters": can_filters, "single_handle": True}
if results.interface:
config["bustype"] = results.interface
if results.bitrate:
Expand Down
2 changes: 1 addition & 1 deletion can/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def main():
logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)]
can.set_logging_level(logging_level_name)

config = {}
config = {"single_handle": True}
if results.interface:
config["bustype"] = results.interface
if results.bitrate:
Expand Down
9 changes: 7 additions & 2 deletions examples/vcan_filtered.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import time
import can

bus = can.interface.Bus(bustype='socketcan', channel='vcan0')
bus = can.interface.Bus(bustype='socketcan',
channel='vcan0',
receive_own_messages=True)

can_filters = [{"can_id": 1, "can_mask": 0xf}]
can_filters = [{"can_id": 1, "can_mask": 0xf, "extended": True}]
bus.set_filters(can_filters)
notifier = can.Notifier(bus, [can.Printer()])
bus.send(can.Message(arbitration_id=1, extended_id=True))
bus.send(can.Message(arbitration_id=2, extended_id=True))
bus.send(can.Message(arbitration_id=1, extended_id=False))
time.sleep(10)
5 changes: 3 additions & 2 deletions test/simplecyclic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ class SimpleCyclicSendTaskTest(unittest.TestCase):
def test_cycle_time(self):
msg = can.Message(extended_id=False, arbitration_id=0x100, data=[0,1,2,3,4,5,6,7])
bus = can.interface.Bus(bustype='virtual')
bus2 = can.interface.Bus(bustype='virtual')
task = bus.send_periodic(msg, 0.01, 1)
self.assertIsInstance(task, can.broadcastmanager.CyclicSendTaskABC)
sleep(1.5)
size = bus.queue.qsize()
size = bus2.queue.qsize()
print(size)
# About 100 messages should have been transmitted. Some overhead will
# make it less though
self.assertTrue(90 < size < 110)
last_msg = bus.recv()
last_msg = bus2.recv()
self.assertEqual(last_msg, msg)


Expand Down