Exemple #1
0
def resetwlan(interface='wlan0'):
    pilib.log(pilib.networklog, 'Resetting ' + interface + ' . ', 3, pilib.networkloglevel)
    try:
        subprocess.check_output(['/sbin/ifdown', '--force', interface], stderr=subprocess.PIPE)
        subprocess.call(['/sbin/ifup', interface], stderr=subprocess.PIPE)
    except Exception, e:
        pilib.log(pilib.networklog, 'Error resetting ' + interface + ' : ' + str(e), 0, pilib.networkloglevel)
Exemple #2
0
def killapservices():
    pilib.log(pilib.networklog, 'Killing AP Services. ', 1, pilib.networkloglevel)
    try:
        killhostapd()
    except:
        pilib.log(pilib.networklog, 'Error killing hostapd. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Killed hostapd. ', 3, pilib.networkloglevel)

    try:
        killdhcpserver()
    except:
        pilib.log(pilib.networklog, 'Error killing dhcp server. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Successfully killed dhcp server. ', 3, pilib.networkloglevel)
def readhardwarefileintoversions():
    import pilib

    devicefile = '/var/wwwsafe/devicedata'
    try:
        file = open(devicefile)
        lines = file.readlines()
        devicedict = {}
        for line in lines:
            split = line.split(':')
            try:
                devicedict[split[0].strip()] = split[1].strip()
            except:
                pilib.log(pilib.syslog, 'Device data parse error', 1, pilib.sysloglevel)
        pilib.sqlitequery(pilib.systemdatadatabase,
                          pilib.makesqliteinsert('versions', ['hardware', devicedict['hardware']], ['item', 'version']))
    except:
        pilib.log(pilib.syslog, 'Cannot find devicedata file to parse', 1,
                               pilib.sysloglevel)
Exemple #4
0
def runIPTables(mode, flush=True):
    import pilib
    if flush:
        pilib.log(pilib.networklog, 'Flushing IPTables', 2, pilib.networkloglevel)
        flushIPTables()
    if mode == 'eth0wlan0bridge':
        pilib.log(pilib.networklog, 'Running eth0wlan0 bridge IPTables', 2, pilib.networkloglevel)
        runeth0wlan0bridgeIPTables()
    elif mode == 'wlan0wlan1bridge':
        pilib.log(pilib.networklog, 'Running wlan0wlan1 bridge IPTables', 2, pilib.networkloglevel)
        runwlan0wlan1bridgeIPTables()
    elif mode == 'wlan1wlan0bridge':
        pilib.log(pilib.networklog, 'Running wlan1wlan0 bridge IPTables', 2, pilib.networkloglevel)
        runwlan1wlan0bridgeIPTables()
Exemple #5
0
def replaceifaceparameters(iffilein, iffileout, iface, parameternames, parametervalues):
    file = open(iffilein)
    lines = file.readlines()
    writestring = ''
    ifacename = None
    for line in lines:
        if line.find('iface') >= 0 > line.find('default'):
            # we are at an iface stanza beginning
            foundname = line[6:11].strip()
            ifacename = foundname

        if ifacename == iface:
            # do our replace
            for parametername, parametervalue in zip(parameternames, parametervalues):
                if line.find(parametername) > 0:
                    split = line.split(' ')
                    # We find where the parameter is, then assume the value is the
                    # next position. We then trim everything past the parameter
                    # This safeguards against whitespace at the end of lines creating problems.
                    index = split.index(parametername)
                    split[index + 1] = str(parametervalue) + '\n'
                    line = ' '.join(split[0:index + 2])

        writestring += line
    try:
        myfile = open(iffileout, 'w')
    except:
        pilib.log(pilib.networklog, 'Error opening interface file. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Interface file read successfully. ', 3, pilib.networkloglevel)

    try:
        myfile.write(writestring)
    except:
        pilib.log(pilib.networklog, 'Error writing interface file. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Interface file written successfully. ', 3, pilib.networkloglevel)
        pilib.log(pilib.networklog, 'Write string: ' + writestring, 3, pilib.networkloglevel)
Exemple #6
0
def getwpasupplicantconfig(conffile='/etc/wpa_supplicant/wpa_supplicant.conf'):
    class data():
        pass

    file = open(conffile)
    lines = file.readlines()
    header = ''
    tail = ''
    datalines = []
    readheader = True
    readbody = False
    readtail = False
    for line in lines:
        if readheader:
            header = header + line
        if '}' in line:
            pilib.log(pilib.networklog, 'Ending supplicant parse. ', 5, pilib.networkloglevel)
            readbody = False
            readtail = True
        if readbody:
            datalines.append(line)
        if readtail:
            tail = tail + line
        if '{' in line:
            pilib.log(pilib.networklog, 'Beginning supplicant parse. ', 5, pilib.networkloglevel)
            readheader = False
            readbody = True

    datadict = {}
    for line in datalines:
        split = line.split('=')
        datadict[split[0].strip()] = split[1].strip()

    returndict = data()
    returndict.header = header
    returndict.tail = tail
    returndict.data = datadict
    return returndict
