Exemple #1
0
    async def handler(self):
        while True:
            await asyncio.sleep_ms(10)
            self.curr = self.adc.read()
            self.his.pop(0)
            self.his.append(self.curr)
            if self.curr > self.limit:
                self.last = ticks_ms()
            if self.his[1] - self.his[0] > 0 and self.his[1] - self.his[
                    2] > 0 and self.his[1] > self.limit:
                self.count += 1

            if ticks_ms() - self.last > 500 and self.count > 0:
                for x in self.cb:
                    if x[0] == 'clap' and x[1] == self.count:
                        try:
                            if x[3] == 'g':
                                loop = asyncio.get_event_loop()
                                loop.create_task(Cancellable(x[2])())
                            if x[3] == 'f':
                                x[2]()
                        except Exception as err:
                            print('sound-event->', err)
                if self.callback[0] != None:
                    if self.callback[1] == 'g':
                        loop = asyncio.get_event_loop()
                        loop.create_task(
                            Cancellable(self.callback[0])(self.count))
                    if self.callback[1] == 'f':
                        self.callback[0](self.count)

                self.count = 0
                self.prev = 0
Exemple #2
0
 def __init__(self, gatherables):
     ncoros = len(gatherables)
     self.barrier = Barrier(ncoros + 1)
     self.results = [None] * ncoros
     loop = asyncio.get_event_loop()
     for n, gatherable in enumerate(gatherables):
         loop.create_task(self.wrap(gatherable, n)())
Exemple #3
0
    def __init__(self, port):
        self.last = None
        self.status = False
        self.message = None
        self.pin = getPin(port)
        self.cb = None
        from machine import UART
        self.ser = UART(1, tx=self.pin[0], rx=self.pin[1], baudrate=115200)
        self.status = True
        self.ser.write('\x55\x55\x00\x00\x00')  # wakeup babe
        self.SAM_configuration()

        loop = asyncio.get_event_loop()
        loop.call_soon(self._handler())
Exemple #4
0
 def __init__(self, port, module='DHT11'):
     pin = getPin(port)
     if (pin[0] == None):
         return
     if module == 'DHT11': self.weather = DHT11(Pin(pin[0]))
     elif module == 'DHT22': self.weather = DHT22(Pin(pin[0]))
     elif module == 'DHTBase': self.weather = DHTBase(Pin(pin[0]))
     else:
         raise NameError
     self.last_poll = runtime()
     self.cb_humidity = []
     self.cb_temperature = []
     loop = asyncio.get_event_loop()
     loop.call_soon(self.handler())
Exemple #5
0
 def __init__(self, port):
     self.p = getPin(port)
     if self.p[0] == None:
         return
     self.last_time = runtime()
     self.last_state = 0
     self.number = 0
     self.ButtonTaskList = {}
     self.his = []
     self.button = Pin(self.p[0], Pin.IN, Pin.PULL_DOWN)
     self.button.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING,
                     handler=self._handler)
     loop = asyncio.get_event_loop()
     loop.create_task(Cancellable(self._async_handler)())
Exemple #6
0
    async def handler(self):

        while True:
            temp = self.weather.temperature()
            humd = self.weather.humidity()

            await asyncio.sleep_ms(2500)
            try:
                self.weather.measure()
            except Exception:
                pass
            if self.weather.temperature() != temp and self.cb_temperature:
                try:
                    if self.cb_temperature[1] == 'f':
                        self.cb_temperature[0](self.weather.temperature())
                    if self.cb_temperature[1] == 'g':
                        loop = asyncio.get_event_loop()
                        loop.create_task(
                            Cancellable(self.cb_temperature[0])(
                                self.weather.temperature()))

                except Exception as err:
                    print('weather-event-temp->', err)
                    pass
            if self.weather.humidity() != temp and self.cb_humidity:
                try:
                    if self.cb_humidity[1] == 'f':
                        self.cb_humidity[0](self.weather.humidity())
                    if self.cb_humidity[1] == 'g':
                        loop = asyncio.get_event_loop()
                        loop.create_task(
                            Cancellable(self.cb_temperature[0])(
                                self.weather.humidity()))

                except Exception:
                    print('weather-event-humd->', err)
                    pass
