Example #1
0
    def _data_transfer_handler(self, msg):
        msg_source = msg.arbitration_id.source_address
        pdu_specific = msg.arbitration_id.pgn.pdu_specific

        if msg_source in self._incomplete_received_pdus:

            if pdu_specific in self._incomplete_received_pdus[msg_source]:
                self._incomplete_received_pdus[msg_source][
                    pdu_specific].data.extend(msg.data[1:])
                total = self._incomplete_received_pdu_lengths[msg_source][
                    pdu_specific]["total"]
                if len(self._incomplete_received_pdus[msg_source]
                       [pdu_specific].data) >= total:
                    if pdu_specific == constants.DESTINATION_ADDRESS_GLOBAL:
                        # Looks strange but makes sense - in the absence of explicit flow control,
                        # the last CAN packet in a long message *is* the end of message acknowledgement
                        return self._process_eom_ack(msg)

                    # Find a Node object so we can search its list of known node addresses for this node
                    # so we can find if we are responsible for sending the EOM ACK message
                    send_ack = any(True for l in self.j1939_notifier.listeners
                                   if isinstance(l, Node) and (
                                       l.address == pdu_specific
                                       or pdu_specific in l.address_list))
                    if send_ack:
                        arbitration_id = ArbitrationID()
                        arbitration_id.pgn.value = constants.PGN_TP_CONNECTION_MANAGEMENT
                        arbitration_id.pgn.pdu_specific = msg_source
                        arbitration_id.source_address = pdu_specific
                        total_length = self._incomplete_received_pdu_lengths[
                            msg_source][pdu_specific]["total"]
                        _num_packages = self._incomplete_received_pdu_lengths[
                            msg_source][pdu_specific]["num_packages"]
                        pgn = self._incomplete_received_pdus[msg_source][
                            pdu_specific].arbitration_id.pgn
                        pgn_msb = ((pgn.value & 0xFF0000) >> 16)
                        _pgn_middle = ((pgn.value & 0x00FF00) >> 8)
                        _pgn_lsb = 0

                        div, mod = divmod(total_length, 256)
                        can_message = Message(
                            arbitration_id=arbitration_id.can_id,
                            extended_id=True,
                            dlc=8,
                            data=[
                                constants.CM_MSG_TYPE_EOM_ACK,
                                mod,  # total_length % 256,
                                div,  # total_length / 256,
                                _num_packages,
                                0xFF,
                                _pgn_lsb,
                                _pgn_middle,
                                pgn_msb
                            ])
                        self.can_bus.send(can_message)

                    return self._process_eom_ack(msg)
Example #2
0
    def _data_transfer_handler(self, msg):
        msg_source = msg.arbitration_id.source_address
        pdu_specific = msg.arbitration_id.pgn.pdu_specific

        if msg_source in self._incomplete_received_pdus:

            if pdu_specific in self._incomplete_received_pdus[msg_source]:
                self._incomplete_received_pdus[msg_source][pdu_specific].data.extend(msg.data[1:])
                total = self._incomplete_received_pdu_lengths[msg_source][pdu_specific]["total"]
                if len(self._incomplete_received_pdus[msg_source][pdu_specific].data) >= total:
                    if pdu_specific == constants.DESTINATION_ADDRESS_GLOBAL:
                        # Looks strange but makes sense - in the absence of explicit flow control,
                        # the last CAN packet in a long message *is* the end of message acknowledgement
                        return self._process_eom_ack(msg)

                    # Find a Node object so we can search its list of known node addresses for this node
                    # so we can find if we are responsible for sending the EOM ACK message
                    send_ack = any(True for l in self.j1939_notifier.listeners
                                   if isinstance(l, Node) and (l.address == pdu_specific or
                                                               pdu_specific in l.address_list))
                    if send_ack:
                        arbitration_id = ArbitrationID()
                        arbitration_id.pgn.value = constants.PGN_TP_CONNECTION_MANAGEMENT
                        arbitration_id.pgn.pdu_specific = msg_source
                        arbitration_id.source_address = pdu_specific
                        total_length = self._incomplete_received_pdu_lengths[msg_source][pdu_specific]["total"]
                        _num_packages = self._incomplete_received_pdu_lengths[msg_source][pdu_specific]["num_packages"]
                        pgn = self._incomplete_received_pdus[msg_source][pdu_specific].arbitration_id.pgn
                        pgn_msb = ((pgn.value & 0xFF0000) >> 16)
                        _pgn_middle = ((pgn.value & 0x00FF00) >> 8)
                        _pgn_lsb = 0

                        div, mod = divmod(total_length, 256)
                        can_message = Message(arbitration_id=arbitration_id.can_id,
                                              extended_id=True,
                                              dlc=8,
                                              data=[constants.CM_MSG_TYPE_EOM_ACK,
                                                    mod, #total_length % 256,
                                                    div, #total_length / 256,
                                                    _num_packages,
                                                    0xFF,
                                                    _pgn_lsb,
                                                    _pgn_middle,
                                                    pgn_msb])
                        self.can_bus.send(can_message)

                    return self._process_eom_ack(msg)