def watchdoghamachi(pingip):
    from netfun import runping, restarthamachi, killhamachi
    import pilib
    try:
        # Turns out this is not going to work, as when it hangs, it hangs hard
        # hamachistatusdata = gethamachistatusdata()

        # So instead, we are going to test with a ping to another member on the network that
        # should always be online. This of course means that we have to make sure that it is, in fact, always
        # online

        pingtimes = runping(pingip, numpings=5)
        pingmax = max(pingtimes)
        pingmin = min(pingtimes)
        pingave = sum(pingtimes)/len(pingtimes)

        # if hamachistatusdata['status'] not in ['logged in']:
        if pingave == 0 or pingave > 3000:
            pilib.log(pilib.networklog, 'Pingtime unacceptable: ' + str(pingave) + '. ', 1, pilib.networkloglevel)
            pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'hamachistatus', 0)
            pilib.log(pilib.networklog, 'Restarting Hamachi. ', 1, pilib.networkloglevel)

            killhamachi()
            restarthamachi()
        else:
            if pingmax > 3000 or pingmin <= 0:
                pilib.log(pilib.syslog, 'Hamachi lives, with issues: ' + str(pingtimes), 3, pilib.sysloglevel)
            else:
                pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'hamachistatus', 1)
                pilib.log(pilib.networklog, 'Hamachi appears fine. ', 3, pilib.networkloglevel)

    except Exception as e:
        pilib.log(pilib.networklog, 'Error checking Hamachi with message:  ' + e.message, 1, pilib.networkloglevel)

        killhamachi()
        restarthamachi()
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)
def processapoverride(pin):
    pilib.log(pilib.networklog, "Reading GPIO override on pin " + str(pin) + '. ', 3, pilib.networkloglevel)
    pilib.log(pilib.syslog, "Reading GPIO override on pin " + str(pin) + '. ', 2, pilib.sysloglevel)

    import RPi.GPIO as GPIO
    import pilib

    try:
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    except:
        pilib.log(pilib.networklog, "Error reading GPIO", 3, pilib.networkloglevel)
    else:
        # jumper in place = input off, --> AP mode
        if not GPIO.input(pin):
            pilib.log(pilib.networklog, "GPIO On. Setting AP Mode.", 3, pilib.networkloglevel)
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'ap')
Exemple #10
0
def startapservices(interface='wlan0'):
    from time import sleep
    try:
        # We name the file by the interfae. This way when we pgrep, we know we're running AP on the right interface
        hostapdfilename = '/etc/hostapd/hostapd' + interface + '.conf'
        updatehostapd(path=hostapdfilename, interface=interface)
        subprocess.call(['/usr/sbin/hostapd', '-B', hostapdfilename])
    except:
        pilib.log(pilib.networklog, 'Error starting hostapd. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Started hostapd without error. ', 3, pilib.networkloglevel)

    sleep(1)

    try:
        updatedhcpd(path='/etc/dhcp/dhcpd.conf', interface=interface)
        subprocess.call(['/usr/sbin/service', 'isc-dhcp-server', 'start'])
    except:
        pilib.log(pilib.networklog, 'Error starting dhcp server. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Started dhcp server without error. ', 3, pilib.networkloglevel)
Exemple #11
0
def setapmode(interface='wlan0', netconfig=None):
    pilib.log(pilib.networklog, 'Setting ap mode for interface ' + interface, 1, pilib.networkloglevel)
    try:
        if interface == 'wlan0':
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.ap', '/etc/network/interfaces'])
        elif interface == 'wlan0wlan1':
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.wlan0dhcp.wlan1cupidwifi', '/etc/network/interfaces'])
        elif interface == 'wlan1wlan0':
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.wlan1dhcp.wlan0cupidwifi', '/etc/network/interfaces'])
    except:
        pilib.log(pilib.networklog, 'Error copying network configuration file. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Copied network configuration file successfully. ', 3, pilib.networkloglevel)

    killapservices()
    resetwlan()
    startapservices(interface)
