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()
def updatedhcpd(path='/etc/dhcp/dhcpd.conf', interface='wlan0', gateway='192.168.0.1', dhcpstart='192.168.0.70', dhcpend='192.168.0.99'): try: netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0] dhcpstart = netconfigdata['dhcpstart'] dhcpend = netconfigdata['dhcpend'] gateway = netconfigdata['gateway'] except: print('we had an error') pass myfile = open(path, 'w') try: subnet = '.'.join(gateway.split['.'][:-1]) + '.0' except: subnet = '192.168.0.0' filestring = 'ddns-update-style none;\noption domain-name "example.org";\n' filestring += 'option domain-name-servers ns1.example.org, ns2.example.org;\n' filestring += 'default-lease-time 600;\nmax-lease-time 7200;\nauthoritative;\nlog-facility local7;\n' filestring += 'subnet ' + subnet + ' netmask 255.255.255.0 {\n' filestring += 'range ' + dhcpstart + ' ' + dhcpend + ';\n' filestring += ' option domain-name-servers 8.8.8.8, 8.8.4.4;\n option routers ' + gateway + ';\n' filestring += ' interface ' + interface + ';\n}' myfile.write(filestring)
def updatewpasupplicant(path='/etc/wpa_supplicant/wpa_supplicant.conf'): netconfig = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0] try: wirelessauths = pilib.readalldbrows(pilib.safedatabase, 'wireless') except: pilib.log(pilib.networklog, 'Error reading wireless data. ', 0, pilib.networkloglevel) else: pilib.log(pilib.networklog, 'Read wireless data. ', 4, pilib.networkloglevel) psk = '' ssid = '' # we only update if we find the credentials try: ourssid = netconfig['SSID'] except KeyError: pilib.log(pilib.syslog, 'No SSID found in netconfig. Finding first in wireless', 1, pilib.sysloglevel) # try to attach to first network by setting SSID to first network in wireless auths # this can help alleviate some headaches down the line, hopefully wirelessauths = pilib.readalldbrows(pilib.safedatabase, 'wireless') try: defaultauths = wirelessauths[0] currssid = defaultauths['SSID'] except: pilib.log(pilib.syslog, 'No SSID in wireless table to default to. ', 1, pilib.sysloglevel) currssid = '' if currssid: for auth in wirelessauths: if auth['SSID'] == netconfig['SSID']: password = auth['password'] ssid = auth['SSID'] pilib.log(pilib.networklog, 'SSID ' + auth['SSID'] + 'found. ', 1, pilib.networkloglevel) psk = password ssid = ssid if psk: myfile = open(path, 'w') filestring = 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n\n' filestring += 'network={\n' filestring += 'psk="' + psk + '"\n' filestring += 'ssid="' + ssid + '"\n' filestring += 'proto=RSN\nauth_alg=OPEN\npairwise=CCMP\nkey_mgmt=WPA-PSK\n}' myfile.write(filestring) else: pilib.log(pilib.networklog, 'No auths recovered for SSID, so not writing wpa_supplicant', 1, pilib.networkloglevel) else: pilib.log(pilib.networklog, 'No SSID found to write, so not writing wpa_supplicant', 1, pilib.networkloglevel)
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'])
def updatehostapd(path='/etc/hostapd/hostapd.conf', interface='wlan0'): try: apsettings = pilib.readonedbrow(pilib.safedatabase, 'apsettings')[0] SSID = apsettings['SSID'] password = apsettings['password'] except: SSID = 'cupidwifi' password = '******' # print(SSID) myfile = open(path, 'w') filestring = 'interface=' + interface + '\n' filestring += 'driver=rtl871xdrv\nssid=' filestring += SSID filestring += '\nchannel=6\nwmm_enabled=1\nwpa=1\nwpa_passphrase=' + password + '\nwpa_key_mgmt=WPA-PSK\n' filestring += 'wpa_pairwise=TKIP\nrsn_pairwise=CCMP\nauth_algs=1\nmacaddr_acl=0' myfile.write(filestring)
#print("reading input") # Read again, once inside each loop so we terminate if the # variable name is changed inputsreadenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select inputsreadenabled from systemstatus') # Set last run time pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set lastinputspoll=\'' + pilib.gettimestring() + '\'') pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set inputsreadstatus=\'1\'') # Read and record everything as specified in controldatabase # Update database of inputs with read data reply = updateio.updateiodata(pilib.controldatabase) result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0) systemsdict = result[0] #print("here is the systems dict") #print(systemsdict) readtime = systemsdict['inputsreadfreq'] plotpoints = 20 logpoints = 100 ################################################### # Update controlvalues in channels channels = pilib.readalldbrows(pilib.controldatabase, 'channels') for channel in channels: # Get controlinput for each channel
inputsreadenabled = pilib.sqlitedatumquery( pilib.controldatabase, 'select inputsreadenabled from systemstatus') # Set last run time pilib.sqlitequery( pilib.controldatabase, 'update systemstatus set lastinputspoll=\'' + pilib.gettimestring() + '\'') pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set updateiostatus=\'1\'') # Read and record everything as specified in controldatabase # Update database of inputs with read data reply = updateio.updateiodata(pilib.controldatabase) result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0) systemsdict = result[0] #print("here is the systems dict") #print(systemsdict) readtime = systemsdict['updateiofreq'] plotpoints = 20 logpoints = 100 ################################################### # Update controlvalues in channels channels = pilib.readalldbrows(pilib.controldatabase, 'channels') for channel in channels: # Get controlinput for each channel
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}
pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running updateifacestatus. ', 4, pilib.systemstatusloglevel) # Update network interfaces statuses for all interfaces, in database tables as well # Check on wpa supplicant status as well. Function returns wpastatusdict try: pilib.writedatedlogmsg(pilib.networklog, 'Running updateifacestatus', 4, pilib.networkloglevel) wpastatusdict = updateifacestatus() except: pilib.writedatedlogmsg(pilib.networklog, 'Exception in updateifacestatus. ') else: pilib.writedatedlogmsg(pilib.networklog, 'Updateifacestatus completed. ') pilib.writedatedlogmsg(pilib.systemstatuslog, 'Completed updateifacestatus. ', 4, pilib.systemstatusloglevel) netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0] netstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0] wpastatusmsg = '' # Do we want to autoconfig the network? # TODO: Better split netconfig up into reporting and configuration if systemstatus['netconfigenabled']: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running interface configuration. ', 4, pilib.systemstatusloglevel) # If mode is ap or tempap if netconfigdata['mode'] in ['ap', 'tempap']: pilib.writedatedlogmsg(pilib.networklog, 'AP Mode is set. ', 1, pilib.networkloglevel) timesincelastretry = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(netconfigdata['laststationretry'])
#!/usr/bin/env python import subprocess import pilib import spilights from time import sleep interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces') systemstatus = pilib.readonedbrow(pilib.controldatabase, 'systemstatus')[0] # Start pigpiod subprocess.call(['killall','pigpiod']) sleep(1) pilib.log(pilib.syslog, 'boot: starting pigpio daemon', 3, pilib.sysloglevel) subprocess.call(['/usr/local/bin/pigpiod']) # Start webserver subprocess.call(['killall','nginx']) subprocess.call(['killall','uwsgi']) subprocess.call(['killall','apache2']) if systemstatus['webserver'] == 'apache': pilib.log(pilib.syslog, 'boot: starting apache', 3, pilib.sysloglevel) subprocess.call(['service', 'apache2', 'start']) elif systemstatus['webserver'] == 'nginx': pilib.log(pilib.syslog, 'boot: starting nginx', 3, pilib.sysloglevel) subprocess.call(['service', 'nginx', 'start']) # Run uwsgi daemon if nginx is running
pilib.writedatedlogmsg(pilib.networklog, 'Running updateifacestatus', 4, pilib.networkloglevel) wpastatusdict = updateifacestatus() except: pilib.writedatedlogmsg(pilib.networklog, 'Exception in updateifacestatus. ') else: pilib.writedatedlogmsg(pilib.networklog, 'Updateifacestatus completed. ') pilib.writedatedlogmsg(pilib.systemstatuslog, 'Completed updateifacestatus. ', 4, pilib.systemstatusloglevel) netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0] netstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0] wpastatusmsg = '' # Do we want to autoconfig the network? # TODO: Better split netconfig up into reporting and configuration if systemstatus['netconfigenabled']: pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running interface configuration. ', 4, pilib.systemstatusloglevel) # If mode is ap or tempap if netconfigdata['mode'] in ['ap', 'tempap']: