Beispiel #1
0
def updatesupplicantdata(configdata):
    from pilib import readalldbrows, safedatabase, systemdatadatabase

    try:
        netconfig = readalldbrows(systemdatadatabase, 'netconfig')[0]
    except:
         writedatedlogmsg(networklog, 'Error reading netconfig data. ', 0, networkloglevel)
    else:
         writedatedlogmsg(networklog, 'Read netconfig data. ', 4, networkloglevel)

    try:
        wirelessauths = readalldbrows(safedatabase, 'wireless')
    except:
         writedatedlogmsg(networklog, 'Error reading wireless data. ', 0, networkloglevel)
    else:
         writedatedlogmsg(networklog, 'Read wireless data. ', 4, networkloglevel)

    password = ''

    writedatedlogmsg(networklog, 'Netconfig data: ' + str(netconfig), 2, networkloglevel)

    # we only update if we find the credentials
    for auth in wirelessauths:
        if auth['SSID'] == netconfig['SSID']:
            password = '******' + auth['password'] + '"'
            ssid = '"' + auth['SSID'] + '"'
            writedatedlogmsg(networklog, 'SSID ' + auth['SSID'] + 'found. ', 1, networkloglevel)
            configdata.data['psk'] = password
            configdata.data['ssid'] = ssid
    return configdata
Beispiel #2
0
def updatewpasupplicant(path='/etc/wpa_supplicant/wpa_supplicant.conf'):

    netconfig = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0]

    try:
        wirelessauths = pilib.readalldbrows(pilib.safedatabase, 'wireless')
    except:
         pilib.log(pilib.networklog, 'Error reading wireless data. ', 0, pilib.networkloglevel)
    else:
         pilib.log(pilib.networklog, 'Read wireless data. ', 4, pilib.networkloglevel)

    psk = ''
    ssid = ''

    # we only update if we find the credentials
    try:
        ourssid = netconfig['SSID']
    except KeyError:
        pilib.log(pilib.syslog, 'No SSID found in netconfig. Finding first in wireless', 1, pilib.sysloglevel)
        # try to attach to first network by setting SSID to first network in wireless auths
        # this can help alleviate some headaches down the line, hopefully
        wirelessauths = pilib.readalldbrows(pilib.safedatabase, 'wireless')

        try:
            defaultauths = wirelessauths[0]
            currssid = defaultauths['SSID']
        except:
            pilib.log(pilib.syslog, 'No SSID in wireless table to default to. ', 1, pilib.sysloglevel)
            currssid = ''

    if currssid:
        for auth in wirelessauths:
            if auth['SSID'] == netconfig['SSID']:
                password = auth['password']
                ssid = auth['SSID']
                pilib.log(pilib.networklog, 'SSID ' + auth['SSID'] + 'found. ', 1, pilib.networkloglevel)
                psk = password
                ssid = ssid

        if psk:

            myfile = open(path, 'w')

            filestring = 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n\n'
            filestring += 'network={\n'
            filestring += 'psk="' + psk + '"\n'
            filestring += 'ssid="' + ssid + '"\n'
            filestring += 'proto=RSN\nauth_alg=OPEN\npairwise=CCMP\nkey_mgmt=WPA-PSK\n}'

            myfile.write(filestring)

        else:
            pilib.log(pilib.networklog, 'No auths recovered for SSID, so not writing wpa_supplicant', 1, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'No SSID found to write, so not writing wpa_supplicant', 1, pilib.networkloglevel)
Beispiel #3
0
def disablealloutputs():
    from pilib import controldatabase, readalldbrows

    outputs = readalldbrows(controldatabase,'outputs')

    querylist=[]
    for output in outputs:
        querylist.append('update outputs set enabled=0 where name=\'' + output['name'] + '\'')

    print('all outputs disabled')
Beispiel #4
0
def disablealloutputs():
    from pilib import controldatabase, readalldbrows

    outputs = readalldbrows(controldatabase, 'outputs')

    querylist = []
    for output in outputs:
        querylist.append('update outputs set enabled=0 where name=\'' +
                         output['name'] + '\'')

    print('all outputs disabled')
Beispiel #5
0
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)
Beispiel #6
0
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)
Beispiel #7
0
def checklivesessions(authdb, user, expiry):
    import pilib
    import time

    activesessions = 0
    sessions = pilib.readalldbrows(authdb, 'sessions')
    for session in sessions:
        sessioncreation = pilib.timestringtoseconds(session['timecreated'])
        currenttime = time.mktime(time.localtime())
        if currenttime - sessioncreation < expiry:
            activesessions += 1

    return activesessions
Beispiel #8
0
def updatesupplicantdata(configdata):
    from pilib import readalldbrows, safedatabase, systemdatadatabase

    try:
        netconfig = readalldbrows(systemdatadatabase, 'netconfig')[0]
    except:
        writedatedlogmsg(networklog, 'Error reading netconfig data. ', 0,
                         networkloglevel)
    else:
        writedatedlogmsg(networklog, 'Read netconfig data. ', 4,
                         networkloglevel)

    try:
        wirelessauths = readalldbrows(safedatabase, 'wireless')
    except:
        writedatedlogmsg(networklog, 'Error reading wireless data. ', 0,
                         networkloglevel)
    else:
        writedatedlogmsg(networklog, 'Read wireless data. ', 4,
                         networkloglevel)

    password = ''

    writedatedlogmsg(networklog, 'Netconfig data: ' + str(netconfig), 2,
                     networkloglevel)

    # we only update if we find the credentials
    for auth in wirelessauths:
        if auth['SSID'] == netconfig['SSID']:
            password = '******' + auth['password'] + '"'
            ssid = '"' + auth['SSID'] + '"'
            writedatedlogmsg(networklog, 'SSID ' + auth['SSID'] + 'found. ', 1,
                             networkloglevel)
            configdata.data['psk'] = password
            configdata.data['ssid'] = ssid
    return configdata
Beispiel #9
0
def getCuPIDlightsentries(table, CS, previndicators=None):
    querylist=[]

    if not previndicators:
        from pilib import readalldbrows, controldatabase
        previndicators = readalldbrows(controldatabase, 'indicators')

    previndicatorsnames = []
    for previndicator in previndicators:
        previndicatorsnames.append(previndicator['name'])

    interface = 'SPI' + str(CS)
    names = ['SPI' + str(CS) + '_RGB1_R',
             'SPI' + str(CS) + '_RGB1_G',
             'SPI' + str(CS) + '_RGB1_B',
             'SPI' + str(CS) + '_RGB2_R',
             'SPI' + str(CS) + '_RGB2_G',
             'SPI' + str(CS) + '_RGB2_B',
             'SPI' + str(CS) + '_RGB3_R',
             'SPI' + str(CS) + '_RGB3_G',
             'SPI' + str(CS) + '_RGB3_B',
             'SPI' + str(CS) + '_RGB4_R',
             'SPI' + str(CS) + '_RGB4_G',
             'SPI' + str(CS) + '_RGB4_B',
             'SPI' + str(CS) + '_SC_R',
             'SPI' + str(CS) + '_SC_G',
             'SPI' + str(CS) + '_SC_B',
             'SPI' + str(CS) + '_SC_Y']
    details = ['red', 'green', 'blue', 'red', 'green', 'blue', 'red',
               'green', 'blue', 'red', 'green', 'blue', 'red', 'green', 'blue', 'yellow']
    setlist = []
    valuelist = []
    for name, detail in zip(names, details):
        if name in previndicatorsnames:
            value = previndicators[previndicatorsnames.index(name)]['status']
        else:
            value = 0
        valuelist.append(value)
        querylist.append("insert into " + table + " values ('" + name + "','" + interface + "', 'CuPIDlights', " + str(value) + ",'" + detail + "')")

    setlist = [[valuelist[0], valuelist[1], valuelist[2]],
               [valuelist[3], valuelist[4], valuelist[5]],
               [valuelist[6], valuelist[7], valuelist[8]],
               [valuelist[7], valuelist[8], valuelist[9]],
               valuelist[10], valuelist[11], valuelist[12], valuelist[13]]

    return querylist, setlist
Beispiel #10
0
def processsystemflags(systemflags=None):
    import pilib
    from pilib import log, syslog, sysloglevel

    if not systemflags:
        systemflags = pilib.readalldbrows(pilib.systemdatadatabase, 'systemflags')

    flagnames = []
    flagvalues = []
    for flag in systemflags:
        flagnames.append(flag['name'])
        flagvalues.append(flag['value'])

    stop = False
    if 'reboot' in flagnames:
        if flagvalues[flagnames.index('reboot')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, "name='reboot'")
            import subprocess

            log(syslog, 'Rebooting for system flag', 0, sysloglevel)
            subprocess.call(['/sbin/reboot'])
    if 'netconfig' in flagnames:
        if flagvalues[flagnames.index('netconfig')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, "name='netconfig'")
            from netconfig import runconfig

            log(syslog, 'Restarting network configuration', 0, sysloglevel)
            runconfig()
    if 'updateiicontrollibs' in flagnames and not stop:
        if flagvalues[flagnames.index('updateiicontrollibs')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, 'name=\'updateiicontrollibs\'')
            from misc.gitupdatelib import updateiicontrollibs

            log(syslog, 'Updating iicontrollibs', 0, sysloglevel)
            updateiicontrollibs(True)
    if 'updatecupidweblib' in flagnames and not stop:
        if flagvalues[flagnames.index('updatecupidweblib')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, 'name=\'updatecupidweblib\'')
            from misc.gitupdatelib import updatecupidweblib

            log(syslog, 'Updating cupidweblib', 0, sysloglevel)
            updatecupidweblib(True)
Beispiel #11
0
def getCuPIDlightsentries(table, CS, previndicators=None):
    querylist = []

    if not previndicators:
        from pilib import readalldbrows, controldatabase
        previndicators = readalldbrows(controldatabase, 'indicators')

    previndicatorsnames = []
    for previndicator in previndicators:
        previndicatorsnames.append(previndicator['name'])

    interface = 'SPI' + str(CS)
    names = [
        'SPI' + str(CS) + '_RGB1_R', 'SPI' + str(CS) + '_RGB1_G',
        'SPI' + str(CS) + '_RGB1_B', 'SPI' + str(CS) + '_RGB2_R',
        'SPI' + str(CS) + '_RGB2_G', 'SPI' + str(CS) + '_RGB2_B',
        'SPI' + str(CS) + '_RGB3_R', 'SPI' + str(CS) + '_RGB3_G',
        'SPI' + str(CS) + '_RGB3_B', 'SPI' + str(CS) + '_RGB4_R',
        'SPI' + str(CS) + '_RGB4_G', 'SPI' + str(CS) + '_RGB4_B',
        'SPI' + str(CS) + '_SC_R', 'SPI' + str(CS) + '_SC_G',
        'SPI' + str(CS) + '_SC_B', 'SPI' + str(CS) + '_SC_Y'
    ]
    details = [
        'red', 'green', 'blue', 'red', 'green', 'blue', 'red', 'green', 'blue',
        'red', 'green', 'blue', 'red', 'green', 'blue', 'yellow'
    ]
    setlist = []
    valuelist = []
    for name, detail in zip(names, details):
        if name in previndicatorsnames:
            value = previndicators[previndicatorsnames.index(name)]['status']
        else:
            value = 0
        valuelist.append(value)
        querylist.append("insert into " + table + " values ('" + name + "','" +
                         interface + "', 'CuPIDlights', " + str(value) + ",'" +
                         detail + "')")

    setlist = [[valuelist[0], valuelist[1], valuelist[2]],
               [valuelist[3], valuelist[4], valuelist[5]],
               [valuelist[6], valuelist[7], valuelist[8]],
               [valuelist[7], valuelist[8], valuelist[9]], valuelist[10],
               valuelist[11], valuelist[12], valuelist[13]]

    return querylist, setlist
Beispiel #12
0
def processactions():

    # Read database to get our actions

    actiondicts = pilib.readalldbrows(pilib.controldatabase, 'actions')

    for actiondict in actiondicts:
        alert = False


        # print("ACTIONDICT")
        # print(actiondatadict)

        thisaction = action(actiondict)

        thisaction.process()

        print(thisaction.statusmsg)
        thisaction.publish()