Exemple #12
0
def writesupplicantfile(filedata, filepath='/etc/wpa_supplicant/wpa_supplicant.conf'):
    writestring = ''

    supplicantfilepath = '/etc/wpa_supplicant/wpa_supplicant.conf'
    # We are hard-coding this, as this will unfortunately propagate a mangled file
    subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/wpa_supplicant.conf', supplicantfilepath])

    # iterate over fed data
    ssid = 'not found'
    psk = 'not found'
    for key, value in filedata.data.items():
        if key == 'ssid':
            ssid=value
        elif key == 'psk':
            psk = value

    file = open(supplicantfilepath)
    lines = file.readlines()
    writestring = ''
    ifacename = None
    for line in lines:
        if line.find('psk=') >= 0:
            # insert our iface parameters
            try:
                writestring +='psk=' + psk + '\n'
            except:
                writestring +='psk=error'
        elif line.find('ssid=') >= 0:
            # insert our iface parameters
            try:
                writestring +='ssid=' + ssid + '\n'
            except:
                writestring +='psk=error'
        else:
            writestring += line

    pilib.log(pilib.networklog, 'Writing supplicant file. ', 1, pilib.networkloglevel)
    try:
        myfile = open(filepath, 'w')
        myfile.write(writestring)
    except:
        pilib.log(pilib.networklog, 'Error writing supplicant file. ', 1, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Supplicant file written. ', 3, pilib.networkloglevel)
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)
def updatenetstatus(lastnetstatus=None):
    import pilib
    import time
    import subprocess
    from netfun import getifacestatus, getwpaclientstatus, getifconfigstatus

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

    """ We get last netstatus so that we can save last online times, previous online status, etc. """

    if not lastnetstatus:
        try:
            lastnetstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
        except:
            pilib.log(pilib.syslog, 'Error reading netstatus. Attempting to recreate netstatus table with default values. ', 1, pilib.networkloglevel)
            try:
                pilib.emptyandsetdefaults(pilib.systemdatadatabase, 'netstatus')
                lastnetstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
            except:
                pilib.log(pilib.syslog, 'Error recreating netstatus. ', 1, pilib.networkloglevel)

    """ Pyiface is one way to read some iface data, but it doesn't always appear to show all interfaces(?!)
        So we wrote our own instead. A work in progress but quite functional at the moment. """

    pilib.log(pilib.networklog, 'Reading ifaces with ifconfig status. ', 4, pilib.networkloglevel)
    ifacesdictarray = getifconfigstatus()
    # ifacesdictarray = getifacestatus()

    """ We supplement with wpa status on the wlan interfaces """

    updateddictarray = []
    for interface in ifacesdictarray:
        if interface['name'].find('wlan') >= 0:
            interface['wpastate'] = pilib.dicttojson(getwpaclientstatus(interface['name']))
        else:
            interface['wpastate'] = ''
        updateddictarray.append(interface)
    ifacesdictarray = updateddictarray

    """ Then write it to the table """

    if ifacesdictarray:
        pilib.log(pilib.networklog, 'Sending ifaces query. ', 5, pilib.networkloglevel)
        # print(ifacesdictarray)
        pilib.insertstringdicttablelist(pilib.systemdatadatabase, 'netifaces', ifacesdictarray)
    else:
        pilib.log(pilib.networklog, 'Empty ifaces query. ', 2, pilib.networkloglevel)

    pilib.log(pilib.networklog, 'Completed pyiface ifaces. ', 4, pilib.networkloglevel)

    """ Now we check to see if we can connect to WAN """

    pilib.log(pilib.networklog, 'Checking pingtimes. ', 4, pilib.networkloglevel)
    okping = float(netconfigdata['pingthreshold'])

    from netfun import runping

    netstatusdict = {}

    querylist=[]
    pingresults = runping('8.8.8.8')

    # pingresults = [20, 20, 20]
    pingresult = sum(pingresults) / float(len(pingresults))

    if pingresult == 0:
        wanaccess = 0
        latency = 0
    else:
        if pingresult < okping:
            wanaccess = 1
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccess', 1)
            if lastnetstatus['WANaccess'] == 0 or not lastnetstatus['onlinetime']:
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'onlinetime', pilib.gettimestring())

        else:
            wanaccess = 0
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccess', 0)
            if lastnetstatus['WANaccess'] == 1 or not lastnetstatus['offlinetime']:
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'offlinetime', pilib.gettimestring())

        latency = pingresult

    # we set all the values here, so when we retreive it we get changed and also whatever else happens to be there.
    pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'latency', latency)
    updatetime = pilib.gettimestring()
    pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'updatetime', updatetime)
    pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccess', wanaccess)

    pilib.log(pilib.networklog, 'Done checking pings. ', 4, pilib.networkloglevel)

    if netconfigdata['netstatslogenabled']:
        # print('going to log stuff')
        pilib.logtimevaluedata(pilib.logdatabase, 'system_WANping', time.time(), pingresult, 1000,
                               netconfigdata['netstatslogfreq'])

    #This is kinda ugly. Should be fixed.
    # netstatusdict = {'WANaccess':wanaccess, 'latency': latency, 'updatetime': updatetime}
    netstatusdict = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]

    return {'netstatusdict': netstatusdict, 'ifacesdictarray': ifacesdictarray, 'netconfigdata':netconfigdata}
Exemple #15
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:
        ssid = 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)

    if ssid:
        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)
Exemple #16
0
    sleep(1)

    # Refresh after set
    itemstatuses = findprocstatuses(pilib.daemonprocs)
    for item in pilib.daemonprocs:
        index = pilib.daemonprocs.index(item)
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1')
        else:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0')

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(bool(enabled)) + ' Status: ' + str(status) + '. '
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus','systemmessage', systemstatusmsg)

    # Rotate all logs
    pilib.rotatelogs(pilib.networklog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.syslog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.iolog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.controllog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.daemonlog, pilib.numlogs, pilib.maxlogsize)

if __name__ == "__main__":
    from pilib import log, daemonlog, daemonloglevel
    log(daemonlog, 'Running daemon.', 1, daemonloglevel)
    rundaemon()
    log(daemonlog, 'Daemon complete.',1,daemonloglevel)
