def setrecipe(controldatabase, channelname, recipe, startstage=0): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set controlrecipe=\'' + recipe + '\' where name=\'' + channelname + '\'') sqlitequery(controldatabase, 'update channels set recipestage=\'' + str(startstage) + '\' where name=\'' + channelname + '\'')
def updatelightsfromdb(database, table, CS): import pilib # get settings from database query = 'select status from \'' + table + '\' where type=\'SPI' + str( CS) + '\'' query2 = 'select name from \'' + table + '\' where type=\'SPI' + str( CS) + '\'' statuses = pilib.sqlitequery(database, query) names = pilib.sqlitequery(database, query2) d = {} for status, name in zip(statuses, names): d[name[0]] = status[0] setarray = [[ d['SPI' + str(CS) + '_RGB1_R'], d['SPI' + str(CS) + '_RGB1_G'], d['SPI' + str(CS) + '_RGB1_B'] ], [ d['SPI' + str(CS) + '_RGB2_R'], d['SPI' + str(CS) + '_RGB2_G'], d['SPI' + str(CS) + '_RGB2_B'] ], [ d['SPI' + str(CS) + '_RGB3_R'], d['SPI' + str(CS) + '_RGB3_G'], d['SPI' + str(CS) + '_RGB3_B'] ], [ d['SPI' + str(CS) + '_RGB4_R'], d['SPI' + str(CS) + '_RGB4_G'], d['SPI' + str(CS) + '_RGB4_B'] ], d['SPI' + str(CS) + '_SC_R'], d['SPI' + str(CS) + '_SC_G'], d['SPI' + str(CS) + '_SC_B'], d['SPI' + str(CS) + '_SC_Y']] setspilights(setarray, CS)
def updatelightsfromdb(database, table, CS): import pilib # get settings from database query = "select status from '" + table + "' where interface='SPI" + str(CS) + "'" query2 = "select name from '" + table + "' where interface='SPI" + str(CS) + "'" statuses = pilib.sqlitequery(database, query) names = pilib.sqlitequery(database, query2) # print(statuses) # print(names) d = {} for status, name in zip(statuses, names): d[name[0]] = status[0] # print(d) try: setarray = [ [d["SPI_RGB1_R"], d["SPI_RGB1_G"], d["SPI_RGB1_B"]], [d["SPI_RGB2_R"], d["SPI_RGB2_G"], d["SPI_RGB2_B"]], [d["SPI_RGB3_R"], d["SPI_RGB3_G"], d["SPI_RGB3_B"]], [d["SPI_RGB4_R"], d["SPI_RGB4_G"], d["SPI_RGB4_B"]], d["SPI_SC_R"], d["SPI_SC_G"], d["SPI_SC_B"], d["SPI_SC_Y"], ] except KeyError: print("key error on indicator keys") else: setspilights(setarray, CS)
def setmode(controldatabase, channelname, mode): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set mode=\'' + mode + '\' where name=\'' + channelname + '\'') # set action to 0 if we switch to manual if mode == 'manual': setaction(controldatabase, channelname, 0)
def setrecipe(controldatabase, channelname, recipe, startstage=0): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set controlrecipe=\'' + recipe + '\' where name=\'' + channelname + '\'') sqlitequery( controldatabase, 'update channels set recipestage=\'' + str(startstage) + '\' where name=\'' + channelname + '\'')
def setmode(controldatabase, channelname, mode): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set mode=\'' + mode + '\' where name=\'' + channelname + '\'') # set action to 0 if we switch to manual if mode == 'manual': setaction(controldatabase, channelname, 0)
def updatelightsfromdb(database,table): import pilib # get settings from database query='select status from \"' + table + '\" where type="SPI"' query2='select name from \"' + table + '\" where type="SPI"' statuses=pilib.sqlitequery(database,query) names=pilib.sqlitequery(database,query2) d={} for status,name in zip(statuses,names): d[name[0]]=status[0] setarray=[[d['SPI_RGB1_R'],d['SPI_RGB1_G'],d['SPI_RGB1_B']],[d['SPI_RGB2_R'],d['SPI_RGB2_G'],d['SPI_RGB2_B']],[d['SPI_RGB3_R'],d['SPI_RGB3_G'],d['SPI_RGB3_B']],[d['SPI_RGB4_R'],d['SPI_RGB4_G'],d['SPI_RGB4_B']],d['SPI_SC_R'],d['SPI_SC_G'],d['SPI_SC_B'],d['SPI_SC_Y']] setspilights(setarray)
def updateowfsentries(database, tablename, busdevices, myProxy=None): import pilib querylist = [] querylist.append('delete from ' + tablename + ' where interface = \'i2c1wire\'') # We're going to set a name because calling things by their ids is getting # a bit ridiculous, but we can't have empty name fields if we rely on them # being there. They need to be unique, so we'll name them by type and increment them for device in busdevices: # print(device.id) if device.type == 'DS18B20': sensorid = 'i2c1wire' + '_' + device.address # Get name if one exists name = pilib.sqlitedatumquery(database, 'select name from ioinfo where id=\'' + sensorid + '\'') # If doesn't exist, check to see if proposed name exists. If it doesn't, add it. # If it does, keep trying. if name == '': for index in range(100): # check to see if name exists name = device.type + '-' + str(int(index + 1)) print(name) foundid = pilib.sqlitedatumquery(database, 'select id from ioinfo where name=\'' + name + '\'') print('foundid' + foundid) if foundid: pass else: pilib.sqlitequery(database, pilib.makesqliteinsert('ioinfo', valuelist=[sensorid, name], valuenames=['id', 'name'])) break # Is it time to read temperature? # At the moment, we assume yes. device.readprop('temperature', myProxy) # print('temperature:') # print(device.temperature) querylist.append(pilib.makesqliteinsert(tablename, [sensorid, 'i2c1wire', device.type, device.address, name, float(device.temperature), 'F', pilib.gettimestring(), ''])) # print(querylist) pilib.sqlitemultquery(database, querylist)
def recordowfsdata(controldatabase, ROMsandvalues=None): # Write to database # At the moment all are enabled by default. # Eventually we'll read this before we delete all entries if ROMsandvalues: for tuple in ROMsandvalues: ROM = tuple[0] temp = tuple[1] queryresult = pilib.sqlitequery( controldatabase, 'select name from inputsinfo where inputID = ' + "'" + ROM + "'") if not queryresult: name = '' else: name = queryresult[0][0] valuelist = [ 'OWROM' + tuple[0], tuple[1], 'F', pilib.gettimestring(), 1, name ] query = pilib.makesqliteinsert(controldatabase, 'inputsdata', valuelist) # print(query) querylist.append(query) else: return ("no ROMs passed")
def readhardwarefileintoversions(): from pilib import systemdatadatabase, makesqliteinsert, sqlitequery devicefile = '/var/wwwsafe/devicedata' try: file = open(devicefile) lines = file.readlines() devicedict={} for line in lines: split = line.split(':') try: devicedict[split[0].strip()] = split[1].strip() except: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Device data parse error', 1, pilib.systemstatusloglevel) sqlitequery(systemdatadatabase, makesqliteinsert('versions', ['hardware',devicedict['hardware']], ['item', 'version'])) except: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Cannot find devicedata file to parse', 1, pilib.systemstatusloglevel)
def getmode(controldatabase, channelname): from pilib import sqlitequery mode = sqlitequery( controldatabase, 'select mode from channels where name=\'' + channelname + '\'')[0][0] return mode
def getaction(controldatabase, channelname): from pilib import sqlitequery action = sqlitequery( controldatabase, 'select action from channels where name=\'' + channelname + '\'')[0][0] return action
def onact(self): if self.actiontype == 'email': # process email action self.statusmsg += 'Processing email alert. ' email = self.actiondetail message = 'Alert is active for ' + self.name + '. Criterion ' + self.variablename + ' in ' + self.tablename + ' has value ' + str(self.variablevalue) + ' with a criterion of ' + str(self.criterion) + ' with an operator of ' + self.operator + '. This alarm status has been on since ' + self.ontime + '.' subject = 'CuPID Alert : Alarm On - ' + self.name actionmail = pilib.gmail(message=message, subject=subject, recipient=email) actionmail.send() elif self.actiontype == 'indicator': # process indicator action self.statusmsg += 'Processing indicator on action. ' indicatorname = self.actiondetail pilib.sqlitequery(pilib.controldatabase, 'update indicators set status=1 where name = \'' + indicatorname + '\'') elif self.actiontype == 'output': self.statusmsg += 'Processing output on action. ' pilib.setsinglevalue(pilib.controldatabase, 'outputs', 'value', '1', condition='"id"=\'' + self.actiondetail +"'") # This should be the generic handler that we migrate to elif self.actiontype == 'setvalue': # to set a value, we need at minimum: # dbname, tablename, valuename, setmethod and either: # setmethod = increment, incrementvalue=1 # setmethod = value dbvndict = parsedbvn(self.actiondetail) dbpath = pilib.dbnametopath(dbvndict['dbname']) # Special set formula? if 'setvalueformula' in self.actiondatadict: # Stuff that we don't know yet. pilib.setsinglevalue(dbpath, dbvndict['tablename'], dbvndict['valuename'], 'formulastuff here', dbvndict['condition']) else: """ TODO: Fix this hack. We cannot currently single quote in the database entry because it breaks the reinsert. So for now, we have to add quotes on either side of the string literal before executing the sqlite query. """ if dbvndict['condition']: querycondition = dbvndict['condition'].split('=')[0] + "='" + dbvndict['condition'].split('=')[1] + "'" # print('FIXED CONDITION') # print(querycondition) else: querycondition = None pilib.setsinglevalue(dbpath, dbvndict['tablename'], dbvndict['valuename'], '1', querycondition)
def readhardwarefileintoversions(): from pilib import systemdatadatabase, makesqliteinsert, sqlitequery devicefile = '/var/wwwsafe/devicedata' try: file = open(devicefile) lines = file.readlines() devicedict = {} for line in lines: split = line.split(':') try: devicedict[split[0].strip()] = split[1].strip() except: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Device data parse error', 1, pilib.systemstatusloglevel) sqlitequery( systemdatadatabase, makesqliteinsert('versions', ['hardware', devicedict['hardware']], ['item', 'version'])) except: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Cannot find devicedata file to parse', 1, pilib.systemstatusloglevel)
def recordowfsdata(controldatabase,ROMsandvalues=None): # Write to database # At the moment all are enabled by default. # Eventually we'll read this before we delete all entries if ROMsandvalues: for tuple in ROMsandvalues: ROM=tuple[0] temp=tuple[1] queryresult=pilib.sqlitequery(controldatabase,'select name from inputsinfo where inputID = ' + "'" + ROM + "'") if not queryresult: name='' else: name = queryresult[0][0] valuelist = ['OWROM' + tuple[0],tuple[1],'F',pilib.gettimestring(),1,name] query = pilib.makesqliteinsert(controldatabase,'inputsdata',valuelist) # print(query) querylist.append(query) else: return("no ROMs passed")
# Read inputs (done by updateio, through periodicreadio) # Set physical outputs (this is done by updateio) systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0] while systemstatus['picontrolenabled']: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running picontrol', 3, pilib.systemstatusloglevel) pilib.writedatedlogmsg(pilib.controllog, 'Running picontrol', 3, pilib.controlloglevel) # Set poll date. While intuitively we might want to set this # after the poll is complete, if we error below, we will know # from this stamp when it barfed. This is arguably more valuable # then 'last time we didn't barf' pilib.sqlitequery(pilib.controldatabase, "update systemstatus set lastpicontrolpoll='" + pilib.gettimestring() + "'") channels = pilib.readalldbrows(pilib.controldatabase, 'channels') outputs = pilib.readalldbrows(pilib.controldatabase, 'outputs') controlalgorithms = pilib.readalldbrows(pilib.controldatabase, 'controlalgorithms') algorithmnames=[] for algorithm in controlalgorithms: algorithmnames.append(algorithm['name']) # Cycle through channels and set action based on setpoint # and algorithm if set to auto mode for channel in channels: statusmsg = '' querylist = [] channelindex = str(int(channel['channelindex']))
def setaction(controldatabase, channelname, action): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set action = \'' + str(action) + '\' where name = \'' + channelname + '\'')
#################################################### # Log value into tabled log # Get data for all sensors online inputsdata = pilib.readalldbrows(pilib.controldatabase, 'inputs') for inputrow in inputsdata: logtablename = 'input_' + inputrow['id'] + '_log' if pilib.isvalidtimestring(inputrow['polltime']): # Create table if it doesn't exist query = 'create table if not exists \'' + logtablename + '\' ( value real, time text primary key)' pilib.sqlitequery(pilib.logdatabase, query) # Enter row pilib.sqliteinsertsingle(pilib.logdatabase, logtablename, valuelist=[inputrow['value'], inputrow['polltime']], valuenames=['value', 'time']) # Clean log pilib.cleanlog(pilib.logdatabase, logtablename) # Size log based on specified size pilib.sizesqlitetable(pilib.logdatabase, logtablename, logpoints) ####################################################
def runalgorithm(controldatabase, recipedatabase, channelname): from pilib import sqlitequery, datarowtodict, gettimestring, timestringtoseconds import time message = '' # get our details of our channel channeldata = sqlitequery(controldatabase, 'select * from channels where name=' + "'" + channelname + "'")[0] channeldict = datarowtodict(controldatabase, 'channels', channeldata) # check to see if we are running a recipe controlrecipename = channeldict['controlrecipe'] if controlrecipename and controlrecipename != 'none': # Get recipe details # If recipes get too big, we'll just get # a couple stages. For now, we make a # dictionary array #print('we are in recipe ' + controlrecipename) #print(recipedatabase) recipedata = sqlitequery(recipedatabase, 'select * from \'' + controlrecipename + '\'') recipedictarray = [] for stage in recipedata: recipedict = datarowtodict(recipedatabase, controlrecipename, stage) recipedictarray.append(recipedict) # get current stage currentstagenumber = int(channeldict['recipestage']) #print('current stage is ' + str(currentstagenumber) ) # Get data for current stage stagefound = False for stage in recipedictarray: if int(stage['stagenumber']) == currentstagenumber: currentstage = stage stagefound = True break if stagefound: #print("stage found") pass else: print('error. stage not found.') # Check to see if we need to move to next stage currenttime = time.time() #print('Time') #print(currenttime) #print(gettimestring(currenttime)) if currentstagenumber == 0 or currenttime - timestringtoseconds(channeldict['recipestagestarttime']) > int( currentstage['stagelength']): print('stage time expired for stage ' + str(currentstagenumber) + '. Checking on stage advance. ') # Advance stage if there is another stage. Otherwise # update channel to be off a recipe. We assume explicitly # that the stages are sequential integers. nextstagenumber = currentstagenumber + 1 # look for next stage stagefound = False for stage in recipedictarray: if int(stage['stagenumber']) == nextstagenumber: nextstage = stage stagefound = True break if stagefound: print(' Next stage was found. Setting next stage. ') if currentstagenumber == 0: print("Stagenumber is 0. Setting recipe start time. ") # Set recipe start time sqlitequery(controldatabase, 'update channels set recipestarttime=\'' + gettimestring( currenttime) + '\' where name=\'' + channelname + '\'') # Set stage to new stage number sqlitequery(controldatabase, 'update channels set recipestage=\'' + str( nextstagenumber) + '\' where name=\'' + channelname + '\'') # Set setpointvalue sqlitequery(controldatabase, 'update channels set setpointvalue=\'' + str( nextstage['setpointvalue']) + '\' where name=\'' + channelname + '\'') # Set stage start time to now sqlitequery(controldatabase, 'update channels set recipestagestarttime=\'' + gettimestring( currenttime) + '\' where name=\'' + channelname + '\'') # Set new controlalgorithm sqlitequery(controldatabase, 'update channels set controlalgorithm=\'' + nextstage[ 'controlalgorithm'] + '\' where name=\'' + channelname + '\'') else: # Take channel off recipe sqlitequery(controldatabase, 'update channels set controlrecipe=\'none\' where name=\'' + channelname + '\'') sqlitequery(controldatabase, 'update channels set recipestate=\'0\' where name=\'' + channelname + '\'') sqlitequery(controldatabase, 'update channels set recipestage=\'0\' where name=\'' + channelname + '\'') # if lengthmode is setpoint # get current stage # check stage start against stage length # and current time # move to next stage if time and revise setpoint # adjust setpoint based on stage # set action based on setpoint else: # make sure we're not on recipe and on stage 0 sqlitequery(controldatabase, 'update channels set controlrecipe=\'none\' where name=\'' + channelname + '\'') sqlitequery(controldatabase, 'update channels set recipestate=\'0\' where name=\'' + channelname + '\'') sqlitequery(controldatabase, 'update channels set recipestage=\'0\' where name=\'' + channelname + '\'') algorithm = channeldict['controlalgorithm'] setpointvalue = float(channeldict['setpointvalue']) controlvalue = float(channeldict['controlvalue']) algorithmrows = sqlitequery(controldatabase, 'select * from controlalgorithms where name=' + "'" + algorithm + "'") algorithmrow = algorithmrows[0] algorithm = datarowtodict(controldatabase, 'controlalgorithms', algorithmrow) type = algorithm['type'] if type == 'on/off with deadband': #print(type) deadbandhigh = algorithm['deadbandhigh'] deadbandlow = algorithm['deadbandlow'] if setpointvalue > (controlvalue + deadbandhigh): action = 100 elif setpointvalue < (controlvalue - deadbandlow): action = -100 else: action = 0 #print('setpoint' + str(setpoint)) #print('controlvalue' + str(controlvalue)) #print(action) #print(message) return [action, message]
def setmode(self,mode): from pilib import controldatabase, sqlitequery sqlitequery(controldatabase, 'update channels set mode=\'' + str(mode) + '\' where name=\'' + channel.name + '\'')
systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0] while systemstatus['picontrolenabled']: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running picontrol', 3, pilib.systemstatusloglevel) pilib.writedatedlogmsg(pilib.controllog, 'Running picontrol', 3, pilib.controlloglevel) # Set poll date. While intuitively we might want to set this # after the poll is complete, if we error below, we will know # from this stamp when it barfed. This is arguably more valuable # then 'last time we didn't barf' pilib.sqlitequery( pilib.controldatabase, "update systemstatus set lastpicontrolpoll='" + pilib.gettimestring() + "'") channels = pilib.readalldbrows(pilib.controldatabase, 'channels') outputs = pilib.readalldbrows(pilib.controldatabase, 'outputs') controlalgorithms = pilib.readalldbrows(pilib.controldatabase, 'controlalgorithms') algorithmnames = [] for algorithm in controlalgorithms: algorithmnames.append(algorithm['name']) # Cycle through channels and set action based on setpoint # and algorithm if set to auto mode for channel in channels: statusmsg = ''
T = True F = False GPIO.setmode(GPIO.BCM) # Run the script periodically based on systemstatus systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0] while systemstatus['picontrolenabled']: # Set poll date. While intuitively we might want to set this # after the poll is complete, if we error below, we will know # from this stamp when it barfed. This is arguably more valuable # then 'last time we didn't barf' pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set lastpicontrolpoll=\'' + pilib.gettimestring() + '\'') channels = pilib.readalldbrows(pilib.controldatabase, 'channels') outputs = pilib.readalldbrows(pilib.controldatabase, 'outputs') controlalgorithms = pilib.readalldbrows(pilib.controldatabase, 'controlalgorithms') # Cycle through channels and set action based on setpoint # and algorithm if set to auto mode for channel in channels: statusmessage = '' channelindex = str(int(channel['channelindex'])) channelname = channel['name'] logtablename = channel['name'] + '_log' time = pilib.gettimestring()
def updateiodata(database): # This recreates all input and output tables based on the interfaces table. # Thus way we don't keep around stale data values. We could at some point incorporate # a retention feature that keeps them around in case they disappear temporarily. # It also reads the elements if they are enabled and it's time to read them import pilib import traceback import RPi.GPIO as GPIO allowedGPIOaddresses = [18, 23, 24, 25, 4, 17, 21, 22] logconfig = pilib.getlogconfig() GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) tables = pilib.gettablenames(pilib.controldatabase) if 'interfaces' in tables: interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces') else: pilib.writedatedlogmsg(pilib.iolog, 'interfaces table not found. Exiting', 1, logconfig['iologlevel']) return if 'inputs' in tables: previnputs = pilib.readalldbrows(pilib.controldatabase, 'inputs') # Make list of IDs for easy indexing previnputids = [] for input in previnputs: previnputids.append(input['id']) else: previnputs = [] previnputids = [] if 'outputs' in tables: prevoutputs = pilib.readalldbrows(pilib.controldatabase, 'outputs') # Make list of IDs for easy indexing prevoutputids = [] prevoutputvalues = [] for output in prevoutputs: prevoutputids.append(output['id']) prevoutputvalues.append(output['value']) else: prevoutputs = {} prevoutputids = [] if 'defaults' in tables: defaults = pilib.readalldbrows(pilib.controldatabase, 'defaults')[0] defaultinputpollfreq = defaults['inputpollfreq'] defaultoutputpollfreq = defaults['outputpollfreq'] else: defaults = [] defaultinputpollfreq = 60 defaultoutputpollfreq = 60 if 'indicators' in tables: indicatornames = [] previndicators = pilib.readalldbrows(pilib.controldatabase, 'indicators') for indicator in previndicators: indicatornames.append(indicator['name']) else: previndicators = [] indicatornames = [] # We drop all inputs and outputs and recreate # Add all into one query so there is no time when the IO don't exist. querylist = [] querylist.append('delete from inputs') querylist.append('delete from outputs') # This is temporary. Clearing the table here and adding entries below can result in a gap in time # where there are no database indicator entries. This is not too much of a problem with indicators, as we # update the hardware explicitly after we add the entries. If the interface queries the table during # this period, however, we could end up with an apparently empty table. # TODO: FIX update on indicators in updateio pilib.sqlitequery(pilib.controldatabase, 'delete from indicators') owfsupdate = False for interface in interfaces: if interface['interface'] == 'I2C': pilib.writedatedlogmsg(pilib.iolog, 'Processing I2C interface' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.writedatedlogmsg(pilib.iolog, 'I2C Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) if interface['type'] == 'DS2483': pilib.writedatedlogmsg(pilib.iolog, 'Interface type is DS2483', 3, logconfig['iologlevel']) owfsupdate = True elif interface['interface'] == 'USB': pilib.writedatedlogmsg(pilib.iolog, 'Processing USB interface' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.writedatedlogmsg(pilib.iolog, 'USB Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) if interface['type'] == 'DS9490': pilib.writedatedlogmsg(pilib.iolog, 'Interface type is DS9490', 3, logconfig['iologlevel']) owfsupdate = True elif interface['interface'] == 'MOTE': pilib.writedatedlogmsg(pilib.iolog, 'Processing Mote interface' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.writedatedlogmsg(pilib.iolog, 'Mote Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) # Grab mote entries from remotes table nodeaddress = int(interface['address']) nodeentries = pilib.dynamicsqliteread(pilib.controldatabase, 'remotes', condition="\"nodeid\"='" + str(nodeaddress) + "'") # Create queries for table insertion # TODO: process mote pollfreq, ontime, offtime moteentries = [] for nodeentry in nodeentries: datadict = pilib.parseoptions(nodeentry['data']) try: entrytype = nodeentry['msgtype'] entryid = 'MOTE' + str(nodeentry['nodeid']) + '_' + nodeentry['keyvaluename'] + '_' + nodeentry['keyvalue'] entrymetareturn = pilib.dynamicsqliteread(pilib.controldatabase, 'ioinfo', condition="\"id\"='" + entryid + "'") try: entrymeta = entrymetareturn[0] except: entrymeta = [] # print(entrymeta) entryoptions={} if entrymeta: entryname = entrymeta['name'] if entrymeta['options']: entryoptions = pilib.parseoptions(entrymeta['options']) else: entryname = '[MOTE' + str(nodeentry['nodeid']) + '] ' + nodeentry['keyvaluename'] + ':' + nodeentry['keyvalue'] except KeyError: print('OOPS KEY ERROR') else: if entrytype == 'iovalue': if 'scale' in entryoptions: entryvalue = str(float(entryoptions['scale']) * float(datadict['iovalue'])) else: entryvalue = datadict['iovalue'] elif entrytype == 'owdev': if 'owtmpasc' in datadict: if 'scale' in entryoptions: entryvalue = str(float(entryoptions['scale']) * float(datadict['owtmpasc'])) else: entryvalue = datadict['owtmpasc'] else: entryvalue = -1 else: entryvalue = -1 moteentries.append('insert into inputs values (\'' + entryid + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(address) + '\',\'' + entryname + '\',\'' + str(entryvalue) + "','','" + nodeentry['time'] + '\',\'' + str(15) + "','" + '' + "','" + '' + "')") # print('querylist') # print(moteentries) querylist.extend(moteentries) elif interface['interface'] == 'LAN': pilib.writedatedlogmsg(pilib.iolog, 'Processing LAN interface' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.writedatedlogmsg(pilib.iolog, 'LAN Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) if interface['type'] == 'MBTCP': pilib.writedatedlogmsg(pilib.iolog, 'Interface ' + interface['name'] + ' type is MBTCP', 3, logconfig['iologlevel']) try: mbentries = processMBinterface(interface, prevoutputs, prevoutputids, previnputs, previnputids, defaults, logconfig) except: pilib.writedatedlogmsg(pilib.iolog, 'Error processing MBTCP interface ' + interface['name'], 0, logconfig['iologlevel']) errorstring = traceback.format_exc() pilib.writedatedlogmsg(pilib.iolog, 'Error of kind: ' + errorstring, 0, logconfig['iologlevel']) else: pilib.writedatedlogmsg(pilib.iolog, 'Done processing MBTCP interface ' + interface['name'], 3, logconfig['iologlevel']) querylist.extend(mbentries) elif interface['interface'] == 'GPIO': try: address = int(interface['address']) except KeyError: pilib.writedatedlogmsg(pilib.iolog, 'GPIO address key not found for ' + interface['name'], 1, logconfig['iologlevel']) continue pilib.writedatedlogmsg(pilib.iolog, 'Processing GPIO interface ' + str(interface['address']), 3, logconfig['iologlevel']) if address in allowedGPIOaddresses: pilib.writedatedlogmsg(pilib.iolog, 'GPIO address' + str(address) + ' allowed', 4, logconfig['iologlevel']) # Check if interface is enabled if interface['enabled']: GPIOentries = processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids, previnputs, previnputids, defaults, logconfig) querylist.extend(GPIOentries) else: pilib.writedatedlogmsg(pilib.iolog, 'GPIO address' + str(address) + ' disabled', 4, logconfig['iologlevel']) GPIO.setup(address, GPIO.IN) else: pilib.writedatedlogmsg(pilib.iolog, 'GPIO address' + str(address) + ' not allowed. Bad things can happen. ', 4, logconfig['iologlevel']) elif interface['interface'] == 'SPI0': pilib.writedatedlogmsg(pilib.iolog, 'Processing SPI0', 1, logconfig['iologlevel']) if interface['type'] == 'SPITC': import readspi spidata = readspi.readspitc(0) spitcentries = readspi.recordspidata(database, spidata) querylist.extend(spitcentries) if interface['type'] == 'CuPIDlights': import spilights spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 0, previndicators) querylist.extend(spilightsentries) spilights.updatelightsfromdb(pilib.controldatabase, 'indicators', 0) spilights.setspilights(setlist, 0) elif interface['interface'] == 'SPI1': pilib.writedatedlogmsg(pilib.iolog, 'Processing SPI1', 1, logconfig['iologlevel']) if interface['type'] == 'CuPIDlights': import spilights spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 1, previndicators) querylist.extend(spilightsentries) spilights.setspilights(setlist, 1) # Set tables querylist.append(pilib.makesinglevaluequery('systemstatus', 'lastiopoll', pilib.gettimestring())) if owfsupdate: from owfslib import runowfsupdate devices, owfsentries = runowfsupdate(execute=False) querylist.extend(owfsentries) pilib.writedatedlogmsg(pilib.iolog, 'Executing query: ' + str(querylist), 5, logconfig['iologlevel']) try: pilib.sqlitemultquery(pilib.controldatabase, querylist) except: errorstring = traceback.format_exc() pilib.writedatedlogmsg(pilib.iolog, 'Error executing query, message: ' + errorstring, 0, logconfig['iologlevel']) pilib.writedatedlogmsg(pilib.errorlog, 'Error executing updateio query, message: ' + errorstring) pilib.writedatedlogmsg(pilib.errorlog, 'Query: ' + str(querylist))
def setnegout(controldatabase, channelname, outputname): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set negativeoutput=\'' + outputname + '\' where name=\'' + channelname + '\'')
def setnegout(controldatabase, channelname, outputname): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set negativeoutput=\'' + outputname + '\' where name=\'' + channelname + '\'')
def setalgorithm(controldatabase, channelname, algorithm): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set controlalgorithm=\'' + algorithm + '\' where name=\'' + channelname + '\'')
def setsetpoint(controldatabase, channelname, setpointvalue): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set setpointvalue=\'' + str(setpointvalue) + '\' where name=\'' + channelname + '\'')
ROMsandtemps.append([onlineROMlist[i],tempfile.readline().strip()]) i +=1 #print("ROM tuples\n") #print(ROMsandtemps) # Write to database # At the moment all are enabled by default. # Eventually we'll read this before we delete all entries for tuple in ROMsandtemps: ROM=tuple[0] temp=tuple[1] queryresult=pilib.sqlitequery(database,'select name from sensorinfo where sensorID = ' + "'" + ROM + "'") if not queryresult: name='' else: name = queryresult[0][0] valuelist = [tuple[0],tuple[1],'F',pilib.gettimestring(),1,name] query = pilib.makesqliteinsert('sensordata',valuelist) # print(query) querylist.append(query) # execute combined query #print(querylist) ######################################## # Do thermocouple stuff
def getsetpoint(controldatabase, channelname): from pilib import sqlitequery currentsetpoint = \ sqlitequery(controldatabase, 'select setpointvalue from channels where name=\'' + channelname + '\'')[0][0] return currentsetpoint
readtime = 10 # default, seconds # Read from systemstatus to make sure we should be running inputsreadenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select inputsreadenabled from systemstatus') while inputsreadenabled: #print("runtime") #print("reading input") # Read again, once inside each loop so we terminate if the # variable name is changed inputsreadenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select inputsreadenabled from systemstatus') # Set last run time pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set lastinputspoll=\'' + pilib.gettimestring() + '\'') pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set inputsreadstatus=\'1\'') # Read and record everything as specified in controldatabase # Update database of inputs with read data reply = updateio.updateiodata(pilib.controldatabase) result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0) systemsdict = result[0] #print("here is the systems dict") #print(systemsdict) readtime = systemsdict['inputsreadfreq'] plotpoints = 20 logpoints = 100
def updateowfsdevices(busdevices, myProxy=None): import pilib # get defaults defaults = pilib.readalldbrows(pilib.controldatabase, 'defaults')[0] # get current entries previnputs = pilib.readalldbrows(pilib.controldatabase, 'inputs') # Make list of IDs for easy indexing previnputids = [] for input in previnputs: previnputids.append(input['id']) # Iterate over devices. Determine if values exist for polltime, frequency. # If so, update the device. If not, use defaults. # Then determine whether we should update value or not (Read temperature) for index, device in enumerate(busdevices): if device.sensorid in previnputids: try: newpollfreq = int(previnputs[previnputids.index(device.sensorid)]['pollfreq']) except ValueError: device.pollfreq = defaults['inputpollfreq'] else: if newpollfreq >= 0: device.pollfreq = previnputs[previnputids.index(device.sensorid)]['pollfreq'] else: device.pollfreq = defaults['inputpollfreq'] device.ontime = previnputs[previnputids.index(device.sensorid)]['ontime'] device.offtime = previnputs[previnputids.index(device.sensorid)]['offtime'] device.polltime = previnputs[previnputids.index(device.sensorid)]['polltime'] device.value = previnputs[previnputids.index(device.sensorid)]['value'] else: device.pollfreq = defaults['inputpollfreq'] device.ontime = '' device.offtime = '' device.polltime = '' device.value = '' # We're going to set a name because calling things by their ids is getting # a bit ridiculous, but we can't have empty name fields if we rely on them # being there. They need to be unique, so we'll name them by type and increment them if device.type == 'DS18B20': # Get name if one exists name = pilib.sqlitedatumquery(pilib.controldatabase, 'select name from ioinfo where id=\'' + device.sensorid + '\'') # If doesn't exist, check to see if proposed name exists. If it doesn't, add it. # If it does, keep trying. if name == '': for rangeindex in range(100): # check to see if name exists name = device.type + '-' + str(int(index + 1)) # print(name) foundid = pilib.sqlitedatumquery(pilib.controldatabase, 'select id from ioinfo where name=\'' + name + '\'') # print('foundid' + foundid) if foundid: pass else: pilib.sqlitequery(pilib.controldatabase, pilib.makesqliteinsert('ioinfo', valuelist=[device.sensorid, name], valuenames=['id', 'name'])) break device.name = name # Is it time to read temperature? if pilib.timestringtoseconds(pilib.gettimestring()) - pilib.timestringtoseconds(device.polltime) > device.pollfreq: device.readprop('temperature', myProxy) device.polltime = pilib.gettimestring() device.value = device.temperature else: pass # print('not time to poll') device.unit = 'F' # We update the device and send them back for other purposes. busdevices[index] = device return busdevices
def runpicontrol(runonce=False): systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0] while systemstatus['picontrolenabled']: pilib.log(pilib.syslog, 'Running picontrol', 3, pilib.sysloglevel) pilib.log(pilib.controllog, 'Running picontrol', 3, pilib.controlloglevel) # Set poll date. While intuitively we might want to set this # after the poll is complete, if we error below, we will know # from this stamp when it barfed. This is arguably more valuable # then 'last time we didn't barf' pilib.sqlitequery(pilib.controldatabase, "update systemstatus set lastpicontrolpoll='" + pilib.gettimestring() + "'") channels = pilib.readalldbrows(pilib.controldatabase, 'channels') outputs = pilib.readalldbrows(pilib.controldatabase, 'outputs') controlalgorithms = pilib.readalldbrows(pilib.controldatabase, 'controlalgorithms') algorithmnames=[] for algorithm in controlalgorithms: algorithmnames.append(algorithm['name']) # Cycle through channels and set action based on setpoint # and algorithm if set to auto mode for channel in channels: statusmsg = '' querylist = [] channelindex = str(int(channel['channelindex'])) channelname = channel['name'] logtablename = 'channel' + '_' + channel['name'] + '_log' time = pilib.gettimestring() disableoutputs = True # Make sure channel is enabled if channel['enabled']: # Create log if it doesn't exist query = 'create table if not exists \'' + logtablename + '\' (time text, controlinput text, controlvalue real, setpointvalue real, action real, algorithm text, enabled real, statusmsg text)' pilib.sqlitequery(pilib.logdatabase, query) statusmsg = '' if 'setpointvalue' in channel: setpointvalue = float(channel['setpointvalue']) else: statusmsg += 'No setpoint. ' # Need to test for age of data. If stale or disconnected, invalidate if 'controlvalue' in channel: try: controlvalue = float(channel['controlvalue']) except (ValueError, TypeError) as e: statusmsg += 'Invalid control value. ' controllib.setcontrolvalue(pilib.controldatabase, channelname, 0) else: statusmsg += 'No controlvalue. ' # Test to see if key exists and is true if 'enabled' in channel: if channel['enabled']: pass else: statusmsg += 'Channel disabled. ' else: statusmsg += 'Error. Enabled key does not exist' mode = channel['mode'] channelalgorithmname = channel['controlalgorithm'] controlinput = channel['controlinput'] logpoints = channel['logpoints'] # Move forward if everything is defined for control if channel['enabled'] and 'controlvalue' in locals() and 'setpointvalue' in locals(): statusmsg += 'Channel Enabled. ' if mode == 'auto': statusmsg += 'Mode:Auto. ' #print('running auto sequence') # run algorithm on channel response = controllib.runalgorithm(pilib.controldatabase, pilib.recipedatabase, channelname) action = response[0] message = response[1] statusmsg += ' ' + response[1] + ' ' statusmsg += 'Action: ' + str(action) + '. ' # Set action in channel controllib.setaction(pilib.controldatabase, channelname, action) elif mode == 'manual': #print('manual mode') statusmsg += 'Mode:Manual. ' # action = controllib.getaction(pilib.controldatabase, channelname) else: #print('error, mode= ' + mode) statusmsg += 'Mode:Error. ' if systemstatus['enableoutputs']: statusmsg += 'System outputs enabled. ' if channel['outputsenabled']: statusmsg += 'Channel outputs enabled. ' disableoutputs = False # find out whether action is positive or negative or # not at all. # and act. for now, this is binary, but in the future # this will be a duty cycle daemon outputsetnames = [] outputresetnames = [] if action > 0: print("set positive output on") outputsetnames.append(channel['positiveoutput']) outputresetnames.append(channel['negativeoutput']) elif action < 0: print("set negative output on") outputsetnames.append(channel['negativeoutput']) outputresetnames.append(channel['positiveoutput']) elif action == 0: statusmsg += 'No action. ' outputresetnames.append(channel['positiveoutput']) outputresetnames.append(channel['negativeoutput']) else: statusmsg += 'Algorithm error. Doing nothing.' outputsetname = None # Check to see if outputs are ready to enable/disable # If not, pull them from list of set/reset outputstoset=[] for outputname in outputsetnames: if channelalgorithmname in algorithmnames: offtime = pilib.sqlitedatumquery(pilib.controldatabase, "select offtime from outputs where name='" + outputname + "'" ) if pilib.timestringtoseconds(pilib.gettimestring()) - pilib.timestringtoseconds(offtime) > controlalgorithms[algorithmnames.index(channelalgorithmname)]['minofftime']: outputstoset.append(outputname) else: statusmsg += 'Output ' + outputname + ' not ready to enable. ' else: statusmsg += 'Algorithm Error: Not found. ' outputstoreset=[] for outputname in outputresetnames: if channelalgorithmname in algorithmnames: ontime = pilib.sqlitedatumquery(pilib.controldatabase, "select ontime from outputs where name='" + outputname +"'") if pilib.timestringtoseconds(pilib.gettimestring()) - pilib.timestringtoseconds(ontime) > controlalgorithms[algorithmnames.index(channelalgorithmname)]['minontime']: outputstoreset.append(outputname) else: statusmsg += 'Output ' + outputname + ' not ready to disable. ' else: statusmsg += 'Algorithm Error: Not found. ' """ TODO: Change reference to controlinputs to name rather than id. Need to double-check enforcement of no duplicates.""" # Find output in list of outputs if we have one to set time = pilib.gettimestring() if len(outputstoset) > 0 or len(outputstoreset) > 0: for output in outputs: if output['name'] in outputstoset: # check current status currvalue = output['value'] if currvalue == 0: # No need to set if otherwise. Will be different for analog out # set ontime querylist.append('update outputs set ontime=\'' + time + '\' ' + 'where id=\'' + output['id'] + '\'') # set value querylist.append("update outputs set value = 1 where id='" + output['id'] + '\'') statusmsg += 'Output ' + output['name'] + ' enabled. ' else: statusmsg += 'Output ' + output['name'] + ' already enabled. ' if output['name'] in outputstoreset: # check current status currvalue = output['value'] if currvalue == 1: # No need to set if otherwise. Will be different for analog out # set ontime querylist.append('update outputs set offtime=\'' + time + '\' ' + 'where id=\'' + output['id'] + '\'') # set value querylist.append('update outputs set value = 0 where id=\'' + output['id'] + '\'') statusmsg += 'Output ' + output['name'] + ' disabled. ' else: statusmsg += 'Output ' + output['name'] + ' already disabled. ' else: statusmsg += 'Channel outputs disabled. ' action = 0 else: statusmsg += 'System outputs disabled. ' action = 0 # Insert entry into control log pilib.makesqliteinsert(pilib.logdatabase, logtablename, [time, controlinput, controlvalue, setpointvalue, action, channelalgorithmname, channel['enabled'], statusmsg]) pilib.sqliteinsertsingle(pilib.logdatabase, logtablename, [time, controlinput, controlvalue, setpointvalue, action, channelalgorithmname, channel['enabled'], statusmsg]) # Size log pilib.sizesqlitetable(pilib.logdatabase, logtablename, logpoints) # print(statusmsg) else: # print('channel not enabled') statusmsg += 'Channel not enabled. ' # If active reset and we didn't set channel modes, disable outputs # Active reset is not yet explicitly declared, but implied if disableoutputs: statusmsg += 'Disabling Outputs. ' for output in outputs: if output['name'] in [channel['positiveoutput'], channel['negativeoutput']]: # set value querylist.append("update outputs set value = 0 where id='" + output['id'] + '\'') statusmsg += 'Output ' + output['name'] + ' disabled. ' # Set status message for channel # print(statusmsg) querylist.append('update channels set statusmessage=\'' + statusmsg + '\'' + 'where channelindex=' + channelindex) # Set update time for channel querylist.append('update channels set controlupdatetime=\'' + time + '\'' + 'where channelindex=' + channelindex) # Execute query pilib.sqlitemultquery(pilib.controldatabase, querylist) # We do this system status again to refresh settings systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0] from actions import processactions processactions() # Wait for delay time #print('sleeping') # spilights.updatelightsfromdb(pilib.controldatabase, 'indicators') if runonce: break pilib.log(pilib.syslog, 'Picontrol Sleeping for ' + str(systemstatus['picontrolfreq']), 2, pilib.sysloglevel) pilib.log(pilib.controllog, 'Picontrol Sleeping for ' + str(systemstatus['picontrolfreq']), 2, pilib.sysloglevel) sleep(systemstatus['picontrolfreq']) pilib.log(pilib.syslog, 'picontrol not enabled. exiting.', 1, pilib.sysloglevel)
def setcontrolinput(controldatabase, channelname, inputid): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set controlinput = \'' + inputid + '\' where name = \'' + channelname + '\'')
def setmode(self, mode): from pilib import controldatabase, sqlitequery sqlitequery( controldatabase, 'update channels set mode=\'' + str(mode) + '\' where name=\'' + channel.name + '\'')
def getaction(controldatabase, channelname): from pilib import sqlitequery action = sqlitequery(controldatabase, 'select action from channels where name=\'' + channelname + '\'')[0][0] return action
def rundaemon(startall=False): from subprocess import Popen, PIPE from time import sleep from pilib import log, daemonlog, daemonloglevel # Set up list of enabled statuses (whether to restart if # we find that the process is not currently running picontrolenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select picontrolenabled from systemstatus') updateioenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select updateioenabled from systemstatus') systemstatusenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select systemstatusenabled from systemstatus') sessioncontrolenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select sessioncontrolenabled from systemstatus') serialhandlerenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select serialhandlerenabled from systemstatus') enableditemlist = [(int(updateioenabled)), (int(picontrolenabled)), int(systemstatusenabled), int(sessioncontrolenabled), int(serialhandlerenabled)] itemstatuses = findprocstatuses(pilib.daemonprocs) # Set system message systemstatusmsg = '' for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses): systemstatusmsg += name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. ' if pilib.daemonloglevel > 0: pilib.log(pilib.daemonlog, name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. ') pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'systemmessage', systemstatusmsg) # Set up list of itemnames in the systemstatus table that # we assign the values to when we detect if the process # is running or not statustableitemnames = ['updateiostatus', 'picontrolstatus', 'systemstatusstatus', 'sessioncontrolstatus', 'serialhandlerstatus'] for index, item in enumerate(pilib.daemonprocs): # set status if itemstatuses[index]: pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1') if pilib.daemonloglevel > 0: pilib.log(pilib.daemonlog, 'Process is running: ' + pilib.baselibdir + pilib.daemonprocs[index]) else: pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0') if pilib.daemonloglevel > 0: pilib.log(pilib.daemonlog, 'Process is not running: ' + pilib.baselibdir + pilib.daemonprocs[index]) # run if set to enable if enableditemlist[index]: # print(pilib.baselibdir + pilib.daemonprocs[index]) if pilib.daemonloglevel > 0: pilib.log(pilib.daemonlog, 'Starting ' + pilib.baselibdir + pilib.daemonprocs[index]) procresult = Popen([pilib.baselibdir + pilib.daemonprocs[index]], stdout=PIPE, stderr=PIPE) # if pilib.daemonloglevel > 0: # pilib.writedatedlogmsg(pilib.daemonproclog, procresult.stdout.read()) sleep(1) # Refresh after set itemstatuses = findprocstatuses(pilib.daemonprocs) for item in pilib.daemonprocs: index = pilib.daemonprocs.index(item) # set status if itemstatuses[index]: pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1') else: pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0') # Set system message systemstatusmsg = '' for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses): systemstatusmsg += name + ' - Enabled: ' + str(bool(enabled)) + ' Status: ' + str(status) + '. ' pilib.setsinglevalue(pilib.controldatabase, 'systemstatus','systemmessage', systemstatusmsg) # Rotate all logs pilib.rotatelogs(pilib.networklog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.syslog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.iolog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.controllog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.daemonlog, pilib.numlogs, pilib.maxlogsize)
def runalgorithm(controldatabase, recipedatabase, channelname): from pilib import sqlitequery, datarowtodict, gettimestring, timestringtoseconds import time message = '' # get our details of our channel channeldata = sqlitequery( controldatabase, 'select * from channels where name=' + "'" + channelname + "'")[0] channeldict = datarowtodict(controldatabase, 'channels', channeldata) # check to see if we are running a recipe controlrecipename = channeldict['controlrecipe'] if controlrecipename and controlrecipename != 'none': # Get recipe details # If recipes get too big, we'll just get # a couple stages. For now, we make a # dictionary array #print('we are in recipe ' + controlrecipename) #print(recipedatabase) recipedata = sqlitequery(recipedatabase, 'select * from \'' + controlrecipename + '\'') recipedictarray = [] for stage in recipedata: recipedict = datarowtodict(recipedatabase, controlrecipename, stage) recipedictarray.append(recipedict) # get current stage currentstagenumber = int(channeldict['recipestage']) #print('current stage is ' + str(currentstagenumber) ) # Get data for current stage stagefound = False for stage in recipedictarray: if int(stage['stagenumber']) == currentstagenumber: currentstage = stage stagefound = True break if stagefound: #print("stage found") pass else: print('error. stage not found.') # Check to see if we need to move to next stage currenttime = time.time() #print('Time') #print(currenttime) #print(gettimestring(currenttime)) if currentstagenumber == 0 or currenttime - timestringtoseconds( channeldict['recipestagestarttime']) > int( currentstage['stagelength']): print('stage time expired for stage ' + str(currentstagenumber) + '. Checking on stage advance. ') # Advance stage if there is another stage. Otherwise # update channel to be off a recipe. We assume explicitly # that the stages are sequential integers. nextstagenumber = currentstagenumber + 1 # look for next stage stagefound = False for stage in recipedictarray: if int(stage['stagenumber']) == nextstagenumber: nextstage = stage stagefound = True break if stagefound: print(' Next stage was found. Setting next stage. ') if currentstagenumber == 0: print("Stagenumber is 0. Setting recipe start time. ") # Set recipe start time sqlitequery( controldatabase, 'update channels set recipestarttime=\'' + gettimestring(currenttime) + '\' where name=\'' + channelname + '\'') # Set stage to new stage number sqlitequery( controldatabase, 'update channels set recipestage=\'' + str(nextstagenumber) + '\' where name=\'' + channelname + '\'') # Set setpointvalue sqlitequery( controldatabase, 'update channels set setpointvalue=\'' + str(nextstage['setpointvalue']) + '\' where name=\'' + channelname + '\'') # Set stage start time to now sqlitequery( controldatabase, 'update channels set recipestagestarttime=\'' + gettimestring(currenttime) + '\' where name=\'' + channelname + '\'') # Set new controlalgorithm sqlitequery( controldatabase, 'update channels set controlalgorithm=\'' + nextstage['controlalgorithm'] + '\' where name=\'' + channelname + '\'') else: # Take channel off recipe sqlitequery( controldatabase, 'update channels set controlrecipe=\'none\' where name=\'' + channelname + '\'') sqlitequery( controldatabase, 'update channels set recipestate=\'0\' where name=\'' + channelname + '\'') sqlitequery( controldatabase, 'update channels set recipestage=\'0\' where name=\'' + channelname + '\'') # if lengthmode is setpoint # get current stage # check stage start against stage length # and current time # move to next stage if time and revise setpoint # adjust setpoint based on stage # set action based on setpoint else: # make sure we're not on recipe and on stage 0 sqlitequery( controldatabase, 'update channels set controlrecipe=\'none\' where name=\'' + channelname + '\'') sqlitequery( controldatabase, 'update channels set recipestate=\'0\' where name=\'' + channelname + '\'') sqlitequery( controldatabase, 'update channels set recipestage=\'0\' where name=\'' + channelname + '\'') algorithm = channeldict['controlalgorithm'] setpointvalue = float(channeldict['setpointvalue']) controlvalue = float(channeldict['controlvalue']) algorithmrows = sqlitequery( controldatabase, 'select * from controlalgorithms where name=' + "'" + algorithm + "'") algorithmrow = algorithmrows[0] algorithm = datarowtodict(controldatabase, 'controlalgorithms', algorithmrow) type = algorithm['type'] if type == 'on/off with deadband': #print(type) deadbandhigh = algorithm['deadbandhigh'] deadbandlow = algorithm['deadbandlow'] if setpointvalue > (controlvalue + deadbandhigh): action = 100 elif setpointvalue < (controlvalue - deadbandlow): action = -100 else: action = 0 #print('setpoint' + str(setpoint)) #print('controlvalue' + str(controlvalue)) #print(action) #print(message) return [action, message]
def setsetpoint(self,setpointvalue): from pilib import controldatabase, sqlitequery sqlitequery(controldatabase, 'update channels set setpointvalue=\'' + str(setpointvalue) + '\' where name=\'' + channel.name + '\'')
def updateiodata(database, **kwargs): # This recreates all input and output tables based on the interfaces table. # Thus way we don't keep around stale data values. We could at some point incorporate # a retention feature that keeps them around in case they disappear temporarily. # It also reads the elements if they are enabled and it's time to read them import pilib import traceback if 'piobject' in kwargs: pi = kwargs['piobject'] else: import pigpio pi = pigpio.pi() allowedGPIOaddresses = [18, 23, 24, 25, 4, 17, 27, 22, 5, 6, 13, 19, 26, 16, 20, 21] logconfig = pilib.getlogconfig() tables = pilib.gettablenames(pilib.controldatabase) if 'interfaces' in tables: interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces') else: pilib.log(pilib.iolog, 'interfaces table not found. Exiting', 1, logconfig['iologlevel']) return if 'inputs' in tables: previnputs = pilib.readalldbrows(pilib.controldatabase, 'inputs') # Make list of IDs for easy indexing previnputids = [] for input in previnputs: previnputids.append(input['id']) else: previnputs = [] previnputids = [] if 'outputs' in tables: prevoutputs = pilib.readalldbrows(pilib.controldatabase, 'outputs') # Make list of IDs for easy indexing prevoutputids = [] prevoutputvalues = [] for output in prevoutputs: prevoutputids.append(output['id']) prevoutputvalues.append(output['value']) else: prevoutputs = {} prevoutputids = [] if 'defaults' in tables: defaults = pilib.readalldbrows(pilib.controldatabase, 'defaults')[0] defaultinputpollfreq = defaults['inputpollfreq'] defaultoutputpollfreq = defaults['outputpollfreq'] else: defaults = [] defaultinputpollfreq = 60 defaultoutputpollfreq = 60 if 'indicators' in tables: indicatornames = [] previndicators = pilib.readalldbrows(pilib.controldatabase, 'indicators') for indicator in previndicators: indicatornames.append(indicator['name']) else: previndicators = [] indicatornames = [] # We drop all inputs and outputs and recreate # Add all into one query so there is no time when the IO don't exist. querylist = [] querylist.append('delete from inputs') querylist.append('delete from outputs') # This is temporary. Clearing the table here and adding entries below can result in a gap in time # where there are no database indicator entries. This is not too much of a problem with indicators, as we # update the hardware explicitly after we add the entries. If the interface queries the table during # this period, however, we could end up with an apparently empty table. # TODO: FIX update on indicators in updateio # We drop this table, so that if SP1 has been disabled, the entries do not appear as valid indicators pilib.sqlitequery(pilib.controldatabase, 'delete from indicators') owfsupdate = False for interface in interfaces: if interface['interface'] == 'I2C': pilib.log(pilib.iolog, 'Processing I2C interface ' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.log(pilib.iolog, 'I2C Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) if interface['type'] == 'DS2483': pilib.log(pilib.iolog, 'Interface type is DS2483', 3, logconfig['iologlevel']) owfsupdate = True else: pilib.log(pilib.iolog, 'I2C Interface ' + interface['name'] + ' disabled', 3, logconfig['iologlevel']) elif interface['interface'] == 'USB': pilib.log(pilib.iolog, 'Processing USB interface ' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.log(pilib.iolog, 'USB Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) if interface['type'] == 'DS9490': pilib.log(pilib.iolog, 'Interface type is DS9490', 3, logconfig['iologlevel']) owfsupdate = True else: pilib.log(pilib.iolog, 'USB Interface ' + interface['name'] + ' disabled', 3, logconfig['iologlevel']) elif interface['interface'] == 'MOTE': #determine and then update id based on fields entryid = interface['interface'] + '_' + interface['type'] + '_' + interface['address'] condition = '"interface"=\'' + interface['interface'] + '\' and "type"=\'' + interface['type'] + '\' and "address"=\'' + interface['address'] + '\'' print(condition) pilib.setsinglevalue(pilib.controldatabase, 'interfaces', 'id', entryid, condition) pilib.log(pilib.iolog, 'Processing Mote interface' + interface['name'] + ', id:' + entryid, 3, logconfig['iologlevel']) if interface['enabled']: pilib.log(pilib.iolog, 'Mote Interface ' + interface['name'] + ', id:' + entryid + ' enabled', 3, logconfig['iologlevel']) # Grab mote entries from remotes table # nodeid and keyvalue are keyed into address in remotes table # keyvalues are : # channel: channel number # iovalue: ionumber # owdev: ROM # This would look like, for example # 1:1 for a nodeid:channel scenario for a controller split = interface['address'].split(':') nodeid = split[0] keyvalue = split[1] # so we used to enable an interface and then take all entries from a node # Now, we have to explicitly add an interface for each device, unless the keychar * is used as the # keyvalue. This will allow us to insert all automatically, for example for owdevs or iovals from a # node. # This pulls out all mote entries that have nodeid and keyvalue that match the interface address # We should just find one, ideally if keyvalue == '*': pass else: condition = "\"nodeid\"='" + nodeid + "' and \"keyvalue\"='" + keyvalue + "'" nodeentries = pilib.dynamicsqliteread(pilib.controldatabase, 'remotes', condition=condition) print("WE FOUND MOTE") print(condition) print(len(nodeentries)) if interface['type'] == 'channel': print('channel') if len(nodeentries) == 1: print('one entry found') nodeentry = nodeentries[0] nodedata = pilib.parseoptions(nodeentry['data']) # Find existing channel so we can get existing data, settings, etc., and retain channel ordering newchanneldata = {'name':interface['name'], 'controlvalue':nodedata['pv'], 'setpointvalue':nodedata['sv'],'controlvaluetime':pilib.gettimestring(), 'data':nodeentry['data'], 'type':'remote'} newchannel = {} existingchannels = pilib.readalldbrows(pilib.controldatabase, 'channels') for channel in existingchannels: if channel['name'] == interface['name']: print('updating') print(channel) newchannel.update(channel) print(newchannel) newchannel.update(newchanneldata) print(newchannel) keys = [] values = [] for key, value in newchannel.iteritems(): keys.append(key) values.append(value) query = pilib.makesqliteinsert('channels',values, keys) # print(query) pilib.sqlitequery(pilib.controldatabase,query) else: print('multiple entries found for channel. not appropriate') else: pass # Create queries for table insertion # TODO: process mote pollfreq, ontime, offtime moteentries = [] for nodeentry in nodeentries: # THis breaks out all of the strictly json-encoded data. datadict = pilib.parseoptions(nodeentry['data']) try: entrytype = nodeentry['msgtype'] # now treat each mote type entry specially # if entrytype == 'channel': entryid = 'MOTE' + str(nodeentry['nodeid']) + '_' + nodeentry['keyvaluename'] + '_' + nodeentry['keyvalue'] entrymetareturn = pilib.dynamicsqliteread(pilib.controldatabase, 'ioinfo', condition="\"id\"='" + entryid + "'") try: entrymeta = entrymetareturn[0] except: entrymeta = [] # print(entrymeta) entryoptions={} if entrymeta: entryname = entrymeta['name'] if entrymeta['options']: entryoptions = pilib.parseoptions(entrymeta['options']) else: entryname = '[MOTE' + str(nodeentry['nodeid']) + '] ' + nodeentry['keyvaluename'] + ':' + nodeentry['keyvalue'] except KeyError: print('OOPS KEY ERROR') else: if entrytype == 'iovalue': if 'scale' in entryoptions: entryvalue = str(float(entryoptions['scale']) * float(datadict['ioval'])) elif 'formula' in entryoptions: x = float(datadict['ioval']) try: entryvalue = eval(entryoptions['formula']) except: entryvalue = float(datadict['ioval']) else: entryvalue = float(datadict['ioval']) elif entrytype == 'owdev': if 'owtmpasc' in datadict: if 'scale' in entryoptions: entryvalue = str(float(entryoptions['scale']) * float(datadict['owtmpasc'])) elif 'formula' in entryoptions: x = float(datadict['owtmpasc']) try: entryvalue = eval(entryoptions['formula']) except: entryvalue = float(datadict['owtmpasc']) else: entryvalue = datadict['owtmpasc'] else: entryvalue = -1 else: entryvalue = -1 moteentries.append('insert into inputs values (\'' + entryid + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(address) + '\',\'' + entryname + '\',\'' + str(entryvalue) + "','','" + nodeentry['time'] + '\',\'' + str(15) + "','" + '' + "','" + '' + "')") # print('querylist') # print(moteentries) querylist.extend(moteentries) else: pilib.log(pilib.iolog, 'Mote Interface ' + interface['name'] + ' disnabled', 3, logconfig['iologlevel']) elif interface['interface'] == 'LAN': pilib.log(pilib.iolog, 'Processing LAN interface' + interface['name'], 3, logconfig['iologlevel']) if interface['enabled']: pilib.log(pilib.iolog, 'LAN Interface ' + interface['name'] + ' enabled', 3, logconfig['iologlevel']) if interface['type'] == 'MBTCP': pilib.log(pilib.iolog, 'Interface ' + interface['name'] + ' type is MBTCP', 3, logconfig['iologlevel']) try: mbentries = processMBinterface(interface, prevoutputs, prevoutputids, previnputs, previnputids, defaults, logconfig) except: pilib.log(pilib.iolog, 'Error processing MBTCP interface ' + interface['name'], 0, logconfig['iologlevel']) errorstring = traceback.format_exc() pilib.log(pilib.iolog, 'Error of kind: ' + errorstring, 0, logconfig['iologlevel']) else: pilib.log(pilib.iolog, 'Done processing MBTCP interface ' + interface['name'], 3, logconfig['iologlevel']) querylist.extend(mbentries) else: pilib.log(pilib.iolog, 'LAN Interface ' + interface['name'] + ' disabled', 3, logconfig['iologlevel']) elif interface['interface'] == 'GPIO': try: address = int(interface['address']) except KeyError: pilib.log(pilib.iolog, 'GPIO address key not found for ' + interface['name'], 1, logconfig['iologlevel']) continue if interface['enabled']: pilib.log(pilib.iolog, 'Processing GPIO interface ' + str(interface['address']), 3, logconfig['iologlevel']) if address in allowedGPIOaddresses: pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' allowed. Processing.', 4, logconfig['iologlevel']) GPIOentries = processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids, previnputs, previnputids, defaults, logconfig, piobject=pi) if GPIOentries: querylist.extend(GPIOentries) else: pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' not allowed. Bad things can happen. ', 4, logconfig['iologlevel']) else: pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' disabled. Doing nothing.', 4, logconfig['iologlevel']) elif interface['interface'] == 'SPI0': pilib.log(pilib.iolog, 'Processing SPI0', 1, logconfig['iologlevel']) if interface['enabled']: pilib.log(pilib.iolog, 'SPI0 enabled', 1, logconfig['iologlevel']) if interface['type'] == 'SPITC': pilib.log(pilib.iolog, 'Processing SPITC on SPI0', 3, logconfig['iologlevel']) import readspi tcdict = readspi.getpigpioMAX31855temp(0,0) # Convert to F for now spitcentries = readspi.recordspidata(database, {'SPITC1' :tcdict['tctemp']*1.8+32}) querylist.extend(spitcentries) if interface['type'] == 'CuPIDlights': import spilights spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 0, previndicators) querylist.extend(spilightsentries) spilights.updatelightsfromdb(pilib.controldatabase, 'indicators', 0) spilights.setspilights(setlist, 0) else: pilib.log(pilib.iolog, 'SPI0 not enabled', 1, logconfig['iologlevel']) elif interface['interface'] == 'SPI1': pilib.log(pilib.iolog, 'Processing SPI1', 1, logconfig['iologlevel']) if interface['enabled']: pilib.log(pilib.iolog, 'SPI1 enabled', 1, logconfig['iologlevel']) if interface['type'] == 'CuPIDlights': pilib.log(pilib.iolog, 'Processing CuPID Lights on SPI1', 1, logconfig['iologlevel']) import spilights spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 1, previndicators) querylist.extend(spilightsentries) spilights.setspilights(setlist, 1) else: pilib.log(pilib.iolog, 'SPI1 disaabled', 1, logconfig['iologlevel']) # Set tables querylist.append(pilib.makesinglevaluequery('systemstatus', 'lastiopoll', pilib.gettimestring())) if owfsupdate: from owfslib import runowfsupdate pilib.log(pilib.iolog, 'Running owfsupdate', 1, logconfig['iologlevel']) devices, owfsentries = runowfsupdate(execute=False) querylist.extend(owfsentries) else: pilib.log(pilib.iolog, 'owfsupdate disabled', 3, logconfig['iologlevel']) pilib.log(pilib.iolog, 'Executing query: ' + str(querylist), 5, logconfig['iologlevel']) try: # print(querylist) pilib.sqlitemultquery(pilib.controldatabase, querylist) except: errorstring = traceback.format_exc() pilib.log(pilib.iolog, 'Error executing query, message: ' + errorstring, 0, logconfig['iologlevel']) pilib.log(pilib.errorlog, 'Error executing updateio query, message: ' + errorstring) pilib.log(pilib.errorlog, 'Query: ' + str(querylist))
def setaction(controldatabase, channelname, action): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set action = \'' + str(action) + '\' where name = \'' + channelname + '\'')
def setcontrolinput(controldatabase, channelname, inputid): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set controlinput = \'' + inputid + '\' where name = \'' + channelname + '\'')
def setcontrolvalue(controldatabase, channelname, controlvalue): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set controlvalue = \'' + str(controlvalue) + '\' where name = \'' + channelname + '\'')
ROMsandtemps.append([onlineROMlist[i], tempfile.readline().strip()]) i += 1 #print("ROM tuples\n") #print(ROMsandtemps) # Write to database # At the moment all are enabled by default. # Eventually we'll read this before we delete all entries for tuple in ROMsandtemps: ROM = tuple[0] temp = tuple[1] queryresult = pilib.sqlitequery( database, 'select name from sensorinfo where sensorID = ' + "'" + ROM + "'") if not queryresult: name = '' else: name = queryresult[0][0] valuelist = [tuple[0], tuple[1], 'F', pilib.gettimestring(), 1, name] query = pilib.makesqliteinsert('sensordata', valuelist) # print(query) querylist.append(query) # execute combined query #print(querylist) ########################################
# Read from systemstatus to make sure we should be running updateioenabled = pilib.getsinglevalue(pilib.controldatabase, 'systemstatus', 'updateioenabled') while updateioenabled: #print("runtime") #print("reading input") # Read again, once inside each loop so we terminate if the # variable name is changed inputsreadenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select inputsreadenabled from systemstatus') # Set last run time pilib.sqlitequery( pilib.controldatabase, 'update systemstatus set lastinputspoll=\'' + pilib.gettimestring() + '\'') pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set updateiostatus=\'1\'') # Read and record everything as specified in controldatabase # Update database of inputs with read data reply = updateio.updateiodata(pilib.controldatabase) result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0) systemsdict = result[0] #print("here is the systems dict") #print(systemsdict) readtime = systemsdict['updateiofreq']
def getmode(controldatabase, channelname): from pilib import sqlitequery mode = sqlitequery(controldatabase, 'select mode from channels where name=\'' + channelname + '\'')[0][0] return mode
def setchanneloutputsenabled(controldatabase, channelname, newstatus): from pilib import sqlitequery sqlitequery( controldatabase, 'update channels set outputsenabled=\'' + newstatus + '\' where name=\'' + channelname + '\'')
def setalgorithm(controldatabase, channelname, algorithm): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set controlalgorithm=\'' + algorithm + '\' where name=\'' + channelname + '\'')
def updateowfsdevices(busdevices, myProxy=None): import pilib # get defaults defaults = pilib.readalldbrows(pilib.controldatabase, 'defaults')[0] # get current entries previnputs = pilib.readalldbrows(pilib.controldatabase, 'inputs') # Make list of IDs for easy indexing previnputids = [] for input in previnputs: previnputids.append(input['id']) # Iterate over devices. Determine if values exist for polltime, frequency. # If so, update the device. If not, use defaults. # Then determine whether we should update value or not (Read temperature) for index, device in enumerate(busdevices): if device.sensorid in previnputids: try: newpollfreq = int(previnputs[previnputids.index( device.sensorid)]['pollfreq']) except ValueError: device.pollfreq = defaults['inputpollfreq'] else: if newpollfreq >= 0: device.pollfreq = previnputs[previnputids.index( device.sensorid)]['pollfreq'] else: device.pollfreq = defaults['inputpollfreq'] device.ontime = previnputs[previnputids.index( device.sensorid)]['ontime'] device.offtime = previnputs[previnputids.index( device.sensorid)]['offtime'] device.polltime = previnputs[previnputids.index( device.sensorid)]['polltime'] device.value = previnputs[previnputids.index( device.sensorid)]['value'] else: device.pollfreq = defaults['inputpollfreq'] device.ontime = '' device.offtime = '' device.polltime = '' device.value = '' # We're going to set a name because calling things by their ids is getting # a bit ridiculous, but we can't have empty name fields if we rely on them # being there. They need to be unique, so we'll name them by type and increment them if device.type == 'DS18B20': # Get name if one exists name = pilib.sqlitedatumquery( pilib.controldatabase, 'select name from ioinfo where id=\'' + device.sensorid + '\'') # If doesn't exist, check to see if proposed name exists. If it doesn't, add it. # If it does, keep trying. if name == '': for rangeindex in range(100): # check to see if name exists name = device.type + '-' + str(int(index + 1)) # print(name) foundid = pilib.sqlitedatumquery( pilib.controldatabase, 'select id from ioinfo where name=\'' + name + '\'') # print('foundid' + foundid) if foundid: pass else: pilib.sqlitequery( pilib.controldatabase, pilib.makesqliteinsert( 'ioinfo', valuelist=[device.sensorid, name], valuenames=['id', 'name'])) break device.name = name # Is it time to read temperature? if pilib.timestringtoseconds( pilib.gettimestring()) - pilib.timestringtoseconds( device.polltime) > device.pollfreq: device.readprop('temperature', myProxy) device.polltime = pilib.gettimestring() device.value = device.temperature else: pass # print('not time to poll') device.unit = 'F' # We update the device and send them back for other purposes. busdevices[index] = device return busdevices
def setchanneloutputsenabled(controldatabase, channelname, newstatus): from pilib import sqlitequery sqlitequery(controldatabase, 'update channels set outputsenabled=\'' + newstatus + '\' where name=\'' + channelname + '\'')
def rundaemon(startall=False): from subprocess import Popen, PIPE from time import sleep from pilib import writedatedlogmsg, daemonlog, daemonloglevel # Set up list of enabled statuses (whether to restart if # we find that the process is not currently running picontrolenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select picontrolenabled from systemstatus') updateioenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select updateioenabled from systemstatus') systemstatusenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select systemstatusenabled from systemstatus') sessioncontrolenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select sessioncontrolenabled from systemstatus') serialhandlerenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select serialhandlerenabled from systemstatus') enableditemlist = [(int(updateioenabled)), (int(picontrolenabled)), int(systemstatusenabled), int(sessioncontrolenabled), int(serialhandlerenabled)] itemstatuses = findprocstatuses(pilib.daemonprocs) # Set system message systemstatusmsg = '' for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses): systemstatusmsg += name + ' - Enabled: ' + str( enabled) + ' Status: ' + str(status) + '. ' if pilib.daemonloglevel > 0: pilib.writedatedlogmsg( pilib.daemonlog, name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. ') pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'systemmessage', systemstatusmsg) # Set up list of itemnames in the systemstatus table that # we assign the values to when we detect if the process # is running or not statustableitemnames = [ 'updateiostatus', 'picontrolstatus', 'systemstatusstatus', 'sessioncontrolstatus', 'serialhandlerstatus' ] for index, item in enumerate(pilib.daemonprocs): # set status if itemstatuses[index]: pilib.sqlitequery( pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1') if pilib.daemonloglevel > 0: pilib.writedatedlogmsg( pilib.daemonlog, 'Process is running: ' + pilib.baselibdir + pilib.daemonprocs[index]) else: pilib.sqlitequery( pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0') if pilib.daemonloglevel > 0: pilib.writedatedlogmsg( pilib.daemonlog, 'Process is not running: ' + pilib.baselibdir + pilib.daemonprocs[index]) # run if set to enable if enableditemlist[index]: print(pilib.baselibdir + pilib.daemonprocs[index]) if pilib.daemonloglevel > 0: pilib.writedatedlogmsg( pilib.daemonlog, 'Starting ' + pilib.baselibdir + pilib.daemonprocs[index]) procresult = Popen( [pilib.baselibdir + pilib.daemonprocs[index]], stdout=PIPE) # if pilib.daemonloglevel > 0: # pilib.writedatedlogmsg(pilib.daemonproclog, procresult.stdout.read()) sleep(1) # Refresh after set itemstatuses = findprocstatuses(pilib.daemonprocs) for item in pilib.daemonprocs: index = pilib.daemonprocs.index(item) # set status if itemstatuses[index]: pilib.sqlitequery( pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1') else: pilib.sqlitequery( pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0') # Set system message systemstatusmsg = '' for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses): systemstatusmsg += name + ' - Enabled: ' + str( bool(enabled)) + ' Status: ' + str(status) + '. ' pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'systemmessage', systemstatusmsg) # Rotate all logs pilib.rotatelogs(pilib.networklog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.systemstatuslog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.iolog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.controllog, pilib.numlogs, pilib.maxlogsize) pilib.rotatelogs(pilib.daemonlog, pilib.numlogs, pilib.maxlogsize)