Skip to content

Commit

Permalink
Several minor fix, asyncio, gpio, rotary encoder, config saving, OLED
Browse files Browse the repository at this point in the history
  • Loading branch information
enesbcs committed Nov 28, 2022
1 parent b21a330 commit e90610b
Show file tree
Hide file tree
Showing 32 changed files with 356 additions and 3,230 deletions.
469 changes: 0 additions & 469 deletions src/_C020_LoraDirect.py

This file was deleted.

7 changes: 6 additions & 1 deletion src/_N006_Telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import inc.misc as misc
import webserver_global as ws
from commands import parseruleline
import urequests
try:
import urequests
except:
import requests as urequests
try:
import ujson
except:
Expand Down Expand Up @@ -52,6 +55,7 @@ def webform_load(self): # create html page for settings
ws.addFormTextBox("Server","server",self.server,128)
ws.addFormNumericBox("Port","port",self.port,1,65535)
ws.addFormPasswordBox("Token","passw",self.passw,64)
ws.addFormTextBox("Chat-id","chatid",self.chatid,255)
ws.addHtml("<TR><TD>Body:<TD><textarea name='body' rows='5' cols='80' size=255 wrap='off'>")
ws.addHtml(str(self.body))
ws.addHtml("</textarea>")
Expand All @@ -72,6 +76,7 @@ def webform_save(self,params): # process settings post reply
if "**" not in passw:
self.passw = passw
self.chatid = ""
self.chatid = str(ws.arg("chatid",params))
self.body = ws.arg("body",params)
self.plugin_init()
return True
Expand Down
49 changes: 23 additions & 26 deletions src/_P001_Switch.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
########################################################################
##################### GPIO input plugin for mpyEasy ####################
################## GPIO input plugin for mpyEasy-async #################
########################################################################
#
# Copyright (C) 2020 by Alexander Nagy - https://bitekmindenhol.blog.hu/
# Copyright (C) 2022 by Alexander Nagy - https://bitekmindenhol.blog.hu/
#
import plugin
import pglobals
Expand Down Expand Up @@ -33,35 +33,35 @@ def __init__(self,taskindex): # general init
self._pin = None

def plugin_exit(self):
try:
self._pin.irq(handler=None)
except:
pass
return True

def plugin_init(self,enableplugin=None):
plugin.PluginProto.plugin_init(self,enableplugin)
self.decimals[0]=0
if int(self.taskdevicepin[0])>=0 and self.enabled:
import inc.libhw as libhw
self._pin = libhw.setgpio(int(self.taskdevicepin[0]))
self.set_value(1,self._pin.value(),True) # Sync plugin value with real pin state
try:
self.plugin_exit()
if self.taskdevicepluginconfig[0]:
misc.addLog(pglobals.LOG_LEVEL_INFO,"Registering 10/sec timer as asked")
self.taskdevicepluginconfig[0] = True #force hack
try:
if int(self.taskdevicepin[0])>=0 and self.enabled:
import inc.libhw as libhw
self._pin = libhw.setgpio(int(self.taskdevicepin[0]))
self.set_value(1,self._pin.value(),True) # Sync plugin value with real pin state
try:
if self.taskdevicepluginconfig[0]:
misc.addLog(pglobals.LOG_LEVEL_INFO,"Registering 10/sec timer as asked")
self.timer100ms = True
return True
self._pin.irq(trigger=3,handler=self.p001_handler) # https://github.com/peterhinch/micropython-async/blob/master/v3/docs/INTERRUPTS.md
misc.addLog(pglobals.LOG_LEVEL_DEBUG,"Event registered to pin "+str(self.taskdevicepin[0]))
self.timer100ms = False
except:
misc.addLog(pglobals.LOG_LEVEL_ERROR,"Event can not be added, register backup timer")
self.timer100ms = True
return True
self._pin.irq(trigger=3,handler=self.p001_handler)
misc.addLog(pglobals.LOG_LEVEL_DEBUG,"Event registered to pin "+str(self.taskdevicepin[0]))
self.timer100ms = False
except:
misc.addLog(pglobals.LOG_LEVEL_ERROR,"Event can not be added, register backup timer")
self.timer100ms = True
except:
pass

def webform_load(self):
# ws.addFormNote("Please make sure to select <a href='hardware'>pin configured</a> for input for default (or output to report back its state)!")
ws.addFormCheckBox("Force 10/sec periodic checking of pin","p001_per",self.taskdevicepluginconfig[0])
# ws.addFormNote("For output pin, only 10/sec periodic method will work!")
ws.addFormNote("Only 10/sec periodic method will work because asyncio!")
# ws.addFormNumericBox("De-bounce (ms)","p001_debounce",self.taskdevicepluginconfig[1],0,1000)
options = ["Normal Switch","Push Button Active Low","Push Button Active High"]
optionvalues = [0,1,2]
Expand All @@ -70,10 +70,7 @@ def webform_load(self):
return True