Exemple #17
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)
Exemple #18
0
def processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids, previnputs, previnputids, defaults, logconfig, **kwargs):

    import pilib

    if 'method' in kwargs:
        method = kwargs['method']
    else:
        method = 'pigpio'

    if method == 'rpigpio':
        import RPi.GPIO as GPIO
    elif method == 'pigpio':
        import pigpio

    try:
        if method == 'rpigpio':
            GPIO.setmode(GPIO.BCM)
            GPIO.setwarnings(False)
        elif method == 'pigpio':
            if 'piobject' in kwargs:
                pilib.log(pilib.iolog,
                       'Pigpio object already exists. ', 4, logconfig['iologlevel'])
                pi = kwargs['piobject']
            else:
                pilib.log(pilib.iolog,
                       'Instantiating pigpio. ', 4, logconfig['iologlevel'])
                pi = pigpio.pi()
    except:
        pilib.log(pilib.iolog,
                       'Error setting up GPIO. ', 1, logconfig['iologlevel'])
    else:
        pilib.log(pilib.iolog,
                       'Done setting up GPIO. ', 4, logconfig['iologlevel'])

    options = pilib.parseoptions(interface['options'])
    address = int(interface['address'])

    pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' enabled', 4, logconfig['iologlevel'])
    # Get name from ioinfo table to give it a colloquial name
    gpioname = pilib.sqlitedatumquery(pilib.controldatabase, 'select name from ioinfo where id=\'' + interface['id'] + '\'')
    polltime = pilib.gettimestring()

    querylist = []
    # Append to inputs and update name, even if it's an output (can read status as input)
    if options['mode'] == 'output':
        pilib.log(pilib.iolog, 'Setting output mode for GPIO address' + str(address), 3, logconfig['iologlevel'])
        try:
            if method == 'rpigpio':
                GPIO.setup(address, GPIO.OUT)
            elif method == 'pigpio':
                pi.set_mode(address, pigpio.OUTPUT)

        except TypeError:
            pilib.log(pilib.iolog, 'You are trying to set a GPIO with the wrong variable type : ' +
                                                str(type(address)), 0, logconfig['iologlevel'])
            pilib.log(pilib.iolog, 'Exiting interface routine for  ' + interface['id'], 0, logconfig['iologlevel'])
            return
        except:
            pilib.log(pilib.iolog, 'Error setting GPIO : ' +
                                                str(address), 1, logconfig['iologlevel'])
            pilib.log(pilib.iolog, 'Exiting interface routine for  ' + interface['id'], 0, logconfig['iologlevel'])
            return

        # Set the value of the gpio.
        # Get previous value if exists
        if interface['id'] in prevoutputids:
            value = prevoutputvalues[prevoutputids.index(interface['id'])]

        else:
            value = 0
        if value == 1:
            if method == 'rpigpio':
                GPIO.output(address, True)
            elif method == 'pigpio':
                pi.write(address, 1)
            pilib.log(pilib.iolog, 'Setting output ON for GPIO address' + str(address), 3,
                                   logconfig['iologlevel'])
        else:
            if method == 'rpigpio':
                GPIO.output(address, False)
            elif method == 'pigpio':
                pi.write(address,0)
            pilib.log(pilib.iolog, 'Setting output OFF for GPIO address' + str(address), 3,
                                   logconfig['iologlevel'])

        # Get output settings and keep them if the GPIO previously existed
        if interface['id'] in prevoutputids:
            pollfreq = prevoutputs[prevoutputids.index(interface['id'])]['pollfreq']
            ontime = prevoutputs[prevoutputids.index(interface['id'])]['ontime']
            offtime = prevoutputs[prevoutputids.index(interface['id'])]['offtime']
        else:
            try:
                pollfreq = defaults['defaultoutputpollfreq']
            except:
                pollfreq = 60
            ontime = ''
            offtime = ''

        # Add entry to outputs tables
        querylist.append('insert into outputs values (\'' + interface['id'] + '\',\'' +
                         interface['interface'] + '\',\'' + interface['type'] + '\',\'' + str(
            address) + '\',\'' +
                         gpioname + '\',\'' + str(value) + "','','" + str(polltime) + '\',\'' +
                         str(pollfreq) + "','" + ontime + "','" + offtime + "')")
    elif options['mode'] == 'input':
        if method == 'rpigpio':
            GPIO.setup(address, GPIO.IN)
        elif method == 'pigpio':
            if 'pullupdown' in options:
                if options['pullupdown'] == 'pullup':
                    pi.set_pull_up_down(address, pigpio.PUD_UP)
                elif options['pullupdown'] == 'pulldown':
                    pi.set_pull_up_down(address, pigpio.PUD_DOWN)
                else:
                    pi.set_pull_up_down(address, pigpio.PUD_OFF)
            else:
                pi.set_pull_up_down(17, pigpio.PUD_OFF)

            pi.set_mode(address, pigpio.INPUT)

        if method == 'rpigpio':
            value = GPIO.input(address)
        elif method == 'pigpio':
            value = pi.read(address)

        if 'function' in options:
            if options['function'] == 'shutdown':
                # TODO : The reboot function is still held in a shell script, because it works.
                if 'functionstate' in options:
                    if value == 1 and options['functionstate'] in ['true', 'On', 'True', '1']:
                        from systemstatus import processsystemflags
                        processsystemflags()

        pilib.log(pilib.iolog, 'Setting input mode for GPIO address' + str(address), 3,
                               logconfig['iologlevel'])

        # Get input settings and keep them if the GPIO previously existed
        if interface['id'] in previnputids:
            pollfreq = previnputs[previnputids.index(interface['id'])]['pollfreq']
            ontime = previnputs[previnputids.index(interface['id'])]['ontime']
            offtime = previnputs[previnputids.index(interface['id'])]['offtime']
            pilib.log(pilib.iolog,
                                   'Restoring values from previous inputids: pollfreq = ' + str(
                                       pollfreq) + ' ontime = ' + str(ontime) + ' offtime = ' + str(
                                       offtime), 3, logconfig['iologlevel'])

        else:
            try:
                pollfreq = defaults['defaultinputpollfreq']
            except:
                pollfreq = 60
            ontime = ''
            offtime = ''
            pilib.log(pilib.iolog,
                                   'Setting values to defaults, defaultinputpollfreq = ' + str(
                                       pollfreq), 3, logconfig['iologlevel'])
    querylist.append(
        'insert into inputs values (\'' + interface['id'] + '\',\'' + interface['interface'] + '\',\'' +
        interface['type'] + '\',\'' + str(address) + '\',\'' + gpioname + '\',\'' + str(
            value) + "','','" +
        str(polltime) + '\',\'' + str(pollfreq) + "','" + ontime + "','" + offtime + "')")

    if method == 'pigpio' and 'piobject' not in kwargs:
        pi.stop()

    return querylist
