########################################################################### # # Copyright (c) 2020-2023 Diality Inc. - All Rights Reserved. # # THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN # WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. # # @file messageBuilder.py # # @author (last) Quang Nguyen # @date (last) 22-Jul-2021 # @author (original) Peter Lucia # @date (original) 11-Nov-2020 # ############################################################################ from dialin.ui import utils, crc syncByte = 'A5' def toCandumpFormat(msg: any) -> str: """ the converter method which converts the message vMsg to the string that candump tool understands. @param msg: the message @return: converted string to candump tool format """ if type(msg) == list: for index, value in enumerate(msg): msg[index] = ".".join(utils.partition(value, 2, False)) else: msg = ".".join(utils.partition(msg, 2, False)) return msg def toFrames(msg: any) -> list: """ converts the message vMsg to frames @param msg: adds the crc8 checksum at the end of the message vMsg @return: the frames """ mlen = 16 padded = utils.padding(msg, mlen) frames = utils.partition(padded, mlen, False) return frames def addCRC8(string: str, delimiter: str = "") -> str: """ adds the crc8 checksum at the end of the string vString @param string: (str) the string to be used @param delimiter: (str) the string delimiter @return: the string with crc8 """ return string + delimiter + crc.calc_crc8(string, delimiter) def textToByte(text: str, length) -> str: """ converts the string text to bytes by the given length @param text: (str) given string @param length: (int) given length @return: converted text """ new_text = "" text_len = len(text) for i in range(length): if i < text_len: new_text += utils.toI08(ord(text[i])) else: new_text += utils.toI08(0) new_text += utils.toI08(0) # null /0 return new_text def buildMessage(msg_id: int, length: int, ack: bool, *args) -> str: """ builds message from the parameter givven @param msg_id: (int) the message ID @param length: (int) length of the message payload in bytes @param ack: (bool) if true the message requires acknowledge back @param args: payload arguments. @return: built message """ msg = "" if ack: seq = -1 else: seq = 1 msg += utils.toI16(seq) # always used seq# (-)1 (for now) msg += utils.toI16(msg_id) msg += utils.toI08(length) for arg in args: msg += arg msg += crc.calc_crc8(msg) return syncByte + msg