Example #3
0
    def _process_incoming_message(self, msg):
        logger.debug("Processing incoming message")
        logging.debug(msg)
        arbitration_id = ArbitrationID()
        arbitration_id.can_id = msg.arbitration_id
        if arbitration_id.pgn.is_destination_specific:
            arbitration_id.pgn.value -= arbitration_id.pgn.pdu_specific
        pdu = self._pdu_type(timestamp=msg.timestamp, data=msg.data, info_strings=[])
        pdu.arbitration_id.can_id = msg.arbitration_id
        pdu.info_strings = []

        if arbitration_id.pgn.value == constants.PGN_TP_CONNECTION_MANAGEMENT:
            retval = self._connection_management_handler(pdu)
        elif arbitration_id.pgn.value == constants.PGN_TP_DATA_TRANSFER:
            retval = self._data_transfer_handler(pdu)
        else:
            retval = pdu

        return retval
Example #4
0
    def _process_incoming_message(self, msg):
        logger.debug("Processing incoming message")
        logging.debug(msg)
        arbitration_id = ArbitrationID()
        arbitration_id.can_id = msg.arbitration_id
        if arbitration_id.pgn.is_destination_specific:
            arbitration_id.pgn.value -= arbitration_id.pgn.pdu_specific
        pdu = self._pdu_type(timestamp=msg.timestamp, data=msg.data, info_strings=[])
        pdu.arbitration_id.can_id = msg.arbitration_id
        pdu.info_strings = []

        if arbitration_id.pgn.value == constants.PGN_TP_CONNECTION_MANAGEMENT:
            retval = self._connection_management_handler(pdu)
        elif arbitration_id.pgn.value == constants.PGN_TP_DATA_TRANSFER:
            retval = self._data_transfer_handler(pdu)
        else:
            retval = pdu

        return retval