Exemple #19
0
def runconfig(onboot=False):
    import subprocess
    try:
        netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0]
        # print(netconfigdata)
    except:
        pilib.log(pilib.networklog, 'Error reading netconfig data. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Successfully read netconfig data', 3, pilib.networkloglevel)

        pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', netconfigdata['mode'])

        pilib.log(pilib.networklog, 'Netconfig is enabled', 3, pilib.networkloglevel)

        # This will grab the specified SSID and the credentials and update
        # the wpa_supplicant file
        updatewpasupplicant()

        # Copy the correct interfaces file
        if netconfigdata['mode'] == 'station':
            setstationmode(netconfigdata)
        elif netconfigdata['mode'] in ['ap', 'tempap', 'eth0wlan0bridge']:
            pilib.log(pilib.networklog, 'Setting eth0wlan0 bridge (or bare ap mode). ', 0, pilib.networkloglevel)
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.ap', '/etc/network/interfaces'])
            killapservices()
            resetwlan()
            startapservices('wlan0')

        # All of these require ipv4 being enabled in /etc/sysctl.conf
        # First interface is DHCP, second is CuPIDwifi
        elif netconfigdata['mode'] == 'wlan0wlan1bridge':
            pilib.log(pilib.networklog, 'Setting wlan0wlan1 bridge', 0, pilib.networkloglevel)
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.wlan0dhcp.wlan1cupidwifi', '/etc/network/interfaces'])
            killapservices()
            resetwlan('wlan0')
            resetwlan('wlan1')
            startapservices('wlan1')

        elif netconfigdata['mode'] == 'wlan1wlan0bridge':
            pilib.log(pilib.networklog, 'Setting wlan1wlan0 bridge', 0, pilib.networkloglevel)
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.wlan1dhcp.wlan0cupidwifi', '/etc/network/interfaces'])
            killapservices()
            resetwlan('wlan0')
            resetwlan('wlan1')
            startapservices('wlan0')

        runIPTables(netconfigdata['mode'])
Exemple #20
0
def updatewpasupplicantOLD(interface='wlan0'):
    # print('I AM UPDATING SUPPLICANT DATA')
    try:
        suppdata = getwpasupplicantconfig()
    except:
        pilib.log(pilib.networklog, 'Error getting supplicant data. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Supplicant data retrieved successfully. ', 3, pilib.networkloglevel)

    try:
        updateddata = updatesupplicantdata(suppdata)
    except:
        pilib.log(pilib.networklog, 'Error updating supplicant data. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Supplicant data retrieved successfully. ', 3, pilib.networkloglevel)

    try:
        writesupplicantfile(updateddata)
    except:
        pilib.log(pilib.networklog, 'Error writing supplicant data. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Supplicant data written successfully. ', 3, pilib.networkloglevel)
Exemple #21
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))
Exemple #22
0
def updatesupplicantdata(configdata):
    from pilib import readalldbrows, safedatabase, systemdatadatabase

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

    try:
        wirelessauths = readalldbrows(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)

    password = ''

    pilib.log(pilib.networklog, 'Netconfig data: ' + str(netconfig), 2, pilib.networkloglevel)

    # we only update if we find the credentials
    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)
            configdata.data['psk'] = password
            configdata.data['ssid'] = ssid
    return configdata
Exemple #23
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
Exemple #24
0
def setstationmode(netconfigdata=None):
    pilib.log(pilib.networklog, 'Setting station mode. ', 3, pilib.networkloglevel)

    from time import sleep
    if not netconfigdata:
        pilib.log(pilib.networklog, 'Retrieving unfound netconfig data. ', 3, pilib.networkloglevel)
        try:
            netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0]
        except:
            pilib.log(pilib.networklog, 'Error reading netconfig data. ', 0, pilib.networkloglevel)
        else:
            pilib.log(pilib.networklog, 'Read netconfig data. ', 4, pilib.networkloglevel)

    killapservices()
    if netconfigdata['addtype'] == 'static':
        pilib.log(pilib.networklog, 'Configuring static address. ', 3, pilib.networkloglevel)

        subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.sta.static', '/etc/network/interfaces'])

        # update IP from netconfig
        pilib.log(pilib.networklog, 'Updating netconfig with ip ' + netconfigdata['address'], 3, pilib.networkloglevel)
        replaceifaceparameters('/etc/network/interfaces', '/etc/network/interfaces', 'wlan0', ['address', 'gateway'],
                               [netconfigdata['address'], netconfigdata['gateway']])
    elif netconfigdata['addtype'] == 'dhcp':
        pilib.log(pilib.networklog, 'Configuring dhcp. ', 3, pilib.networkloglevel)
        subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.sta.dhcp', '/etc/network/interfaces'])

    pilib.log(pilib.networklog, 'Resetting wlan. ', 3,pilib.networkloglevel)
    resetwlan()
    sleep(1)
    resetwlan()
# specified interval, sends to log, channels and plot dbs

# TODO: Update to include better logging

import pilib
import updateio
from time import sleep

readtime = 10  # default, seconds

# Read from systemstatus to make sure we should be running
updateioenabled = pilib.getsinglevalue(pilib.controldatabase, 'systemstatus', 'updateioenabled')

while updateioenabled:

    pilib.log(pilib.iolog, 'Running periodicupdateio', 3, pilib.iologlevel)
    pilib.log(pilib.syslog, 'Running periodicupdateio', 3, pilib.sysloglevel)

    # Set last run time
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'lastinputpoll', pilib.gettimestring())
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'updateiostatus', '1')

    # Read and record everything as specified in controldatabase
    # Update database of inputs with read data

    # DEBUG
    runupdate = True
    if runupdate:
        reply = updateio.updateiodata(pilib.controldatabase)
    else:
        pilib.log(pilib.iolog,'DEBUG: Update IO disabled', 1, pilib.iologlevel)
                runconfig=True

    elif netconfigdata['mode'] == 'wlan0wlan1bridge' or 'wlan1wlan0bridge':
        if netconfigdata['mode'] == 'wlan0wlan1bridge':
            stationinterface = 'wlan0'
            apinterface = 'wlan1'
        else:
            stationinterface = 'wlan1'
            apinterface = 'wlan0'
        runconfig = False

        # Check station address (not yet implemented) and wpa status (implemented)
        try:
            stationifacedata = ifacedict[stationinterface]
        except KeyError:
            pilib.log(pilib.networklog, 'No stationiface data(' + stationinterface + ') present for mode ' + netconfigdata['mode'], 1, pilib.networkloglevel)
            statusmsg += 'No stationiface data(' + stationinterface + ') present for mode ' + netconfigdata['mode']
            runconfig = True
        else:
            wpadata = pilib.parseoptions(stationifacedata['wpastate'])
            if wpadata['wpa_state'] == 'COMPLETED':
                pilib.log(pilib.networklog, 'station interface ' + stationinterface + ' wpastatus appears ok. ', 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'station interface for ' + stationinterface + ' does not appear ok judged by wpa_state. ', 1, pilib.networkloglevel)
                statusmsg += 'station interface does not appear ok judged by wpa_state. '
                runconfig = True

        # Check wlan1 dhcp and hostapd status
        try:
            apifacedata = ifacedict[apinterface]
        except KeyError:
