Python can.Notifier() Examples

The following are 8 code examples of can.Notifier(). 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 .
Example #1
Source File: electronic_control_unit.py    From j1939 with MIT License 6 votes vote down vote up
def connect(self, *args, **kwargs):
        """Connect to CAN bus using python-can.

        Arguments are passed directly to :class:`can.BusABC`. Typically these
        may include:

        :param channel:
            Backend specific channel for the CAN interface.
        :param str bustype:
            Name of the interface. See
            `python-can manual <https://python-can.readthedocs.io/en/latest/configuration.html#interface-names>`__
            for full list of supported interfaces.
        :param int bitrate:
            Bitrate in bit/s.

        :raises can.CanError:
            When connection fails.
        """
        self._bus = can.interface.Bus(*args, **kwargs)
        logger.info("Connected to '%s'", self._bus.channel_info)
        self._notifier = can.Notifier(self._bus, self._listeners, 1) 
Example #2
Source File: test_can_connector.py    From thingsboard-gateway with Apache License 2.0 5 votes vote down vote up
def test_multiple_polling(self):
        reader = BufferedReader()
        bus_notifier = Notifier(self.bus, [reader])
        self._create_connector("multiple_polling.json")
        config1 = self.config["devices"][0]["timeseries"][0]
        config2 = self.config["devices"][0]["timeseries"][1]
        config3 = self.config["devices"][0]["timeseries"][2]

        time_to_wait = config2["polling"]["period"] * 4
        message_count = int(time_to_wait / config2["polling"]["period"]) + 1 + \
                        int(time_to_wait / config3["polling"]["period"]) + 1 + \
                        1  # one time polling task

        sleep(time_to_wait)
        self.connector.close()
        bus_notifier.stop()

        messages = []
        while True:
            msg = reader.get_message(time_to_wait)
            if msg is None:
                break
            messages.append(msg)

        self.assertEqual(len(messages), message_count)

        expected_message_ids = [config1["nodeId"], config2["nodeId"], config3["nodeId"],
                                config2["nodeId"], config3["nodeId"], config2["nodeId"],
                                config3["nodeId"], config2["nodeId"], config3["nodeId"],
                                config2["nodeId"]]
        for i in range(0, message_count):
            self.assertEqual(messages[i].arbitration_id, expected_message_ids[i]) 
Example #3
Source File: monitor.py    From cantools with MIT License 5 votes vote down vote up
def __init__(self, stdscr, args):
        self._stdscr = stdscr
        self._dbase = database.load_file(args.database,
                                         encoding=args.encoding,
                                         frame_id_mask=args.frame_id_mask,
                                         strict=not args.no_strict)
        self._single_line = args.single_line
        self._filtered_sorted_message_names = []
        self._filter = ''
        self._compiled_filter = None
        self._formatted_messages = {}
        self._playing = True
        self._modified = True
        self._show_filter = False
        self._queue = Queue()
        self._nrows, self._ncols = stdscr.getmaxyx()
        self._received = 0
        self._discarded = 0
        self._basetime = None
        self._page = 0

        stdscr.keypad(True)
        stdscr.nodelay(True)
        curses.use_default_colors()
        curses.curs_set(False)
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)

        bus = self.create_bus(args)
        self._notifier = can.Notifier(bus, [self]) 
Example #4
Source File: CanConnection.py    From python-uds with MIT License 5 votes vote down vote up
def __init__(self, callback, filter, bus):
        self.__bus = bus
        listener = can.Listener()
        listener.on_message_received = callback
        self.__notifier = can.Notifier(self.__bus, [listener], 0)
        self.__listeners = [listener]
        self.addFilter(filter)

    ##
    # @brief Adds call back (via additional listener) to the notifier which is attached to this bus 
Example #5
Source File: network.py    From canopen with MIT License 5 votes vote down vote up
def connect(self, *args, **kwargs):
        """Connect to CAN bus using python-can.

        Arguments are passed directly to :class:`can.BusABC`. Typically these
        may include:

        :param channel:
            Backend specific channel for the CAN interface.
        :param str bustype:
            Name of the interface. See
            `python-can manual <https://python-can.readthedocs.io/en/latest/configuration.html#interface-names>`__
            for full list of supported interfaces.
        :param int bitrate:
            Bitrate in bit/s.

        :raises can.CanError:
            When connection fails.
        """
        # If bitrate has not been specified, try to find one node where bitrate
        # has been specified
        if "bitrate" not in kwargs:
            for node in self.nodes.values():
                if node.object_dictionary.bitrate:
                    kwargs["bitrate"] = node.object_dictionary.bitrate
                    break
        self.bus = can.interface.Bus(*args, **kwargs)
        logger.info("Connected to '%s'", self.bus.channel_info)
        self.notifier = can.Notifier(self.bus, self.listeners, 1)
        return self 