Beispiel #13
0
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
Beispiel #14
0
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)
Beispiel #15
0
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))
Beispiel #16
0
    reply = updateio.updateiodata(pilib.controldatabase)

    result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0)
    systemsdict = result[0]
    #print("here is the systems dict")
    #print(systemsdict)
    readtime = systemsdict['updateiofreq']

    plotpoints = 20
    logpoints = 100

    ###################################################
    # Update controlvalues in channels

    channels = pilib.readalldbrows(pilib.controldatabase, 'channels')
    for channel in channels:

        # Get controlinput for each channel
        channelname = channel['name']
        controlinput = channel['controlinput']

        # Get the input for the name from inputs info
        # Then get the value and readtime from the input if it
        # can be found

        if controlinput:
            controlvalue = pilib.sqlitedatumquery(
                pilib.controldatabase, 'select value from inputs where name=' +
                "'" + controlinput + "'")
            controltime = pilib.sqlitedatumquery(
Beispiel #17
0
#!/usr/bin/env python

# Mount 1wire master

import subprocess
import pilib
import spilights

interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces')

runi2cowfs = False
runusbowfs = False
for interface in interfaces:
    if interface['interface'] == 'I2C' and interface['type'] == 'DS2483':
        runi2cowfs = True
    if interface['interface'] == 'USB' and interface['type'] == 'DS9490':
        runusbowfs = True

    if interface['interface'] == 'SPI1' and type == 'CuPIDlights':
        spilights.updatelightsfromdb(pilib.controldatabase, 'indicators', 1)
    if interface['interface'] == 'SPI0' and type == 'CuPIDlights':
        spilights.updatelightsfromdb(pilib.controldatabase, 'indicators', 0)

if runi2cowfs or runusbowfs:
    if runi2cowfs:
        subprocess.call([
            '/opt/owfs/bin/owserver', '-F', '--i2c=/dev/i2c-1:ALL', '-p',
            '4304'
        ])
    if runusbowfs:
        subprocess.call(['/opt/owfs/bin/owserver', '-F', '-u', '-p', '4304'])
Beispiel #18
0
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
Beispiel #19
0
import pilib
import controllib
from time import sleep

# Run the script periodically based on systemstatus

# This script does the following:
# Processes channels data into output settings and channels data (action, etc)
# Log data

# What it does not do:
# Read inputs (done by updateio, through periodicreadio)
# Set physical outputs (this is done by updateio)

systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

while systemstatus['picontrolenabled']:

    pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running picontrol', 3,
                           pilib.systemstatusloglevel)
    pilib.writedatedlogmsg(pilib.controllog, 'Running picontrol', 3,
                           pilib.controlloglevel)

    # Set poll date. While intuitively we might want to set this
    # after the poll is complete, if we error below, we will know
    # from this stamp when it barfed. This is arguably more valuable
    # then 'last time we didn't barf'

    pilib.sqlitequery(
        pilib.controldatabase, "update systemstatus set lastpicontrolpoll='" +
Beispiel #20
0
    # This doesn't update git libraries. It checks current versions and updates the database

    try:
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Checking git versions',
                               3, pilib.systemstatusloglevel)
        updategitversions()
    except:
        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'Error in git version check', 0,
                               pilib.systemstatusloglevel)
    else:
        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'Git version check complete', 3,
                               pilib.systemstatusloglevel)

    systemstatus = pilib.readalldbrows(pilib.controldatabase,
                                       'systemstatus')[0]

    # Keep reading system status?
    while systemstatus['systemstatusenabled']:

        starttime = time.time()
        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'System status routine is starting. ', 3,
                               pilib.systemstatusloglevel)

        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'Beginning network routines. ', 3,
                               pilib.systemstatusloglevel)

        currenttime = pilib.gettimestring()
        pilib.setsinglevalue(pilib.controldatabase, 'systemstatus',
Beispiel #21
0
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
Beispiel #22
0
#!/usr/bin/env python

import pilib
import spilights
import controllib
import RPi.GPIO as GPIO
from time import sleep

T = True
F = False
GPIO.setmode(GPIO.BCM)

# Run the script periodically based on systemstatus

systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

while systemstatus['picontrolenabled']:

    # Set poll date. While intuitively we might want to set this
    # after the poll is complete, if we error below, we will know 
    # from this stamp when it barfed. This is arguably more valuable
    # then 'last time we didn't barf'

    pilib.sqlitequery(pilib.controldatabase,
                      'update systemstatus set lastpicontrolpoll=\'' + pilib.gettimestring() + '\'')

    channels = pilib.readalldbrows(pilib.controldatabase, 'channels')
    outputs = pilib.readalldbrows(pilib.controldatabase, 'outputs')
    controlalgorithms = pilib.readalldbrows(pilib.controldatabase, 'controlalgorithms')

    # Cycle through channels and set action based on setpoint
Beispiel #23
0
__license__ = "Apache 2.0"
__version__ = "1.0"
__maintainer__ = "Colin Reese"
__email__ = "*****@*****.**"
__status__ = "Development"

import os
import sys
import math
import pilib
import controllib
import RPi.GPIO as GPIO
from time import sleep

T = True
F = False
GPIO.setmode(GPIO.BCM)

database = '/var/www/data/controldata.db'
logdatabase = '/var/www/data/logdata.db'

# Kill everything

outputs = pilib.readalldbrows(database, 'outputs')

for output in outputs:
    GPIO.setup(int(output['GPIO']), GPIO.OUT)
    GPIO.output(int(output['GPIO']), F)

print('all outputs disabled')
Beispiel #24
0
    import time

    from misc.gitupdatelib import updategitversions

    # This doesn't update git libraries. It checks current versions and updates the database

    try:
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Checking git versions', 3, pilib.systemstatusloglevel)
        updategitversions()
    except:
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Error in git version check', 0, pilib.systemstatusloglevel)
    else:
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Git version check complete', 3, pilib.systemstatusloglevel)


    systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

    # Keep reading system status?
    while systemstatus['systemstatusenabled']:

        starttime = time.time()
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'System status routine is starting. ', 3, pilib.systemstatusloglevel)

        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Beginning network routines. ', 3, pilib.systemstatusloglevel)

        currenttime = pilib.gettimestring()
        pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'lastsystemstatuspoll', pilib.gettimestring())

        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running updateifacestatus. ', 4, pilib.systemstatusloglevel)

        # Update network interfaces statuses for all interfaces, in database tables as well
