Index: DialityCoreCanProtocol.py =================================================================== diff -u -rbacdac2eb5cc03bfad1c55e9a3cb0f2f4bda95f5 -rf2b88894a458d9e03a9cb005af02ef16fd5e6f32 --- DialityCoreCanProtocol.py (.../DialityCoreCanProtocol.py) (revision bacdac2eb5cc03bfad1c55e9a3cb0f2f4bda95f5) +++ DialityCoreCanProtocol.py (.../DialityCoreCanProtocol.py) (revision f2b88894a458d9e03a9cb005af02ef16fd5e6f32) @@ -21,22 +21,42 @@ from time import sleep -class LongDialityPacketBuilder: +class DialinChannels: + # This are all the channels available + hd_alarm_broadcast_ch_id = 0x001 + dg_alarm_broadcast_ch_id = 0x002 + ui_alarm_broadcast_ch_id = 0x004 + hd_to_dg_ch_id = 0x008 + dg_to_hd_ch_id = 0x010 + hd_to_ui_ch_id = 0x020 + hd_sync_broadcast_ch_id = 0x040 + dg_sync_broadcast_ch_id = 0x080 + ui_to_hd_ch_id = 0x100 + dialin_to_hd_ch_id = 0x400 + hd_to_dialin_ch_id = 0x401 + dialin_to_dg_ch_id = 0x402 + dg_to_dialin_ch_id = 0x403 + dialin_to_ui_ch_id = 0x404 + ui_to_dialin_ch_id = 0x405 + + +class LongDialityMessageBuilder: + def __init__(self, can_message): """ - LongDialityPacketBuilder is a utility object that helps construct a diality packet + LongDialityMessageBuilder is a utility object that helps construct a diality message that is longer than 8 bytes. Basic principle is to construct an object with the - first 8 byte message which contains the length of the packet, and the later push the + first 8 byte message which contains the length of the message, and the later push the remaining messages. e.g., let's imagine a 3 message packet. - obj = LongDialityPacketBuilder(msg1) + obj = LongDialityMessageBuilder(msg1) - packet = obj.push(msg2), returns None + message = obj.push(msg2), returns None, message is not complete - packet = obj.push(msg3), return the packet which is the concatenation of msg1, msg2 and msg3 + message = obj.push(msg3), return the packet which is the concatenation of msg1, msg2 and msg3 - :param can_message: an 8 byte message needed to build a Diality packet. + :param can_message: an 8 byte message needed to build a diality message. :returns object @@ -71,28 +91,31 @@ return None -class DialityCanMessenger: +class DialinCanMessenger: START_BYTE = 0xA5 def __init__(self, can_interface='can0'): """ - DialityCanMesseger constructor + DialityCanMessenger constructor :param can_interface - string containing the can interface, e.g., 'can0" :returns DialityCanMessenger object """ - self.__canConnection = can.interface.Bus(can_interface, bustype='socketcan') + BusType = 'socketcan' + self.__canConnection = can.interface.Bus(channel=can_interface, bustype=BusType) self.__sendPacketRequestID = -1 self.__sendEvent = threading.Event() - self.__longPacketsBuilders = {} - self.__dialityPacket = None - self.__dialityResponsePacket = None - self.__dialityResponseChannelID = -1 + self.__longMessageBuilders = {} + self.__longMsgChannelIDSet = set() + self.__dialinMessage = None + self.__dialinCommandResponseMessage = None + self.__dialinResponseChannelID = -1 + self.__run = False self.__sync_response_dictionary = {} @@ -125,10 +148,6 @@ self.__run = False print("Can listener has stopped.") - def __getRequestID(self, message): - - return int.from_bytes(message[1:3], byteorder='big', signed=False) - def __listener(self): """ listens for diality message on the can interface passed during construction. @@ -145,258 +164,324 @@ can_data = [b for b in message.data] channel_id = message.arbitration_id - packet_length = can_data[3] + message_length = can_data[3] - # We decide what to do with it + # if we are building a long message, then proceed to push it to the channel dictionary + if channel_id in self.__longMsgChannelIDSet: - if can_data[0] == self.START_BYTE and packet_length <= 4: # This is a short packet + self.__dialinMessage = self.__longMessageBuilders[channel_id].push(can_data) - self.__dialityPacket = can_data # deliver the packet + elif can_data[0] == self.START_BYTE and message_length <= 4: # This is a short packet + # This is the first time that we are building a message - elif can_data[0] == self.START_BYTE and packet_length > 4: # This is the start of a long packet + self.__dialinMessage = can_data # deliver the packet - if channel_id not in self.__longPacketsBuilders.keys(): # if we don't have a builder. Create it! + elif can_data[0] == self.START_BYTE and message_length > 4: # This is the start of a long packet - self.__longPacketsBuilders[channel_id] = LongDialityPacketBuilder(can_data) - self.__dialityPacket = None + # We are starting to build a long message, include it in the lonMsgChannelIDSet + self.__longMsgChannelIDSet.add(channel_id) - else: #if we do have a builder. This is the first time + if channel_id not in self.__longMessageBuilders.keys(): # if we don't have a builder. Create it! - self.__dialityPacket = self.__longPacketsBuilders[channel_id].push(can_data, first_packet=True) + self.__longMessageBuilders[channel_id] = LongDialityMessageBuilder(can_data) + self.__dialinMessage = None - else: # this is the continuation of a long message + else: # if we do have a builder. This is the first time - if channel_id in self.__longPacketsBuilders.keys(): - self.__dialityPacket = self.__longPacketsBuilders[channel_id].push(can_data) + self.__dialinMessage = self.__longMessageBuilders[channel_id].push(can_data, first_packet=True) # At this point we have a complete (long or short) Diality Packet - if self.__dialityPacket is not None: + if self.__dialinMessage is not None: - dialityPacketRequestID = DialityPacket.getRequestID(self.__dialityPacket) - self.__dialityPacket[0] = channel_id + completeDialinMessage = DialinMessage.buildBasicMessage(channel_id=channel_id, + message=self.__dialinMessage) + dialin_msg_id = DialinMessage.getMessageID(completeDialinMessage) + dialin_ch_id = DialinMessage.getChannelID(completeDialinMessage) + if dialin_ch_id in self.__longMsgChannelIDSet: + # We need to remove channel ID from the long message set + self.__longMsgChannelIDSet.remove(dialin_ch_id) + # We first check if this is a response to a send request that is pending - if dialityPacketRequestID == self.__sendPacketRequestID: + if dialin_msg_id == self.__sendPacketRequestID: - self.__dialityResponsePacket = self.__dialityPacket + self.__dialinCommandResponseMessage = completeDialinMessage self.__sendEvent.set() self.__sendPacketRequestID = -1 - # If it is not, this is a sync packet and we need to call it's register function + # If it is not, this is a publication message and we need to call it's register function - elif channel_id in self.__sync_response_dictionary.keys() and \ - dialityPacketRequestID in self.__sync_response_dictionary[channel_id].keys(): + elif dialin_ch_id in self.__sync_response_dictionary.keys() and \ + dialin_msg_id in self.__sync_response_dictionary[channel_id].keys(): - self.__sync_response_dictionary[channel_id][dialityPacketRequestID](self.__dialityPacket) + self.__sync_response_dictionary[dialin_ch_id][dialin_msg_id](completeDialinMessage) - # Done with this packet, let's get the next one + # Done with this message, let's get the next one - self.__dialityPacket = None + self.__dialinMessage = None else: # We have received nothing, let's sleep 1 msec and let's check again sleep(0.001) - def registerSyncFunction(self, channel_id, request_id, function): + def registerReceivingPublicationFunction(self, channel_id, message_id, function): """ assign a function with packet parameter to an sync request id, e.g., def function(packet). :param channel_id: can channel number where messages are received - :param request_id: Diality request ID in message + :param message_id: Diality request ID in message :param function: function reference """ # if the channel_id exist, we just update the dictionary for the channel_id if channel_id in self.__sync_response_dictionary.keys(): - self.__sync_response_dictionary[channel_id].update({request_id: function}) + self.__sync_response_dictionary[channel_id].update({message_id: function}) # otherwise, we need to create the dictionary for the channel_id else: - self.__sync_response_dictionary[channel_id] = {request_id: function} + self.__sync_response_dictionary[channel_id] = {message_id: function} - def send(self, channel_id, can_packet, time_out=1): + def send(self, built_message, time_out=1): """ sends can_packet to channel_id. - :param channel_id: CAN channel ID - :param can_packet: list of integers with the Diality format + :param built_message: message built using DialinMessage class :param time_out: time it will wait for a response in seconds :return: Diality Packet, it it times out it returns None """ - padded_can_packet = DialityPacket.padPacketWithZeros(can_packet) + channel_id = DialinMessage.getChannelID(built_message) - padded_can_packet_length = padded_can_packet[3] + padded_can_message_array = built_message['message'] - self.__sendPacketRequestID = DialityPacket.getRequestID(can_packet) + padded_can_message_length = padded_can_message_array[3] - # A packet can be longer than 8 bytes, so we need to split it - # into 8 bytes messages. + self.__sendPacketRequestID = DialinMessage.getMessageID(built_message) - number_of_messages = math.ceil((padded_can_packet_length + 5) / 8) + # A message can be longer than 8 bytes, so we need to split it + # into 8 bytes packets. + number_of_packets = math.ceil((padded_can_message_length + 5) / 8) + # We are sending one message at a time on CAN - for n in range(number_of_messages): - message = padded_can_packet[n * 8:n * 8 + 8] + for n in range(number_of_packets): + packet = padded_can_message_array[n * 8:n * 8 + 8] - # Sending one message at a time - msg = can.Message(arbitration_id=channel_id, - data=message, - is_extended_id=False) + # Sending one packet at a time + pckt = can.Message(arbitration_id=channel_id, + data=packet, + is_extended_id=False) - self.__canConnection.send(msg) + self.__canConnection.send(pckt) # Sending - self.__dialityResponsePacket = None + self.__dialinCommandResponseMessage = None # After all message has been sent, we clear a flag self.__sendEvent.clear() # At this point, we sleep until the system times out or flag is set - didTimeOut = not self.__sendEvent.wait(time_out) + self.__sendEvent.wait(time_out) # We are ready to send again. Reset request ID appropriately self.__sendPacketRequestID = -1 # This value is None or it has a message depending of the listener - return self.__dialityResponsePacket + return self.__dialinCommandResponseMessage -class DialityPacket: - +class DialinMessage: BYTE_ORDER = 'little' @staticmethod - def buildPacket(request_id=0, cargo=[]): + def buildBasicMessage(channel_id=0, message=None): """ + build a message using channel_id and dialin message + :param channel_id: integer with channel id + :param message: array of int with message + :return: dictionary with channel_id and message keys + """ + if message is None: + message = [] + return {'channel_id': channel_id, 'message': message} + + @staticmethod + def buildMessage(channel_id=0, message_id=0, payload=None): + """ buildPacket builds a Diality Packet - :param request_id: is an integer indicating request ID - :param cargo: list with cargo. It does not include length + :param channel_id: is an integer with channel ID + :param message_id: is an integer indicating request ID + :param payload: list with payload. It does not include length + :return dictionary with channel_id and 8-byte padded message """ - packet = [DialityCanMessenger.START_BYTE] + if payload is None: + payload = [] + message = [DialinCanMessenger.START_BYTE] - if 0 <= request_id <= (2 ** 16 - 1): + if 0 <= message_id <= (2 ** 16 - 1): # Make sure an int was passed - request_id_in_bytes = request_id.to_bytes(2, byteorder=DialityPacket.BYTE_ORDER) + message_id_in_bytes = message_id.to_bytes(2, byteorder=DialinMessage.BYTE_ORDER) - packet += [request_id_in_bytes[0]] - packet += [request_id_in_bytes[1]] + message += [message_id_in_bytes[0]] + message += [message_id_in_bytes[1]] else: return [] - # Check cargo length - cargo_length = len(cargo) + # Check payload length + payload_length = len(payload) - # if cargo is larger than 255 return nothing - if cargo_length <= 255: - # cargo has to be a list - packet += [cargo_length] + # if payload is larger than 255 return nothing + if payload_length <= 255: + # payload has to be a list + message += [payload_length] else: return [] - packet += cargo + message += payload - return DialityPacket.padPacketWithZeros(packet) + message = DialinMessage.__padMessageWithZeros(message) + return DialinMessage.buildBasicMessage(channel_id=channel_id, message=message) + @staticmethod - def padPacketWithZeros(packet): + def __padMessageWithZeros(message): """ returns a packet padded with zeros that guarantees that the packet is a multiple of 8 bytes. - :param packet: packet that may or may not be multiple of 8 bytes + :param message: packet that may or may not be multiple of 8 bytes :return: packet that is 8-byte multiple """ - packet_length = len(packet) + message_length = len(message) # message must be multiple of 8 - if packet_length % 8 != 0: + if message_length % 8 != 0: # We need to pad the message with trailing zeros - add_these_many_zeros = math.ceil(packet_length / 8) * 8 - packet_length + add_these_many_zeros = math.ceil(message_length / 8) * 8 - message_length - packet += [0] * add_these_many_zeros + message += [0] * add_these_many_zeros - return packet + return message @staticmethod - def getRequestID(packet): + def getChannelID(message): """ + returns request ID from message + + :param message: dictionary with channel_id and message keys + :return: integer with channel id + + """ + + return message['channel_id'] + + @staticmethod + def getMessageID(message): + """ returns request ID from packet - :param packet: complete Diality Packet + :param message: complete Diality Packet :return: integer with request ID """ + msg_id_array = message['message'][1:3] - return int.from_bytes(packet[1:3], byteorder=DialityPacket.BYTE_ORDER) + return int.from_bytes(msg_id_array, byteorder=DialinMessage.BYTE_ORDER) + @staticmethod + def getPayloadLength(message): + """ + returns payload length from message + :param message: dictionary with channel_id and message keys + :return: a unsigned payload length + """ -def test_print_received_packet(packet, sync=False): - channel_id = packet[0] - packet[0] = 0xA5 + return message['message'][4] + @staticmethod + def getPayload(message): + """ + returns payload array from message + :param message: dictionary with channel_id and message keys + :return: a payload array if exist + """ + + payload_length = DialinMessage.getPayloadLength(message) + + if payload_length == 0: + return None + else: + return message['message'][5:] + + +def test_print_received_packet(messsage, sync=False): + channel_id = messsage[0] + messsage[0] = 0xA5 + introduction = "Received: " if sync: introduction = "Sync " + introduction - print(introduction, packet, " in channel: ", channel_id) + print(introduction, messsage, " in channel: ", channel_id) -def test_print_to_screen(packet): - if packet is None: +def test_print_to_screen(message): + if message is None: print("Timeout!!!") else: - test_print_received_packet(packet) + test_print_received_packet(message) -def test_function_for_sync(packet): - test_print_received_packet(packet, sync=True) +def test_function_for_sync(message): + test_print_received_packet(message, sync=True) -def test_print_sending_dg_board(channel_id, packet): - print("Sending to board: ", packet, " in channel: ", channel_id) +def test_print_sending_dg_board(channel_id, message): + print("Sending to board: ", message, " in channel: ", channel_id) -def test_print_sending_dg_sim(channel_id, packet): - print("Sending to DG simulator: ", packet, " in channel", channel_id, end=" ---> ") +def test_print_sending_dg_sim(channel_id, messsage): + print("Sending to DG simulator: ", messsage, " in channel", channel_id, end=" ---> ") if __name__ == "__main__": - test_messenger = DialityCanMessenger() - test_channel_id = 0x100 + test_messenger = DialinCanMessenger() + test_channel_id = DialinMessage.ui_to_hd_ch_id - test_received_channel_id = 0x20 - test_received_request_id = 0x100 + test_received_channel_id = DialinMessage.hd_to_ui_ch_id + test_received_message_id = 0x100 - test_messenger.registerSyncFunction(test_received_channel_id, test_received_request_id, test_function_for_sync) + test_messenger.registerReceivingPublicationFunction(test_received_channel_id, test_received_message_id, + test_function_for_sync) - test_dg_simulator_received_channel_id = 0x01 - test_dg_simulator_sync_req_id = 0x05 - test_dg_simulator_req_id = 0x03 + test_dg_simulator_received_channel_id = DialinMessage.dialin_to_dg_ch_id + test_dg_simulator_sync_msg_id = 0x05 + test_dg_simulator_msg_id = 0x03 - test_messenger.registerSyncFunction(test_dg_simulator_received_channel_id, test_dg_simulator_sync_req_id, - test_function_for_sync) + test_messenger.registerReceivingPublicationFunction(test_dg_simulator_received_channel_id, + test_dg_simulator_sync_msg_id, + test_function_for_sync) test_messenger.start() - #test_packet = DialityPacket.buildPacket(0x01, [1]) - test_packet = DialityPacket.buildPacket(1000, [1]) - test_dg_packet = DialityPacket.buildPacket(test_dg_simulator_req_id, []) + # test_packet = DialityPacket.buildPacket(0x01, [1]) + test_packet = DialinMessage.buildMessage(channel_id=1000, message_id=0x01, payload=[1]) + test_dg_packet = DialinMessage.buildMessage(test_dg_simulator_msg_id, []) sleep(3.0) test_print_sending_dg_board(test_channel_id, test_packet)