Example #5
0
    def _process_rts(self, msg):
        if msg.arbitration_id.source_address not in self._incomplete_received_pdus:
            self._incomplete_received_pdus[
                msg.arbitration_id.source_address] = {}
            self._incomplete_received_pdu_lengths[
                msg.arbitration_id.source_address] = {}

        # Delete any previous messages that were not finished correctly
        if msg.arbitration_id.pgn.pdu_specific in self._incomplete_received_pdus[
                msg.arbitration_id.source_address]:
            del self._incomplete_received_pdus[
                msg.arbitration_id.source_address][
                    msg.arbitration_id.pgn.pdu_specific]
            del self._incomplete_received_pdu_lengths[
                msg.arbitration_id.source_address][
                    msg.arbitration_id.pgn.pdu_specific]

        if msg.data[0] == constants.CM_MSG_TYPE_BAM:
            self._incomplete_received_pdus[
                msg.arbitration_id.source_address][0xFF] = self._pdu_type()
            self._incomplete_received_pdus[msg.arbitration_id.source_address][
                0xFF].arbitration_id.pgn.value = int(
                    ("%.2X%.2X%.2X" % (msg.data[7], msg.data[6], msg.data[5])),
                    16)
            if self._incomplete_received_pdus[
                    msg.arbitration_id.source_address][
                        0xFF].arbitration_id.pgn.is_destination_specific:
                self._incomplete_received_pdus[msg.arbitration_id.source_address][
                    0xFF].arbitration_id.pgn.pdu_specific = msg.arbitration_id.pgn.pdu_specific
            self._incomplete_received_pdus[msg.arbitration_id.source_address][
                0xFF].arbitration_id.source_address = msg.arbitration_id.source_address
            self._incomplete_received_pdus[
                msg.arbitration_id.source_address][0xFF].data = []
            _message_size = int("%.2X%.2X" % (msg.data[2], msg.data[1]), 16)
            self._incomplete_received_pdu_lengths[
                msg.arbitration_id.source_address][0xFF] = {
                    "total": _message_size,
                    "chunk": 255,
                    "num_packages": msg.data[3],
                }
        else:
            self._incomplete_received_pdus[msg.arbitration_id.source_address][
                msg.arbitration_id.pgn.pdu_specific] = self._pdu_type()
            self._incomplete_received_pdus[msg.arbitration_id.source_address][
                msg.arbitration_id.pgn.
                pdu_specific].arbitration_id.pgn.value = int(
                    ("%.2X%.2X%.2X" % (msg.data[7], msg.data[6], msg.data[5])),
                    16)
            if self._incomplete_received_pdus[msg.arbitration_id.source_address][
                    msg.arbitration_id.pgn.
                    pdu_specific].arbitration_id.pgn.is_destination_specific:
                self._incomplete_received_pdus[msg.arbitration_id.source_address][
                    msg.arbitration_id.pgn.
                    pdu_specific].arbitration_id.pgn.pdu_specific = msg.arbitration_id.pgn.pdu_specific
            self._incomplete_received_pdus[msg.arbitration_id.source_address][
                msg.arbitration_id.pgn.
                pdu_specific].arbitration_id.source_address = msg.arbitration_id.source_address
            self._incomplete_received_pdus[msg.arbitration_id.source_address][
                msg.arbitration_id.pgn.pdu_specific].data = []
        _message_size = int("%.2X%.2X" % (msg.data[2], msg.data[1]), 16)
        self._incomplete_received_pdu_lengths[
            msg.arbitration_id.source_address][
                msg.arbitration_id.pgn.pdu_specific] = {
                    "total": _message_size,
                    "chunk": 255,
                    "num_packages": msg.data[3],
                }

        if msg.data[0] != constants.CM_MSG_TYPE_BAM:
            for _listener in self.j1939_notifier.listeners:
                if isinstance(_listener, Node):
                    # find a Node object so we can search its list of known node addresses
                    # for this node - if we find it we are responsible for sending the CTS message
                    if _listener.address == msg.arbitration_id.pgn.pdu_specific or msg.arbitration_id.pgn.pdu_specific in _listener.address_list:
                        _cts_arbitration_id = ArbitrationID(
                            source_address=msg.arbitration_id.pgn.pdu_specific)
                        _cts_arbitration_id.pgn.value = constants.PGN_TP_CONNECTION_MANAGEMENT
                        _cts_arbitration_id.pgn.pdu_specific = msg.arbitration_id.source_address
                        _data = [0x11, msg.data[4], 0x01, 0xFF, 0xFF]
                        _data.extend(msg.data[5:])
                        cts_msg = Message(
                            extended_id=True,
                            arbitration_id=_cts_arbitration_id.can_id,
                            data=_data,
                            dlc=8)

                        # send clear to send
                        self.can_bus.send(cts_msg)
                        return