def processactions():

    # Read database to get our actions

    actiondicts = pilib.readalldbrows(pilib.controldatabase, 'actions')

    for actiondict in actiondicts:
        alert = False

        # Instantiate the action class
        thisaction = pilib.action(actiondict)
        thisaction.statusmsg = ''
        # print(actiondict)
        # process condition
        if thisaction.conditiontype == 'dbvalue':
            if thisaction.enabled:
                thisaction.statusmsg += 'Action enabled.'

                dbdir = getattr(pilib, 'databasedir')
                # print(dbdir)
                dbpath = dbdir + thisaction.database + '.db'

                # variablename is columnname for dbvalue conditiontype
                thisaction.variablevalue = pilib.getsinglevalue(dbpath, thisaction.tablename, thisaction.variablename, 'rowid=' + str(thisaction.valuerowid))

                # get variable type to handle
                variablestypedict = pilib.getpragmanametypedict(dbpath, thisaction.tablename)
                vartype = variablestypedict[thisaction.variablename]
                thisaction.statusmsg += ' Variablevalue: ' + str(thisaction.variablevalue) + '. Criterion: ' + str(thisaction.criterion) + ' . '

                # process criterion according to type
                curstatus = False
                if vartype == 'boolean':
                    thisaction.statusmsg += ' Processing boolean. '
                    # TODO: String conversion is a hack here and needs series work.
                    if str(thisaction.variablevalue) == str(thisaction.criterion):
                        curstatus = True
                elif vartype == 'integer' or vartype == 'real':
                    thisaction.statusmsg += ' Processing integer/real. '
                    # print(thisaction.operator)
                    thisaction.variablevalue = float(thisaction.variablevalue)
                    thisaction.criterion = float(thisaction.criterion)
                    if thisaction.operator == 'greater':
                        if thisaction.variablevalue > thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == 'greaterorequal':
                        if thisaction.variablevalue >= thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == 'less':
                        if thisaction.variablevalue < thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == 'lessorequal':
                        if thisaction.variablevalue <= thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == 'equal':
                        if thisaction.variablevalue == thisaction.criterion:
                            curstatus = True
                    else:
                        thisaction.statusmsg += 'Operator error. '
                    if thisaction.variablevalue == thisaction.criterion:
                        curstatus = True
                elif vartype == 'text':
                    thisaction.statusmsg += ' Processing text. '
                    if thisaction.variablevalue == thisaction.criterion:
                        curstatus = True
                else:
                    thisaction.statusmsg += ' Mode Error for vartype ' + vartype + '. '

                if curstatus:
                    thisaction.statusmsg += 'Status is true. '
                else:
                    thisaction.statusmsg += 'Status is not true. '

                currenttime = pilib.gettimestring()

                # if status is true and current status is false, set ontime
                if curstatus and not thisaction.status:
                    # print(str(curstatus) + ' ' + str(thisaction.status))
                    thisaction.statusmsg += 'Setting status ontime. '
                    thisaction.ontime = pilib.gettimestring()
                    thisaction.status = 1
                elif not curstatus and thisaction.status:
                    thisaction.statusmsg += 'Setting status offtime. '
                    thisaction.offtime = pilib.gettimestring()
                    thisaction.status = 0

                # Set current status
                if curstatus:
                    thisaction.status = 1
                    # print('settings status')
                else:
                    thisaction.status = 0
                    # print('resetting status')

                # if status is true and alarm isn't yet active, see if ondelay exceeded
                if curstatus and not thisaction.active:
                    # print(pilib.timestringtoseconds(currenttime))
                    statusontime = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(thisaction.ontime)
                    # print(statusontime)
                    if statusontime > thisaction.ondelay:
                        thisaction.statusmsg += 'Setting action active'
                        thisaction.active = 1
                    else:
                        thisaction.statusmsg += 'On delay not reached'

                # if status is not true and alarm is active, see if offdelay exceeded
                if not curstatus and thisaction.active:
                    statusofftime = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(thisaction.offtime)
                    if statusofftime > thisaction.offdelay:
                        thisaction.statusmsg += 'Setting action inactive'
                        thisaction.active = 0
                        # Send an alert / reset indicator if activereset is on
                        if thisaction.activereset:
                            thisaction.offact()
                    else:
                        thisaction.statusmsg += 'Off delay not reached'

                # test to see if it is time to alert, based on delay ond alert time
                if thisaction.active:
                    # check to see if it is time to alert
                    # For things like outputs, actionfrequency should be zero to always enforce that action is on.

                    # print(pilib.timestringtoseconds(currenttime))
                    # print(pilib.timestringtoseconds(thisaction.lastactiontime))
                    # print(float(thisaction.actionfrequency))
                    # print(pilib.timestringtoseconds(currenttime)-pilib.timestringtoseconds(thisaction.lastactiontime))
                    if pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(thisaction.lastactiontime) > float(thisaction.actionfrequency):
                        alert = True
                        thisaction.statusmsg += "Time to act. "
                    else:
                        alert = False
                        thisaction.statusmsg += "Not yet time to act."

                if alert:
                    # We're ready to alert or alert again.
                    thisaction.lastactiontime = currenttime
                    if curstatus:
                        thisaction.onact()
                    else:
                        thisaction.offact()
            else:
                thisaction.statusmsg += 'Action disabled.'
                thisaction.status = 0
        else:
            thisaction.statusmsg += 'Mode unrecognized.'

        # print(thisaction.statusmsg)
        thisaction.publish()
    reply = updateio.updateiodata(pilib.controldatabase)

    result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0)
    systemsdict = result[0]
    #print("here is the systems dict")
    #print(systemsdict)
    readtime = systemsdict['inputsreadfreq']

    plotpoints = 20
    logpoints = 100

    ################################################### 
    # Update controlvalues in channels

    channels = pilib.readalldbrows(pilib.controldatabase, 'channels')
    for channel in channels:

        # Get controlinput for each channel
        channelname = channel['name']
        controlinput = channel['controlinput']

        # Get the input for the name from inputs info
        # Then get the value and readtime from the input if it
        # can be found

        if controlinput:
            controlvalue = pilib.sqlitedatumquery(pilib.controldatabase,
                                                  'select value from inputsdata where id=' + "'" + controlinput + "'")
            controltime = pilib.sqlitedatumquery(pilib.controldatabase,
                                                 'select polltime from inputsdata where id=' + "'" + controlinput + "'")
Beispiel #27
0
#!/usr/bin/env python

import subprocess
import pilib
import spilights
from time import sleep

interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces')
systemstatus = pilib.readonedbrow(pilib.controldatabase, 'systemstatus')[0]

# Start pigpiod

subprocess.call(['killall','pigpiod'])
sleep(1)
pilib.log(pilib.syslog, 'boot: starting pigpio daemon', 3, pilib.sysloglevel)
subprocess.call(['/usr/local/bin/pigpiod'])

# Start webserver

subprocess.call(['killall','nginx'])
subprocess.call(['killall','uwsgi'])
subprocess.call(['killall','apache2'])

if systemstatus['webserver'] == 'apache':
    pilib.log(pilib.syslog, 'boot: starting apache', 3, pilib.sysloglevel)
    subprocess.call(['service', 'apache2', 'start'])
elif systemstatus['webserver'] == 'nginx':
    pilib.log(pilib.syslog, 'boot: starting nginx', 3, pilib.sysloglevel)
    subprocess.call(['service', 'nginx', 'start'])

