Example #1
0
	def __init__ (self,config = {}):
		import network as Network;self.config = config
		import socket,time,random,binascii,machine,re,ustruct,gc,ujson
		self.wlan_ap = Network.WLAN(Network.AP_IF)
		self.wlan_sta = Network.WLAN(Network.STA_IF)
		self.srv = None
		id = binascii.hexlify(machine.unique_id()).decode('ascii')
		code = [id[i:i+2] for i in range(0, len(id), 2)]

		max_index = 0 ; max_value = 0
		for x in range(6):
		  if int(code[x],16) > max_value:
			max_value = int(code[x],16)
			max_index = x
		color = []
		if max_index == 0 : color = ['red',(255,59,48)]
		if max_index == 1 : color = ['green',(76,217,100)]
		if max_index == 2 : color = ['blue',(0,122,255)]
		if max_index == 3 : color = ['pink',(255,45,85)]
		if max_index == 4 : color = ['purple',(88,86,214)]
		if max_index == 5 : color = ['yello',(255,204,0)]
			
		
		try :
			f = open('config.json')
			self.ap_name = loads(f.read()).get('device_name')
			if self.ap_name == None :
				raise Exception
		except Exception:
			self.ap_name = 'Blocky ' + color[0].upper() +' '+ binascii.hexlify(machine.unique_id()).decode('ascii')[0:4];print(self.ap_name)
		indicator.animate()
		indicator.rgb[0] = color[1]
		indicator.rgb.write()
		self.ap_password = ''
		self.wifi_status = 0
Example #2
0
 def process(self):  # Feed function , run as much as possible
     indicator.animate('heartbeat', (100, 0, 0))
     self.last_call = runtime()
     if self.state != 1:
         return
     try:
         self.mqtt.check_msg()
     except Exception as err:
         print('nw-mqtt-> ', err)
Example #3
0
	def log(self,message):
	
		if self.state != 1 or not message:
			return 
		prefix = self.config.get('auth_key') + '/sys/' + CHIP_ID + '/log'
		try :
			indicator.animate('pulse' , (0,50,50))
			self.mqtt.publish(topic=prefix,msg=str(message))
		except Exception as err:
			print('nw-log->',err,message)
Example #4
0
	def send(self,topic,data,echo=False):
		if self.state!=1 or not topic or not data:
			return 
		topic = self.config.get('auth_key') + '/user/' + topic
		if not echo and self.message_handlers.get(topic):
			self.echo.append(self.userPrefix+str(topic))
		try :
			indicator.animate('pulse' , (0,0,100))
			self.mqtt.publish(topic = topic,msg = str(data))
		except Exception as err:
			print('nw-send->',err,topic,data)
Example #5
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 = ''
Example #6
0
if not error:
    if latest > firmware:
        import os
        list = (urequests.get(
            'https://raw.githubusercontent.com/curlyz/Firmware/master/branch/'
            + board + '/' + str(latest_version) + '/list.json').text)

        print(list)
        list = ujson.loads(list)
        for x in list['update_list']:
            if x != 'Blocky/system.json':
                try:
                    f = open(x, 'w')
                    f.write(
                        urequests.get(
                            'https://raw.githubusercontent.com/curlyz/Firmware/master/branch/TheShield/'
                            + str(latest_version) + "/" + x).text)
                    f.close()
                    print('File', x, 'updated')
                    indicator.animate('pulse', (0, 0, 100), 20)
                except Exception as err:
                    print(err)
        f = open('Blocky/system.json', 'w')
        f.write(
            urequests.get(
                'https://raw.githubusercontent.com/curlyz/Firmware/master/branch/TheShield/'
                + str(latest_version) + "/" + x).text)
        f.close()
        print('File', x, 'updated')
        print('Done +>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        indicator.animate('pulse', (0, 100, 0), 50)
Example #7
0
	def connect(self):
		from network import WLAN , STA_IF
		wlan_sta = WLAN(STA_IF)
		wlan_sta.active(True)
		wifi_list = []
		indicator.animate('heartbeat' , (100,0,0))
		print('Scanning wifi')
		for wifi in wlan_sta.scan():
			print(wifi)
			wifi_list.append(wifi[0].decode('utf-8'))
		for preference in [p for p in self.config.get('known_networks') if p['ssid'] in wifi_list]:
			indicator.animate('heartbeat' , (100,50,0))
			wlan_sta.connect(preference['ssid'],preference['password'])
			print('[',runtime(),'] Connecting to network {0}...'.format(preference['ssid']))
			for check in range(0,5):
				if wlan_sta.isconnected():
					break
				print('.',end='')
				sleep_ms(1000)
			if wlan_sta.isconnected():
				print('Connected to ' , preference)
				self.mqtt_connected = False
				for i in range(5):
					indicator.animate('heartbeat' , (200,100,0))
					try :
						print('Retry..')
						self.mqtt.connect()
						self.mqtt_connected = True
						sleep_ms(2000)
						break
					except Exception:
						pass

		if not wlan_sta.isconnected() or not self.mqtt_connected :
			ConfigManager()
		indicator.animate('pulse' , (10,50,100))	
		# At this poinrt , wifi and broker are connected
		self.mqtt.set_callback(self.handler)
		register_data = {'event': 'register', 
			'chipId': CHIP_ID, 
			'firmwareVersion': '1.0',
			'name': self.config.get('device_name', 'Blocky_' + CHIP_ID),
			'type': 'esp32'
		}
		
		
		self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/ota/#')
		self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/run/#')
		self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/rename/#')
		self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/reboot/#')
		self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/upload/#')
		self.mqtt.subscribe(self.config['auth_key'] + '/sys/' + CHIP_ID + '/upgrade/#')
		self.mqtt.publish(topic=self.config['auth_key'] + '/sys/', msg=dumps(register_data))
    
		self.state = 1
		print('Connected to broker')
		indicator.animate()
		for x in range(0,250,1):
			indicator.rgb[0] = (0,x,x);indicator.rgb.write()
			sleep_ms(1)
		for x in range(250,0,-1):
			indicator.rgb[0] = (0,x,x);indicator.rgb.write()
			sleep_ms(1)	
		return True 
Example #8
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 = ''
Example #9
0
from Blocky.Indicator import indicator
import network, socket, time, random, binascii, machine, re, ustruct, gc, ujson
from json import dumps, loads
from os import stat
from _thread import start_new_thread
import socket
from Blocky.MicroWebSrv import MicroWebSrv
from time import sleep_ms
"""
class config is called when esp boot and cant connect or the connection is dropped randomly 
therefore , when the network is restore  , this will reset ,
"""

indicator.animate(type='heartbeat', color=(50, 0, 0), speed=10)
sleep_ms(2000)


class ConfigManager:
    def __init__(self, config={}):
        self.config = config
        self.wlan_ap = network.WLAN(network.AP_IF)
        self.wlan_sta = network.WLAN(network.STA_IF)

        id = binascii.hexlify(machine.unique_id()).decode('ascii')
        code = [id[i:i + 2] for i in range(0, len(id), 2)]

        max_index = 0
        max_value = 0
        for x in range(6):
            if int(code[x], 16) > max_value:
                max_value = int(code[x], 16)