Exemple #27
0
def setrawspilights(enabledlists, CS=1, **kwargs):

    from pilib import log, syslog, sysloglevel

    if "method" in kwargs:
        method = kwargs["method"]
    else:
        method = "spidev"

    # Notes:
    # Low is on. Cathodes are open drain.
    # This unforunately means we need to initialize
    # to off on start-up. not a huge deal

    spiassignments = []
    for enabledlist in enabledlists:
        bytesum = 0
        for index, bit in enumerate(enabledlist):
            bytesum += bit * (2 ** index)

        spiassign = 255 - bytesum
        spiassignments.append(spiassign)

    resp = []
    if method == "spidev":
        try:
            import spidev
        except ImportError:
            log(syslog, "You have not installed the spidev python package. Exiting.", 0, sysloglevel)
            exit
        else:
            spi = spidev.SpiDev()
        try:
            spi.open(0, CS)  # Port 0, CS1
            spi.max_speed_hz = 50000
        except:
            log(syslog, "Error raised on spi open. exiting.", 0, sysloglevel)
            exit
        else:

            # Transfer bytes
            # print('spi assignments')
            # print(spiassignments)
            resp = spi.xfer2(spiassignments)
            # resp = spi.xfer2(spiassignments)

    elif method == "pigpio":
        import pigpio
        import array

        if "piobject" in kwargs:
            pi = kwargs["piobject"]
        else:
            pi = pigpio.pi()

        handle = pi.spi_open(0, 50000, 0)

        resp = pi.spi_write(handle, array.array(spiassignments).tostring())
        print(resp)

    if method == "pigpio" and "piobject" not in kwargs:
        pi.stop()

    return resp