def webform_save(self,params):
if (ws.arg("p001_per",params)=="on"):
self.taskdevicepluginconfig[0] = True
else:
self.taskdevicepluginconfig[0] = False
self.taskdevicepluginconfig[0] = True
# par = ws.arg("p001_debounce",params)
# try:
# self.taskdevicepluginconfig[1] = int(par)
Expand Down
87 changes: 83 additions & 4 deletions src/_P023_OLED.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@
import pglobals
import inc.misc as misc
import webserver_global as ws
from commands import parseruleline
import commands
import inc.utime as utime
import inc.libhw as libhw
try:
from inc.ssd1306 import SSD1306_I2C
except:
pass
from inc.writer.writer import Writer
import settings

class Plugin(plugin.PluginProto):
PLUGIN_ID = 23
Expand Down Expand Up @@ -48,6 +49,11 @@ def __init__(self,taskindex): # general init
self.textlines = 0
self.graphmode = False
self.rgb = False
self.powerstate = -1
self.trigtask = ""
self.trigtime = 0
self._trigger = None
self.lastactive = 0

def plugin_init(self,enableplugin=None):
plugin.PluginProto.plugin_init(self,enableplugin)
Expand Down Expand Up @@ -133,7 +139,19 @@ def plugin_init(self,enableplugin=None):
err += str(e)
if self._device is not None and self._dispimage is not None:
self.initialized = True
self.powerstate = 1
misc.addLog(pglobals.LOG_LEVEL_INFO,"OLED initialized!")
try:
dstr = str(self.trigtask).strip()
didx = dstr.split("_")
self._trigger = settings.Tasks[int(didx[0])]
except Exception as e:
self._trigger = None
if self.trigtime == 0:
self._trigger = None
if self._trigger is not None:
self.lastactive = utime.time()
self._trigger._writecallback = self.triggerhandle
else:
misc.addLog(pglobals.LOG_LEVEL_ERROR,"OLED can not be initialized! "+str(err))
else:
Expand Down Expand Up @@ -177,6 +195,26 @@ def webform_load(self): # create html page for settings
except:
linestr = ""
ws.addFormTextBox("Line"+str(l+1),"p023_template"+str(l),linestr,128)
options1 = ["None"]
optionvalues1 = ["_"]
try:
for t in range(0,len(settings.Tasks)):
try:
if (settings.Tasks[t]):
options1.append("T"+str(t+1)+" / "+str(settings.Tasks[t].taskname))
optionvalues1.append(str(t))
except:
pass
except Exception as e:
print(e)
ws.addHtml("<tr><td>Stay on trigger task:<td>")
ws.addSelector_Head("p023_trig",False)
for o in range(len(options1)):
ws.addSelector_Item(options1[o],optionvalues1[o],(str(optionvalues1[o])==str(self.trigtask)),False)
ws.addSelector_Foot()
options1 = ["None","2 min","5 min","10 min","15 min","30 min"]
optionvalues1 = [0,2,5,10,15,30]
ws.addFormSelector("Trigger wake on time","p023_trigtime",len(options1),options1,optionvalues1,None,int(self.trigtime))

return True

Expand Down Expand Up @@ -230,11 +268,28 @@ def webform_save(self,params): # process settings post reply
self.lines[l]=linestr
except:
self.lines.append(linestr)

par = ws.arg("p023_trig",params)
self.trigtask = str(par)
par = ws.arg("p023_trigtime",params)
if par == "":
par = 0
self.trigtime = int(par)

self.plugin_init()
return True

def plugin_read(self): # deal with data processing at specified time interval
def plugin_read(self): # deal with data processing at specified time interval
if self.initialized and self.enabled:
if self._trigger is not None:
try:
if self.powerstate==1:
if self.lastactive+(self.trigtime*60)<utime.time():
self._device.poweroff()
self.powerstate=0
except:
pass
if self.powerstate==1:
try:
if self.taskdevicepluginconfig[6] == False:
self._device.fill(0)
Expand All @@ -252,12 +307,19 @@ def plugin_read(self): # deal with data processing at specified time interval
self._device.fill_rect( 0,y+2, self._device.width, y+self.lineheight, 0)
self._dispimage.set_textpos(self._device,y,0)
self._dispimage._printline(resstr,False)
if self.powerstate==1:
self._device.show()
except Exception as e:
misc.addLog(pglobals.LOG_LEVEL_ERROR,"OLED write error! "+str(e))
self._lastdataservetime = utime.ticks_ms()
self._lastdataservetime = utime.ticks_ms()
return True