Exemple #7
0
	def handler(self,topic,message):
		try :
			indicator.animate('pulse' , (0,100,0))
			print('handle',topic  , message)
			self.topic = topic.decode()
			self.message = message.decode()
			print(self.topic  , self.message,self.topic.startswith(self.userPrefix))
			if self.topic.startswith(self.userPrefix):
				if self.topic in self.echo:
					print('echo' , self.topic)
					self.echo.remove(self.topic)
					return 
					
				function = self.message_handlers.get(self.topic)
				print('func' , function)
				if function :
					print('init')
					loop = asyncio.get_event_loop()
					try :
						if not str(function(self.topic.split('/')[-1],self.message)).split("'")[1] in loop.tasks :
							loop.call_soon(function(self.topic.split('/')[-1],self.message),self.topic.split('/')[-1],self.message)
					except Exception as err:
						print('['+str(clock())+']','nw-handler->' , err)
						
					
			elif self.topic.startswith(self.sysPrefix):
				if self.topic==self.sysPrefix+'ota':
					print('['+str(clock())+']' , 'OTA Message' , len(self.message))
					f = open('user_code.py','w')
					f.write(self.message)
					f.close()
					otaAckMsg = {'chipId': CHIP_ID, 'event': 'ota_ack'}				 
					self.mqtt.publish(topic=self.config['auth_key'] + '/sys/', msg=dumps(otaAckMsg))
					sleep_ms(500)
					from machine import reset
					reset()
				elif self.topic == sysPrefix + 'run':
					print('['+str(clock())+']' , 'RUN message' , len(self.message))
					exec(self.message , globals())
					# this will be used to handle upgrade firmwareVersion
				
				
					
		except Exception as err:
			print('nw-handler->' , err)
		finally :
			gc.collect()
			self.topic = ''
			self.message = ''
Exemple #8
0
    def execute(self, type, time):
        try:

            function = self.ButtonTaskList.get(str(type) + str(time))
            if function == None:
                raise Exception
            if str(function).find('generator'):
                loop = asyncio.get_event_loop()
                loop.create_task(Cancellable(function)())
            else:
                function()

        except Exception as err:
            print('btn-exec->', err)
            pass
Exemple #9
0
    def event(self, type, function):
        if type == 'temperature':
            self.cb_temperature = function
        if type == 'humidity':
            self.cb_humidity = function
        if not self._handler:
            try:
                loop = asyncio.get_event_loop()
                print(str(self.handler()))
                if not str(self.handler()).split("'")[1] in loop.tasks:
                    self._handler = True
                    loop.call_soon(self.handler())

            except Exception:
                pass
Exemple #10
0
    def __init__(self, port, limit=500, sensitive=3):
        self.p = getPin(port)
        if self.p[2] == None:
            return

        self.adc = ADC(Pin(self.p[2]))
        self.adc.atten(ADC.ATTN_11DB)
        self.count = 0
        self.limit = limit
        self.his = [0, 0, 0]
        self.curr = 0
        self.last = ticks_ms()
        self.cb = []
        self.callback = [None, None]
        loop = asyncio.get_event_loop()
        #loop.call_soon(self.handler())
        loop.create_task(Cancellable(self.handler)())
Exemple #11
0
	async def _handler(self):
		while True :
			await asyncio.sleep_ms(500)
			now = self.read_passive_target()
			if (self.last != now and now != None):
				try :
					print('rfid',now)
					if callable(self.cb):
						if str(self.cb).find('generator'):
							
							loop = asyncio.get_event_loop()
							loop.create_task(Cancellable(self.cb)())
						else :
							self.cb(now)
				except Exception as err:
					print('rfid-event' , err , now )
					
			self.last = now