# Run uwsgi daemon if nginx is running
Beispiel #28
0
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)
Beispiel #29
0
def runsystemstatus(runonce=False):
    import pilib
    import time
    import netconfig

    from misc.gitupdatelib import updategitversions

    # This doesn't update git libraries. It checks current versions and updates the database

    try:
        pilib.log(pilib.syslog, 'Checking git versions', 3, pilib.sysloglevel)
        updategitversions()
    except:
        pilib.log(pilib.syslog, 'Error in git version check', 0, pilib.sysloglevel)
    else:
        pilib.log(pilib.syslog, 'Git version check complete', 3, pilib.sysloglevel)

    systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

    ## Read wireless config via iwconfig
    # this is breaking systemstatus for some reason
    # updateiwstatus()

    ## Read current netstatus
    lastnetstatus={}
    try:
        lastnetstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
    except:
        pilib.log(pilib.networklog, 'Error reading network status. ', 1, pilib.networkloglevel)
    else:
        pilib.log(pilib.syslog, 'Completed network status. ', 3, pilib.networkloglevel)

    # Poll netstatus and return data
    allnetstatus = updatenetstatus(lastnetstatus)
    # wpastatusdict = allnetstatus['wpastatusdict']

    # Keep reading system status?
    while systemstatus['systemstatusenabled']:

        currenttime = pilib.gettimestring()
        pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'lastsystemstatuspoll', pilib.gettimestring())

        starttime = time.time()
        pilib.log(pilib.syslog, 'System status routine is starting. ', 3,
                               pilib.sysloglevel)

        """
        Check all network statuses. The goal here is to totally decouple status read and reconfigure
        When we need to check all status data, we'll have it either in a dict or dict array, or in a database table
        """

        if systemstatus['netstatusenabled']:
            pilib.log(pilib.syslog, 'Beginning network routines. ', 3, pilib.sysloglevel)

            # Update network interfaces statuses for all interfaces, in database tables as well
            # Check on wpa supplicant status as well. Function returns wpastatusdict
            try:
                pilib.log(pilib.syslog, 'Running updateifacestatus. ', 4, pilib.sysloglevel)
                pilib.log(pilib.networklog, 'Running updateifacestatus', 4, pilib.networkloglevel)
                allnetstatus = updatenetstatus(lastnetstatus)
            except:
                pilib.log(pilib.networklog, 'Exception in updateifacestatus. ')
            else:
                pilib.log(pilib.networklog, 'Updateifacestatus completed. ')

            pilib.log(pilib.syslog, 'Completed net status update. ', 4, pilib.sysloglevel)
        else:
            allnetstatus={'netstatusdict': {}, 'ifacesdictarray': {}}


        """
        End network configuration status
        """

        """
        Do we want to autoconfig the network? If so, we analyze our netstatus data against what should be going on,
        and translate this into a network status
        """
        if systemstatus['netconfigenabled'] and systemstatus['netstatusenabled']:

            # No need to get this fresh. We have it stored.
            netconfigdata = allnetstatus['netconfigdata']

            # We are going to hack in a jumper that sets AP configuration. This isn't the worst thing ever.
            if netconfigdata['apoverride']:
                result = processapoverride(21)

            ''' Now we check network status depending on the configuration we have selected '''
            ''' Now we check network status depending on the configuration we have selected '''
            pilib.log(pilib.syslog, 'Running interface configuration watchdog. ', 4,
                                   pilib.sysloglevel)
            pilib.log(pilib.networklog, 'Running interface configuration. Mode: ' + netconfigdata['mode'], 4,
                                   pilib.networkloglevel)

            result = watchdognetstatus()

        else:
            pilib.log(pilib.syslog, 'Netconfig disabled. ', 1, pilib.sysloglevel)
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', 'manual')
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'statusmsg', 'netconfig is disabled')


        if systemstatus['checkhamachistatus']:
            pilib.log(pilib.syslog, 'Hamachi watchdog is enabled', 3, pilib.sysloglevel)
            pilib.log(pilib.networklog, 'Hamachi watchdog is enabled. ', 3, pilib.networkloglevel)

            # Only watchdog haamchi if we are connected to the network.
            netstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
            if netstatus['WANaccess']:
                pilib.log(pilib.syslog, 'We appear to be online. Checking Hamachi Status. ', 3, pilib.sysloglevel)
                pilib.log(pilib.networklog, 'We appear to be online. Checking Hamachi Status. ', 3, pilib.networkloglevel)
                watchdoghamachi(pingip='25.37.18.7')
            else:
                pilib.log(pilib.syslog, 'We appear to be offline. Not checking Hamachi Status. ', 3, pilib.sysloglevel)
                pilib.log(pilib.networklog, 'We appear to be offline. Not checking Hamachi Status. ', 3, pilib.networkloglevel)

        else:
            pilib.log(pilib.syslog, 'Hamachi watchdog is disnabled', 3, pilib.sysloglevel)

        pilib.log(pilib.syslog, 'Finished interface configuration. ', 4,
                               pilib.sysloglevel)
        # pilib.writedatedlogmsg(pilib.networklog, statusmsg)

        pilib.log(pilib.syslog, 'Running updateifacestatus. ', 4, pilib.sysloglevel)
        updatenetstatus()
        pilib.log(pilib.syslog, 'Completed updateifacestatus. ', 4, pilib.sysloglevel)

        pilib.log(pilib.syslog, 'Network routines complete. ', 3, pilib.sysloglevel)

        pilib.log(pilib.syslog, 'Checking system flags. ', 3, pilib.sysloglevel)
        processsystemflags()
        pilib.log(pilib.syslog, 'System flags complete. ', 3, pilib.sysloglevel)

        # Get system status again
        systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

        elapsedtime = int(time.time() - starttime)

        pilib.log(pilib.syslog, 'Status routines complete. Elapsed time: ' + str(elapsedtime), 3,
                               pilib.sysloglevel)

        pilib.log(pilib.syslog,
                               'System status is sleeping for ' + str(systemstatus['systemstatusfreq']) + '. ', 3,
                               pilib.sysloglevel)

        if runonce:
            break

        time.sleep(systemstatus['systemstatusfreq'])


    else:
        pilib.log(pilib.syslog, 'System status is disabled. Exiting. ', 0,
                               pilib.sysloglevel)
