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 updateioinfo(database, table): from pilib import readalldbrows, sqlitedatumquery, sqlitemultquery tabledata = readalldbrows(database, table) querylist = [] for item in tabledata: itemid = item['id'] name = sqlitedatumquery(database, 'select name from ioinfo where id=\'' + itemid + '\'') querylist.append(database, 'update ' + table + ' set name=\'' + name + '\' where id = \'' + itemid + '\'') if querylist: sqlitemultquery(querylist)
import updateio from time import sleep readtime = 10 # default, seconds # 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]
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)
else: foundstatuses.append(False) return foundstatuses if __name__ == "__main__": import pilib from subprocess import Popen procstofind = ['periodicreadio.py', 'picontrol.py', 'sessioncontrol.py', 'systemstatus.py'] # Set up list of enabled statuses (whether to restart if # we find that the process is not currently running picontrolenabled = pilib.sqlitedatumquery(pilib.controldb, 'select picontrolenabled from systemstatus') inputsreadenabled = pilib.sqlitedatumquery(pilib.controldb, 'select inputsreadenabled from systemstatus') sessioncontrolenabled = pilib.sqlitedatumquery(pilib.controldb, 'select sessioncontrolenabled from systemstatus') systemstatusenabled = pilib.sqlitedatumquery(pilib.controldb, 'select systemstatusenabled from systemstatus') enableditemlist = [(int(inputsreadenabled)), (int(picontrolenabled)), int(sessioncontrolenabled), int(systemstatusenabled)] itemstatuses = findprocstatuses(procstofind) # 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 = ['inputsreadstatus', 'picontrolstatus', 'sessioncontrolstatus', 'systemstatusstatus'] for item in procstofind:
def getsetpointvalue(self): from pilib import controldatabase, sqlitedatumquery self.setpointvalue = sqlitedatumquery(controldatabase, 'select setpointvalue from channels where name=\'' + channel.name + '\'')
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 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 processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids, previnputs, previnputids, defaults, logconfig, **kwargs): import pilib if 'method' in kwargs: method = kwargs['method'] else: method = 'pigpio' if method == 'rpigpio': import RPi.GPIO as GPIO elif method == 'pigpio': import pigpio try: if method == 'rpigpio': GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) elif method == 'pigpio': if 'piobject' in kwargs: pilib.log(pilib.iolog, 'Pigpio object already exists. ', 4, logconfig['iologlevel']) pi = kwargs['piobject'] else: pilib.log(pilib.iolog, 'Instantiating pigpio. ', 4, logconfig['iologlevel']) pi = pigpio.pi() except: pilib.log(pilib.iolog, 'Error setting up GPIO. ', 1, logconfig['iologlevel']) else: pilib.log(pilib.iolog, 'Done setting up GPIO. ', 4, logconfig['iologlevel']) options = pilib.parseoptions(interface['options']) address = int(interface['address']) pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' enabled', 4, logconfig['iologlevel']) # Get name from ioinfo table to give it a colloquial name gpioname = pilib.sqlitedatumquery(pilib.controldatabase, 'select name from ioinfo where id=\'' + interface['id'] + '\'') polltime = pilib.gettimestring() querylist = [] # Append to inputs and update name, even if it's an output (can read status as input) if options['mode'] == 'output': pilib.log(pilib.iolog, 'Setting output mode for GPIO address' + str(address), 3, logconfig['iologlevel']) try: if method == 'rpigpio': GPIO.setup(address, GPIO.OUT) elif method == 'pigpio': pi.set_mode(address, pigpio.OUTPUT) except TypeError: pilib.log(pilib.iolog, 'You are trying to set a GPIO with the wrong variable type : ' + str(type(address)), 0, logconfig['iologlevel']) pilib.log(pilib.iolog, 'Exiting interface routine for ' + interface['id'], 0, logconfig['iologlevel']) return except: pilib.log(pilib.iolog, 'Error setting GPIO : ' + str(address), 1, logconfig['iologlevel']) pilib.log(pilib.iolog, 'Exiting interface routine for ' + interface['id'], 0, logconfig['iologlevel']) return # Set the value of the gpio. # Get previous value if exists if interface['id'] in prevoutputids: value = prevoutputvalues[prevoutputids.index(interface['id'])] else: value = 0 if value == 1: if method == 'rpigpio': GPIO.output(address, True) elif method == 'pigpio': pi.write(address, 1) pilib.log(pilib.iolog, 'Setting output ON for GPIO address' + str(address), 3, logconfig['iologlevel']) else: if method == 'rpigpio': GPIO.output(address, False) elif method == 'pigpio': pi.write(address,0) pilib.log(pilib.iolog, 'Setting output OFF for GPIO address' + str(address), 3, logconfig['iologlevel']) # Get output settings and keep them if the GPIO previously existed if interface['id'] in prevoutputids: pollfreq = prevoutputs[prevoutputids.index(interface['id'])]['pollfreq'] ontime = prevoutputs[prevoutputids.index(interface['id'])]['ontime'] offtime = prevoutputs[prevoutputids.index(interface['id'])]['offtime'] else: try: pollfreq = defaults['defaultoutputpollfreq'] except: pollfreq = 60 ontime = '' offtime = '' # Add entry to outputs tables querylist.append('insert into outputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str( address) + '\',\'' + gpioname + '\',\'' + str(value) + "','','" + str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") elif options['mode'] == 'input': if method == 'rpigpio': GPIO.setup(address, GPIO.IN) elif method == 'pigpio': if 'pullupdown' in options: if options['pullupdown'] == 'pullup': pi.set_pull_up_down(address, pigpio.PUD_UP) elif options['pullupdown'] == 'pulldown': pi.set_pull_up_down(address, pigpio.PUD_DOWN) else: pi.set_pull_up_down(address, pigpio.PUD_OFF) else: pi.set_pull_up_down(17, pigpio.PUD_OFF) pi.set_mode(address, pigpio.INPUT) if method == 'rpigpio': value = GPIO.input(address) elif method == 'pigpio': value = pi.read(address) if 'function' in options: if options['function'] == 'shutdown': # TODO : The reboot function is still held in a shell script, because it works. if 'functionstate' in options: if value == 1 and options['functionstate'] in ['true', 'On', 'True', '1']: from systemstatus import processsystemflags processsystemflags() pilib.log(pilib.iolog, 'Setting input mode for GPIO address' + str(address), 3, logconfig['iologlevel']) # Get input settings and keep them if the GPIO previously existed if interface['id'] in previnputids: pollfreq = previnputs[previnputids.index(interface['id'])]['pollfreq'] ontime = previnputs[previnputids.index(interface['id'])]['ontime'] offtime = previnputs[previnputids.index(interface['id'])]['offtime'] pilib.log(pilib.iolog, 'Restoring values from previous inputids: pollfreq = ' + str( pollfreq) + ' ontime = ' + str(ontime) + ' offtime = ' + str( offtime), 3, logconfig['iologlevel']) else: try: pollfreq = defaults['defaultinputpollfreq'] except: pollfreq = 60 ontime = '' offtime = '' pilib.log(pilib.iolog, 'Setting values to defaults, defaultinputpollfreq = ' + str( pollfreq), 3, logconfig['iologlevel']) querylist.append( 'insert into inputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(address) + '\',\'' + gpioname + '\',\'' + str( value) + "','','" + str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") if method == 'pigpio' and 'piobject' not in kwargs: pi.stop() return querylist
def processMBinterface(interface, prevoutputs, prevoutputids, previnputs, previnputids, defaults, logconfig): from netfun import readMBcodedaddresses, MBFCfromaddress import pilib # get all modbus reads that have the same address from the modbus table try: modbustable = pilib.readalldbrows(pilib.controldatabase, 'modbustcp') except: pilib.writedatedlogmsg(pilib.iolog, 'Error reading modbus table', 0, logconfig['iologlevel']) else: pilib.writedatedlogmsg(pilib.iolog, 'Read modbus table', 4, logconfig['iologlevel']) querylist = [] for entry in modbustable: # Get name from ioinfo table to give it a colloquial name # First we have to give it a unique ID. This is a bit difficult with modbus if entry['mode'] == 'read': shortmode = 'R' elif entry['mode'] == 'write': shortmode = 'W' elif entry['mode'] == 'readwrite': shortmode = 'RW' else: pilib.writedatedlogmsg(pilib.iolog, 'modbus mode error', 1, logconfig['iologlevel']) try: mbid = entry['interfaceid'] + '_' + str(entry['register']) + '_' + str(entry['length']) + '_' + shortmode except KeyError: pilib.writedatedlogmsg(pilib.iolog, 'Cannot form mbid due to key error', 0, logconfig['iologlevel']) return pilib.writedatedlogmsg(pilib.iolog, 'Modbus ID: ' + mbid, 4, logconfig['iologlevel']) mbname = pilib.sqlitedatumquery(pilib.controldatabase, "select name from ioinfo where id='" + mbid + "'") polltime = pilib.gettimestring() if entry['interfaceid'] == interface['id']: # For now, we're going to read them one by one. We'll assemble these into block reads # in the next iteration if entry['mode'] == 'read': # Get previous metadata and data # Get input settings and keep them if the input previously existed if mbid in previnputids: pollfreq = previnputs[previnputids.index(mbid)]['pollfreq'] ontime = previnputs[previnputids.index(mbid)]['ontime'] offtime = previnputs[previnputids.index(mbid)]['offtime'] prevvalue = previnputs[previnputids.index(mbid)]['offtime'] prevpolltime = previnputs[previnputids.index(mbid)]['offtime'] pilib.writedatedlogmsg(pilib.iolog, 'Restoring values from previous inputids: pollfreq = ' + str( pollfreq) + ' ontime = ' + str(ontime) + ' offtime = ' + str( offtime), 3, logconfig['iologlevel']) else: # set values to defaults if it did not previously exist try: pollfreq = defaults['defaultinputpollfreq'] except: pollfreq = 60 ontime = '' offtime = '' prevvalue = '' prevpolltime = '' pilib.writedatedlogmsg(pilib.iolog, 'Setting values to defaults, defaultinputpollfreq = ' + str(pollfreq), 3, logconfig['iologlevel']) # Read data try: readresult = readMBcodedaddresses(interface['address'], entry['register'], entry['length']) except: pilib.writedatedlogmsg(pilib.iolog, 'Uncaught reror reading modbus value', 0, logconfig['iologlevel']) else: if readresult['statuscode'] == 0: values = readresult['values'] try: FC = MBFCfromaddress(int(entry['register'])) except ValueError: pilib.writedatedlogmsg(pilib.iolog, 'Malformed address for FC determination : ' + str(entry['address']), 0, logconfig['iologlevel']) else: pilib.writedatedlogmsg(pilib.iolog, 'Function code : ' + str(FC), 4, logconfig['iologlevel']) returnvalue = 0 if len(values) > 0: pilib.writedatedlogmsg(pilib.iolog, 'Multiple values returned', 4, logconfig['iologlevel']) if not entry['bigendian']: try: values.reverse() except AttributeError: pilib.writedatedlogmsg(pilib.iolog, 'Error on reverse of MB values: ' + str(values), 0, logconfig['iologlevel']) if entry['format'] == 'float32': import struct byte2 = values[0] % 256 byte1 = (values[0] - byte2)/256 byte4 = values[1] % 256 byte3 = (values[1] - byte4)/256 byte1hex = chr(byte1) byte2hex = chr(byte2) byte3hex = chr(byte3) byte4hex = chr(byte4) hexstring = byte1hex + byte2hex + byte3hex + byte4hex returnvalue = struct.unpack('>f',hexstring)[0] else: for index, val in enumerate(values): if FC in [0, 1]: returnvalue += val * 2 ** index elif FC in [3, 4]: returnvalue += val * 256 ** index else: pilib.writedatedlogmsg(pilib.iolog, 'Invalid function code', 0, logconfig['iologlevel']) else: returnvalue = values[0] if entry['options'] != '': options = pilib.parseoptions(entry['options']) if 'scale' in options: # try: returnvalue = returnvalue * float(options['scale']) # except: # pilib.writedatedlogmsg(pilib.iolog, 'Error on scale operation', 0, logconfig['iologlevel']) if 'precision' in options: # try: returnvalue = round(returnvalue, int(options['precision'])) # except: # pilib.writedatedlogmsg(pilib.iolog, 'Error on precision operation', 0, logconfig['iologlevel']) pilib.writedatedlogmsg(pilib.iolog, 'Values read: ' + str(values), 4, logconfig['iologlevel']) pilib.writedatedlogmsg(pilib.iolog, 'Value returned: ' + str(returnvalue), 4, logconfig['iologlevel']) # Contruct entry for newly acquired data querylist.append('insert into inputs values (\'' + mbid + '\',\'' + interface['id'] + '\',\'' + interface['type'] + '\',\'' + str(entry['register']) + '\',\'' + mbname + '\',\'' + str( returnvalue) + "','','" + str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") else: pilib.writedatedlogmsg(pilib.iolog, 'Statuscode ' + str(readresult['statuscode']) + ' on MB read : ' + readresult['message'] , 0, logconfig['iologlevel']) # restore previous value and construct entry if it existed (or not) querylist.append('insert into inputs values (\'' + mbid + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(entry['register']) + '\',\'' + mbname + '\',\'' + str(prevvalue) + "','','" + str(prevpolltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") pilib.writedatedlogmsg(pilib.iolog, 'Querylist: ' + str(querylist) , 4, logconfig['iologlevel']) return querylist
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
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. '
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 RPi.GPIO as GPIO allowedGPIOaddresses = [18, 23, 24, 25, 4, 17, 21, 22] dontrun = False GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) tables = pilib.gettablenames(pilib.controldatabase) if 'interfaces' in tables: interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces') else: print('interfaces table not found. Exiting') 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 # 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') pilib.sqlitemultquery(pilib.controldatabase, querylist) querylist = [] for interface in interfaces: if interface['interface'] == 'I2C': if interface['enabled']: # print('processing enabled I2C') if interface['type'] == 'DS2483': from owfslib import runowfsupdate runowfsupdate() elif interface['interface'] == 'GPIO': options = pilib.parseoptions(interface['options']) # TODO : respond to more option, like pullup and pulldown address = int(interface['address']) if address in allowedGPIOaddresses: # Check if interface is enabled if interface['enabled']: # Get name from ioinfo table to give it a colloquial name gpioname = pilib.sqlitedatumquery(database, 'select name from ioinfo where id=\'' + interface['id'] + '\'') polltime = pilib.gettimestring() # Append to inputs and update name, even if it's an output (can read status as input) if options['mode'] == 'output': GPIO.setup(address, GPIO.OUT) # Set the value of the gpio. # Get previous value if exists if interface['id'] in prevoutputids: value = prevoutputvalues[prevoutputids.index(interface['id'])] else: value = 0 if value == 1: GPIO.output(address, True) else: GPIO.output(address, False) # Get output settings and keep them if the GPIO previously existed if interface['id'] in prevoutputids: pollfreq = prevoutputs[prevoutputids.index(interface['id'])]['pollfreq'] else: pollfreq = defaultoutputpollfreq # Add entry to outputs tables querylist.append('insert into outputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(address) + '\',\'' + gpioname + '\',\'' + str(value) + '\',\'\',\'' + str(polltime) + '\',\'' + str(pollfreq) + '\')') else: GPIO.setup(address, GPIO.IN) value = GPIO.input(address) polltime = pilib.gettimestring() # Get input settings and keep them if the GPIO previously existed if interface['id'] in prevoutputids: pollfreq = previnputs[prevoutputids.index(interface['id'])]['pollfreq'] polltime = previnputs[prevoutputids.index(interface['id'])]['polltime'] else: pollfreq = defaultinputpollfreq # Add entry to inputs tables # Get output settings and keep them if the GPIO previously existed if interface['id'] in prevoutputids: pollfreq = prevoutputs[prevoutputids.index(interface['id'])]['pollfreq'] else: pollfreq = defaultoutputpollfreq querylist.append( 'insert into inputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(address) + '\',\'' + gpioname + '\',\'' + str(value) + '\',\'\',\'' + str(polltime) + '\',\'' + str(pollfreq) + '\')') else: GPIO.setup(address, GPIO.IN) else: print('GPIO address ' + address + 'not allowed. BAD THINGS CAN HAPPEN.') elif interface['interface'] == 'SPI': # print('processing SPI') if interface['type'] == 'SPITC': import readspi spidata = readspi.readspitc() readspi.recordspidata(database, spidata) elif interface['type'] == 'CuPIDLights': import spilights spilights.updatelightsfromdb(pilib.controldatabase, 'indicators') # Set tables # print(querylist) pilib.sqlitemultquery(pilib.controldatabase, querylist)
# Colin Reese # 9/9/2013 # This script updates the number of sessions currently # active by deleting expired sessions (those that did # not include a log out) and counting those that are # active. Besides being able to tell who is online at # any given time and from where, this will allow us to # limit the number of sessions per user import pilib import time # Determine whether this process is enabled: enabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select sessioncontrolenabled from \'systemstatus\'') while enabled: #print('enabled') polltime = pilib.sqlitedatumquery(pilib.sessiondatabase, 'select updatefrequency from \'settings\'') # Go through sessions and delete expired ones sessions = pilib.readalldbrows(pilib.sessiondatabase, 'sessions') sessions = pilib.readalldbrows(pilib.sessiondatabase, 'sessions') arrayquery = [] for session in sessions: sessionstart = pilib.timestringtoseconds(session['timecreated']) sessionlength = session['sessionlength'] if time.time() - sessionstart > sessionlength: arrayquery.append('delete from sessions where sessionid=\'' + session['sessionid'] + '\'')
def processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids, previnputs, previnputids, defaults, logconfig): import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) import pilib options = pilib.parseoptions(interface['options']) address = int(interface['address']) # TODO : respond to more options, like pullup and pulldown pilib.writedatedlogmsg(pilib.iolog, 'GPIO address' + str(address) + ' enabled', 4, logconfig['iologlevel']) # Get name from ioinfo table to give it a colloquial name gpioname = pilib.sqlitedatumquery(pilib.controldatabase, 'select name from ioinfo where id=\'' + interface['id'] + '\'') polltime = pilib.gettimestring() querylist = [] # Append to inputs and update name, even if it's an output (can read status as input) if options['mode'] == 'output': pilib.writedatedlogmsg(pilib.iolog, 'Setting output mode for GPIO address' + str(address), 3, logconfig['iologlevel']) try: GPIO.setup(address, GPIO.OUT) except TypeError: pilib.writedatedlogmsg(pilib.iolog, 'You are trying to set a GPIO with the wrong variable type : ' + str(type(address)), 0, logconfig['iologlevel']) pilib.writedatedlogmsg(pilib.iolog, 'Exiting interface routine for ' + interface['id'], 0, logconfig['iologlevel']) return # Set the value of the gpio. # Get previous value if exists if interface['id'] in prevoutputids: value = prevoutputvalues[prevoutputids.index(interface['id'])] else: value = 0 if value == 1: GPIO.output(address, True) pilib.writedatedlogmsg(pilib.iolog, 'Setting output ON for GPIO address' + str(address), 3, logconfig['iologlevel']) else: GPIO.output(address, False) pilib.writedatedlogmsg(pilib.iolog, 'Setting output OFF for GPIO address' + str(address), 3, logconfig['iologlevel']) # Get output settings and keep them if the GPIO previously existed if interface['id'] in prevoutputids: pollfreq = prevoutputs[prevoutputids.index(interface['id'])]['pollfreq'] ontime = prevoutputs[prevoutputids.index(interface['id'])]['ontime'] offtime = prevoutputs[prevoutputids.index(interface['id'])]['offtime'] else: try: pollfreq = defaults['defaultoutputpollfreq'] except: pollfreq = 60 ontime = '' offtime = '' # Add entry to outputs tables querylist.append('insert into outputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str( address) + '\',\'' + gpioname + '\',\'' + str(value) + "','','" + str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") else: GPIO.setup(address, GPIO.IN) value = GPIO.input(address) pilib.writedatedlogmsg(pilib.iolog, 'Setting input mode for GPIO address' + str(address), 3, logconfig['iologlevel']) # Get input settings and keep them if the GPIO previously existed if interface['id'] in previnputids: pollfreq = previnputs[previnputids.index(interface['id'])]['pollfreq'] ontime = previnputs[previnputids.index(interface['id'])]['ontime'] offtime = previnputs[previnputids.index(interface['id'])]['offtime'] pilib.writedatedlogmsg(pilib.iolog, 'Restoring values from previous inputids: pollfreq = ' + str( pollfreq) + ' ontime = ' + str(ontime) + ' offtime = ' + str( offtime), 3, logconfig['iologlevel']) else: try: pollfreq = defaults['defaultinputpollfreq'] except: pollfreq = 60 ontime = '' offtime = '' pilib.writedatedlogmsg(pilib.iolog, 'Setting values to defaults, defaultinputpollfreq = ' + str( pollfreq), 3, logconfig['iologlevel']) querylist.append( 'insert into inputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(address) + '\',\'' + gpioname + '\',\'' + str( value) + "','','" + str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") return querylist
def processMBinterface(interface, prevoutputs, prevoutputids, previnputs, previnputids, defaults, logconfig): from netfun import readMBcodedaddresses, MBFCfromaddress import pilib # get all modbus reads that have the same address from the modbus table try: modbustable = pilib.readalldbrows(pilib.controldatabase, 'modbustcp') except: pilib.log(pilib.iolog, 'Error reading modbus table', 0, logconfig['iologlevel']) else: pilib.log(pilib.iolog, 'Read modbus table', 4, logconfig['iologlevel']) querylist = [] for entry in modbustable: # Get name from ioinfo table to give it a colloquial name # First we have to give it a unique ID. This is a bit difficult with modbus if entry['mode'] == 'read': shortmode = 'R' elif entry['mode'] == 'write': shortmode = 'W' elif entry['mode'] == 'readwrite': shortmode = 'RW' else: pilib.log(pilib.iolog, 'modbus mode error', 1, logconfig['iologlevel']) try: mbid = entry['interfaceid'] + '_' + str(entry['register']) + '_' + str(entry['length']) + '_' + shortmode except KeyError: pilib.log(pilib.iolog, 'Cannot form mbid due to key error', 0, logconfig['iologlevel']) return pilib.log(pilib.iolog, 'Modbus ID: ' + mbid, 4, logconfig['iologlevel']) mbname = pilib.sqlitedatumquery(pilib.controldatabase, "select name from ioinfo where id='" + mbid + "'") polltime = pilib.gettimestring() if entry['interfaceid'] == interface['id']: # For now, we're going to read them one by one. We'll assemble these into block reads # in the next iteration if entry['mode'] == 'read': # Get previous metadata and data # Get input settings and keep them if the input previously existed if mbid in previnputids: pollfreq = previnputs[previnputids.index(mbid)]['pollfreq'] ontime = previnputs[previnputids.index(mbid)]['ontime'] offtime = previnputs[previnputids.index(mbid)]['offtime'] prevvalue = previnputs[previnputids.index(mbid)]['offtime'] prevpolltime = previnputs[previnputids.index(mbid)]['offtime'] pilib.log(pilib.iolog, 'Restoring values from previous inputids: pollfreq = ' + str( pollfreq) + ' ontime = ' + str(ontime) + ' offtime = ' + str( offtime), 3, logconfig['iologlevel']) else: # set values to defaults if it did not previously exist try: pollfreq = defaults['defaultinputpollfreq'] except: pollfreq = 60 ontime = '' offtime = '' prevvalue = '' prevpolltime = '' pilib.log(pilib.iolog, 'Setting values to defaults, defaultinputpollfreq = ' + str(pollfreq), 3, logconfig['iologlevel']) # Read data try: readresult = readMBcodedaddresses(interface['address'], entry['register'], entry['length']) except: pilib.log(pilib.iolog, 'Uncaught reror reading modbus value', 0, logconfig['iologlevel']) else: if readresult['statuscode'] == 0: values = readresult['values'] try: FC = MBFCfromaddress(int(entry['register'])) except ValueError: pilib.log(pilib.iolog, 'Malformed address for FC determination : ' + str(entry['address']), 0, logconfig['iologlevel']) else: pilib.log(pilib.iolog, 'Function code : ' + str(FC), 4, logconfig['iologlevel']) returnvalue = 0 if len(values) > 0: pilib.log(pilib.iolog, 'Multiple values returned', 4, logconfig['iologlevel']) if not entry['bigendian']: try: values.reverse() except AttributeError: pilib.log(pilib.iolog, 'Error on reverse of MB values: ' + str(values), 0, logconfig['iologlevel']) if entry['format'] == 'float32': import struct byte2 = values[0] % 256 byte1 = (values[0] - byte2)/256 byte4 = values[1] % 256 byte3 = (values[1] - byte4)/256 byte1hex = chr(byte1) byte2hex = chr(byte2) byte3hex = chr(byte3) byte4hex = chr(byte4) hexstring = byte1hex + byte2hex + byte3hex + byte4hex returnvalue = struct.unpack('>f',hexstring)[0] else: for index, val in enumerate(values): if FC in [0, 1]: returnvalue += val * 2 ** index elif FC in [3, 4]: returnvalue += val * 256 ** index else: pilib.log(pilib.iolog, 'Invalid function code', 0, logconfig['iologlevel']) else: returnvalue = values[0] if entry['options'] != '': options = pilib.parseoptions(entry['options']) if 'scale' in options: # try: returnvalue = returnvalue * float(options['scale']) # except: # pilib.writedatedlogmsg(pilib.iolog, 'Error on scale operation', 0, logconfig['iologlevel']) if 'precision' in options: # try: returnvalue = round(returnvalue, int(options['precision'])) # except: # pilib.writedatedlogmsg(pilib.iolog, 'Error on precision operation', 0, logconfig['iologlevel']) pilib.log(pilib.iolog, 'Values read: ' + str(values), 4, logconfig['iologlevel']) pilib.log(pilib.iolog, 'Value returned: ' + str(returnvalue), 4, logconfig['iologlevel']) # Contruct entry for newly acquired data querylist.append('insert into inputs values (\'' + mbid + '\',\'' + interface['id'] + '\',\'' + interface['type'] + '\',\'' + str(entry['register']) + '\',\'' + mbname + '\',\'' + str( returnvalue) + "','','" + str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") else: pilib.log(pilib.iolog, 'Statuscode ' + str(readresult['statuscode']) + ' on MB read : ' + readresult['message'] , 0, logconfig['iologlevel']) # restore previous value and construct entry if it existed (or not) querylist.append('insert into inputs values (\'' + mbid + '\',\'' + interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(entry['register']) + '\',\'' + mbname + '\',\'' + str(prevvalue) + "','','" + str(prevpolltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')") pilib.log(pilib.iolog, 'Querylist: ' + str(querylist) , 4, logconfig['iologlevel']) return querylist
def getaction(self): from pilib import controldatabase, sqlitedatumquery self.action = sqlitedatumquery( controldatabase, 'select action from channels where name=\'' + channel.name + '\'')
__version__ = "1.0" __maintainer__ = "Colin Reese" __email__ = "*****@*****.**" __status__ = "Development" # This script runs the input reading scripts # specified interval, sends to log, channels and plot dbs import pilib import updateio from time import sleep 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
def getsetpointvalue(self): from pilib import controldatabase, sqlitedatumquery self.setpointvalue = sqlitedatumquery( controldatabase, 'select setpointvalue from channels where name=\'' + channel.name + '\'')
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:
def getmode(self): from pilib import controldatabase, sqlitedatumquery self.mode = sqlitedatumquery( controldatabase, 'select mode from channels where name=\'' + channel.name + '\'')
def getaction(self): from pilib import controldatabase, sqlitedatumquery self.action = sqlitedatumquery(controldatabase,'select action from channels where name=\'' + channel.name + '\'')
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 getmode(self): from pilib import controldatabase, sqlitedatumquery self.mode = sqlitedatumquery(controldatabase, 'select mode from channels where name=\'' + channel.name + '\'')
# 9/9/2013 # This script updates the number of sessions currently # active by deleting expired sessions (those that did # not include a log out) and counting those that are # active. Besides being able to tell who is online at # any given time and from where, this will allow us to # limit the number of sessions per user import pilib import time # Determine whether this process is enabled: enabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select sessioncontrolenabled from \'systemstatus\'') while enabled: #print('enabled') polltime = pilib.sqlitedatumquery( pilib.sessiondatabase, 'select updatefrequency from \'settings\'') # Go through sessions and delete expired ones sessions = pilib.readalldbrows(pilib.sessiondatabase, 'sessions') sessions = pilib.readalldbrows(pilib.sessiondatabase, 'sessions') arrayquery = [] for session in sessions: sessionstart = pilib.timestringtoseconds(session['timecreated']) sessionlength = session['sessionlength'] if time.time() - sessionstart > sessionlength: