Skip to content

Commit

Permalink
Adding Generic UDP controller, experimental Dashboard.esp support, fi…
Browse files Browse the repository at this point in the history
…xing mqtt controller disabling artifacts
  • Loading branch information
enesbcs committed Jan 18, 2019
1 parent b0ca949 commit fcfe5c4
Show file tree
Hide file tree
Showing 8 changed files with 240 additions and 11 deletions.
4 changes: 4 additions & 0 deletions RPIEasy.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,12 @@ def CPluginInit():
for y in range(0,len(Settings.Controllers)):
if (Settings.Controllers[y]):
if (Settings.Controllers[y].enabled):
try:
Settings.Controllers[y].controller_init(None) # init controller at startup
Settings.Controllers[y].setonmsgcallback(Settings.callback_from_controllers) # set global msg callback for 2way comm
except Exception as e:
Settings.Controllers[y] = False
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Controller" +str(y+1)+ " is malformed, deleted! "+str(e))

return 0

Expand Down
19 changes: 12 additions & 7 deletions _C002_DomoMQTT.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,18 @@ def connect(self):
return self.isconnected()

def disconnect(self):
try:
self.mqttclient.loop_stop(True)
self.mqttclient.disconnect()
except:
pass
stat=self.isconnected()
return stat
try:
self.mqttclient.loop_stop(True)
except:
pass
try:
self.mqttclient.disconnect()
except:
pass
stat=self.isconnected()
if self.enabled!=True:
commands.rulesProcessing("DomoMQTT#Disconnected",rpieGlobals.RULE_SYSTEM)
return stat

def isconnected(self,ForceCheck=True):
res = False
Expand Down
81 changes: 81 additions & 0 deletions _C010_GenUDP.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
#############################################################################
################## Generic UDP controller for RPIEasy #######################
#############################################################################
#
# Generic UDP controller
#
# Copyright (C) 2018-2019 by Alexander Nagy - https://bitekmindenhol.blog.hu/
#
import controller
import misc
import rpieGlobals
import time
import webserver
import Settings
import socket
import threading
import commands

class Controller(controller.ControllerProto):
CONTROLLER_ID = 10
CONTROLLER_NAME = "Generic UDP"

def __init__(self,controllerindex):
controller.ControllerProto.__init__(self,controllerindex)
self.usesID = False
self.onmsgcallbacksupported = False # use direct set_value() instead of generic callback to make sure that values setted anyway
self.controllerport = 514
self.inchannel = "%sysname%_%tskname%_%valname%=%value%"
self.templatestr = ""

def controller_init(self,enablecontroller=None):
if enablecontroller != None:
self.enabled = enablecontroller
self.templatestr, state = commands.parseruleline(self.inchannel) # replace global variables
self.templatestr = self.templatestr.replace("==","=")
self.initialized = True
return True

def webform_load(self): # create html page for settings
webserver.addFormTextBox("Report template","inchannel",self.inchannel,255)
return True

def webform_save(self,params): # process settings post reply
self.inchannel = webserver.arg("inchannel",params)
return True

def udpsender(self,data):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if str(self.controllerip).endswith(".255"):
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
if type(data) is bytes:
dsend = data
elif type(data) is str:
dsend = bytes(data,"utf-8")
else:
dsend = bytes(data)
s.sendto(dsend, (self.controllerip,int(self.controllerport)))
# print(self.controllerip,self.controllerport,dsend) # DEBUG
except Exception as e:
print(e)

