Exemplo n.º 1
0
 def testAddListenerToNotifier(self):
     a_listener = can.Printer()
     notifier = can.Notifier(self.bus, [], 0.1)
     notifier.stop()
     self.assertNotIn(a_listener, notifier.listeners)
     notifier.add_listener(a_listener)
     self.assertIn(a_listener, notifier.listeners)
Exemplo n.º 2
0
 def testRemoveListenerFromNotifier(self):
     a_listener = can.Printer()
     notifier = can.Notifier(self.bus, [a_listener], 0.1)
     notifier.stop()
     self.assertIn(a_listener, notifier.listeners)
     notifier.remove_listener(a_listener)
     self.assertNotIn(a_listener, notifier.listeners)
Exemplo n.º 3
0
    def __new__(cls, filename: Optional[StringPathLike], *args, **kwargs):
        """
        :param filename: the filename/path of the file to write to,
                         may be a path-like object or None to
                         instantiate a :class:`~can.Printer`
        :raises ValueError: if the filename's suffix is of an unknown file type
        """
        if filename is None:
            return can.Printer(*args, **kwargs)

        if not Logger.fetched_plugins:
            Logger.message_writers.update(
                {
                    writer.name: writer.load()
                    for writer in
                    can.iter_entry_points("can.io.message_writer")
                }
            )
            Logger.fetched_plugins = True

        suffix = pathlib.PurePath(filename).suffix.lower()
        try:
            return Logger.message_writers[suffix](filename, *args, **kwargs)
        except KeyError:
            raise ValueError(
                f'No write support for this unknown log format "{suffix}"'
            ) from None
Exemplo n.º 4
0
def main(args):
    """Send some messages to itself and apply filtering."""
    with can.Bus(bustype='socketcan', channel='can0', bitrate=500000, receive_own_messages=False) as bus:

        can_filters = [{"can_id": 0x14ff0331, "can_mask": 0xF, "extended": True}]
        bus.set_filters(can_filters)
        # set to read-only, only supported on some interfaces
        #bus.state = BusState.PASSIVE

        # print all incoming messages, wich includes the ones sent,
        # since we set receive_own_messages to True
        # assign to some variable so it does not garbage collected
        #notifier = can.Notifier(bus, [can.Printer()])  # pylint: disable=unused-variable


        notifier = can.Notifier(bus, [can.Logger("logfile.asc"), can.Printer()]) #can.Logger("recorded.log")

        #bus.send(can.Message(arbitration_id=1, is_extended_id=True))
        #bus.send(can.Message(arbitration_id=2, is_extended_id=True))
        #bus.send(can.Message(arbitration_id=1, is_extended_id=False))


        try:
            while True:
                #msg = bus.recv(1)
                #if msg is not None:
                #    print(msg)
                time.sleep(1.0)
        except KeyboardInterrupt:
            logging.debug(f"KeyboardInterrupt")
        except Exception as e:
            logging.debug(f"other exception")
Exemplo n.º 5
0
def xcp_test():
    # connect to can2
    vcan2 = connect_bus(0)
    xcp_tx_id = 0xE927F8
    xcp_rx_id = 0x1CE9F827

    notifier = can.Notifier(vcan2, [can.Printer()])


    # create master to slave message
    xcp_message = can.Message(arbitration_id=xcp_tx_id, dlc=8, extended_id=True, data=[0xFF, 0, 0, 0, 0, 0, 0, 0])
Exemplo n.º 6
0
def main():
    """Send some messages to itself and apply filtering."""
    with can.Bus(bustype="virtual", receive_own_messages=True) as bus:

        can_filters = [{"can_id": 1, "can_mask": 0xF, "extended": True}]
        bus.set_filters(can_filters)

        # print all incoming messages, wich includes the ones sent,
        # since we set receive_own_messages to True
        # assign to some variable so it does not garbage collected
        notifier = can.Notifier(bus, [can.Printer()])  # pylint: disable=unused-variable

        bus.send(can.Message(arbitration_id=1, is_extended_id=True))
        bus.send(can.Message(arbitration_id=2, is_extended_id=True))
        bus.send(can.Message(arbitration_id=1, is_extended_id=False))

        time.sleep(1.0)
def read_iterate_msg(bus=None):
    # create a bus instance
    # many other interfaces are supported as well
    if bus is None:
        bus = can.Bus(interface='socketcan',
                      channel='vcan0',
                      recieve_own_messages=True)

    #send a message
    """
    message = can.Message(arbitration_id=1234, is_extended_id=True,
                          data=[0x11, 0x22, 0x33])
    bus.send(message, timeout=0.2)
    """

    # iterate over received messages
    """
    for msg in bus:
        print("{}: {}".format(msg.arbitration_id, msg.data))
    """

    # or use an asynchronous notifier
    notifier = can.Notifier(bus, [can.Logger("recorded.log"), can.Printer()])
Exemplo n.º 8
0
 def testBasicListenerCanBeAddedToNotifier(self):
     a_listener = can.Printer()
     notifier = can.Notifier(self.bus, [a_listener], 0.1)
     notifier.stop()
     self.assertIn(a_listener, notifier.listeners)
Exemplo n.º 9
0
 def test_not_crashes_with_file(self):
     with tempfile.NamedTemporaryFile('w', delete=False) as temp_file:
         with can.Printer(temp_file) as printer:
             for message in self.messages:
                 printer(message)
Exemplo n.º 10
0
 def test_not_crashes_with_stdout(self):
     with can.Printer() as printer:
         for message in self.messages:
             printer(message)
