async def Run(self, aSleep: float = 1.0): ConnSTA = Plugin.Find('ConnSTA')[0] self.Mqtt = Mqtt = MQTTClient('%s-%s' % (cName, ConnSTA.Mac()) , ConfApp.Mqtt_Host, ConfApp.get('Mqtt_Port', 1883), ConfApp.Mqtt_User, ConfApp.Mqtt_Passw) Mqtt.set_callback(self.DoSubscribe) while True: try: await ConnSTA.Event.wait() Mqtt.disconnect() await asyncio.sleep(1) Mqtt.connect() await Mqtt.subscribe('%s/sub/#' % (cName)) while True: # simlify nesting. too many recursion #await Mqtt.check_msg() Mqtt.sock.setblocking(False) await Mqtt.wait_msg() await asyncio.sleep(aSleep) except Exception as E: Log.Print(1, 'x', 'TMqtt.Run()', E) await asyncio.sleep(aSleep)
async def DownloadList(aUrl: str) -> bool: Buf = uio.BytesIO() try: await UrlLoad(aUrl, Buf) Data = Buf.getvalue().decode("utf-8") Data = json.loads(Data) Buf.close() except Exception as E: Log.Print(1, 'x', 'DownloadList()', E) return False Size = 0 Root = aUrl.rsplit('/', 1)[0] Files = Data.get('Files', []) for File in Files: Arr = File.rsplit('/', 1) if (len(Arr) == 2): try: os.mkdir(Arr[0]) except: pass Url = Root + '/' + File with open(File, "w") as hFile: await UrlLoad(Url, hFile) hFile.seek(0, 2) Size += hFile.tell() return (Data.get('Size', 0) == Size)
async def DoRead(self, aCmd, aRes, aErr): Log.Print(1, 'i', 'Handle', aCmd, aRes, aErr) if (aCmd == 'AT+CGNSINF'): #+CGNSINF: 1,1,20210224133650.000,49.550612,25.592956,334.900,0.00,323.3,1,,2.8,2.9,1.0,,11,3,,,38,, #Date, Lat, Lon, Alt, Speed = aRes.split(',')[2:7] pass
async def Exec(self, aPort: int, aSpeed: int) -> dict: try: Obj = MHZ19(aPort, aSpeed) R = await Obj.GetCO2() except Exception as E: Log.Print(1, 'x', 'dev_mhz19', E) R = None return {'co2': R}
async def Exec(self, aPin: int) -> dict: try: Obj = DHT11(aPin) R = await Obj.Get() except Exception as E: Log.Print(1, 'x', 'dev_dht11', E) R = [None, None] return {'temperature': R[0], 'humidity': R[1]}
async def Send(self, aData) -> bool: if (self.Mqtt) and (self.Mqtt.is_connected()): Topic, Data = aData try: await self.Mqtt.publish(Topic, json.dumps(Data)) #print('---TMqtt.Send', aData) return True except Exception as E: Log.Print(1, 'x', 'Send()', E)
async def Exec(self, aScl: int, aSda: int) -> dict: i2c = machine.I2C(scl = machine.Pin(aScl), sda = machine.Pin(aSda)) try: Obj = SHT21(i2c) R = [await Obj.ReadTemper(), await Obj.ReadHumid()] except Exception as E: Log.Print(1, 'x', 'dev_sht21', E) R = [None, None] return {'temperature': R[0], 'humidity': R[1]}
async def Exec(self, aScl: int, aSda: int) -> dict: i2c = machine.I2C(scl=machine.Pin(aScl), sda=machine.Pin(aSda)) try: Obj = SHT31(i2c) R = await Obj.get_temp_humi() except Exception as E: Log.Print(1, 'x', 'Sen_sht31', E) R = [None, None] return {'temperature': R[0], 'humidity': R[1]}
async def _DoPost(self, aOwner, aMsg): if (aMsg.get('Val')): Log.Print(1, 'i', 'TDB._DoPost()', aMsg) db = self.Init(self.File) db.RecAdd() db.SetField('Alias', aMsg.get('Alias', 'X')) db.SetField('Time', time.time()) db.SetField('Val', aMsg.get('Val')) db.Close()
async def Exec(self, aScl: int, aSda: int) -> dict: i2c = machine.I2C(scl=machine.Pin(aScl), sda=machine.Pin(aSda)) try: Obj = AM2320(i2c) await Obj.measure() R = [Obj.temperature(), Obj.humidity()] except Exception as E: Log.Print(1, 'x', 'dev_am2320', E) R = [None, None] return {'temperature': R[0], 'humidity': R[1]}
def _IRQ(self, aEvent: int, aData): if (aEvent == _IRQ_CENTRAL_CONNECT): conn_h, _, addr = aData self._conns.add(conn_h) Log.Print(1, 'i', 'Connect', PrettifyMac(addr)) self._DoConnect(True, addr) elif (aEvent == _IRQ_CENTRAL_DISCONNECT): conn_h, _, addr = aData if (conn_h in self._conns): self._conns.remove(conn_h) Log.Print(1, 'i', 'Disconnect', PrettifyMac(addr)) self._Advertise() self._DoConnect(False, addr) elif (aEvent == _IRQ_GATTS_WRITE): Buf = self._ble.gatts_read(self._rx) Msg = Buf.decode('UTF-8').strip() self._DoReceive(Msg)
async def Exec(self, aPins: list) -> dict: R = {} try: for PinNo in aPins: Obj = Pin(PinNo, Pin.IN) R[str(PinNo)] = Obj.value() except Exception as E: Log.Print(1, 'x', 'gpio_read', E) R[str(PinNo)] = None return R
async def Check(self) -> bool: try: Val = await self.Get() Res = (Val is not None) and (abs(Val - self.Val) > self.ValD) or ( time.time() - self.Time > self.SecD) if (Res): self.Time = time.time() self.Val = Val return Res except Exception as E: Log.Print(1, 'x', 'Check()', E)
async def Run(): Log.Print(1, 'i', 'Run', os.uname()) #DSleep = (machine.reset_cause() == machine.DEEPSLEEP_RESET) #print('DSleep', DSleep) Plugin.LoadList(ConfApp.get('Plugins', 'App.HttpSrv')) Plugin.LoadDir('Plugin/App') #Plugins = sorted(list(Plugin.keys())) #print('Plugins', Plugins) gc.collect() Log.Print(1, 'i', 'Run()', 'MemFree %d' % (gc.mem_free())) try: await Plugin.Run() except KeyboardInterrupt: print('Ctrl-C') finally: await Plugin.StopAll()
async def Send(self, aData): if (await self.OnSend(aData)): # send unsend data while (len(self.Buf) > 0): Data = self.Buf.popleft() if (not await self.OnSend(Data)): break await asyncio.sleep(0.1) else: Log.Print(1, 'i', 'UnSent', aData) self.Buf.append(aData)
async def Exec(self, aDelay: float, aAsync: bool, aEcho: bool) -> dict: async with Lock: if (aAsync): await asyncio.sleep(aDelay) else: time.sleep(aDelay) R = {'delay': aDelay, 'async': aAsync, 'echo': aEcho} if (aEcho): Log.Print(1, 'i', 'sys_sleep', R) return R
async def Exec(self, aScl: int, aSda: int) -> dict: i2c = machine.I2C(scl=machine.Pin(aScl), sda=machine.Pin(aSda), freq=10000) try: Obj = BME280(i2c=i2c) R = await Obj.read_compensated_data() except Exception as E: Log.Print(1, 'x', 'dev_bme280', E) R = [None, None, None] return {'temperature': R[0], 'humidity': R[2], 'preasure': R[1]}
async def Exec(self, aPairs: list) -> dict: R = {} try: for PinNo, Val in aPairs: Obj = Pin(PinNo, Pin.OUT) Obj.value(Val) R[str(PinNo)] = Obj.value() except Exception as E: Log.Print(1, 'x', 'gpio_write', E) R[str(PinNo)] = None return R
async def Connect(self, aESSID: str, aPassw: str, aAddr: tuple = None): Log.Print(1, 'i', 'Connect() %s, %s, %s' % (aESSID, aPassw, aAddr)) # Improve connection integrity at cost of power consumption if (platform == 'esp8266'): from esp import sleep_type sleep_type(0) R = WLAN(STA_IF) R.active(False) await sleep(1) R.active(True) if (aAddr): R.ifconfig(aAddr) R.connect(aESSID, aPassw) await self._WaitForReady(R.isconnected) Log.Print(1, 'i', 'Net', R.ifconfig()) return R
def LoadMod(self, aPath: str): if (aPath == '') or (aPath.startswith('-')) or (self.get(aPath)): return __import__(aPath) Mod = sys.modules.get(aPath) Depends = getattr(Mod, 'Depends', '') for iDepend in Depends.split(): if (iDepend): Log.Print(1, 'i', '%s depends on %s' % (aPath, iDepend)) self.LoadMod(iDepend) self.AddTask(Mod, aPath)
async def EnableAP(self, aMode: bool, aPassw=None): Log.Print(1, 'i', 'EnableAP() %s, %s ' % (aMode, aPassw)) R = WLAN(AP_IF) R.active(False) await sleep(1) R.active(aMode) if (aMode): R.config(essid='vRelay-' + GetMac(R)[-4:], authmode=AUTH_WPA_WPA2_PSK, password=aPassw) await self._WaitForReady(R.active) return R
def AddTask(self, aModule, aPath: str): gc.collect() Log.Print(1, 'i', 'Plugin %s' % (aPath)) File = 'Conf/' + aPath.replace('.', '~') Conf = TConf(File + '.py') Conf.Load() ConfClass = TConfClass(File + '.json', Conf) ConfClass.Load() Arr = aModule.Main(Conf) if (Arr): Class, AFunc = Arr self[aPath] = (Class, asyncio.create_task(AFunc)) if (Conf) or (ConfClass): Class.CC = ConfClass
async def Exec(self, aPin: int, aIDs: list) -> dict: HexID = [] for ID in aIDs: HexID.append(binascii.unhexlify(ID)) R = [] try: Obj = DS1820(aPin) Data = await Obj.Get(HexID) for Item in Data: R.append({ 'id': binascii.hexlify(Item['id']), 'value': Item['value'] }) except Exception as E: Log.Print(1, 'x', 'Sen_ds18b20', E) return R
async def Connector(self): if (not await self.IsOk()): try: await self.Connect(ConfApp.STA_ESSID, ConfApp.STA_Paswd, ConfApp.STA_Net) except Exception as E: Log.Print(1, 'x', 'Connector()', E) Ok = await self.IsOk() if (self.Last != Ok): self.Last = Ok await self.Post(int(Ok)) if (Ok): self.Event.set() SetTime(ConfApp.get('TZone', 2)) else: self.Event.clear()
async def CallBack(self, aReader: asyncio.StreamReader, aWriter: asyncio.StreamWriter): Head = await ReadHead(aReader, True) #Log.Print(2, 'i', 'CallBack()', 'path: %s, query: %s' % (Head.get('path'), Head.get('query'))) Path = Head.get('path') Method = self.GetMethod(Path) Obj = getattr(self, Method, None) try: if (Obj): await Obj(aReader, aWriter, Head) elif (UFS.FileExists(self.DirRoot + '/' + Method + '.py')): Lib = __import__(self.DirRoot + '/' + Method) await Lib.THttpApiEx(self).Query(aReader, aWriter, Head) else: await self.DoUrl(aReader, aWriter, Head) except Exception as E: Data = Log.Print(1, 'x', 'CallBack()', E) await self.Answer(aWriter, 404, 'html', Data) finally: await aWriter.aclose()
def _Load(self, aFile: str): with open(aFile) as hF: Data = self._Replace(hF.read()) try: Data = json.loads(Data) for Item in Data.get('Classes', []): Alias = Item.get('Alias') Class = Item.get('Class') Param = Item.get('Param', {}) Module = Item.get('Module') Mod = __import__(Module, None, None, [Class]) TClass = getattr(Mod, Class) Obj = TClass(**Param) Obj.Descr = Item.get('Descr', '') Obj.Alias = Alias self[Alias] = Obj except Exception as E: Log.Print(1, 'x', '_Load()', E) print('Data', Data)
async def LoadFile(self, aWriter: asyncio.StreamWriter, aPath: str): if (aPath == '/'): aPath = self.FIndex if (UFS.FileExists(self.DirRoot + aPath)): Path = aPath Code = 200 else: Log.Print(1, 'e', 'File not found %s' % self.DirRoot + aPath) Path = self.F404 Code = 404 Ext = Path.split('.')[-1] if (Ext in ['html', 'txt', 'css', 'json']): Mode = 'r' else: Mode = 'rb' Header = THeader() Header.Create(Code, Ext, UFS.FileSize(self.DirRoot + Path)) await aWriter.awrite(str(Header)) await self.FileToStream(aWriter, self.DirRoot + Path, Mode)
def on_message(self, client, topic, payload, qos, properties): #print('on_message()', topic, payload.decode(), properties) Log.Print(1, 'on_message()', 'topic %s, payload %s, qos %s, time %s' % (topic, payload, qos, round(time.time() - self.Last, 1))) self.Last = time.time()
def DoTimeout(self, aTimer): Log.Print(2, 'i', 'TWDog timeout') time.sleep(3) aTimer.deinit() machine.reset()
#!/usr/bin/env python import os import signal import asyncio import time from gmqtt import Client as MQTTClient import sys sys.path.append('../../src') from Inc.Log import Log, TEchoFile Log.AddEcho(TEchoFile('a_sub.py.log')) Log.Print(1, 'start', 0) AEvent = asyncio.Event() async def TaskPulse(): Cnt = 0 while True: Cnt += 1 print('TaskPulse', Cnt) await asyncio.sleep(5) def ask_exit(*args): AEvent.set()