def senddata(self,idx,sensortype,value,userssi=-1,usebattery=-1,tasknum=-1,changedvalue=-1): # called by plugin
if tasknum!=-1 and self.enabled:
if tasknum<len(Settings.Tasks):
if Settings.Tasks[tasknum] != False:
templatestra = self.templatestr.replace('%tskname%',Settings.Tasks[tasknum].gettaskname())
procarr = []
for u in range(Settings.Tasks[tasknum].valuecount):
vn = str(Settings.Tasks[tasknum].valuenames[u]).strip()
if vn!="":
templatestr = templatestra.replace('%valname%',vn)
templatestr = templatestr.replace('%value%',str(Settings.Tasks[tasknum].uservar[u]))
t = threading.Thread(target=self.udpsender, args=(templatestr,))
t.daemon = True
procarr.append(t)
t.start()
if len(procarr)>0:
for process in procarr:
process.join()
6 changes: 6 additions & 0 deletions _C014_GenMQTT.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ def controller_init(self,enablecontroller=None):
misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"MQTT: Try to connect")
self.connect()
else:
self.laststatus = -1
self.disconnect()
return True

Expand Down Expand Up @@ -138,10 +139,15 @@ def connect(self):
def disconnect(self):
try:
self.mqttclient.loop_stop(True)
except:
pass
try:
self.mqttclient.disconnect()
except:
pass
stat=self.isconnected()
if self.enabled!=True:
commands.rulesProcessing("GenMQTT#Disconnected",rpieGlobals.RULE_SYSTEM)
return stat

def isconnected(self,ForceCheck=True):
Expand Down
3 changes: 2 additions & 1 deletion commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,8 @@ def parseruleline(linestr,rulenum=-1):
m = re.findall(r"\%([A-Za-z0-9_#]+)\%", cline)
if len(m)>0: # replace with values
for r in range(len(m)):
cline = cline.replace("%"+m[r]+"%",str(getglobalvar(m[r])))
if m[r] in SysVars:
cline = cline.replace("%"+m[r]+"%",str(getglobalvar(m[r])))
if "=" == getequchars(cline):
cline = cline.replace("=","==") # prep for python interpreter
equ = getfirstequpos(cline)
Expand Down
14 changes: 14 additions & 0 deletions linux_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,3 +544,17 @@ def checkboot_ro():
err = False
return err

def getfilecontent(fname):
resbuf = []
cfname = str(fname)
if fname.startswith("files/") == False:
cfname = "files/"+cfname
try:
if os.path.exists(cfname):
with open(cfname) as f:
for line in f:
line = line.strip()
resbuf.append(line)
except:
resbuf = []
return resbuf
2 changes: 1 addition & 1 deletion rpieGlobals.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
# Copyright (C) 2018-2019 by Alexander Nagy - https://bitekmindenhol.blog.hu/
#
PROGNAME = "RPIEasy"
BUILD = 19016
BUILD = 19018
PROGVER = "0."+str(BUILD/1000)

gpMenu = []
Expand Down
122 changes: 120 additions & 2 deletions webserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ def handle_controllers(self):
protocol=0
controlleruser = arg("controlleruser",responsearr)
controllerpassword = arg("controllerpassword",responsearr)
enabled = arg("controllerenabled",responsearr)
enabled = (arg("controllerenabled",responsearr)=="on")

if ((protocol == 0) and (edit=='') and (controllerindex!='')) or (arg('del',responsearr) != ''):
try:
Expand Down Expand Up @@ -2421,7 +2421,125 @@ def handle_upload_post(self):
fout.close()
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, "Exception while uploading "+str(e))
self.redirect("filelist?chgto="+str(upath))
return self.redirect("filelist?chgto="+str(upath))