def triggerhandle(self,taskindex,valuenum):
self.lastactive = utime.time()
if self.powerstate<1:
self._device.poweron()
self.powerstate=1

def plugin_write(self,cmd):
res = False
cmdarr = cmd.split(",")
Expand All @@ -271,9 +333,11 @@ def plugin_write(self,cmd):
if self._device is not None:
if cmd == "on":
self._device.poweron()
self.powerstate=1
res = True
elif cmd == "off":
self._device.poweroff()
self.powerstate=0
res = True
elif cmd == "clear":
self._device.fill(0)
Expand Down Expand Up @@ -331,7 +395,7 @@ def plugin_write(self,cmd):
return res

def oledparse(self,ostr):
cl, st = parseruleline(ostr)
cl, st = commands.parseruleline(ostr)
if st=="CMD":
resstr=str(cl)
else:
Expand Down Expand Up @@ -379,3 +443,18 @@ def getFrameBuf(self):

def show(self):
self._device.show()

def power(self,status=None):
res = False
if status is not None:
if status == 1:
self._device.poweron()
self.powerstate=1
res = True
else:
self._device.poweroff()
self.powerstate=0
res = True
else:
return self.powerstate
return res
117 changes: 117 additions & 0 deletions src/_P051_AM2320.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#############################################################################
############################# AM2320 for mpyEasy ############################
#############################################################################
#
# Copyright (C) 2022 by Alexander Nagy - https://bitekmindenhol.blog.hu/
#
import plugin
import pglobals
import misc
import webserver_global as ws
import utime
import inc.libhw as libhw
import ustruct

class Plugin(plugin.PluginProto):
PLUGIN_ID = 51
PLUGIN_NAME = "Environment - AM2320"
PLUGIN_VALUENAME1 = "Temperature"
PLUGIN_VALUENAME2 = "Humidity"

def __init__(self,taskindex): # general init
plugin.PluginProto.__init__(self,taskindex)
self.dtype = pglobals.DEVICE_TYPE_I2C
self.vtype = pglobals.SENSOR_TYPE_TEMP_HUM
self.readinprogress = 0
self.valuecount = 2
self.senddataoption = True
self.timeroption = True
self.timeroptional = False
self.formulaoption = True
self._nextdataservetime = 0
self._temp = None

def plugin_init(self,enableplugin=None):
plugin.PluginProto.plugin_init(self,enableplugin)
self.uservar[0] = 0
self.uservar[1] = 0
self.readinprogress = 0
if self.enabled:
i2cl = None
try:
if int(self.i2c)==0:
i2cl = libhw.i2c0
elif int(self.i2c)==1:
i2cl = libhw.i2c1
except:
pass
try:
self._temp = AM2320(i2cl)
except Exception as e:
self.initialized = False
if self._temp is None:
self.initialized = False
if self.initialized:
misc.addLog(pglobals.LOG_LEVEL_INFO,"AM2320 initialized")
else:
misc.addLog(pglobals.LOG_LEVEL_ERROR,"AM2320 can not be initialized!")

def plugin_read(self): # deal with data processing at specified time interval
result = False
if self.initialized and self.readinprogress==0 and self.enabled:
self.readinprogress = 1
try:
self._temp.measure()
temp = self._temp.temperature()
hum = self._temp.humidity()
if temp is not None and hum is not None:
self.set_value(1,temp,False)
self.set_value(2,hum,False)
except Exception as e:
misc.addLog(pglobals.LOG_LEVEL_ERROR,"AM2320 read error! "+str(e))
self.plugin_senddata()
self._lastdataservetime = utime.ticks_ms()
result = True
self.readinprogress = 0
return result

class AM2320:
def __init__(self, i2c=None, address=0x5c):
self.i2c = i2c
self.address = address
self.buf = bytearray(8)
def measure(self):
buf = self.buf
address = self.address
# wake sensor
try:
self.i2c.writeto(address, b'')
except OSError:
pass
# read 4 registers starting at offset 0x00
self.i2c.writeto(address, b'\x03\x00\x04')
# wait at least 1.5ms
utime.sleep_ms(2)
# read data
self.i2c.readfrom_mem_into(address, 0, buf)
crc = ustruct.unpack('<H', bytearray(buf[-2:]))[0]
if (crc != self.crc16(buf[:-2])):
raise Exception("checksum error")
def crc16(self, buf):
crc = 0xFFFF
for c in buf:
crc ^= c
for i in range(8):
if crc & 0x01:
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc
def humidity(self):
return (self.buf[2] << 8 | self.buf[3]) * 0.1
def temperature(self):
t = ((self.buf[4] & 0x7f) << 8 | self.buf[5]) * 0.1
if self.buf[4] & 0x80:
t = -t
return t
Loading

0 comments on commit e90610b

Please sign in to comment.