def watchdognetstatus(allnetstatus=None):
    import pilib
    import netconfig
    import subprocess
    from cupiddaemon import pgrepstatus

    """
    And now comes the checking of configuration specific statuses and restarting them if enabled
    and necessary

    NOW
    Set number configuration types:
    eth0 is always dhcp

    if interface is not specified, it is assumed that the specified configuration applies to wlan0
    ap : access point on wlan0.
        Currently, address is hard-coded as 192.168.0.1 as set in hostapd (to have dhcp all on same subnet)
    station : station mode on wlan0
        IP address mode set in 'addtype' field. If DHCP, set as DHCP. If static, set as address field
    eth0wlan0bridge :
        wlan0 set as AP mode with bridge to eth0
    wlan0wlan1bridge :
        wlan0 set as station mode, wlan1 as ap mode with bridge
    wlan1wlan0bridge
        wlan1 set as station mode, wlan0 as ap mode with bridge

    IN THE FUTURE
    netconfigdata will have a row for each interface that needs to be configured.
    Each interface can be either static, dhcp, or ap.
    Each interface can also bridge, but this will be limited at first, due to the number of combinations.
    If bridge is selected, the mode will be checked, and the appropriate IPTables will be set based on which one is AP

    """

    if not allnetstatus:
        allnetstatus = updatenetstatus()

    netconfigdata = allnetstatus['netconfigdata']
    netstatus = allnetstatus['netstatusdict']

    # Refactor ifaces array. We could probably do this earlier and pass it around like this
    ifacedict = {}
    for iface in allnetstatus['ifacesdictarray']:
        # print(iface['name'])
        # print(iface)
        ifacedict[iface['name']] = iface

    # print(ifacedict)

    statusmsg = ''
    currenttime = pilib.gettimestring()

    runconfig = False
    if netconfigdata['mode'] in ['ap', 'tempap']:
        pilib.log(pilib.networklog, 'AP Mode is set. ', 1, pilib.networkloglevel)

        """

        THIS NEEDS TO BE REWRITTEN ( or absorbed into eth0wlan0bridge )

        """

        if netconfigdata['mode'] == 'tempap':
            timesincelastretry = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(netconfigdata['laststationretry'])
            pilib.log(pilib.networklog, 'TempAP mode: Time since last retry:  ' + str(timesincelastretry) + '. Station retry time: '
                                   + str(netconfigdata['stationretrytime']), 1, pilib.networkloglevel)

            if timesincelastretry > netconfigdata['stationretrytime']:
                # We go back to station mode
                statusmsg += 'Time to go back to station mode. '
                pilib.log(pilib.networklog, 'Time to go back to station mode. ', 1, pilib.networkloglevel)
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'station')
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'laststationretry', '')
                netconfig.runconfig()
        else:
            # If we have ap up, do nothing

            if netstatus['dhcpstatus']:
                statusmsg += 'AP checked and ok. '
                pilib.log(pilib.networklog, 'AP checked and ok. ', 1, pilib.networkloglevel)
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', 'ap')
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'SSID', 'cupidwifi')
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'offlinetime', '')

            # If we don't have dhcp up, restart ap mode
            # this will currently cause reboot if we don't set onboot=True
            # We set status message in case we change our minds and reboot here.
            else:
                statusmsg += 'Restarting AP. '
                pilib.log(pilib.networklog, 'Restarting AP mode. ', 1, pilib.networkloglevel)
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'statusmsg', statusmsg)
                netconfig.runconfig()

    #    Station Mode. Again, like above, this should be modular.

    elif netconfigdata['mode'] == 'station':

        pilib.log(pilib.networklog, 'Station mode is set. ', 3, pilib.networkloglevel)

        # Check station address (not yet implemented) and wpa status (implemented)
        stationinterface = 'wlan0'
        try:
            stationifacedata = ifacedict[stationinterface]
        except KeyError:
            pilib.log(pilib.networklog, 'No stationiface data(' + stationinterface + ') present for mode ' + netconfigdata['mode'], 1, pilib.networkloglevel)
            statusmsg += 'No stationiface data(' + stationinterface + ') present for mode ' + netconfigdata['mode']
            runconfig = True
        else:
            wpadata = pilib.parseoptions(stationifacedata['wpastate'])
            if wpadata['wpa_state'] == 'COMPLETED' and stationifacedata['address']:
                pilib.log(pilib.networklog, 'station interface ' + stationinterface + ' wpastatus appears ok with address ' + str(stationifacedata['address']), 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'station interface for ' + stationinterface + ' does not appear ok judged by wpa_state: wpastate = ' + wpadata['wpa_state'] + ' address= ' + stationifacedata['address'], 1, pilib.networkloglevel)
                statusmsg += 'station interface does not appear ok judged by wpa_state. '
                runconfig = True

        # Should do special handling in here to verify address for static mode.

        # # If we have wpa up, do nothing
        # if int(netstatus['connected']):
        #     statusmsg += 'Station wpamode appears ok. '
        #     pilib.log(pilib.networklog, 'wpamode appears ok. ', 1, pilib.networkloglevel)
        #
        # # If wpa is not connected
        # else:
        #     statusmsg += 'Station wpamode appears disconnected. '
        #     pilib.log(pilib.networklog, 'wpamode appears disconnected. ', 1, pilib.networkloglevel)
        #
        #     if netstatus['offlinetime'] == '':
        #         pilib.log(pilib.networklog, 'Setting offline time for empty value. ', 4,
        #                                pilib.networkloglevel)
        #         pilib.setsinglevalue('netstatus', 'offlinetime', pilib.gettimestring())
        #         offlinetime = 0
        #     else:
        #         pilib.log(pilib.networklog, 'Calculating offline time. ', 4, pilib.networkloglevel)
        #         offlinetime = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(
        #             netstatus['offlinetime'])
        #
        #     pilib.log(pilib.networklog, 'wpa has been offline for ' + str(offlinetime) + '. ', 3,
        #                            pilib.networkloglevel)
        #     statusmsg += 'We have been offline for ' + str(offlinetime) + '. '
        #
        #     # If aprevert is aprevert or temprevert and we've been offline long enough, flip over to ap
        #     # then set offline time to now (otherwise this keeps happening)
        #     if netconfigdata['aprevert'] in ['temprevert', 'aprevert'] and offlinetime > netconfigdata[
        #         'apreverttime']:
        #
        #         # set laststationretry to currenttime. This marks when we flipped over to ap
        #         statusmsg += 'Setting last station retry time. '
        #         pilib.log(pilib.networklog, 'Reverting to AP mode', 3, pilib.networkloglevel)
        #         pilib.log(pilib.networklog,
        #                                'Setting last station retry time to ' + str(currenttime), 0,
        #                                pilib.networkloglevel)
        #         pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'laststationretry', currenttime)
        #         pilib.setsinglevalue('netstatus', 'offlinetime', currenttime)
        #
        #         if netconfigdata['aprevert'] == 'aprevert':
        #             # set mode to ap
        #             statusmsg += 'Setting mode to ap. '
        #             pilib.log(pilib.networklog, 'Setting mode to ap ' + str(currenttime), 3,
        #                                    pilib.networkloglevel)
        #             pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'ap')
        #         elif netconfigdata['aprevert'] == 'temprevert':
        #             # set mode to tempap
        #             statusmsg += 'Setting mode to tempap. '
        #             pilib.log(pilib.networklog, 'Setting mode to tempap ' + str(currenttime), 3,
        #                                    pilib.networkloglevel)
        #             pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'tempap')
        #
        #         # Unfortunately, to revert to ap mode successfully, we currently have to reboot
        #         # this is built into the netconfig script - any time you set ap mode except at boot, it reboots
        #         pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'statusmsg', statusmsg)
        #         pilib.log(pilib.syslog, 'Running netconfig . ', 4,
        #                                pilib.sysloglevel)
        #         netconfig.runconfig()
        #     elif offlinetime > 15:
        #         pilib.log(pilib.syslog, 'Restarting netconfig on bad wpastatus', 1,
        #                                pilib.sysloglevel)
        #         runconfig = True
        #
        #     # Here, we need to check the ifaces address. Netstatus address is ambiguous
        #     if netstatus['ip_address'] != netconfigdata['address']:
        #         pilib.log(pilib.networklog, 'IP address mismatch ( Configured for ' + netconfigdata['address'] + '. Reporting' + netstatus['ip_address'] + ' ). Running config.', 1, pilib.networkloglevel)
        #         runconfig = True
        #     else:
        #         pilib.log(pilib.networklog, 'IP address match for ' + netconfigdata['address'] + '. ', 3, pilib.networkloglevel)

    elif netconfigdata['mode'] == 'eth0wlan0bridge':

        # We don't actually check eth0. This is because we shouldn't have to. Also, if we don't check on eth0, we can
        # use the same mode for wlan0 AP and eth0wlan0 bridge. Hot plug, works fine.

        # Check wlan0 dhcp and hostapd status
        try:
            wlan0ifacedata =ifacedict['wlan0']
        except KeyError:
            pilib.log(pilib.networklog, 'No wlan0 data present in configuration of eth0wlan0bridge. ', 1, pilib.networkloglevel)
            statusmsg += 'wlan0 data is not present. '
            runconfig = True
        else:
            pilib.log(pilib.networklog, 'Checking dhcp server status on wlan0. ', 4, pilib.networkloglevel)
            try:
                result = subprocess.check_output(['/usr/sbin/service', 'isc-dhcp-server', 'status'], stderr=subprocess.PIPE)
            except Exception, e:
                # If not running, the subprocess call will throw an error
                pilib.log(pilib.networklog, 'Error in reading dhcp server status. Assumed down. ', 1, pilib.networkloglevel)
                statusmsg += 'dhcp server appears down. '
                runconfig = True
            else:
                pilib.log(pilib.networklog, 'DHCP server appears to be up. ', 1,  pilib.networkloglevel)

            """ Check ifconfig ipaddress for wlan0
                This should be programmable. """

            if wlan0ifacedata['address'] == '192.168.0.1':
                pilib.log(pilib.networklog, 'wlan0 address is appears to be set properly:  ' + str(wlan0ifacedata['address']), 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'wlan0 address is not set properly:  ' + str(wlan0ifacedata['address']), 1, pilib.networkloglevel)
                statusmsg += 'wlan0 address does not appear ok. '
                runconfig = True

            if pgrepstatus('hostapd.*wlan0')['count'] == 1:
                pilib.log(pilib.networklog, 'hostapd on wlan0 appears to be ok. ', 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'hostapd on wlan0 does NOT appear to be ok. ', 1, pilib.networkloglevel)
                statusmsg += 'wlan0 hostpad does not appear ok. '
                runconfig=True
