def _run_mqtt_process(self): pubwait = self.mqtt_check() while True: try: next(pubwait) except StopIteration: if self.debug: print("StopIteration") _thread.wait(1000)
def _serverProcess(self): self._started = True self._state = "Running" while True: try: client, cliAddr = self._server.accepted() if client == None: if self.isThreaded: notify = _thread.getnotification() if notify == _thread.EXIT: break elif notify == _thread.SUSPEND: self._state = "Suspended" while _thread.wait() != _thread.RESUME: pass self._state = "Running" # gc.collect() time.sleep_ms(2) continue except Exception as e: if not self.isThreaded: print(e) break self._client(self, client, cliAddr) self._started = False self._state = "Stoped" self.thID = None
def run_script_threaded(filename): try: thread.stack_size(5*1024) thread.allowsuspend(True) file = open(filename) content = file.read() file.close() fix = '''while True: ntf = thread.getnotification() if ntf: if ntf == thread.EXIT: sys.exit() elif ntf == thread.SUSPEND: while thread.wait() != thread.RESUME: pass''' content = content.replace('while True:', fix) content = content.replace('while 1:', fix) exec(content) while True: ntf = thread.getnotification() if ntf: if ntf == thread.EXIT: return elif ntf == thread.SUSPEND: while thread.wait() != thread.RESUME: pass except Exception as e: print(red(thread.getSelfName() + str(e))) return
def __getEncoderValue(self): """Thread for fast polling encoder value""" while True: ntf = _thread.wait(0) if ntf == _thread.EXIT: # Terminate the thread return self.encoder_value = self.encoder_state_machine.value() time.sleep(0.001)
def checkMessages(self, wait = False, timeout = None): if wait: # Wait for message if timeout: _thread.wait(timeout) else: _thread.wait() message_type, sender_ID, message_JSON = _thread.getmsg() if message_type == 2: # If the message is a string # Parse the topic and message msg = json.loads(message_JSON) topic = msg["topic"] message = msg["message"] return (topic, message) return (None, None)
def video_thread_fn(data, clock, latch, buffer, mask, refresh_interval): print("video_thread: started") _thread.allowsuspend(True) d = [ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1] ] r = [0, 1, 2, 3, 4, 5, 6] row = 0 while True: row %= 5 for x in r: # (mask[1][row] >> x) data.value(1 - ((buffer[1][row] >> x & 1) & (mask[1] >> row & 1))) clock.value(1) clock.value(0) for j in d[row]: data.value(j) clock.value(1) clock.value(0) for x in r: data.value(1 - ((buffer[0][row] >> x & 1) & (mask[0] >> row & 1))) clock.value(1) clock.value(0) for j in d[row]: data.value(j) clock.value(1) clock.value(0) latch.value(0) latch.value(1) row += 1 _thread.wait(refresh_interval)
def video_thread_fn(data, clock, latch, buffer, mask, refresh_interval): print("video_thread: started") _thread.allowsuspend(True) d = [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] r = [0, 1, 2, 3, 4, 5, 6] row = 0 while True: row %= 5 for x in r: # (mask[1][row] >> x) data.value(1 - ((buffer[1][row] >> x & 1) & (mask[1] >> row & 1))) clock.value(1) clock.value(0) for j in d[row]: data.value(j) clock.value(1) clock.value(0) for x in r: data.value(1 - ((buffer[0][row] >> x & 1) & (mask[0] >> row & 1))) clock.value(1) clock.value(0) for j in d[row]: data.value(j) clock.value(1) clock.value(0) latch.value(0) latch.value(1) row += 1 _thread.wait(refresh_interval)
def waitForExitNotification(timeout): """ waitForExitNotification(timeout) uses _thread.wait(timeout) to sleep for amount of ms saved in timeout and checks notfication for _thread.EXIT notification. Returns True if _thread.EXIT notification is recieved, else returns False timeout: (ms) time in ms used for _thread.wait() return: (boolean) True if _thread.EXIT is recieved, else False. """ ntf = _thread.wait(timeout) if ntf == _thread.EXIT: return True return False
def test(): i = 0 while i<10: i=i+1 print("Hello from thread") print(_thread.getSelfName()) mainID = _thread.getReplID() print(mainID) print(_thread.getmsg()) print(_thread.wait()) while _thread.wait() : #_thread.sendmsg(mainID, i) time.sleep(2) thrID = _thread.start_new_thread("test",test,()) _thread.sendmsg(thrID, 5) _thread.getmsg() _thread.list() _thread.notify(thrID, 1) #k=_thread.start_new_thread("testThr",testThread,(1,)) _thread.start_new_thread(testThread()) k=0 while k<15: k=k+1 time.sleep(1) print("Hello from main") pass
def ThrTimePolSec(self): # Поток для вызова ф-ций каждые пол секунды i = 0 try: while i < 100: self.IndProc() notification = _thread.wait(500) if (notification == _thread.EXIT): print("ThrTimePolSec.EXIT") break except KeyboardInterrupt: print("ThrTimePolSec KeyboardInterrupt") except Exception: print("ThrTimePolSec Exception")
def __shotState(self): """Thread for checking states""" self.state_old = self.encoder_value while True: ntf = _thread.wait(50) if ntf == _thread.EXIT: # Terminate the thread return if not self.edit_state: self.state = self.encoder_value if self.state_old != self.state: self.run = True self.state_old = self.state else: self.seconds = self.encoder_value
def waitForExitNotification(timeout): """ waitForExitNotification(timeout) uses _thread.wait(timeout) to sleep for amount of ms saved in timeout and checks notfication for _thread.EXIT notification. Returns True if _thread.EXIT notification is recieved, else returns False timeout: (ms) time in ms used for _thread.wait() return: (boolean) True if _thread.EXIT is recieved, else False. """ notification = _thread.wait(timeout) if notification == _thread.EXIT: strip.set(0, 0x00, num=num_pixels) print("stopping animation") return True else: return False
def ThrReadTemperature(self): # Поток для вызова ф-ций каждые пол секунды i = 0 try: while i < 100: #self.IndProc() self.getAllTemperature() #self.printTemperature() #print("ThrReadTemperature") notification = _thread.wait(100) if (notification == _thread.EXIT): #print("ThrReadTemperature.EXIT") break except KeyboardInterrupt: print("ThrTimePolSec KeyboardInterrupt") except Exception: print("ThrTimePolSec Exception")
def heartbeat(self, isReversed=False): _thread.allowsuspend(True) while True: ntf = _thread.getnotification() if ntf == _thread.EXIT: # return from thread terminates the thread #print("heartbeat: terminated") return elif ntf == _thread.SUSPEND: while _thread.wait() != _thread.RESUME: pass else: # default notification handling pass # regular application code self._heartbeat(isReversed)
def _run_http_process(self): while True: self._http_server.server_process() _thread.wait(300)
def button_push_check(self): while True: self.btn_ctrl.push_check _thread.wait(200)
def th_func(threads: dict): # ------------------------------------------------------------ # Allow suspending this thread from other threads using # _thread.suspend(th_id) / _thread.resume(th_id) functions. # If not set, the thread connot be suspended. # Still, "soft" suspend handling via notifications can be used # ------------------------------------------------------------ _thread.allowsuspend(True) cur_name = _thread.getSelfName() cur_id = threads[cur_name] print("{}: started with id {}".format(cur_name.upper(), cur_id)) # --------------------------------------------- # Thread function usually runs in infinite loop # --------------------------------------------- while True: # ================================================ # It is recommended to handle thread notifications # ================================================ ntf = _thread.getnotification() if ntf: # some notification received if ntf == _thread.EXIT: # ------------------------------------------------- # Return from thread function terminates the thread # ------------------------------------------------- print("{}: terminated".format(cur_name.upper())) return elif ntf == _thread.SUSPEND: # ------------------------------------------------------------------- # The thread can be suspended using _thread.suspend(th_id) function, # but sometimes it is more convenient to implement the "soft" suspend # ------------------------------------------------------------------- print("{}: suspended".format(cur_name.upper())) # wait for RESUME notification indefinitely, some other thread must # send the resume notification: _thread.notify(th_id, _thread.RESUME) while _thread.wait() != _thread.RESUME: pass print("{}: resumed".format(cur_name.upper())) # --------------------------------------------- # Handle the application specific notifications # --------------------------------------------- elif ntf == 1234: # Your notification handling code pass else: # ----------------------------- # Default notification handling # ----------------------------- pass # ---------------------------------- # Put your thread function code here # ---------------------------------- # --------------------------------------------------------------------------- # Thread function execution can be suspended until a notification is received # Without argument '_thread.wait' will wait for notification indefinitely # If the timeout argument is given, the function will return even if # no notification is received after the timeout expires with result 'None' # --------------------------------------------------------------------------- # ntf = _thread.wait(30000) # if ntf: # # -------------------------------------------- # # Check if terminate notification was received # # -------------------------------------------- # if ntf == _thread.EXIT: # return # #print("TH_FUNC: Notification received: ", ntf) # # # --------------------------------------------- # # Execute some code based on notification value # # --------------------------------------------- # if ntf == 77: # print("Notification 77 received") # elif ntf == 8888: # myvar += 100 # else: # # --------------------------------- # # Execute some code on wait timeout # # --------------------------------- # print("TH_FUNC: Wait notification timeout") # --------------------------------------------------------------- # - Using sleep in thread function - # --------------------------------------------------------------- # 'utime.sleep(sec, True)' & 'utime.sleep_ms(ms, True)' functions returns the # actual ellapsed sleep time. The sleep will be interrupted if # a notification is received and the returned value will be less # than the requested one # --------------------------------------------------------------- # Example: # print("TH_FUNC: Loop started") # for i in range(0, 5): # print("TH_FUNC: Loop no:", i) # sleep_time = utime.sleep_ms(10000, True) # if sleep_time < 10000: # # Notification received while sleeping # print("TH_FUNC: Notification while sleeping", st) # # Sleep for the remaining interval if needed # utime.sleep_ms(10000 - sleep_time) # print("TH_FUNC: Loop ended") # =================================================================================== # Handle inter thread message # Sender thread ID, message type (string or integer) and message itself are available # =================================================================================== typ, sender, msg = _thread.getmsg() if msg: # ------------------------------------- # message received from 'sender' thread # ------------------------------------- if typ == 1 and msg == thr_msg.HEARTBEAT: # Reply to sender, we can analyze the message first _thread.sendmsg(sender, thr_msg.HEARTBEAT) else: # We can inform the main MicroPython thread (REPL) about received message _thread.sendmsg( threads["log"], "[%s] Received message from '%s'\n'%s'" % (_thread.getSelfName(), _thread.getThreadName(sender), msg))
def __threadfunc(self): while(True): self.running = False self.joints.clear() thread.wait() ntf = thread.getnotification() if(ntf == thread.STOP): return sync = self.syncMode if(sync): top = -1 synctime = None for j in self.joints: r = abs(j.curPos - j.newPos) if(r > top): top = r synctime = r / j.speed jdata = [] for j in self.joints: posdiff = abs(j.curPos - j.newPos) if(posdiff == 0): continue if(sync): step = _DELAY * (posdiff / synctime) else: step = _DELAY * j.speed steps = int(posdiff / step) step *= 1 if j.curPos < j.newPos else -1 jdata.append([j.curPos, steps, step, j.servo.setRaw, j.newPos]) j.curPos = j.newPos jdata.sort(key = lambda x: x[1], reverse = True) jlen = len(jdata) pos = jlen while(jlen): while(pos): pos -= 1 j = jdata[pos] j[1] -= 1 # steps - 1 j[0] += j[2] # curPos + step if(j[1] <= 0): # steps == 0 j[3](round(j[4])) # j.setRaw(j.newPos) jlen -= 1 else: j[3](round(j[0])) # j.setRaw(j.curPos) pos = jlen sleep_ms(_TDELAY)
def button_push_check(): while True: b4.push_check _thread.wait(200)
def th_cam_to_motor(threads: dict, thctm_values: dict, m, config: dict): _thread.allowsuspend(True) cur_name = _thread.getSelfName() cur_id = threads[cur_name] print("{}: started with id {}".format(cur_name.upper(), cur_id)) while True: """Notification Handling""" ntf = _thread.getnotification() if ntf: if ntf == _thread.EXIT: print("{}: terminated".format(cur_name.upper())) return elif ntf == _thread.SUSPEND: print("{}: suspended".format(cur_name.upper())) m.stop() # wait for RESUME notification indefinitely, some other thread must # send the resume notification: _thread.notify(th_id, _thread.RESUME) while _thread.wait() != _thread.RESUME: pass print("{}: resumed".format(cur_name.upper())) else: # Default notification handling pass # --------------------------------------------------------------- # - Using sleep in thread function - # --------------------------------------------------------------- # 'utime.sleep(sec, True)' & 'utime.sleep_ms(ms, True)' functions returns the # actual ellapsed sleep time. The sleep will be interrupted if # a notification is received and the returned value will be less # than the requested one # --------------------------------------------------------------- # Example: # print("TH_FUNC: Loop started") # for i in range(0, 5): # print("TH_FUNC: Loop no:", i) # sleep_time = utime.sleep_ms(10000, True) # if sleep_time < 10000: # # Notification received while sleeping # print("TH_FUNC: Notification while sleeping", st) # # Sleep for the remaining interval if needed # utime.sleep_ms(10000 - sleep_time) # print("TH_FUNC: Loop ended") # =================================================================================== # Handle inter thread message # Sender thread ID, message type (string or integer) and message itself are available # =================================================================================== "" # <MAIN CODE> """Line Parsing and Motor controlling""" line_angle = thctm_values["line"][1] line_type = thctm_values["line"][0] l_value = r_value = config["drive_speed"] if line_type == CUART.ltype_straight: x = line_angle # l_value = constrain(maprange([-90, 0], [0, config["drive_speed"]], line_angle), 0, config["drive_speed"]) # r_value = constrain(maprange([0, 90], [config["drive_speed"], 0], line_angle), 0, config["drive_speed"]) l_value = int(0.0006911 * x * x * x - 0.011111 * x * x + 0.044657 * x + 20) r_value = int(-0.0006911 * x * x * x - 0.011111 * x * x - 0.044657 * x + 20) # print(l_value, r_value) m.move(l_value, r_value) # </MAIN CODE> """Message handling""" typ, sender, msg = _thread.getmsg() if msg: if typ == 1 and msg == thr_msg.HEARTBEAT: _thread.sendmsg(sender, thr_msg.HEARTBEAT) # else: # _thread.sendmsg(threads["log"], "[%s] Received message from '%s'\n'%s'" % ( # _thread.getSelfName(), _thread.getThreadName(sender), msg)) utime.sleep_ms(10) # Weird bug (was 10 before, trying to minimize)
def ThrReciveSocket(self): print("thrReciveSocket is RUN") #_thread.allowsuspend(True) # while True: i = 0 while i < 100: i = i + 1 print("Hello from thread") print(_thread.getSelfName()) # mainID = _thread.getReplID() # print(mainID) # print(_thread.getmsg()) if (self.isConnect()): # если есть соеденение то читаем из соккета isOk = False cntByte = 0 self.datafromserver = bytearray() while (isOk != True): try: bn = self.serversock.read(1) self.datafromserver.extend(chr(bn[0])) cntByte += 1 except OSError as e: if e.args[0] == 110: if cntByte > 0: isOk = True #print(e) #print("cntByte = ", cntByte) self.isDataFromServer = True print("read data size = ", cntByte) print("len data size = ", len(self.datafromserver)) print(self.datafromserver) """ try: print("self.isConnect()") bn = self.serversock.readinto(self.datafromserver) if(bn >0): self.isDataFromServer = True else: self.err_thr_read = ERR_READ_DATA_FROM_SERVER print("read data size = ",bn) print("len data size = ", len(self.datafromserver)) print(self.datafromserver) except OSError as e: print("!!!!!!!! except OSError in ThrReciveSocket") # выставляем флаг того что была ошибка """ notification = _thread.wait() print("notification = ", notification) if (notification == _thread.EXIT): print("_thread.EXIT") break #if (notification == 10): #print("SEND_DATA_TO_SERBER == 1") #if (self.isConnect()): # try: # self.serversock.send(self.datatoserver) # except OSError as e: # print("!!!!!!!! except OSError in ThrReciveSocket") # выставляем флаг того что была ошибка #continue print("Stop thrReciveSocket")
def _serverProcess(self): try: self._started = True self._state = "Running" notify = -1 while True: try: client, cliAddr = self._server.accepted() if client == None: if self.isThreaded: notify = _thread.getnotification() if notify == _thread.EXIT: if self._debug: print("[{}] [SERVER] Stop request".format( time.ticks_ms())) try: self._server.close() except Exception as err: sys.print_exception(err) break elif notify == _thread.SUSPEND: self._state = "Suspended" while _thread.wait() != _thread.RESUME: pass self._state = "Running" else: if not self._started: break # gc.collect() # time.sleep_ms(2) continue except Exception as err: print("[{}] [SERVER]: Main loop exception".format( time.ticks_ms())) sys.print_exception(err) try: self._server.close() except Exception as err: sys.print_exception(err) break if self._debug: print("[{}] [SERVER] Accepted from {}; socket {}".format( time.ticks_ms(), cliAddr, client.getFD())) client.settimeout(0.4) self._client(self, client, cliAddr) if self._debug: print("[{}] [SERVER] Client finished".format( time.ticks_ms())) if self._debug: print("[{}] [SERVER] Exit".format(time.ticks_ms())) self._started = False self._state = "Stopped" self.thID = None except Exception as err: print("[{}] [SERVER]: Server process xxception".format( time.ticks_ms())) sys.print_exception(err) finally: try: self._server.close() except Exception as err: sys.print_exception(err) self._server = None self._started = False self._state = "Stopped" self.thID = None gc.collect()