Example #6
0
    def send(self, msg):
        messages = []
        if len(msg.data) > 8:
            # Making a copy of the PDU so that the original
            # is not altered by the data padding.
            pdu = copy.deepcopy(msg)
            pdu.data = bytearray(pdu.data)

            pdu_length_lsb, pdu_length_msb = divmod(len(pdu.data), 256)

            while len(pdu.data) % 7 != 0:
                pdu.data += b'\xFF'

            for i, segment in enumerate(pdu.data_segments(segment_length=7)):
                arbitration_id = copy.deepcopy(pdu.arbitration_id)
                arbitration_id.pgn.value = constants.PGN_TP_DATA_TRANSFER
                if pdu.arbitration_id.pgn.is_destination_specific and \
                   pdu.arbitration_id.destination_address != constants.DESTINATION_ADDRESS_GLOBAL:
                    arbitration_id.pgn.pdu_specific = pdu.arbitration_id.pgn.pdu_specific
                else:
                    arbitration_id.pgn.pdu_specific = constants.DESTINATION_ADDRESS_GLOBAL

                message = Message(arbitration_id=arbitration_id.can_id,
                                  extended_id=True,
                                  dlc=(len(segment) + 1),
                                  data=(bytearray([i + 1]) + segment))
                messages.append(message)

            if pdu.arbitration_id.pgn.is_destination_specific and \
               pdu.arbitration_id.destination_address != constants.DESTINATION_ADDRESS_GLOBAL:
                destination_address = pdu.arbitration_id.pgn.pdu_specific
                if pdu.arbitration_id.source_address in self._incomplete_transmitted_pdus:
                    if destination_address in self._incomplete_transmitted_pdus[
                            pdu.arbitration_id.source_address]:
                        logger.warning(
                            "Duplicate transmission of PDU:\n{}".format(pdu))
                else:
                    self._incomplete_transmitted_pdus[
                        pdu.arbitration_id.source_address] = {}
                self._incomplete_transmitted_pdus[
                    pdu.arbitration_id.
                    source_address][destination_address] = messages
            else:
                destination_address = constants.DESTINATION_ADDRESS_GLOBAL

            rts_arbitration_id = ArbitrationID(source_address=pdu.source)
            rts_arbitration_id.pgn.value = constants.PGN_TP_CONNECTION_MANAGEMENT
            rts_arbitration_id.pgn.pdu_specific = pdu.arbitration_id.pgn.pdu_specific

            temp_pgn = copy.deepcopy(pdu.arbitration_id.pgn)
            if temp_pgn.is_destination_specific:
                temp_pgn.value -= temp_pgn.pdu_specific

            pgn_msb = ((temp_pgn.value & 0xFF0000) >> 16)
            pgn_middle = ((temp_pgn.value & 0x00FF00) >> 8)
            pgn_lsb = (temp_pgn.value & 0x0000FF)

            if pdu.arbitration_id.pgn.is_destination_specific and \
               pdu.arbitration_id.destination_address != constants.DESTINATION_ADDRESS_GLOBAL:
                # send request to send
                rts_msg = Message(extended_id=True,
                                  arbitration_id=rts_arbitration_id.can_id,
                                  data=[
                                      constants.CM_MSG_TYPE_RTS,
                                      pdu_length_msb, pdu_length_lsb,
                                      len(messages), 0xFF, pgn_lsb, pgn_middle,
                                      pgn_msb
                                  ],
                                  dlc=8)
                self.can_bus.send(rts_msg)
            else:
                rts_arbitration_id.pgn.pdu_specific = constants.DESTINATION_ADDRESS_GLOBAL
                bam_msg = Message(extended_id=True,
                                  arbitration_id=rts_arbitration_id.can_id,
                                  data=[
                                      constants.CM_MSG_TYPE_BAM,
                                      pdu_length_msb, pdu_length_lsb,
                                      len(messages), 0xFF, pgn_lsb, pgn_middle,
                                      pgn_msb
                                  ],
                                  dlc=8)
                # send BAM
                self.can_bus.send(bam_msg)

                for message in messages:
                    # send data messages - no flow control, so no need to wait
                    # for receiving devices to acknowledge
                    self._long_message_segment_queue.put_nowait(message)
        else:
            can_message = Message(arbitration_id=msg.arbitration_id.can_id,
                                  extended_id=True,
                                  dlc=len(msg.data),
                                  data=msg.data)

            self.can_bus.send(can_message)