Exemple #29
0
def rundaemon(startall=False):
    from subprocess import Popen, PIPE
    from time import sleep
    from pilib import log, daemonlog, daemonloglevel

    # Set up list of enabled statuses (whether to restart if
    # we find that the process is not currently running

    picontrolenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select picontrolenabled from systemstatus')
    updateioenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select updateioenabled from systemstatus')
    systemstatusenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select systemstatusenabled from systemstatus')
    sessioncontrolenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select sessioncontrolenabled from systemstatus')
    serialhandlerenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select serialhandlerenabled from systemstatus')


    enableditemlist = [(int(updateioenabled)), (int(picontrolenabled)), int(systemstatusenabled), int(sessioncontrolenabled), int(serialhandlerenabled)]

    itemstatuses = findprocstatuses(pilib.daemonprocs)

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. '
        if pilib.daemonloglevel > 0:
            pilib.log(pilib.daemonlog, name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. ')

    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'systemmessage', systemstatusmsg)

    # Set up list of itemnames in the systemstatus table that
    # we assign the values to when we detect if the process
    # is running or not

    statustableitemnames = ['updateiostatus', 'picontrolstatus', 'systemstatusstatus', 'sessioncontrolstatus', 'serialhandlerstatus']

    for index, item in enumerate(pilib.daemonprocs):
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1')
            if pilib.daemonloglevel > 0:
                pilib.log(pilib.daemonlog, 'Process is running: ' + pilib.baselibdir + pilib.daemonprocs[index])
        else:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0')
            if pilib.daemonloglevel > 0:
                pilib.log(pilib.daemonlog, 'Process is not running: ' + pilib.baselibdir + pilib.daemonprocs[index])

            # run if set to enable
            if enableditemlist[index]:
                # print(pilib.baselibdir + pilib.daemonprocs[index])
                if pilib.daemonloglevel > 0:
                    pilib.log(pilib.daemonlog, 'Starting ' + pilib.baselibdir + pilib.daemonprocs[index])
                procresult = Popen([pilib.baselibdir + pilib.daemonprocs[index]], stdout=PIPE, stderr=PIPE)
                # if pilib.daemonloglevel > 0:
                #     pilib.writedatedlogmsg(pilib.daemonproclog, procresult.stdout.read())

    sleep(1)

    # Refresh after set
    itemstatuses = findprocstatuses(pilib.daemonprocs)
    for item in pilib.daemonprocs:
        index = pilib.daemonprocs.index(item)
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1')
        else:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0')

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(bool(enabled)) + ' Status: ' + str(status) + '. '
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus','systemmessage', systemstatusmsg)

    # Rotate all logs
    pilib.rotatelogs(pilib.networklog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.syslog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.iolog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.controllog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.daemonlog, pilib.numlogs, pilib.maxlogsize)
Exemple #30
0
        pilib.log(pilib.networklog, 'Copied network configuration file successfully. ', 3, pilib.networkloglevel)

    killapservices()
    resetwlan()
    startapservices(interface)


def resetwlan(interface='wlan0'):
    pilib.log(pilib.networklog, 'Resetting ' + interface + ' . ', 3, pilib.networkloglevel)
    try:
        subprocess.check_output(['/sbin/ifdown', '--force', interface], stderr=subprocess.PIPE)
        subprocess.call(['/sbin/ifup', interface], stderr=subprocess.PIPE)
    except Exception, e:
        pilib.log(pilib.networklog, 'Error resetting ' + interface + ' : ' + str(e), 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Completed resetting '+ interface + '. ', 3, pilib.networkloglevel)


def runconfig(onboot=False):
    import subprocess
    try:
        netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0]
        # print(netconfigdata)
    except:
        pilib.log(pilib.networklog, 'Error reading netconfig data. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Successfully read netconfig data', 3, pilib.networkloglevel)

        pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', netconfigdata['mode'])

        pilib.log(pilib.networklog, 'Netconfig is enabled', 3, pilib.networkloglevel)