Skip to content

Commit

Permalink
BREAKING Core changes in I2C handling, BACKUP first!
Browse files Browse the repository at this point in the history
  • Loading branch information
enesbcs committed Oct 24, 2020
1 parent 88d9cd4 commit 2366fe1
Show file tree
Hide file tree
Showing 39 changed files with 611 additions and 291 deletions.
23 changes: 16 additions & 7 deletions Settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,25 +80,34 @@ def callback_from_controllers(controllerindex,idx,values,taskname="",valuename="
tvalues = []
for u in range(rpieGlobals.VARS_PER_TASK): # fill unused values with -9999, handle at plugin side!!!
tvalues.append(-9999)
for v in range(Tasks[x].valuecount): # match with valuename
if Tasks[x].valuenames[v]==valuename:
tvalues[v] = values
Tasks[x].plugin_receivedata(tvalues)
break
if valuename=="":
Tasks[x].plugin_receivedata(values) # send all
else:
for v in range(Tasks[x].valuecount): # match with valuename
if Tasks[x].valuenames[v]==valuename:
tvalues[v] = values
Tasks[x].plugin_receivedata(tvalues)
break
break

def get_i2c_pins(): # get list of enabled i2c pin numbers
def get_i2c_pins(channel=-1): # get list of enabled i2c pin numbers
global Pinout
gplist = []
sname = "I2C"
if channel>-1:
sname += str(channel)
try:
for p in range(len(Pinout)):
if int(Pinout[p]["altfunc"])!=0:
n = Pinout[p]["name"]
for i in range(len(n)):
if "I2C" in Pinout[p]["name"][i]:
if sname in Pinout[p]["name"][i]:
gplist.append(Pinout[p]["name"][0]+"/"+Pinout[p]["name"][i])
except:
pass
if len(gplist)<1:
gplist.append("I2C")
gplist.append(channel)
return gplist

def savesettings():
Expand Down
135 changes: 104 additions & 31 deletions _C014_GenMQTT.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import commands
import Settings
import os
import json

class Controller(controller.ControllerProto):
CONTROLLER_ID = 14
Expand Down Expand Up @@ -57,6 +58,7 @@ def __init__(self,controllerindex):
self.lwt_t = ""
self.lwtconnmsg = "Online"
self.lwtdisconnmsg = "Offline"
self.useJSON = False

def controller_init(self,enablecontroller=None):
if enablecontroller != None:
Expand Down Expand Up @@ -89,6 +91,11 @@ def controller_init(self,enablecontroller=None):
self.lwt_t, state = commands.parseruleline(self.lwt_topic)
except:
self.lwt_topic = ""
try:
if self.useJSON: #check if var exists
pass
except:
self.useJSON = False
self.mqttclient = GMQTTClient()
self.mqttclient.subscribechannel = self.outch
self.mqttclient.controllercb = self.on_message
Expand Down Expand Up @@ -245,6 +252,10 @@ def webform_load(self): # create html page for settings
webserver.addFormTextBox("LWT Connect Message","c014_cmsg",lwt1,255)
webserver.addFormTextBox("LWT Disconnect Message","c014_dcmsg",lwt2,255)
webserver.addFormCheckBox("Check conn & reconnect if needed at every 30 sec","c014_reconnect",self.timer30s)
try:
webserver.addFormCheckBox("Use JSON payload","c014_usejson",self.useJSON)
except:
self.useJSON = False
return True

def webform_save(self,params): # process settings post reply
Expand Down Expand Up @@ -293,6 +304,11 @@ def webform_save(self,params): # process settings post reply
self.timer30s = True
else:
self.timer30s = False
if (webserver.arg("c014_usejson",params)=="on"):
self.useJSON = True
else:
self.useJSON = False

if pchange and self.enabled:
self.disconnect()
time.sleep(0.1)
Expand Down Expand Up @@ -326,46 +342,74 @@ def on_message(self, msg):
v2 = -1
if self.outchannel.endswith("/"+dnames[len(dnames)-1]): # set command arrived, forward it to the Task
ttaskname = ""
try:
v1 = dnames2.index("#")
v2 = v1+1
except:
v1 = -1
if v1 == -1:
if self.useJSON:
mlist = []
if ('{' in msg2):
try:
mlist = json.loads(msg2)
except Exception as e:
mlist = []
if ("taskname" in mlist):
ttaskname = mlist['taskname']
dnames = []
# print(msg2,mlist,ttaskname,dnames)#debug
if ttaskname=="":
try:
v1 = dnames2.index("%tskname%")
v1 = dnames2.index("#")
v2 = v1+1
except:
v1 = -1
try:
v2 = dnames2.index("%valname%")
except:
v2 = -1
try:
v3 = dnames2.index("%tskid%")
except:
v3 = -1
if v3>-1:
if v1 == -1:
try:
t = int(dnames[v3])-1
if Settings.Tasks[t] and type(Settings.Tasks[t]) is not bool:
ttaskname = Settings.Tasks[t].gettaskname().strip()
v1 = dnames2.index("%tskname%")
except:
pass
elif v1==-1 and v2>-1:
v1 = -1
try:
v2 = dnames2.index("%valname%")
except:
v2 = -1
try:
v3 = dnames2.index("%tskid%")
except:
v3 = -1
if v3>-1:
try:
t = int(dnames[v3])-1
if Settings.Tasks[t] and type(Settings.Tasks[t]) is not bool:
ttaskname = Settings.Tasks[t].gettaskname().strip()
except:
pass
elif v1==-1 and v2>-1:
try:
for x in range(len(Settings.Tasks)):
if Settings.Tasks[x] and type(Settings.Tasks[x]) is not bool:
for u in range(Settings.Tasks[x].valuecount):
if Settings.Tasks[x].valuenames[u] == dnames[v2]:
ttaskname = Settings.Tasks[x].gettaskname().strip()
break
if ttaskname != "":
break
except:
pass
if ttaskname=="" and v1>-1:
ttaskname = dnames[v1]

if self.useJSON and ttaskname != "":
try:
pvalues = [-1,-1,-1,-1]
for x in range(len(Settings.Tasks)):
if Settings.Tasks[x] and type(Settings.Tasks[x]) is not bool:
for u in range(Settings.Tasks[x].valuecount):
if Settings.Tasks[x].valuenames[u] == dnames[v2]:
ttaskname = Settings.Tasks[x].gettaskname().strip()
break
if ttaskname != "":
if Settings.Tasks[x].gettaskname() == ttaskname:
for u in range(Settings.Tasks[x].valuecount):
valnam = Settings.Tasks[x].valuenames[u]
if valnam in mlist:
pvalues[u] = mlist[valnam]
break
except:
except:
pass
if ttaskname=="" and v1>-1:
ttaskname = dnames[v1]
# print(v1,v2,ttaskname,dnames) #debug
self.onmsgcallbackfunc(self.controllerindex,-1,pvalues,taskname=ttaskname,valuename="") #-> Settings.callback_from_controllers()
success = True
return success
if ttaskname != "" and v2>-1 and v2<len(dnames):
self.onmsgcallbackfunc(self.controllerindex,-1,msg2,taskname=ttaskname,valuename=dnames[v2]) #-> Settings.callback_from_controllers()
success = True
Expand All @@ -374,6 +418,8 @@ def senddata(self,idx,sensortype,value,userssi=-1,usebattery=-1,tasknum=-1,chang
if self.enabled:
success = False
if self.isconnected(False):
if self.useJSON:
changedvalue = 1 # force only one msg sending
if tasknum!=-1:
tname = Settings.Tasks[tasknum].gettaskname()
if changedvalue==-1:
Expand Down Expand Up @@ -409,15 +455,42 @@ def senddata(self,idx,sensortype,value,userssi=-1,usebattery=-1,tasknum=-1,chang
gtopic = gtopic.replace('%tskid%',str(tasknum+1))
gtopic = gtopic.replace('%valname%',vname)
else:
if self.useJSON:
gtopic = self.inch.replace('#',tname) # use only taskname for json reporting
else:
gtopic = self.inch.replace('#',tname+"/"+vname)
if vname != "":
gval = str(value[changedvalue-1])
if gval == "":
gval = "0"
if self.useJSON: # modify payload
gval = '{"taskname":"'+ Settings.Tasks[tasknum].taskname +'",'
for u in range(Settings.Tasks[tasknum].valuecount):
gval += '"'+ Settings.Tasks[tasknum].valuenames[u] + '":'
val = value[u]
if str(val).replace(".","").isnumeric():
gval += str(val)
else:
gval += '"'+ str(val) +'"'
gval += ","
try:
usebattery = float(str(usebattery).strip())
except Exception as e:
usebattery = -1
bval = -1
if usebattery != -1 and usebattery != 255:
bval = usebattery
else:
bval = misc.get_battery_value()
if bval != -1 and bval != 255:
gval += '"battery":'+ str(bval)+ ','
if userssi != -1:
gval += '"rssi":'+ str(userssi)+ ','
gval = gval[:-1]+"}"
mres = 1
try:
(mres,mid) = self.mqttclient.publish(gtopic,gval)
# print(gtopic) # DEBUG
# print(gtopic,gval) # DEBUG
except:
mres = 1
if mres!=0:
Expand Down
11 changes: 4 additions & 7 deletions _P007_PCF8591.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,11 @@ def plugin_init(self,enableplugin=None):
self.decimals[0] = 0
self.initialized = False
if self.enabled:
i2cport = -1
try:
for i in range(0,2):
if gpios.HWPorts.is_i2c_usable(i) and gpios.HWPorts.is_i2c_enabled(i):
i2cport = i
break
i2cport = gpios.HWPorts.geti2clist()
except:
i2cport = -1
if i2cport>-1:
i2cport = []
if len(i2cport)>0:
try:
pinnum = int(self.taskdevicepluginconfig[0])
except:
Expand Down Expand Up @@ -83,6 +79,7 @@ def plugin_init(self,enableplugin=None):
self.ports = 0

def webform_load(self): # create html page for settings
webserver.addFormNote("I2C Line is not selectable currently!")#ToDo!
webserver.addFormNumericBox("Port","p007_pnum",self.taskdevicepluginconfig[0],1,32)
webserver.addFormNote("First extender 1-4 (0x48), Second 5-8 (0x49)...")
return True
Expand Down
20 changes: 11 additions & 9 deletions _P009_MCP.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,17 @@ def plugin_init(self,enableplugin=None):
self.decimals[0] = 0
self.initialized = False
if self.enabled:
i2cport = -1
try:
for i in range(0,2):
if gpios.HWPorts.is_i2c_usable(i) and gpios.HWPorts.is_i2c_enabled(i):
i2cport = i
break
i2cl = self.i2c
except:
i2cport = -1
if i2cport>-1:
i2cl = -1
try:
i2cport = gpios.HWPorts.geti2clist()
if i2cl==-1:
i2cl = int(i2cport[0])
except:
i2cport = []
if len(i2cport)>0 and i2cl>-1:
try:
pinnum = int(self.taskdevicepluginconfig[0])
except:
Expand All @@ -70,7 +72,7 @@ def plugin_init(self,enableplugin=None):
ctype = "MCP23008"
try:
self.i2ca, self.rpin = lib_mcprouter.get_pin_address(pinnum)
self.mcp = lib_mcprouter.request_mcp_device(int(i2cport),pinnum,ctype)
self.mcp = lib_mcprouter.request_mcp_device(int(i2cl),pinnum,ctype)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"MCP device requesting failed: "+str(e))
self.mcp = None
Expand All @@ -94,7 +96,7 @@ def plugin_init(self,enableplugin=None):
self.enabled = False
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"MCP can not be initialized! ")
else:
self.i2cport = int(i2cport)
self.i2cport = int(i2cl)
self.initialized = True
if self.taskdevicepluginconfig[1] != 2:
try:
Expand Down
14 changes: 11 additions & 3 deletions _P010_BH1750.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,22 @@ def __init__(self,taskindex): # general init
self.samples = 3
self.preread = self.samples*2000 # 3 * 2 sec
self.LARR = []
self.i2cbus = None

def plugin_init(self,enableplugin=None):
plugin.PluginProto.plugin_init(self,enableplugin)
self.LARR = []
self.uservar[0] = 0
if self.enabled:
try:
i2cok = gpios.HWPorts.i2c_init()
if i2cok:
try:
i2cl = self.i2c
except:
i2cl = -1
self.i2cbus = gpios.HWPorts.i2c_init(i2cl)
if i2cl==-1:
self.i2cbus = gpios.HWPorts.i2cbus
if self.i2cbus is not None:
if self.interval>2:
nextr = self.interval-2
else:
Expand All @@ -53,6 +60,7 @@ def plugin_init(self,enableplugin=None):
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
self.enabled = False
self.i2cbus = None

def webform_load(self): # create html page for settings
choice1 = self.taskdevicepluginconfig[0]
Expand Down Expand Up @@ -119,7 +127,7 @@ def p010_get_value(self):
if rpieTime.millis()>=(self.lastread+2000):
lux = None
try:
lux = gpios.HWPorts.i2c_read_block(int(self.taskdevicepluginconfig[0]),0x21) # Start measurement at 0.5lx resolution. Measurement Time is typically 120ms. It is automatically set to Power Down mode after measurement.
lux = gpios.HWPorts.i2c_read_block(int(self.taskdevicepluginconfig[0]),0x21,bus=self.i2cbus) # Start measurement at 0.5lx resolution. Measurement Time is typically 120ms. It is automatically set to Power Down mode after measurement.
except:
lux = None
if lux != None:
Expand Down
Loading

0 comments on commit 2366fe1

Please sign in to comment.