Beispiel #30
0
def getCuPIDlightsentries(table, CS, previndicators=None):
    querylist = []

    if not previndicators:
        from pilib import readalldbrows, controldatabase

        previndicators = readalldbrows(controldatabase, "indicators")

    previndicatornames = []
    previndicatorvalues = []
    d = {}
    for previndicator in previndicators:
        previndicatornames.append(previndicator["name"])
        previndicatorvalues.append(previndicator["status"])
        d[previndicator["name"]] = previndicator["status"]

    interface = "SPI" + str(CS)
    names = [
        "SPI_RGB1_R",
        "SPI_RGB1_G",
        "SPI_RGB1_B",
        "SPI_RGB2_R",
        "SPI_RGB2_G",
        "SPI_RGB2_B",
        "SPI_RGB3_R",
        "SPI_RGB3_G",
        "SPI_RGB3_B",
        "SPI_RGB4_R",
        "SPI_RGB4_G",
        "SPI_RGB4_B",
        "SPI_SC_R",
        "SPI_SC_G",
        "SPI_SC_B",
        "SPI_SC_Y",
    ]
    details = [
        "red",
        "green",
        "blue",
        "red",
        "green",
        "blue",
        "red",
        "green",
        "blue",
        "red",
        "green",
        "blue",
        "red",
        "green",
        "blue",
        "yellow",
    ]
    setlist = []
    valuelist = []
    for name, detail in zip(names, details):
        if name in previndicatornames:
            value = previndicators[previndicatornames.index(name)]["status"]
        else:
            value = 0
        valuelist.append(value)
        querylist.append(
            "insert or replace into "
            + table
            + " values ('"
            + name
            + "','"
            + interface
            + "', 'CuPIDlights', "
            + str(value)
            + ",'"
            + detail
            + "')"
        )

    setlist = [
        [valuelist[0], valuelist[1], valuelist[2]],
        [valuelist[3], valuelist[4], valuelist[5]],
        [valuelist[6], valuelist[7], valuelist[8]],
        [valuelist[7], valuelist[8], valuelist[9]],
        valuelist[10],
        valuelist[11],
        valuelist[12],
        valuelist[13],
    ]

    return querylist, setlist