Exemplo n.º 11
0
from socketsocketcan import TCPBus
import can
from datetime import datetime   
from time import sleep

bus = TCPBus(5000)
print("socket connected!")

#create a listener to print all received messages
listener = can.Printer()
notifier = can.Notifier(bus,(listener,),timeout=None)

try:
    msg = can.Message(
    is_extended_id=False,
    dlc=6)
    count = 0
    while bus.is_connected:
        msg.arbitration_id = count
        msg.data = (count).to_bytes(6,"little")
        bus.send(msg)
        msg.timestamp = datetime.now().timestamp() #just needed for printing
        print(msg) #print sent message
        count+=1
        sleep(0.5)
    print("socket disconnected.")

except KeyboardInterrupt:
    print("ctrl+c, exiting...")
    notifier.stop()
    if bus.is_connected:
Exemplo n.º 12
0
    results = parser.parse_args()

    verbosity = results.verbosity

    logging_level_name = ['critical', 'error', 'warning', 'info', 'debug', 'subdebug'][min(5, verbosity)]
    can.set_logging_level(logging_level_name)

    can_filters = []
    if len(results.filter) > 0:
        print('Adding filter/s', results.filter)
        for filt in results.filter:
            if ':' in filt:
                _ = filt.split(":")
                can_id, can_mask = int(_[0], base=16), int(_[1], base=16)
            elif "~" in filt:
                can_id, can_mask = filt.split("~")
                can_id = int(can_id, base=16) | 0x20000000    # CAN_INV_FILTER
                can_mask = int(can_mask, base=16) & socket.CAN_ERR_FLAG
            can_filters.append({"can_id": can_id, "can_mask": can_mask})

    bus = can.interface.Bus(results.channel, bustype=results.interface, can_filters=can_filters)
    print('Can Logger (Started on {})\n'.format(datetime.datetime.now()))
    notifier = can.Notifier(bus, [can.Printer(results.log_file)])

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        bus.shutdown()
Exemplo n.º 13
0
        dolog = True
print('Using bus ' + candev)

bus = can.Bus(bustype='socketcan',
              channel=candev,
              bitrate=500000,
              listen_only=True)

hostname = '701.insi.dev'
user = '******'
password = '******'
database_file = 'model3dbc/Model3CAN.dbc'
sqlitefile = '/var/lib/tescanlogs/canbus.' + str(time.time_ns()) + '.sqlite'

if doprint:
    printer = can.Printer()
if doupload:
    influxwriter = InfluxWriter(hostname,
                                database=vehicle,
                                measurement_name=vehicle,
                                user=user,
                                password=password,
                                database_file=database_file)
    mqttwriter = MqttWriter(hostname,
                            vehicle=vehicle,
                            user=user,
                            password=password,
                            database_file=database_file)
if dolog:
    sqlitewriter = can.SqliteWriter(sqlitefile, table_name=vehicle)
Exemplo n.º 14
0
 def __init__(self, *args, **kwargs) -> None:
     super().__init__(*args, **kwargs)
     self._writer = can.Printer(file=path / "__unused.txt")
Exemplo n.º 15
0
import time
import can

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

can_filters = [{"can_id": 1, "can_mask": 0xf}]
bus.set_filters(can_filters)
notifier = can.Notifier(bus, [can.Printer()])
time.sleep(10)
Exemplo n.º 16
0
# import the library
import can

# create a bus instance
# many other interfaces are supported as well (see below)
bus = can.Bus(interface='socketcan',
              channel='vcan0',
              receive_own_messages=True)

# send a message
message = can.Message(arbitration_id=123,
                      is_extended_id=True,
                      data=[0x11, 0x22, 0x33])
bus.send(message, timeout=0.2)

# iterate over received messages
for msg in bus:
    print("{:X}: {}".format(msg.arbitration_id, msg.data))

# or use an asynchronous notifier
notifier = can.Notifier(bus, [can.Logger("recorded.log"), can.Printer()])
if (USE_EXISTING_BUS == True):
    # Assign network to bus
    network_sim.bus = can_bus
else:
    # Connect network_sim to same CAN bus
    # network_sim.connect(channel='can0', bustype='socketcan')
    network_sim.connect(channel='PCAN_USBBUS2', bustype='pcan', bitrate=250000)

# Create simulated nodes (via network_sim) > called "local"
localSimNode_0x05 = network_sim.create_node(0x05, EDS_PATH)
localSimNode_0x10 = network_sim.create_node(0x10, EDS_PATH)

# =====================================================================================================================================
if (USE_EXISTING_BUS == True):
    # Add network listeners to created bus and start the notifier
    notifier = can.Notifier(can_bus, [can.Printer()] + network_real.listeners + network_real.listeners, 0.5)
    # Add notifier from canopen to notifers of bus
    # can.Notifier.add_listener(listener for listener in network_real.listeners)
    # can.Notifier.add_listener(listener for listener in network_sim.listeners)

# =====================================================================================================================================
# Set Index 0x1000-Subindex 0x00, which is scanned by scanner.search()
localSimNode_0x05.sdo[0x1000].raw = 0x000000AA
# Instead of setting the value, we will check for the default value 
# localSimNode_0x10.sdo[0x1000].raw = 0x000000BB

# Set "Manufacturer Device Name" (index via EDS file), which is later readback
localSimNode_0x05.sdo["Manufacturer Device Name"].raw = "Device-Node 0x05"
localSimNode_0x10.sdo["Manufacturer Device Name"].raw = "Device-Node 0x10"

# =====================================================================================================================================