Esempio n. 1
0
def rgbled(n=200, led=bled):
    notif_exit = 4718
    notif_replay = 2
    notif_count = 3
    x = 0
    _thread.allowsuspend(True)
    while True:
        led.value(1)
        time.sleep_ms(n)
        led.value(0)
        x = x + 1

        t = 10
        while t > 0:
            notif = _thread.getnotification()
            if notif == notif_exit:
                _thread.sendmsg(_thread.getReplID(), "[%s] Exiting" % (_thread.getSelfName()))
                return
            elif notif == notif_replay:
                _thread.sendmsg(_thread.getReplID(), "[%s] I've been notified" % (_thread.getSelfName()))
            elif notif == notif_count:
                _thread.sendmsg(_thread.getReplID(), "[%s] Run counter = %u" % (_thread.getSelfName(), x))
            elif notif == 777:
                _thread.sendmsg(_thread.getReplID(), "[%s] Forced EXCEPTION" % (_thread.getSelfName()))
                time.sleep_ms(1000)
                zz = 234 / 0
            elif notif != 0:
                _thread.sendmsg(_thread.getReplID(), "[%s] Got unknown notification: %u" % (_thread.getSelfName(), notif))

            typ, sender, msg = _thread.getmsg()
            if msg:
                _thread.sendmsg(_thread.getReplID(), "[%s] Message from '%s'\n'%s'" % (_thread.getSelfName(), _thread.getThreadName(sender), msg))
            time.sleep_ms(100)
            t = t - 1
        gc.collect()
Esempio n. 2
0
 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
Esempio n. 3
0
                 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
Esempio n. 4
0
def check_notify(nquit):
    notif = _thread.getnotification()
    if notif == nquit:
        print("[ftpserver] Received QUIT notification, exiting")
    elif notif != 0:
        print("[ftpserver] Notification %u unknown" % (notif))
    return notif
Esempio n. 5
0
 def check_notify_quit():
     notif = _thread.getnotification()
     if notif == _thread.EXIT:
         print("[MicroFtpSrv] Received QUIT notification, exiting")
         return True
     elif notif != 0:
         print("[MicroFtpSrv] Notification {} unknown".format(notif))
     return False
Esempio n. 6
0
def thrainbow():
    pos = 0
    np.brightness(25)
    while True:
        np.rainbow(pos, 3)
        notif = _thread.getnotification()
        if (notif > 0) and (notif <= 100):
            np.brightness(math.trunc(notif * 2.55))
            
        elif notif == 1000:
            _thread.sendmsg(_thread.getReplID(), "[%s] Run counter = %u" % (_thread.getSelfName(), pos))
        pos = pos + 1
Esempio n. 7
0
def thrainbow_py():
    pos = 0
    bri = 0.02
    while True:
        for i in range(0, num_np):
            dHue = 360.0/num_np * (pos+i);
            hue = dHue % 360;
            np.setHSB(i, hue, 1.0, bri, 1, False)
        np.show()
        notif = _thread.getnotification()
        if (notif > 0) and (notif <= 100):
            bri =  notif / 100.0
        elif notif == 1000:
            _thread.sendmsg(_thread.getReplID(), "[%s] Run counter = %u" % (_thread.getSelfName(), pos))
        pos = pos + 1
Esempio n. 8
0
 def mqtt_send_loop(self):
     """ send mqtt loop """
     # threading is different in lobo micropython
     if sys.platform.startswith("esp32_LoBo"):
         _thread.allowsuspend(True)
         while True:
             ntf = _thread.getnotification()
             if ntf:
                 # some notification received
                 if ntf == _thread.EXIT:
                     return
             self.send_one_message()
             time.sleep(0.1)
     else:
         pass