Exemple #12
0
    def handler(self, topic, message):
        try:
            indicator.animate('pulse', (0, 100, 0))
            print('handle', topic, message)
            self.topic = topic.decode()
            self.message = message.decode()
            print(self.topic, self.message,
                  self.topic.startswith(self.userPrefix))
            if self.topic.startswith(self.userPrefix):
                if self.topic in self.echo:
                    print('echo', self.topic)
                    self.echo.remove(self.topic)
                    return

                function = self.message_handlers.get(self.topic)
                print('func', function)
                if function:
                    print('init')
                    loop = asyncio.get_event_loop()
                    try:
                        if not str(
                                function(
                                    self.topic.split('/')[-1],
                                    self.message)).split("'")[1] in loop.tasks:
                            loop.create_task(
                                Cancellable(
                                    function(
                                        self.topic.split('/')[-1],
                                        self.message))(
                                            self.topic.split('/')[-1],
                                            self.message))
                    except Exception as err:
                        print('[' + str(runtime()) + ']', 'nw-handler->', err)

            elif self.topic.startswith(self.sysPrefix):
                if self.topic == self.sysPrefix + 'ota':
                    print('[' + str(runtime()) + ']', 'OTA Message',
                          len(self.message))
                    f = open('user_code.py', 'w')
                    #f.write('import Blocky.asyn as asyn\n'+self.message.replace('async def','@asyn.cancellable\nasync def'))
                    f.write(self.message)
                    f.close()
                    otaAckMsg = {'chipId': CHIP_ID, 'event': 'ota_ack'}

                    #global FLAG_UPCODE
                    #FLAG_UPCODE = True
                    print('Cancelling')
                    try:
                        loop = asyncio.get_event_loop()
                        loop.call_soon(self.cancel())
                    except:
                        pass
                    #loop.call_soon(cancel())
                    import Blocky.Global
                    Blocky.Global.flag_UPCODE = True

                    print('Canceled')

                    print('RUN')
                    self.mqtt.publish(topic=self.config['auth_key'] + '/sys/',
                                      msg=dumps(otaAckMsg))
                    # Clean up
                    """
					from machine import Pin , Timer , PWM
					list = [ 4, 33 , 16, 32, 23, 22, 27 , 19 , 13, 17 , 14, 18 , 25, 26 ]
					for x in list:
						PWM(Pin(x)).deinit()
					for x in range(0 , 10): # Dont touch software timer
						Timer(x).deinit()
					from Blocky.Main import GLOBAL_CAPTURE
					for x in list(globals()):
						if x not in GLOBAL_CAPTURE:
							del globals()[x]
					"""

                elif self.topic == sysPrefix + 'run':
                    print('[' + str(runtime()) + ']', 'RUN message',
                          len(self.message))
                    exec(self.message, globals())
                    # this will be used to handle upgrade firmwareVersion

        except Exception as err:
            print('nw-handler->', err)
        finally:
            gc.collect()
            self.topic = ''
            self.message = ''
Exemple #13
0
def launch(func, tup_args):
    res = func(*tup_args)
    if isinstance(res, type_coro):
        loop = asyncio.get_event_loop()
        loop.create_task(res)
Exemple #14
0
def require_network():
	network.connect()
	loop = asyncio.get_event_loop()
	loop.call_soon(service())
Exemple #15
0
	
else :
	from Blocky.Button import *
	button  = Button(12)
	from Blocky.Network import network
	button.event('pressed' , 1 , require_network)
	




# network will do the wifi and broker
from Blocky.MQTT import *
from Blocky.Network import *
import _thread
loop = asyncio.get_event_loop()
GLOBAL_CAPTURE = list(globals().keys()) 
try :
	exec(open('user_code.py').read())
except Exception as err:
	network.log('Your code crashed because of "' + str(err) + '"')
	
# TODO :
"""
 If inside the setup block contains a blocking operation , the chip will be bricked
 
"""


def atte():
  while True :