def processserialdata(data): from cupid.pilib import parseoptions datadicts = [] messages = [] # try: # Break into chunks # RF Message if data.strip().find('BEGIN RECEIVED') > 0: split1 = data.strip().split('BEGIN RECEIVED') for split in split1: if split.find('END RECEIVED') >= 0: message = split.split('END RECEIVED')[0].replace('\x00', '') # print(message) messages.append(message.strip()) try: datadict = parseoptions(message) except: print('error parsing message: ' + message) else: # print(datadict) datadicts.append(datadict) messages.append(message) # Serial message else: messagesplit = data.strip().split('\n') # print(messagesplit) datadicts=[] for entry in messagesplit: # print(entry) dict = parseoptions(entry) # print('dict') # print(dict) if 'node' or 'cmd' in dict: datadicts.append(dict) messages.append(entry) # except: # print('there was an error processing the message') # return # else: return datadicts, messages
def processserialdata(data): from cupid.pilib import parseoptions datadicts = [] messages = [] # try: # Break into chunks split1 = data.strip().split('BEGIN RECEIVED') for split in split1: if split.find('END RECEIVED') >= 0: message = split.split('END RECEIVED')[0] messages.append(message) try: datadict = parseoptions(message) except: print('error parsing message') else: datadicts.append(datadict) # except: # print('there was an error processing the message') # return # else: return datadicts, messages
def application(environ, start_response): import cgi import json import os, sys, inspect # Set top folder to allow import of modules top_folder = os.path.split(os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])))[0] if top_folder not in sys.path: sys.path.insert(0, top_folder) post_env = environ.copy() post_env['QUERY_STRING'] = '' post = cgi.FieldStorage( fp=environ['wsgi.input'], environ=post_env, keep_blank_values=True ) formname=post.getvalue('name') data={} d = {} for k in post.keys(): d[k] = post.getvalue(k) status = '200 OK' # Get GPIO status # We return this status no matter what gpiolist = [18,23,24,25,4,17,21,22] import cupid.pilib as pilib inputs = pilib.readalldbrows(pilib.controldatabase, 'inputs') interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces') statusdict={} for input in inputs: statusdict[input['id'] + 'value'] = input['value'] for interface in interfaces: if interface['type'] == 'GPIO': options = pilib.parseoptions(interface['options']) statusdict[interface['id'] + 'mode'] = options['mode'] # Execute commands if 'action' in d: querylist = [] if d['action'] == 'toggleGPIOmode': print('stuff') elif d['action'] == 'toggleGPIOvalue': outputs = pilib.readalldbrows(pilib.controldatabase,'outputs') for output in outputs: if output['id'] == d['GPIOid']: curval = output['value'] if curval == 0: setval = 1 else: setval = 0 querylist.append('update outputs set value= ' + str(setval) + ' where id=\'' + d['GPIOid'] + '\'') elif d['action'] == 'wptoggleGPIOvalue': try: BCMpin = int(d['BCMpin']) except KeyError: data['message'] = 'No pin sent with command' else: from subprocess import check_output, call output = int(check_output(['gpio','-g','read',str(BCMpin)])) # call(['gpio','export','18','output']) if output == 0: call(['gpio','-g','write',str(BCMpin),'1']) else: call(['gpio','-g','write',str(BCMpin),'0']) elif d['action'] == 'wptoggleGPIOmode': try: BCMpin = int(d['BCMpin']) except KeyError: data['message'] = 'No pin sent with command' else: from subprocess import check_output, call from cupid.pilib import getgpiostatus pinmode = '' allstatus = getgpiostatus() for status in allstatus: if status['BCM'] == BCMpin: pinmode = status['mode'] if pinmode == 'OUT': call(['gpio','-g','mode',BCMpin,'in']) else: call(['gpio','-g','mode',BCMpin,'out']) elif d['action'] == 'wpgetgpiostatus': from cupid.pilib import getgpiostatus data = getgpiostatus() output = json.dumps(data, indent=1) response_headers = [('Content-type', 'application/json')] start_response(status, response_headers) return [output]
def processremotedata(datadict, stringmessage): import cupid.pilib as pilib if 'nodeid' in datadict: # We are going to search for keywords. Message type will not be explicitly declared so # as not to waste precious message space in transmission. Or we could tack these on in # the gateway, but we won't yet. # Then we have to construct a query where we will replace a unique item # This will take the form : # update or replace in remotes where nodeid=3 and msgtype='iovalue' and iopin=3 # update or repalce in remotes where nodeid=2 and msgtype='owdev' and owrom='28XXXXXXXXXXXXXX' # (and later which IO on this device) # update or replace in remotes where nodeid=2 and msgtype='chanstat' channum=1 # (need to see if all channel variables can be fit into one message: # channum, sv,pv,mode,state runquery = False nodeid = datadict['nodeid'] querylist = [] # Command responses, including value requests if 'cmd' in datadict: if datadict['cmd'] == 'lp': # Remove command key and process remaining data del datadict['cmd'] motetablename = 'node_' + nodeid + '_status' # Create table if it doesn't exist query = 'create table if not exists \'' + motetablename + '\' ( time text, message text primary key, value text)' pilib.sqlitequery(pilib.motesdatabase, query) for key in datadict: thetime = pilib.gettimestring() if key in ['iov', 'iov2', 'iov3', 'pv', 'pv2', 'sv', 'sv2', 'iomd', 'ioen', 'iordf', 'iorpf', 'chen', 'chmd', 'chnf', 'chpf', 'chdb', 'chsv', 'chsv2', 'chpv', 'chpv2']: # We need to process these specially, going back to the original message values = datadict[key] valuelist = values.split('|') print(valuelist) index = 0 if key in ['iov', 'iov2', 'iov3']: base = 'iov_' if key == 'iov2': index = 5 elif key == 'iov3': index = 9 elif key in ['pv', 'pv2']: base = 'pv_' if key == 'pv2': index = 5 elif key in ['sv', 'sv2']: base = 'sv_' if key == 'sv2': index = 5 else: base = key + '_' querylist = [] for value in valuelist: querylist.append(pilib.makesqliteinsert(motetablename, [thetime, base + str(index), value])) index += 1 pilib.sqlitemultquery(pilib.motesdatabase, querylist) # Update table entry. Each entry has a unique key # updatetime, keyname, data else: pilib.sqliteinsertsingle(pilib.motesdatabase, motetablename, [thetime, key, datadict[key]]) print('inserted ' + thetime + ' ' + key + ' ' + datadict[key]) # This is for values that are reported by the node elif 'ioval' in datadict: # check to see if entry exists with node and ionum. Need to generalize these. # Might make sense to put then into an ID to compare. Other database, compatible? # iovalue type message try: msgtype = 'iovalue' keyvalue = datadict['iopin'] keyvaluename = 'iopin' except: print('oops') else: runquery = True elif 'owdev' in datadict: try: msgtype = 'owdev' keyvalue = datadict['owrom'][2:] keyvaluename = 'owrom' if len(keyvalue) != 16: raise NameError('invalid ROM length') else: for romcbar in keyvalue: hexchars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f'] if romcbar not in hexchars: raise NameError('Invalid ROM hex character') except: print("oops") else: runquery = True elif 'chan' in datadict: # insert or update remotes database value # first need to get existing entry if one exists msgtype = 'channel' keyvalue = str(int(datadict['chan'])) # Zeroes bad keyvaluename = str(int(datadict['chan'])) # conditions = '"nodeid"=2 and "msgtype"=\'channel\' and "keyvalue"=\'' + keyvalue + '\'"' # Should be able to offer all conditions, but it is not working for some reason, so we will # iterate over list to find correct enty conditions = '"nodeid"=\''+ datadict['nodeid'] + '\' and "msgtype"=\'channel\'' chanentries = pilib.readalldbrows(pilib.controldatabase, 'remotes', conditions) # parse through to get data from newdata newdata = {} for key, value in datadict.iteritems(): if key not in ['chan','nodeid']: newdata[key] = value updateddata = newdata.copy() # This does not take time into account. This should not be an issue, as there should only be one entry for chanentry in chanentries: if (str(int(chanentry['keyvalue']))) == keyvalue: print('I FOUND') # newdata = {'fakedatatype':'fakedata', 'anotherfakedatatype':'morefakedata'} olddata = pilib.parseoptions(chanentry['data']) olddata.update(updateddata) updateddata = olddata.copy() newqueries = [] conditions += ' and "keyvalue"=\'' + keyvalue +"\'" # Ok, so here we are. We have either added new data to old data, or we have the new data alone. # We take our dictionary and convert it back to json and put it in the text entry updatedjsonentry = pilib.dicttojson(updateddata) conditions += 'and "keyvalue"=\'' + keyvalue +'\'' deletequery = pilib.makedeletesinglevaluequery('remotes',conditions) # hardcode this for now, should supply valuename list. addquery = pilib.makesqliteinsert('remotes',[datadict['nodeid'],'channel',keyvalue,'channel',updatedjsonentry,pilib.gettimestring()]) pilib.sqlitemultquery(pilib.controldatabase, [deletequery, addquery]) # pass elif 'scalevalue' in datadict: querylist.append('create table if not exists scalevalues (value float, time string)') querylist.append(pilib.makesqliteinsert('scalevalues',[datadict['scalevalue'], pilib.gettimestring()],['value','time'])) pilib.sqlitemultquery(pilib.logdatabase, querylist) if runquery: deletequery = pilib.makedeletesinglevaluequery('remotes', {'conditionnames': ['nodeid', 'keyvalue', 'keyvaluename'], 'conditionvalues': [nodeid ,keyvalue, keyvaluename]}) insertquery = pilib.makesqliteinsert('remotes', [nodeid, msgtype, keyvaluename, keyvalue, stringmessage.replace('\x00', ''), pilib.gettimestring()], ['nodeid', 'msgtype', 'keyvaluename', 'keyvalue', 'data', 'time']) querylist.append(deletequery) querylist.append(insertquery) pilib.sqlitemultquery(pilib.controldatabase, querylist) return else: # print('not running query') pass