def recordspidata(database, valuedict): # This is incomplete and hardcoded partially querylist = [] for key, value in valuedict.iteritems(): querylist.append(pilib.makesqliteinsert('inputsdata', valuelist=[key, 'SPI1', 'TC', '1', value, 'F', pilib.gettimestring(), 1, key])) querylist.append(pilib.makesqliteinsert('ioinfo', valuelist=[key, key])) pilib.sqlitemultquery(database, querylist)
def recordspidata(database, valuedict, execute=False): # This is incomplete and hardcoded partially querylist = [] for key, value in valuedict.iteritems(): querylist.append(pilib.makesqliteinsert('inputs', valuelist=[key, 'SPI1', 'TC', '1', 'SPITC1', value, 'F', pilib.gettimestring(), 1, '',''])) querylist.append(pilib.makesqliteinsert('ioinfo', valuelist=[key, key, ''])) if execute: pilib.sqlitemultquery(database, querylist) return querylist
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 recordspidata(database, valuedict, execute=False): # This is incomplete and hardcoded partially querylist = [] for key, value in valuedict.iteritems(): querylist.append( pilib.makesqliteinsert('inputs', valuelist=[ key, 'SPI1', 'TC', '1', 'SPITC1', value, 'F', pilib.gettimestring(), 1, '', '' ])) querylist.append(pilib.makesqliteinsert('ioinfo', valuelist=[key, key])) if execute: pilib.sqlitemultquery(database, querylist) return querylist
def updateowfstable(database, tablename, busdevices): from pilib import makesqliteinsert, sqlitemultquery querylist = [] for device in busdevices: # print(device.id) # print([device.address, device.family, device.id, device.type, device.crc8]) querylist.append( makesqliteinsert(tablename, [device.address, device.family, device.id, device.type, device.crc8])) # print(querylist) sqlitemultquery(database, querylist)
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 updateowfstable(database, tablename, busdevices, execute=True): from pilib import makesqliteinsert, sqlitemultquery querylist = [] for device in busdevices: # print(device.id) # print([device.address, device.family, device.id, device.type, device.crc8]) querylist.append( makesqliteinsert(tablename, [ device.address, device.family, device.id, device.type, device.crc8 ])) # print(querylist) if execute: sqlitemultquery(database, querylist) return 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)
+ output['id'] + '\'') statusmsg += 'Output ' + output[ 'name'] + ' disabled. ' else: statusmsg += 'Output ' + output[ 'name'] + ' already disabled. ' else: statusmsg += 'Channel outputs disabled. ' else: statusmsg += 'System outputs disabled. ' # 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: statusmsg += 'Channel not enabled. ' # If active reset and we didn't set channel modes, disable outputs
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 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 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
# 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 import subprocess tctemp = subprocess.check_output( ['python3', '/usr/lib/modwsgi/max31855-1.0/getmaxtemp.py']) print('temperature is ') print(tctemp)
# 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. ' else: statusmsg += 'System outputs disabled. ' # 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: 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:
# 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 import subprocess tctemp=subprocess.check_output(['python3','/usr/lib/modwsgi/max31855-1.0/getmaxtemp.py']) print('temperature is ') print(tctemp) print(tctemp)
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