Example #6
Source File: can_actions.py    From caringcaribou with GNU General Public License v3.0 5 votes vote down vote up
def enable_notifier(self):
        self.notifier = can.Notifier(self.bus, listeners=[]) 
Example #7
Source File: test_can_connector.py    From thingsboard-gateway with Apache License 2.0 4 votes vote down vote up
def test_update(self):
        reader = BufferedReader()
        bus_notifier = Notifier(self.bus, [reader])
        self._create_connector("attribute_updates.json")

        configs = self.config["devices"][0]["attributeUpdates"]
        updates = {"device": self.config["devices"][0]["name"],
                   "data": {
                       "boolAttr": True,
                       "intAttr": randint(-int(pow(2, configs[1]["dataLength"]) / 2),
                                          pow(2, configs[1]["dataLength"] - 1)),
                       "floatAttr": uniform(-3.1415926535, 3.1415926535),
                       "stringAttr": ''.join(choice(ascii_lowercase) for _ in range(8)),
                       "wrongConfigAttr": True
                   }}

        data_list = [[int(updates["data"]["boolAttr"])],
                     updates["data"]["intAttr"].to_bytes(configs[1]["dataLength"],
                                                         configs[1]["dataByteorder"],
                                                         signed=(updates["data"]["intAttr"] < 0)),
                     list(struct.pack(">f", updates["data"]["floatAttr"])),
                     list(str("Test" + updates["data"]["stringAttr"]).encode(self.connector.DEFAULT_ENCODING))
                     ]

        self.connector.on_attributes_update(updates)

        sleep(1)
        self.connector.close()
        bus_notifier.stop()

        messages = []
        while True:
            msg = reader.get_message(1)
            if msg is None:
                break
            messages.append(msg)

        self.assertEqual(len(messages), len(data_list))

        messages = sorted(messages, key=lambda message: message.arbitration_id)
        for i in range(len(messages)):
            self.assertTrue(messages[i].equals(Message(arbitration_id=configs[i]["nodeId"],
                                                       is_extended_id=configs[i].get("isExtendedId",
                                                                                     self.connector.DEFAULT_EXTENDED_ID_FLAG),
                                                       is_fd=configs[i].get("isFd", self.connector.DEFAULT_FD_FLAG),
                                                       bitrate_switch=configs[i].get("bitrateSwitch",
                                                                                     self.connector.DEFAULT_BITRATE_SWITCH_FLAG),
                                                       data=data_list[i],
                                                       timestamp=messages[i].timestamp,
                                                       channel=messages[i].channel))) 
Example #8
Source File: tester.py    From cantools with MIT License 4 votes vote down vote up
def __init__(self,
                 dut_name,
                 database,
                 can_bus,
                 bus_name=None,
                 on_message=None,
                 decode_choices=True,
                 scaling=True,
                 padding=False):
        self._dut_name = dut_name
        self._bus_name = bus_name
        self._database = database
        self._can_bus = can_bus
        self._input_list = []
        self._input_queue = queue.Queue()
        self._messages = Messages()
        self._is_running = False

        # DUT name validation.
        node_names = [node.name for node in database.nodes]

        if not any([name == dut_name for name in node_names]):
            raise Error(
                "expected DUT name in {}, but got '{}'".format(node_names,
                                                               dut_name))

        # BUS name validation.
        bus_names = [bus.name for bus in database.buses]

        if len(bus_names) == 0:
            if bus_name is not None:
                raise Error(
                    "expected bus name None as there are no buses defined in "
                    "the database, but got '{}'".format(bus_name))
        elif not any([name == bus_name for name in bus_names]):
            raise Error(
                "expected bus name in {}, but got '{}'".format(bus_names,
                                                               bus_name))

        for message in database.messages:
            if message.bus_name == bus_name:
                self._messages[message.name] = Message(message,
                                                       can_bus,
                                                       self._input_list,
                                                       self._input_queue,
                                                       decode_choices,
                                                       scaling,
                                                       padding)

        listener = Listener(self._database,
                            self._messages,
                            self._input_queue,
                            on_message)
        self._notifier = can.Notifier(can_bus, [listener])