Example #7
0
    def create_widgets(self):

        logger = logging.getLogger(__name__)

        os.system('sudo ip link set can0 up type can bitrate 250000')
        time.sleep(0.1)

        try:
            bus = NewBus.Bus(channel='can0', bustype='socketcan_native')
            bus2 = can.interface.Bus(channel='can0',
                                     bustype='socketcan_native')

        except OSError:
            print('Cannot find PiCAN board.')
            exit()

        arbitration_id = ArbitrationID(priority=6, pgn=59904, source_address=1)

        msg2 = PDU(arbitration_id=arbitration_id, data=[229, 254, 000])
        msg3 = PDU(arbitration_id=arbitration_id, data=[233, 254, 000])

        start = time.time()
        runtime = 5  # How long?
        end = start + runtime
        now = time.time()

        bus.send(msg2)
        bus.send(msg3)

        while now < end:

            now = time.time()

            message = bus2.recv()

            my_message = MessageManager.MessageTransceiver()

            my_message.listen_data(message)

            my_message.check_message_type()

            if my_message.pgn_number == 0:
                print('Vehicle Odometer Data Found')
                odometer_module = MessageManager.OdometerData(my_message)
                # round_data_1 = int(round(odometer_module.calculate_element()))

            if my_message.pgn_number == 1:
                print('Total Engine Hours Data Found')
                engine_hours_module = MessageManager.EngineHours(my_message)
                # round_data_4 = int(round(engine_hours_module.calculate_element()))

            if my_message.pgn_number == 2:
                print('Total Fuel Used Data Found')
                fuel_used_module = MessageManager.FuelUsed(my_message)
                # round_data_5 = int(round(fuel_used_module.calculate_element()))

            if my_message.pgn_number == 3:
                print('Fuel Economy Data Found')
                fuel_economy_module = MessageManager.FuelEconomyData(
                    my_message)
                # round_data_2 = int(round(fuel_economy_module.calculate_element()))

            if my_message.pgn_number == 4:
                print('Fuel Level 1 Data Found')
                fuel_level_module = MessageManager.FuelLevel1Data(my_message)
                print(fuel_level_module.calculate_element())
                # round_data_3 = round(fuel_level_module.calculate_element(),1)

        round_data_1 = round(odometer_module.calculate_element(), 1)
        round_data_2 = round(fuel_economy_module.calculate_element(), 1)
        # round_data_3 = round(fuel_level_module.calculate_element(), 1)
        round_data_4 = round(engine_hours_module.calculate_element(), 1)
        round_data_5 = round(fuel_used_module.calculate_element(), 1)

        os.system('pkill gpicview')
        plate = DisplayManager.DataPlate('dataplate.txt')

        plate.openFile()

        qr = DisplayManager.QRCreator(odometer_module.calculate_element(),
                                      fuel_economy_module.calculate_element(),
                                      -1,
                                      engine_hours_module.calculate_element(),
                                      fuel_used_module.calculate_element(),
                                      plate)
        #qr = DisplayManager2.QRCreator(round_data_1, round_data_2, -1, round_data_4, round_data_5, plate)
        # qr = DisplayManager2.QRCreator(round_data_1, round_data_2, round_data_3, round_data_4, round_data_5, plate)
        qr.display()
        self.img = PhotoImage(file='image.png')

        Data = [
            str(plate.serial_number),
            str(plate.niin),
            str(plate.tamcn),
            str(plate.test), "", "   Value:", "   " + str(round_data_1),
            "   " + str(round_data_4), "   " + str(round_data_5),
            "   " + str(round_data_2), "   " + str(-1)
        ]
        # Data = [str(plate.serial_number), str(plate.niin),str(plate.tamcn),str(plate.test),"","   Value:", "   " + str(odometer_module.calculate_element()), "   " + str(engine_hours_module.calculate_element()), "   " + str(fuel_used_module.calculate_element()), "   " + str(fuel_economy_module.calculate_element()), "   " + str(-1)]
        Labels = [
            "Serial Number:", "NIIN:", "TAMCN:", "ID Number:", "",
            "Parameter:", "Vehicle Odometer:", "Total Engine Hours:",
            "Total Fuel Used:", "Fuel Economy:", "Fuel Level 1:"
        ]
        Units = [
            "", "", "", "", "", "Units:", "Miles", "Hours", "Gallons",
            "Miles per Gallon", "%"
        ]
        height = len(Data)
        width = 3

        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()

        x = (ws / 2)
        y = (hs / 2)

        ratio = 1366 / 18
        size = ws / ratio
        font_size = int(round(size))

        wratio_qr = 1366 / 700
        width_qr = ws / wratio_qr
        qr_width = int(round(width_qr))

        hratio_qr = 768 / 700
        height_qr = hs / hratio_qr
        qr_height = int(round(height_qr))

        wratio_dis = 1920 / 825
        width_dis = ws / wratio_dis
        dis_width = int(round(width_dis))

        hratio_dis = 1080 / 500
        height_dis = hs / hratio_dis
        dis_height = int(round(height_dis))

        x_dis = x - dis_width
        dis_xpos = x + (x_dis) / 2

        y_dis = hs - dis_height
        dis_ypos = (y_dis) / 2

        x_qr = x - qr_width
        qr_xpos = (x_qr) / 2

        y_qr = hs - qr_height
        qr_ypos = (y_qr) / 2

        #x_qr = x
        #qr_width = ws/

        for i in range(height):
            for j in range(width):
                if j == 1:
                    label = Label(self.root,
                                  text=Data[i],
                                  font=(None, font_size))
                    label.grid(row=i, column=j, sticky=W)
                elif j == 2:
                    label = Label(self.root,
                                  text=Units[i],
                                  font=(None, font_size))
                    label.grid(row=i, column=j, sticky=W)
                else:
                    label = Label(self.root,
                                  text=Labels[i],
                                  font=(None, font_size))
                    label.grid(row=i, column=j, sticky=W)
        # height = 8
        # width = 3

        self.root.geometry('%dx%d+%d+%d' %
                           (dis_width, dis_height, dis_xpos, dis_ypos))
        self.top.geometry('%dx%d+%d+%d' %
                          (qr_width, qr_height, qr_xpos, qr_ypos))
        # label = Label(root, text= totalData, width=150, font=(None,15))
        # label.pack()

        self.top.title('QR Code')
        self.root.title('Vehicle Information')
        self.panel = Label(self.top, image=self.img)
        self.panel.pack(side='bottom', fill='both', expand='yes')