Beispiel #31
0
def updateiodata(database):
    # This recreates all input and output tables based on the interfaces table.
    # Thus way we don't keep around stale data values. We could at some point incorporate
    # a retention feature that keeps them around in case they disappear temporarily.
    # It also reads the elements if they are enabled and it's time to read them

    import pilib
    import traceback
    import RPi.GPIO as GPIO

    allowedGPIOaddresses = [18, 23, 24, 25, 4, 17, 21, 22]

    logconfig = pilib.getlogconfig()

    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    tables = pilib.gettablenames(pilib.controldatabase)
    if 'interfaces' in tables:
        interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces')
    else:
        pilib.writedatedlogmsg(pilib.iolog, 'interfaces table not found. Exiting', 1,
                               logconfig['iologlevel'])
        return
    if 'inputs' in tables:
        previnputs = pilib.readalldbrows(pilib.controldatabase, 'inputs')

        # Make list of IDs for easy indexing
        previnputids = []
        for input in previnputs:
            previnputids.append(input['id'])
    else:
        previnputs = []
        previnputids = []

    if 'outputs' in tables:
        prevoutputs = pilib.readalldbrows(pilib.controldatabase, 'outputs')

        # Make list of IDs for easy indexing
        prevoutputids = []
        prevoutputvalues = []
        for output in prevoutputs:
            prevoutputids.append(output['id'])
            prevoutputvalues.append(output['value'])
    else:
        prevoutputs = {}
        prevoutputids = []

    if 'defaults' in tables:
        defaults = pilib.readalldbrows(pilib.controldatabase, 'defaults')[0]
        defaultinputpollfreq = defaults['inputpollfreq']
        defaultoutputpollfreq = defaults['outputpollfreq']
    else:
        defaults = []
        defaultinputpollfreq = 60
        defaultoutputpollfreq = 60

    if 'indicators' in tables:
        indicatornames = []
        previndicators = pilib.readalldbrows(pilib.controldatabase, 'indicators')
        for indicator in previndicators:
            indicatornames.append(indicator['name'])
    else:
        previndicators = []
        indicatornames = []

    # We drop all inputs and outputs and recreate
    # Add all into one query so there is no time when the IO don't exist.

    querylist = []
    querylist.append('delete from inputs')
    querylist.append('delete from outputs')

    # This is temporary. Clearing the table here and adding entries below can result in a gap in time
    # where there are no database indicator entries. This is not too much of a problem with indicators, as we
    # update the hardware explicitly after we add the entries. If the interface queries the table during
    # this period, however, we could end up with an apparently empty table.
    # TODO: FIX update on indicators in updateio

    pilib.sqlitequery(pilib.controldatabase, 'delete from indicators')

    owfsupdate = False
    for interface in interfaces:
        if interface['interface'] == 'I2C':
            pilib.writedatedlogmsg(pilib.iolog, 'Processing I2C interface' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.writedatedlogmsg(pilib.iolog, 'I2C Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])
                if interface['type'] == 'DS2483':
                    pilib.writedatedlogmsg(pilib.iolog, 'Interface type is DS2483', 3,
                                           logconfig['iologlevel'])
                    owfsupdate = True
        elif interface['interface'] == 'USB':
            pilib.writedatedlogmsg(pilib.iolog, 'Processing USB interface' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.writedatedlogmsg(pilib.iolog, 'USB Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])
                if interface['type'] == 'DS9490':
                    pilib.writedatedlogmsg(pilib.iolog, 'Interface type is DS9490', 3,
                                           logconfig['iologlevel'])
                    owfsupdate = True
        elif interface['interface'] == 'MOTE':
            pilib.writedatedlogmsg(pilib.iolog, 'Processing Mote interface' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.writedatedlogmsg(pilib.iolog, 'Mote Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])

                # Grab mote entries from remotes table
                nodeaddress = int(interface['address'])
                nodeentries = pilib.dynamicsqliteread(pilib.controldatabase, 'remotes', condition="\"nodeid\"='" + str(nodeaddress) + "'")

                # Create queries for table insertion
                # TODO: process mote pollfreq, ontime, offtime
                moteentries = []
                for nodeentry in nodeentries:

                    datadict = pilib.parseoptions(nodeentry['data'])
                    try:
                        entrytype = nodeentry['msgtype']
                        entryid = 'MOTE' + str(nodeentry['nodeid']) + '_' + nodeentry['keyvaluename'] + '_' + nodeentry['keyvalue']


                        entrymetareturn = pilib.dynamicsqliteread(pilib.controldatabase, 'ioinfo', condition="\"id\"='" + entryid + "'")
                        try:
                            entrymeta = entrymetareturn[0]
                        except:
                            entrymeta = []

                        # print(entrymeta)

                        entryoptions={}
                        if entrymeta:
                            entryname = entrymeta['name']
                            if entrymeta['options']:
                                entryoptions = pilib.parseoptions(entrymeta['options'])
                        else:
                            entryname = '[MOTE' + str(nodeentry['nodeid']) + '] ' + nodeentry['keyvaluename'] + ':' + nodeentry['keyvalue']
                    except KeyError:
                        print('OOPS KEY ERROR')
                    else:
                        if entrytype == 'iovalue':
                            if 'scale' in entryoptions:
                                entryvalue = str(float(entryoptions['scale']) * float(datadict['iovalue']))
                            else:
                                entryvalue = datadict['iovalue']
                        elif entrytype == 'owdev':
                            if 'owtmpasc' in datadict:
                                if 'scale' in entryoptions:
                                    entryvalue = str(float(entryoptions['scale']) * float(datadict['owtmpasc']))
                                else:
                                    entryvalue = datadict['owtmpasc']
                            else:
                                entryvalue = -1
                        else:
                            entryvalue = -1

                        moteentries.append('insert into inputs values (\'' + entryid + '\',\'' + interface['interface'] + '\',\'' +
            interface['type'] + '\',\'' + str(address) + '\',\'' + entryname + '\',\'' + str(entryvalue) + "','','" +
            nodeentry['time'] + '\',\'' + str(15) + "','" + '' + "','" + '' + "')")
                # print('querylist')
                # print(moteentries)
                querylist.extend(moteentries)

        elif interface['interface'] == 'LAN':
            pilib.writedatedlogmsg(pilib.iolog, 'Processing LAN interface' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.writedatedlogmsg(pilib.iolog, 'LAN Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])
                if interface['type'] == 'MBTCP':
                    pilib.writedatedlogmsg(pilib.iolog, 'Interface ' + interface['name'] + ' type is MBTCP',
                                           3, logconfig['iologlevel'])

                    try:
                        mbentries = processMBinterface(interface, prevoutputs, prevoutputids, previnputs, previnputids, defaults, logconfig)
                    except:
                        pilib.writedatedlogmsg(pilib.iolog,
                                               'Error processing MBTCP interface ' + interface['name'], 0,
                                               logconfig['iologlevel'])
                        errorstring = traceback.format_exc()
                        pilib.writedatedlogmsg(pilib.iolog,
                                               'Error of kind: ' + errorstring, 0,
                                               logconfig['iologlevel'])
                    else:
                        pilib.writedatedlogmsg(pilib.iolog,
                                               'Done processing MBTCP interface ' + interface['name'], 3,
                                               logconfig['iologlevel'])
                        querylist.extend(mbentries)


        elif interface['interface'] == 'GPIO':
            try:
                address = int(interface['address'])
            except KeyError:
                pilib.writedatedlogmsg(pilib.iolog, 'GPIO address key not found for ' + interface['name'], 1,
                                       logconfig['iologlevel'])
                continue

            pilib.writedatedlogmsg(pilib.iolog, 'Processing GPIO interface ' + str(interface['address']), 3,
                                   logconfig['iologlevel'])

            if address in allowedGPIOaddresses:
                pilib.writedatedlogmsg(pilib.iolog, 'GPIO address' + str(address) + ' allowed', 4,
                                       logconfig['iologlevel'])

                # Check if interface is enabled
                if interface['enabled']:
                    GPIOentries = processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids,
                                                       previnputs, previnputids, defaults, logconfig)
                    querylist.extend(GPIOentries)
                else:
                    pilib.writedatedlogmsg(pilib.iolog, 'GPIO address' + str(address) + ' disabled', 4,
                                           logconfig['iologlevel'])
                    GPIO.setup(address, GPIO.IN)
            else:
                pilib.writedatedlogmsg(pilib.iolog,
                                       'GPIO address' + str(address) + ' not allowed. Bad things can happen. ', 4,
                                       logconfig['iologlevel'])
        elif interface['interface'] == 'SPI0':
            pilib.writedatedlogmsg(pilib.iolog, 'Processing SPI0', 1, logconfig['iologlevel'])
            if interface['type'] == 'SPITC':
                import readspi

                spidata = readspi.readspitc(0)
                spitcentries = readspi.recordspidata(database, spidata)
                querylist.extend(spitcentries)

            if interface['type'] == 'CuPIDlights':
                import spilights

                spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 0, previndicators)
                querylist.extend(spilightsentries)
                spilights.updatelightsfromdb(pilib.controldatabase, 'indicators', 0)
                spilights.setspilights(setlist, 0)

        elif interface['interface'] == 'SPI1':
            pilib.writedatedlogmsg(pilib.iolog, 'Processing SPI1', 1, logconfig['iologlevel'])

            if interface['type'] == 'CuPIDlights':
                import spilights

                spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 1, previndicators)
                querylist.extend(spilightsentries)
                spilights.setspilights(setlist, 1)

    # Set tables
    querylist.append(pilib.makesinglevaluequery('systemstatus', 'lastiopoll', pilib.gettimestring()))

    if owfsupdate:
        from owfslib import runowfsupdate

        devices, owfsentries = runowfsupdate(execute=False)
        querylist.extend(owfsentries)

    pilib.writedatedlogmsg(pilib.iolog, 'Executing query:  ' + str(querylist), 5, logconfig['iologlevel'])
    try:
        pilib.sqlitemultquery(pilib.controldatabase, querylist)
    except:
        errorstring = traceback.format_exc()
        pilib.writedatedlogmsg(pilib.iolog, 'Error executing query, message:  ' + errorstring, 0, logconfig['iologlevel'])
        pilib.writedatedlogmsg(pilib.errorlog, 'Error executing updateio query, message:  ' + errorstring)
        pilib.writedatedlogmsg(pilib.errorlog, 'Query:  ' + str(querylist))
Beispiel #32
0
def processactions():
    # Read database to get our actions

    actiondicts = pilib.readalldbrows(pilib.controldatabase, 'actions')

    for actiondict in actiondicts:
        alert = False

        thisaction = pilib.action(actiondict)
        thisaction.statusmsg = ''
        # print(actiondict)
        # process condition
        if thisaction.conditiontype == 'dbvalue':
            if thisaction.enabled:
                thisaction.statusmsg += 'Action enabled.'

                dbdir = getattr(pilib, 'databasedir')
                # print(dbdir)
                dbpath = dbdir + thisaction.database + '.db'

                # variablename is columnname for dbvalue conditiontype
                thisaction.variablevalue = pilib.getsinglevalue(
                    dbpath, thisaction.tablename, thisaction.variablename,
                    'rowid=' + str(thisaction.channelindex))

                # get variable type to handle
                variablestypedict = pilib.getpragmanametypedict(
                    pilib.controldatabase, thisaction.tablename)
                vartype = variablestypedict[thisaction.variablename]
                thisaction.statusmsg += ' Variablevalue: ' + str(
                    thisaction.variablevalue) + '. Criterion: ' + str(
                        thisaction.criterion) + ' . '

                # process criterion according to type
                curstatus = False
                if vartype == 'boolean':
                    thisaction.statusmsg += ' Processing boolean. '
                    if thisaction.variablevalue == thisaction.criterion:
                        curstatus = True
                elif vartype == 'integer' or vartype == 'real':
                    thisaction.statusmsg += ' Processing integer/real. '
                    # print(thisaction.operator)
                    thisaction.variablevalue = float(thisaction.variablevalue)
                    thisaction.criterion = float(thisaction.criterion)
                    if thisaction.operator == '>':
                        if thisaction.variablevalue > thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == '>=':
                        if thisaction.variablevalue >= thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == '<':
                        if thisaction.variablevalue < thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == '<=':
                        if thisaction.variablevalue <= thisaction.criterion:
                            curstatus = True
                    elif thisaction.operator == '=':
                        if thisaction.variablevalue == thisaction.criterion:
                            curstatus = True
                    else:
                        thisaction.statusmsg += 'Operator error. '
                    if thisaction.variablevalue == thisaction.criterion:
                        curstatus = True
                elif vartype == 'text':
                    thisaction.statusmsg += ' Processing text. '
                    if thisaction.variablevalue == thisaction.criterion:
                        curstatus = True
                else:
                    thisaction.statusmsg += ' Mode Error for vartype ' + vartype + '. '

                if curstatus:
                    thisaction.statusmsg += 'Status is true. '
                else:
                    thisaction.statusmsg += 'Status is not true. '

                currenttime = pilib.gettimestring()

                # if status is true and current status is false, set ontime
                if curstatus and not thisaction.status:
                    # print(str(curstatus) + ' ' + str(thisaction.status))
                    thisaction.statusmsg += 'Setting status ontime. '
                    thisaction.ontime = pilib.gettimestring()
                    thisaction.status = 1
                elif not curstatus and thisaction.status:
                    thisaction.statusmsg += 'Setting status offtime. '
                    thisaction.offtime = pilib.gettimestring()
                    thisaction.status = 0

                # Set current status
                if curstatus:
                    thisaction.status = 1
                    # print('settings status')
                else:
                    thisaction.status = 0
                    # print('resetting status')

                # if status is true and alarm isn't yet active, see if ondelay exceeded
                if curstatus and not thisaction.active:
                    # print(pilib.timestringtoseconds(currenttime))
                    statusontime = pilib.timestringtoseconds(
                        currenttime) - pilib.timestringtoseconds(
                            thisaction.ontime)
                    # print(statusontime)
                    if statusontime > thisaction.ondelay:
                        thisaction.statusmsg += 'Setting action active'
                        thisaction.active = 1
                    else:
                        thisaction.statusmsg += 'On delay not reached'

                # if status is not true and alarm is active, see if offdelay exceeded
                if not curstatus and thisaction.active:
                    statusofftime = pilib.timestringtoseconds(
                        currenttime) - pilib.timestringtoseconds(
                            thisaction.offtime)
                    if statusofftime > thisaction.offdelay:
                        thisaction.statusmsg += 'Setting action inactive'
                        thisaction.active = 0
                        # Send an alert / reset indicator if activereset is on
                        if thisaction.activereset:
                            thisaction.offact()
                    else:
                        thisaction.statusmsg += 'Off delay not reached'

                # test to see if it is time to alert, based on delay ond alert time
                if thisaction.active:
                    # check to see if it is time to alert
                    # print(pilib.timestringtoseconds(currenttime))
                    # print(pilib.timestringtoseconds(thisaction.lastactiontime))
                    # print(float(thisaction.actionfrequency))
                    # print(pilib.timestringtoseconds(currenttime)-pilib.timestringtoseconds(thisaction.lastactiontime))
                    if pilib.timestringtoseconds(
                            currenttime) - pilib.timestringtoseconds(
                                thisaction.lastactiontime) > float(
                                    thisaction.actionfrequency):
                        alert = True
                        thisaction.statusmsg += "Time to act. "
                    else:
                        alert = False
                        thisaction.statusmsg += "Not yet time to act."

                if alert:
                    # We're ready to alert or alert again.
                    thisaction.lastactiontime = currenttime
                    if curstatus:
                        thisaction.onact()
                    else:
                        thisaction.offact()
            else:
                thisaction.statusmsg += 'Action disabled.'
                thisaction.status = 0
        else:
            thisaction.statusmsg += 'Mode unrecognized.'

        print(thisaction.statusmsg)
        thisaction.publish()
# 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'] + '\'')

    # Delete offensive sessions 
    pilib.sqlitemultquery(pilib.sessiondatabase, arrayquery)

    # Reload surviving sessions and summarize
    sessions = pilib.readalldbrows(pilib.sessiondatabase, 'sessions')
    sessiondictarray = []
    for session in sessions:
#!/usr/bin/env python

__author__ = "Colin Reese"
__copyright__ = "Copyright 2014, Interface Innovations"
__credits__ = ["Colin Reese"]
__license__ = "Apache 2.0"
__version__ = "1.0"
__maintainer__ = "Colin Reese"
__email__ = "*****@*****.**"
__status__ = "Development"

import pilib

# Read database to get our actions

actiondicts = pilib.readalldbrows(pilib.controldatabase, 'actions')

for actiondict in actiondicts:
    alert = False

    thisaction = pilib.action(actiondict)
    thisaction.statusmsg = ''
    # process condition
    if thisaction.conditiontype == 'dbvalue':
        if thisaction.enabled:
            thisaction.statusmsg += 'Action enabled.'

            dbpath = getattr(pilib, thisaction.database + 'database')

            # variablename is columnname for dbvalue conditiontype
            thisaction.variablevalue = pilib.getsinglevalue(dbpath, thisaction.tablename, thisaction.variablename, 'rowid=' + str(thisaction.rowid))
__license__ = "Apache 2.0"
__version__ = "1.0"
__maintainer__ = "Colin Reese"
__email__ = "*****@*****.**"
__status__ = "Development"

import os
import sys
import math
import pilib
import controllib 
import RPi.GPIO as GPIO
from time import sleep
 
T=True
F=False
GPIO.setmode(GPIO.BCM)

database = '/var/www/data/controldata.db'
logdatabase = '/var/www/data/logdata.db'

# Kill everything

outputs = pilib.readalldbrows(database,'outputs')

for output in outputs:
    GPIO.setup(int(output['GPIO']), GPIO.OUT)    
    GPIO.output(int(output['GPIO']), F)    

print('all outputs disabled')
Beispiel #36
0
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
Beispiel #37
0
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'] + '\'')

    # Delete offensive sessions
    pilib.sqlitemultquery(pilib.sessiondatabase, arrayquery)

    # Reload surviving sessions and summarize
    sessions = pilib.readalldbrows(pilib.sessiondatabase, 'sessions')
    sessiondictarray = []