Esempio n. 9
0
    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 _wsProcess(self, acceptCallback) :
     self._socket.settimeout(3600)
     self._closed = False
     try :
         acceptCallback(self, self._httpCli)
     except Exception as ex :
         print("MicroWebSocket : Error on accept callback (%s)." % str(ex))
     while not self._closed :
         if self.isThreaded:
             notify = _thread.getnotification()
             if notify == _thread.EXIT:
                 self.Close()
                 break
         if not self._receiveFrame() :
             self.Close()
     if self.ClosedCallback :
         try :
             self.ClosedCallback(self)
         except Exception as ex :
             print("MicroWebSocket : Error on closed callback (%s)." % str(ex))
Esempio n. 11
0
def bmerun(interval=60):
    _thread.allowsuspend(True)
    sendmsg = True
    send_time = time.time() + interval
    while True:
        while time.time() < send_time:
            notif = _thread.getnotification()
            if notif == 10002:
                _thread.sendmsg(_thread.getReplID(), bmevalues())
            elif notif == 10004:
                sendmsg = False
            elif notif == 10006:
                sendmsg = True
            elif (notif <= 3600) and (notif >= 10):
                interval = notif
                send_time = time.time() + interval
                _thread.sendmsg(_thread.getReplID(), "Interval set to {} seconds".format(interval))
                
            time.sleep_ms(100)
        send_time = send_time + interval
        if sendmsg:
            _thread.sendmsg(_thread.getReplID(), bmevalues())
Esempio n. 12
0
    def _spin(self):
        while True:
            # Check for notification signals
            ntf = _thread.getnotification()
            if ntf:
                if ntf == _thread.EXIT:
                    # ...if received EXIT signal, clear screen to black and exit thread
                    self.tft.clear(self.tft.BLACK)
                    return

            # Draw green and grey (following) arc
            self.tft.arc(160, 120, 20, 5, self.green_arc[0], self.green_arc[1],
                         self.tft.GREEN, self.tft.GREEN)
            self.tft.arc(160, 120, 20, 5, self.grey_arc[0], self.grey_arc[1],
                         self.tft.LIGHTGREY, self.tft.LIGHTGREY)
            # Tiny delay before continuing to keep the animation at a reasonable speed.
            time.sleep_ms(50)

            # Step arc angles forward (accounting for going from 360 back to 0 degrees)
            if (self.green_arc[0] + 45) <= 360:
                self.green_arc[0] += 45
            else:
                self.green_arc[0] = 45 - (360 - self.green_arc[0])

            if (self.green_arc[1] + 45) <= 360:
                self.green_arc[1] += 45
            else:
                self.green_arc[1] = 45 - (360 - self.green_arc[1])

            if (self.grey_arc[0] + 45) <= 360:
                self.grey_arc[0] += 45
            else:
                self.grey_arc[0] = 45 - (360 - self.grey_arc[0])

            if (self.grey_arc[1] + 45) <= 360:
                self.grey_arc[1] += 45
            else:
                self.grey_arc[1] = 45 - (360 - self.grey_arc[1])
Esempio n. 13
0
def main():
    thread.allowsuspend(True)
    gc_count = 0
    if datebase is None:
        pass
    else:
        ssid_text.update(datebase['wifi']['ssid'])
        pwd_text.update(datebase['wifi']['pwd'])
        del_name_list.updatelistdate(namelist)
    while True:
        if buttonA.wasPressed(callback=None):
            window.event(1)
        elif buttonB.wasPressed(callback=None):
            window.event(2)
        elif buttonC.wasPressed(callback=None):
            window.event(3)
        #temp = keyboard.read()
        #if temp != b'\x00':
        #window.event(temp)
        #print(temp)

        ntf = thread.getnotification()
        if ntf:
            if ntf == 1001:  # 获取数据
                # print(internet_date)
                display()
                gc_count += 1
                # gc.collect()

        # 将debug_date 数据显示到debug窗口
        if len(debug_date) > 0:
            de(debug_date[0])
            del debug_date[0]
            gc_count += 1

        if gc_count > 20:
            gc.collect()
            gc_count = 0
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 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)
Esempio n. 16
0
    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()
Esempio n. 17
0
	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)