@WebServer.route('/dashboard.esp') # still experimental!
def handle_custom(self):
global TXBuffer, navMenuIndex
TXBuffer=""
navMenuIndex=0
if (rpieGlobals.wifiSetup):
return self.redirect('/setup')
if (not isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post

webrequest = arg("cmd",responsearr)
if len(webrequest)>0:
responsestr = str(commands.doExecuteCommand(webrequest))

unit = arg("unit",responsearr).strip()
btnunit = arg("btnunit",responsearr).strip()
if unit == "":
unit = btnunit

if str(unit) != "":
if str(unit) != str(Settings.Settings["Unit"]):
ipa = ""
if len(Settings.nodelist)>0:
for n in Settings.nodelist:
if str(n["unitno"]) == str(unit):
ipa = str(n["ip"])
break
if ipa != "":
if str(n["port"]) != "" and str(n["port"]) != "0" and str(n["port"]) != "80":
ipa += ":" + str(n["port"])
return self.redirect("http://"+str(ipa)+"/dashboard.esp")
# sendHeadandTail("TmplDsh",_HEAD)
# TXBuffer += "<meta http-equiv=\"refresh\" content=\"0; URL=http://"
# TXBuffer += ipa
# TXBuffer += "/dashboard.esp\">"
# sendHeadandTail("TmplDsh",_TAIL)
# return TXBuffer

if len(Settings.nodelist)>0:
prevn = 0
nextn = 0
nlen = len(Settings.nodelist)
for n in range(0,nlen):
if str(Settings.nodelist[n]["unitno"]) == str(Settings.Settings["Unit"]):
if n>0:
prevn=n-1
else:
prevn=n
if n<(nlen-1):
nextn=n+1
else:
nextn=n
break

sendHeadandTail("TmplDsh",_HEAD)
TXBuffer += "<script><!--\nfunction dept_onchange(frmselect) {frmselect.submit();}\n//--></script>"
TXBuffer += "<form name='frmselect' method='post'>"
addSelector_Head("unit",True)
choice = int(Settings.Settings["Unit"])
for n in range(nlen):
addSelector_Item((str(Settings.nodelist[n]["unitno"])+" - "+ str(Settings.nodelist[n]["name"])),int(Settings.nodelist[n]["unitno"]),(int(Settings.nodelist[n]["unitno"])==int(choice)),False)
addSelector_Foot()
TXBuffer += "<a class='button link' href='http://"
ipa = str(Settings.nodelist[prevn]["ip"])
iport = str(Settings.nodelist[prevn]["port"])
if str(iport) != "" and str(iport) != "0" and str(iport) != "80":
ipa += ":" + str(iport)
TXBuffer += ipa + "/dashboard.esp"
TXBuffer += "?btnunit="+str(Settings.nodelist[prevn]["unitno"])
TXBuffer += "'>&lt;</a>"

TXBuffer += "<a class='button link' href='http://"
ipa = str(Settings.nodelist[nextn]["ip"])
iport = str(Settings.nodelist[nextn]["port"])
if str(iport) != "" and str(iport) != "0" and str(iport) != "80":
ipa += ":" + str(iport)
TXBuffer += ipa + "/dashboard.esp"
TXBuffer += "?btnunit="+str(Settings.nodelist[nextn]["unitno"])
TXBuffer += "'>&gt;</a>"

try:
customcont = OS.getfilecontent("dashboard.esp")
except Exception as e:
print(e)
if len(customcont)>0:
for l in customcont:
try:
cl, st = commands.parseruleline(str(l))
if st=="CMD":
TXBuffer += str(cl)
else:
TXBuffer += str(l)
except Exception as e:
print(e)
else: # if template not found
sendHeadandTail("TmplDsh",_HEAD);
TXBuffer += "<table class='normal'>"
try:
for sc in range(0,len(Settings.Tasks)):
if Settings.Tasks[sc] != False:
TXBuffer += "<TR><TD>"+Settings.Tasks[sc].gettaskname()
fl = False
for tv in range(0,Settings.Tasks[sc].valuecount):
if str(Settings.Tasks[sc].valuenames[tv])!="":
if fl:
TXBuffer += "<TR><TD>"
TXBuffer += '<TD>' + str(Settings.Tasks[sc].valuenames[tv]) + "<td>" + str(Settings.Tasks[sc].uservar[tv]) + "</TR>"
fl = True
except Exception as e:
print(e)
TXBuffer += "</table><BR>"
sendHeadandTail("TmplDsh",_TAIL);
return TXBuffer

# -----------------------------

Expand Down

0 comments on commit fcfe5c4

Please sign in to comment.