Exemple #1
0
 def get_LCD_print(self, report):
     lcd = self._lcd
     if self._m_queue.qsize() > 0:
         lcd.lcd_clear()
         lcd.lcd_puts('{:^15}'.format("SIP - Messages"), 1)
         lcd.lcd_puts('{:^15}'.format(self._m_queue.get()), 2)
         self.add_status('SIP / new message')
         time.sleep(2)
     elif report == 0:
         lcd.lcd_clear()
         lcd.lcd_puts('{:^15}'.format("SIP - status"), 1)
         lcd.lcd_puts('{:^15}'.format(get_sip_status()), 2)
         self.add_status('SIP / Irrigation syst.')
     elif report == 1:
         lcd.lcd_clear()
         lcd.lcd_puts("Software SIP:", 1)
         lcd.lcd_puts(gv.ver_date, 2)
         self.add_status('Software SIP: / ' + gv.ver_date)
     elif report == 2:
         lcd.lcd_clear()
         ip = get_ip()
         lcd.lcd_puts("My IP is:", 1)
         lcd.lcd_puts(str(ip), 2)
         self.add_status('My IP is: / ' + str(ip))
     elif report == 3:
         lcd.lcd_clear()
         lcd.lcd_puts("Port IP:", 1)
         lcd.lcd_puts("8080", 2)
         self.add_status('Port IP: / 8080')
     elif report == 4:
         lcd.lcd_clear()
         temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
         lcd.lcd_puts("CPU temperature:", 1)
         lcd.lcd_puts(temp, 2)
         self.add_status('CPU temperature: / ' + temp)
     elif report == 5:
         lcd.lcd_clear()
         da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
         ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
         lcd.lcd_puts(da, 1)
         lcd.lcd_puts(ti, 2)
         self.add_status(da + ' ' + ti)
     elif report == 6:
         lcd.lcd_clear()
         up = uptime()
         lcd.lcd_puts("System run time:", 1)
         lcd.lcd_puts(up, 2)
         self.add_status('System run time: / ' + up)
     elif report == 7:
         lcd.lcd_clear()
         if gv.sd['rs']:
             rain_sensor = "Active"
         else:
             rain_sensor = "Inactive"
         lcd.lcd_puts("Rain sensor:", 1)
         lcd.lcd_puts(rain_sensor, 2)
         self.add_status('Rain sensor: / ' + rain_sensor)
Exemple #2
0
def get_LCD_print(self, report):
    """Print messages to LCD 16x2"""
    datalcd = get_lcd_options()
    
    import Adafruit_CharLCD as LCD
    lcd = LCD.Adafruit_CharLCDPlate()
    lcd.set_color(1.0, 0.0, 0.0)
    lcd.clear()
    ##lcd = pylcd2.lcd(adr, 1 if get_rpi_revision() >= 2 else 0)  # Address for PCF8574 = example 0x20, Bus Raspi = 1 (0 = 256MB, 1=512MB)

    if report == 0:
        lcd.clear()
        lcd.message("Open Sprinkler\nIrrigation Syst.")
        self.add_status('Open Sprinkler. / Irrigation syst.')
    elif report == 1:
        lcd.clear()
        lcd.message("Software ospi:\n"+gv.ver_date)
        self.add_status('Software ospi: / ' + gv.ver_date)
    elif report == 2:
        ip = get_ip()
        lcd.clear()
        lcd.message("My RPi IP:\n"+str(ip))
        self.add_status('My IP is: / ' + str(ip))
    elif report == 3:
        lcd.clear()
        lcd.message("My Port:\n8080")
        self.add_status('Port IP: / 8080')
    elif report == 4:
        temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
        lcd.clear()
        lcd.message("CPU Temp.:\n"+temp)
        self.add_status('CPU temperature: / ' + temp)
    elif report == 5:
        da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
        ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
        lcd.clear()
        lcd.message(da+"\n"+ti)
        self.add_status(da + ' ' + ti)
    elif report == 6:
        up = uptime()
        lcd.clear()
        lcd.message("System Run Time:\n"+up)
        self.add_status('System run time: / ' + up)
    elif report == 7:
        if gv.sd['rs']:
            rain_sensor = "Active"
        else:
            rain_sensor = "Inactive"
        lcd.clear()
        lcd.message("Rain Sensor:\n"+rain_sensor)
        self.add_status('Rain sensor: / ' + rain_sensor)
Exemple #3
0
def get_LCD_print(self, report):
    """Print messages to LCD 16x2"""
    datalcd = get_lcd_options()
    adr = 0x20
    if datalcd['adress'] == '0x20':  # range adress from PCF8574 or PCF 8574A
        adr = 0x20
    elif datalcd['adress'] == '0x21':
        adr = 0x21
    elif datalcd['adress'] == '0x22':
        adr = 0x22
    elif datalcd['adress'] == '0x23':
        adr = 0x23
    elif datalcd['adress'] == '0x24':
        adr = 0x24
    elif datalcd['adress'] == '0x25':
        adr = 0x25
    elif datalcd['adress'] == '0x26':
        adr = 0x26
    elif datalcd['adress'] == '0x27':
        adr = 0x27
    elif datalcd['adress'] == '0x38':
        adr = 0x38
    elif datalcd['adress'] == '0x39':
        adr = 0x39
    elif datalcd['adress'] == '0x3a':
        adr = 0x3a
    elif datalcd['adress'] == '0x3b':
        adr = 0x3b
    elif datalcd['adress'] == '0x3c':
        adr = 0x3c
    elif datalcd['adress'] == '0x3d':
        adr = 0x3d
    elif datalcd['adress'] == '0x3e':
        adr = 0x3e
    elif datalcd['adress'] == '0x3f':
        adr = 0x3f
    else:
        self.status = ''
        self.add_status('Error: Address is not range 0x20-0x27 or 0x38-0x3F!')
        self._sleep(5)
        return

    import pylcd2  # Library for LCD 16x2 PCF8574
    lcd = pylcd2.lcd(adr, 1 if get_rpi_revision() >= 2 else 0)  # Address for PCF8574 = example 0x20, Bus Raspi = 1 (0 = 256MB, 1=512MB)

    if report == 0:
        lcd.lcd_clear()
        lcd.lcd_puts("Open Sprinkler", 1)
        lcd.lcd_puts("Irrigation syst.", 2)
        self.add_status('Open Sprinkler. / Irrigation syst.')
    elif report == 1:
        lcd.lcd_clear()
        lcd.lcd_puts("Software ospi:", 1)
        lcd.lcd_puts(gv.ver_date, 2)
        self.add_status('Software ospi: / ' + gv.ver_date)
    elif report == 2:
        lcd.lcd_clear()
        ip = get_ip()
        lcd.lcd_puts("My IP is:", 1)
        lcd.lcd_puts(str(ip), 2)
        self.add_status('My IP is: / ' + str(ip))
    elif report == 3:
        lcd.lcd_clear()
        lcd.lcd_puts("Port IP:", 1)
        lcd.lcd_puts("8080", 2)
        self.add_status('Port IP: / 8080')
    elif report == 4:
        lcd.lcd_clear()
        temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
        lcd.lcd_puts("CPU temperature:", 1)
        lcd.lcd_puts(temp, 2)
        self.add_status('CPU temperature: / ' + temp)
    elif report == 5:
        lcd.lcd_clear()
        da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
        ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
        lcd.lcd_puts(da, 1)
        lcd.lcd_puts(ti, 2)
        self.add_status(da + ' ' + ti)
    elif report == 6:
        lcd.lcd_clear()
        up = uptime()
        lcd.lcd_puts("System run time:", 1)
        lcd.lcd_puts(up, 2)
        self.add_status('System run time: / ' + up)
    elif report == 7:
        lcd.lcd_clear()
        if gv.sd['rs']:
            rain_sensor = "Active"
        else:
            rain_sensor = "Inactive"
        lcd.lcd_puts("Rain sensor:", 1)
        lcd.lcd_puts(rain_sensor, 2)
        self.add_status('Rain sensor: / ' + rain_sensor)
Exemple #4
0
    def POST(self):
        global error_msg

        if not been_through_subconfig:
            self.logger.info('tried Net POST....back to /su')
            raise web.seeother('/su')

        self.logger.debug('in Net POST')
        save_last_get('Net POST')
        form = web.input()
        error_msg = ''
        outdata = []

        for f in [
                'Static IP', 'Netmask', 'Gateway', 'DNS Nameservers', 'SSID',
                'Password', 'Hidden SSID', 'UPnP Refresh Rate', 'Station Name',
                'Station Port', 'External Station Port',
                'Remote Substation Access Port'
        ]:
            if f in form:
                form[f] = form[f].strip()

        # use hidden SSID if provided
        using_hidden_ssid = False
        if 'Hidden SSID' in form and form['Hidden SSID'] != '':
            using_hidden_ssid = True
            form['SSID'] = form['Hidden SSID']
            self.logger.info('using Hidden SSID')

        use_eth0 = 'SSID' not in form or form['SSID'] == 'ethernet'

        if not use_eth0:
            net = 'wlan0'
        else:
            form['SSID'] = 'using eth0'
            net = 'eth0'

        self.logger.debug('in Net POST: ' + form['SSID'])
        gv.sd['light_ip'] = 1
        try:
            if form['DNS Nameservers'][0:1] == 'X' and \
                   (len(form['DNS Nameservers']) == 1 or form['DNS Nameservers'][1:2] == ' '):
                gv.sd[
                    'light_ip'] = 0  # hack to disable blinking led on startup with leading X in nameservers
                form['DNS Nameservers'] = form['DNS Nameservers'][1:].strip()
        except:
            pass

        if 'Use DHCP' in form:
            for d in ['DNS Search', 'DNS Nameservers']:
                if d in form and form[d] != '':
                    error_msg = 'Error:  "' + d + '" must be blank with "Use DHCP".'
                    raise web.seeother('/cn')  # back to form

        if 'Station Name' in form:
            sn = validate_fqdn(form['Station Name'])
            if sn == 'Irricloud':  # error condition
                error_msg = 'Error:  "Station Name" must have only letter and numbers.'
                raise web.seeother('/cn')  # back to form
            elif len(sn) > 50 or len(sn) < 1:
                error_msg = 'Error:  "Station Name" must be at most 50 characters.'
                raise web.seeother('/cn')  # back to form
            form['Station Name'] = sn

        try:
            drop = 0
            with open('/etc/network/interfaces', 'r') as infile:
                iface = infile.readlines()
            for line in iface:
                if 'dns-nameservers' in line:
                    continue  # delete any old dns stuff
                did_iface_wlan0 = False
                if drop > 0:
                    drop -= 1
                    continue
                if 'iface ' + net + ' inet' in line:
                    if net == 'wlan0':
                        did_iface_wlan0 = True
                    if 'Use DHCP' in form:
                        self.logger.info('Using dhcp: ' + form['SSID'])
                        if 'static' in line:
                            drop = 3
                            line = 'iface ' + net + ' inet manual\n'
                    else:
                        self.logger.info('Using static ip: ' +
                                         form['Static IP'] + ' ' +
                                         form['Netmask'] + ' ' +
                                         form['Gateway'])
                        if 'static' in line:
                            drop = 3
                        outdata.append('iface ' + net + ' inet static\n')
                        outdata.append('        address ' + form['Static IP'] +
                                       '\n')
                        outdata.append('        netmask ' + form['Netmask'] +
                                       '\n')
                        line = '        gateway ' + form['Gateway'] + '\n'
                        outdata.append(line)
                        if 'DNS Nameservers' in form and form[
                                'DNS Nameservers'] != '':
                            line = '        dns-nameservers ' + form[
                                'DNS Nameservers'] + '\n'
                        else:  # use gateway
                            line = '        dns-nameservers ' + form[
                                'Gateway'] + '\n'
                elif 'iface ' + 'wlan0' + ' inet' in line:  # using eth0 but need to clean up 10.0.0.1 entry
                    if 'static' in line:
                        drop = 3
                        line = 'iface ' + 'wlan0' + ' inet manual\n'
                        did_iface_wlan0 = True

                outdata.append(line)
                if did_iface_wlan0:
                    outdata.append(
                        '        wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n'
                    )

        except Exception as ex:
            self.logger.exception(
                'Unexpected exception trying to configure network: ' + str(ex))
            raise web.seeother('/cn')

        if len(outdata) == 0:
            self.logger.error('Expected data in /etc/network/interfaces')
            raise web.seeother('/cn')

        for portn in [
                'Station Port', 'External Station Port',
                'Remote Substation Access Port', 'UPnP Refresh Rate'
        ]:
            if portn in form:
                try:
                    port = int(form[portn])
                except:
                    error_msg = 'Error:  "' + portn + '" must be integer.'
                    raise web.seeother('/cn')  # back to form
                if port < 0 or port > 65535:
                    error_msg = 'Error:  "' + portn + '" must be between 0 and 65535.'
                    raise web.seeother('/cn')  # back to form
                if portn == 'Station Port' and port == 9080:  # specially reserved for proxy
                    error_msg = 'Error:  "' + portn + '" cannot be 9080.'
                    raise web.seeother('/cn')  # back to form

        self.logger.info('stopping daemons before updating network interfaces')
        if not use_eth0:
            stop_daemons()
        else:
            stop_daemons()

        try:
            with open('/etc/network/interfaces', 'w') as outfile:
                outfile.writelines(outdata)

            # Do not let dhcpcd get a dhcp address (and dns info?) if we are using a static config
            if 'Use DHCP' in form:
                shutil.copy2('/etc/dhcpcd.conf.yeswlan0', '/etc/dhcpcd.conf')
            else:
                shutil.copy2('/etc/dhcpcd.conf.nowlan0', '/etc/dhcpcd.conf')

            if not use_eth0:
                wpa_supp_lines = [
                    'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'
                ]
                wpa_supp_lines.append('update_config=1\n\n')
                if form['SSID'] != '' and form['Password'] != '':
                    # wpa_passphrase cannot handle blanks so quote strings
                    ssid = form['SSID'].replace('"', '\"')
                    passw = form['Password'].replace('"', '\"')
                    cmd = '/usr/bin/wpa_passphrase "' + ssid + '" "' + passw + '" > passphrase'
                    subprocess.call(cmd, shell=True)
                    with open('passphrase', 'r') as f:
                        pl = f.readlines()
                        for line in pl:
                            if '#psk=' in line:  # drop cleartext password
                                continue
                            wpa_supp_lines.append(line)
                            if using_hidden_ssid and 'ssid' in line:
                                wpa_supp_lines.append('\tscan_ssid=1\n')
                    subprocess.call(['rm', 'passphrase'])
                else:
                    self.logger.warning('missing ssid or password')

                with open('/etc/wpa_supplicant/wpa_supplicant.conf',
                          'w') as outfile:
                    outfile.writelines(wpa_supp_lines)

                # check if network connection was made


#                self.logger.debug('wpa_action stopping wlan0')
#                rc = subprocess.call(['wpa_action', 'wlan0', 'stop'])
#                self.logger.debug( 'wpa_action wlan0 stop return: ' + str(rc))
#                time.sleep(1)
#                self.logger.debug('ifup wlan0')
#                rc = subprocess.call(['ifup', 'wlan0'])
#                self.logger.debug( 'ifup return: ' + str(rc))
#                time.sleep(1)
#                rc = subprocess.call(['wpa_action', 'wlan0', 'reload'])
#                self.logger.debug( 'wpa_action wlan0 reload return: ' + str(rc))
#                time.sleep(1)
#                reset_networking()

            if True or 'Do not validate network connection' in form or network_up(
                    net, self.logger):
                #successful network connection.   Finalize
                # copy the current versions to the save version
                cur_ip = get_ip(net)
                self.logger.info('success...cur_ip: ' + cur_ip)
                if gv.sd[
                        'enable_upnp']:  # was enabled?  Then cleanup.  If network still points to 10.0.0.1 network cant cleanup!
                    deletes = []
                    if gv.sd['external_htp'] != 0:
                        deletes.append(gv.sd['external_htp'])
                    if gv.sd['remote_support_port'] != 0:
                        deletes.append(gv.sd['remote_support_port'])
                    if gv.sd['external_proxy_port'] != 0:
                        deletes.append(gv.sd['external_proxy_port'])
                    update_upnp(cur_ip, self.logger, deletes)
                gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0
                if gv.sd['enable_upnp']:
                    if 'UPnP Refresh Rate' in form:
                        gv.sd['upnp_refresh_rate'] = int(
                            form['UPnP Refresh Rate'])
                if 'Station Name' in form:
                    gv.sd['name'] = form['Station Name']
                    update_hostname(gv.sd['name'])
                if 'Station Port' in form:
                    gv.sd['htp'] = int(form['Station Port'])
                if gv.sd['master']:
                    gv.sd[
                        'master_ip'] = 'localhost'  # update local master_port
                    gv.sd['master_port'] == gv.sd['htp']
                else:
                    gv.sd['master_port'] = 0
                gv.sd['external_htp'] = int(
                    form['External Station Port']
                ) if 'External Station Port' in form else 0
                gv.sd['external_proxy_port'] = int(
                    form['Remote Substation Access Port']
                ) if 'Remote Substation Access Port' in form else 0
                jsave(gv.sd, 'sd')
                self.logger.info('success....copying back interfaces and wpa')
                try:
                    os.remove('/etc/resolv.conf')
                except:
                    pass
                shutil.copy('/etc/network/interfaces',
                            '/etc/network/interfaces.save')
                shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf',
                            '/etc/wpa_supplicant/wpa_supplicant.conf.save')
                #                self.logger.info('success....enabling sip')
                #                subprocess.call(['systemctl', 'enable', 'sip.service'])
                ##                subprocess.call(['update-rc.d', 'sip', 'enable'])
                ##                subprocess.call(['update-rc.d', 'sip', 'defaults'])
                ##                self.logger.info('disabling sip_net_finish')
                #                subprocess.call(['systemctl', 'disable', 'sip_net_finish.service'])
                ##                subprocess.call(['update-rc.d', '-f', 'sip_net_finish', 'remove'])
                #                light_ip(cur_ip)
                self.logger.info('rebooting')
                subprocess.call(['reboot', '-h'])
                exit(0)
            else:
                raise Exception('Network Inaccessible')

        except Exception as ex:
            self.logger.exception('failed: ' + str(ex))
            # restore saved /etc/network/interfaces and wpa_suplicant.conf
            self.logger.info('restore network files and exit.  Exception: ' +
                             str(ex))
            shutil.move('/etc/network/interfaces.save',
                        '/etc/network/interfaces')
            shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save',
                        '/etc/wpa_supplicant/wpa_supplicant.conf')
            exit(1)

        self.logger.error(
            'sip_net_config: should have exited above.  sip_monitor will restart'
        )
        raise web.seeother('/cn')
Exemple #5
0
    def run(self):
        if disable_substations:
            return        

        gv.logger.info('Substation plugin started')        
        time.sleep(7) # let things wake up, but keep less than delay for sending email

        last_message_base = gv.now - 60
        last_day = gv.now//86400 # wait at least a day before removing stale log files so startup does not delete them
        while True:
            try:
                cur_day = gv.now//86400
                if gv.sd['slave'] and gv.now - last_message_base >= 60:
                    try:
                        last_message_base = gv.now
                        data = message_base('suslj')
                        if 'unreachable' in data:
                            raise IOError, 'UnreachableMaster'
                        force_reboot = False
                        # update common data that has changed on the master
                        for grouping in data:
                            if gv.sd['master']:
                                continue
                            for key in data[grouping]:
                                if grouping == 'sd':
                                    if key in gv.sd:
                                        if gv.sd[key] != data['sd'][key]:
                                            gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key]))
                                            if key == 'remote_support_port' and gv.sd['enable_upnp']:
                                                gv.logger.critical('substation_run: Unexpected key of remote_support_port')
                                                if gv.sd[key] != 0: # delete old
                                                    update_upnp(get_ip(), [gv.sd[key]])
                                                if data['sd'][key] != 0:
                                                    update_upnp(get_ip(), [], [[22, data['sd'][key]]])
                                            gv.sd[key] = data['sd'][key]
                                            if key == 'tza':
                                                with open('/etc/timezone','w') as file:
                                                    file.write(qdict['o'+f]+'\n')
                                                subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata'])
                                                force_reboot = True
                                            elif key == 'loc' or key == 'lang':
                                                force_reboot = True
                                    else:
                                        gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key]))
                                        gv.sd[key] = data['sd'][key]
                                elif grouping in gv.plugin_data:
                                    if key in gv.plugin_data[grouping]:
                                        if gv.plugin_data[grouping][key] != data[grouping][key]:
                                            gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key]))
                                            gv.plugin_data[grouping][key] = data[grouping][key]
                                    else:
                                        gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key]))
                                        gv.plugin_data[grouping][key] = data[grouping][key]
                                elif grouping == 'other':
                                    if key == 'websession':
                                        web.config._session.user = data[grouping][key]
                                    elif key == 'datetime':
                                        try:
                                            pass
#                                            subprocess.call(['date', '--set='+data[grouping][key]])
                                        except:
                                            gv.logger.exception('Could not set datetime to ' + data[grouping][key])
                            if grouping == 'sd':
                                jsave(gv.sd, 'sd')
                            elif grouping != 'other':
                                pass
                        if force_reboot:
                            reboot(5) # give a few seconds before reboot

                    except Exception as ex:
                        gv.logger.info('No master response.  ip: ' + get_ip_to_base() + \
                                       ' port: ' + str(gv.sd['master_port']) + \
                                       ' Exception: ' + str(ex))
                        try:
                            iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                            lines = iwout.split('\n')
                            for l in lines:
                                if 'ESSID:' in l:
                                    gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):])
                        except Exception as ex:
                            gv.logger.info('slave could not check iwconfig: ' + str(ex))

                if gv.sd['master']:
                    for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                        sub = gv.plugin_data['su']['subinfo'][subid]
                        try:
                            if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out
                                qd = {'substation':subid}
                                load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive
                        except Exception as ex:
                            gv.logger.info('substations reach out to slave: No response from slave: ' +
                                           sub['name'] + ' Exception: ' + str(ex))
                            sub['status'] = 'unreachable'
                            try:
                                iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                                lines = iwout.split('\n')
                                for l in lines:
                                    if 'ESSID:' in l:
                                        gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):])
                            except Exception as ex:
                                gv.logger.info('master could not check iwconfig: ' + str(ex))

                    if cur_day != last_day:
                        last_day = cur_day
                        # delete any imported log files from substations that are no longer active
                        files = glob.glob('./data/imported_logs/*')
                        for full_name in files:
                            sub_name = full_name[full_name.rfind('/')+1:]
                            found_slave = 0
                            for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                                if sub_name == gv.plugin_data['su']['subinfo'][subid]['name']:
                                    found_slave = subid
                                    break
                            if found_slave == 0:
                                try:
                                    shutil.rmtree(full_name)
                                    gv.logger.info('removed substree: ' + full_name)
                                except Exception as ex:
                                    gv.logger.warning('failed to remove substree: ' + full_name + ' ex: ' + str(ex))

            except Exception as ex:
                self.start_status('', 'Substation encountered error: ' + str(ex))

            self._sleep(30)
Exemple #6
0
def sms_check(self):
    """Control and processing SMS"""
    data = get_sms_options()  # Load data from json file
    tel1 = data["tel1"]
    tel2 = data["tel2"]
    comm1 = data["txt1"]
    comm2 = data["txt2"]
    comm3 = data["txt3"]
    comm4 = data["txt4"]
    comm5 = data["txt5"]
    comm6 = data["txt6"]

    sm = gammu.StateMachine()
    sm.ReadConfig()
    try:
        sm.Init()
        print("Checking SMS...")
    except:
        print("Error: SMS modem fault")

    status = sm.GetSMSStatus()
    remain = status["SIMUsed"] + status["PhoneUsed"] + status["TemplatesUsed"]
    sms = []
    start = True
    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]["Location"], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)
    data = gammu.LinkSMS(sms)
    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        print("%-15s: %s" % ("Sender", m["Number"]))
        print("%-15s: %s" % ("Date", str(m["DateTime"])))
        print("%-15s: %s" % ("State", m["State"]))
        print("%-15s: %s" % ("SMS command", m["Text"]))
        if (m["Number"]
                == tel1) or (m["Number"]
                             == tel2):  # If telephone is admin 1 or admin 2
            self.add_status(
                time.strftime("%d.%m.%Y at %H:%M:%S",
                              time.localtime(time.time())) + " SMS from admin")
            if m["State"] == "UnRead":  # If SMS is unread
                if (
                        m["Text"] == comm1
                ):  # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    self.add_status("Command " + comm1 + " is processed")
                    if gv.lrun[1] == 98:
                        pgr = "Run-once"
                    elif gv.lrun[1] == 99:
                        pgr = "Manual"
                    else:
                        pgr = str(gv.lrun[1])
                    start = time.gmtime(gv.now - gv.lrun[2])
                    if pgr != "0":
                        logline = (
                            " {program: " + pgr + ",station: " +
                            str(gv.lrun[0]) + ",duration: " +
                            timestr(gv.lrun[2]) + ",start: " +
                            time.strftime("%H:%M:%S - %Y-%m-%d", start) + "}")
                    else:
                        logline = " Last program none"
                    revision = " Rev: " + gv.ver_date
                    datastr = ("On " + time.strftime(
                        "%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) +
                               ". Run time: " + uptime() + " IP: " + get_ip() +
                               logline + revision)
                    message = {
                        "Text": datastr,
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm1 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    self.add_status("SMS text: " + datastr)

                    sm.DeleteSMS(m["Folder"], m["Location"])  # SMS deleted
                    self.add_status("Received SMS was deleted")

                elif m["Text"] == comm2:  # If command = comm2 (stop - system SIP off)
                    self.add_status("Command " + comm2 + " is processed")
                    gv.sd["en"] = 0  # disable system SIP
                    jsave(gv.sd, "sd")  # save en = 0
                    message = {
                        "Text": "Command: " + comm2 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm2 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status("Received SMS was deleted")

                elif m["Text"] == comm3:  # If command = comm3 (start - system SIP on)
                    self.add_status("Command " + comm3 + " is processed")
                    gv.sd["en"] = 1  # enable system SIP
                    jsave(gv.sd, "sd")  # save en = 1
                    message = {
                        "Text": "Command: " + comm3 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm3 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status("Received SMS was deleted")

                elif m["Text"] == comm4:  # If command = comm4 (reboot system)
                    self.add_status("Command " + comm4 + " is processed")
                    message = {
                        "Text": "Command: " + comm4 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm4 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status(
                        "Received SMS was deleted and system is now reboot")
                    self._sleep(10)
                    reboot()  # restart linux system

                elif m["Text"] == comm5:  # If command = comm5 (poweroff system)
                    self.add_status("Command " + comm5 + " is processed")
                    message = {
                        "Text": "Command: " + comm5 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm5 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status(
                        "Received SMS was deleted and system is now poweroff")
                    self._sleep(10)
                    poweroff()  # poweroff linux system

                elif m["Text"] == comm6:  # If command = comm6 (update SIP system)
                    self.add_status("Command " + comm6 + " is processed")
                    message = {
                        "Text": "Command: " + comm6 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm6 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    try:
                        from plugins.system_update import perform_update

                        perform_update()
                        self.add_status(
                            "Received SMS was deleted, update was performed and program will restart"
                        )
                    except ImportError:
                        self.add_status(
                            "Received SMS was deleted, but could not perform update"
                        )

                    sm.DeleteSMS(m["Folder"], m["Location"])

                else:  # If SMS command is not defined
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status("Received command " + m["Text"] +
                                    " is not defined!")

            else:  # If SMS was read
                sm.DeleteSMS(m["Folder"], m["Location"])
                self.add_status("Received SMS was deleted - SMS was read")
        else:  # If telephone number is not admin 1 or admin 2 phone number
            sm.DeleteSMS(m["Folder"], m["Location"])
            self.add_status(
                "Received SMS was deleted - SMS was not from admin")
from helpers import get_ip
import numpy as np
import paho.mqtt.client as paho
from random import sample
import itertools
import random
import time
import json
import sys
import os

# --------- initialization parameters ---------
FLAGS = argHandler()
FLAGS.setDefaults()
FLAGS.parseArgs(sys.argv)
FLAGS['node_ip'] = get_ip()
print(os.getcwd())
print(FLAGS)
N = FLAGS['N']
if FLAGS['id'] < 0:
    my_id_list = list(range(FLAGS['s'], FLAGS['f']))
else:
    my_id_list = [FLAGS['id']]  # only one node in a list
print(my_id_list)
my_neighbours = []
paramet = {
    'alpha': [0.5, 0.5],  # infect rate 
    'mu': [0.5, 0.5],  # sleep s 
    'gamma': [0.1, 0.1],  # rec rate 
    'lambda': [0.7, 0.2],  # sleep I1 
    'kappa': [0.7, 0.2]  # sleep I2    % [I2_s -> I2_a, I2_a -> I2_s]
Exemple #8
0
def get_LCD_print(self, report):
    """Print messages to LCD 16x2"""
    
    find_i2c = 'True'
    lcd_adr = 0
    pcf_type = 'None'
 

    import pylcd2  # Library for LCD 16x2 PCF8574
    import smbus

    bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)

    # find i2c adress
    for addr in range(32, 39): # PCF8574 range 0x20-0x27 
      if (find_i2c == 'True'):  
         try:
            bus.write_quick(addr)
            lcd_adr = addr
            find_i2c = 'False'
            pcf_type = 'PCF8574'
            self.add_status('Find: ' + pcf_type + ' on adress 0x' + ('%02x' % lcd_adr))  
                
         except:
            find_i2c = 'True'
           

    for addr in range(56, 63): # PCF8574A range 0x38-0x3F
      if (find_i2c == 'True'):  
         try:
            bus.write_quick(addr)
            lcd_adr = addr
            find_i2c = 'False'
            pcf_type = 'PCF8574A'
            self.add_status('Find: ' + pcf_type + ' on adress 0x' + ('%02x' % lcd_adr))   
                
         except:
            find_i2c = 'True'
           
    if (find_i2c == 'False'):
      lcd = pylcd2.lcd(lcd_adr, 1 if get_rpi_revision() >= 2 else 0)  # Address for PCF8574 = example 0x20, Bus Raspi = 1 (0 = 256MB, 1=512MB)
      if report == 0:
        lcd.lcd_clear()
        lcd.lcd_puts("Open Sprinkler", 1)
        lcd.lcd_puts("Irrigation syst.", 2)
        self.add_status('Open Sprinkler / Irrigation syst.')
      elif report == 1:
        lcd.lcd_clear()
        lcd.lcd_puts("Software OSPy:", 1)
        lcd.lcd_puts(gv.ver_date, 2)
        self.add_status('Software OSPy: / ' + gv.ver_date)
      elif report == 2:
        lcd.lcd_clear()
        ip = get_ip()
        lcd.lcd_puts("My IP is:", 1)
        lcd.lcd_puts(str(ip), 2)
        self.add_status('My IP is: / ' + str(ip))
      elif report == 3:
        lcd.lcd_clear()
        lcd.lcd_puts("Port IP:", 1)
        lcd.lcd_puts("8080", 2)
        self.add_status('Port IP: / 8080')
      elif report == 4:
        lcd.lcd_clear()
        temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
        lcd.lcd_puts("CPU temperature:", 1)
        lcd.lcd_puts(temp, 2)
        self.add_status('CPU temperature: / ' + temp)
      elif report == 5:
        lcd.lcd_clear()
        da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
        ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
        lcd.lcd_puts(da, 1)
        lcd.lcd_puts(ti, 2)
        self.add_status(da + ' ' + ti)
      elif report == 6:
        lcd.lcd_clear()
        up = uptime()
        lcd.lcd_puts("System run time:", 1)
        lcd.lcd_puts(up, 2)
        self.add_status('System run time: / ' + up)
      elif report == 7:
        lcd.lcd_clear()
        if gv.sd['rs']:
            rain_sensor = "Active"
        else:
            rain_sensor = "Inactive"
        lcd.lcd_puts("Rain sensor:", 1)
        lcd.lcd_puts(rain_sensor, 2)
        self.add_status('Rain sensor: / ' + rain_sensor)
      elif report == 8:
        lcd.lcd_clear()
        try: 
            from pressure_adj import get_check_pressure
            state_press = get_check_pressure()
            if state_press: 
                lcd.lcd_puts("Pressure sensor:", 1)
                lcd.lcd_puts("GPIO is HIGH", 2)
                self.add_status('Pressure sensor: / GPIO is HIGH')

            else:
                lcd.lcd_puts("Pressure sensor:", 1)
                lcd.lcd_puts("GPIO is LOW", 2)
                self.add_status('Pressure sensor: / GPIO is LOW')

        except:
                lcd.lcd_puts("Pressure sensor:", 1)
                lcd.lcd_puts("Not used", 2)
                self.add_status('Pressure sensor: / Not used')
      elif report == 9:
        lcd.lcd_clear()
        if gv.lrun[1] == 98:
           pgr = 'Run-once'
        elif gv.lrun[1] == 99:
           pgr = 'Manual'
        else:
           pgr = str(gv.lrun[1])
        stop = time.gmtime(gv.lrun[2])
        if pgr != '0':
             logline2 = 'P' + pgr + ' ' + timestr(gv.lrun[2])
        else:
             logline2 = 'None' 
        lcd.lcd_puts('Last program', 1)
        lcd.lcd_puts(logline2, 2)
        self.add_status('Last program / ' + logline2)
       
      #------- end text to 16x2 -----------------

      elif report == 100: # start text to 16x1
        lcd.lcd_clear()
        lcd.lcd_puts("Open Sprinkler", 1)
        self.add_status('Open Sprinkler')
      elif report == 101:
        lcd.lcd_clear()
        lcd.lcd_puts("Irrigation syst.", 1)
        self.add_status('Irrigation syst.')
      elif report == 102:
        lcd.lcd_clear()
        lcd.lcd_puts("Software OSPy:", 1)
        self.add_status('Software OSPy:')
      elif report == 103:
        lcd.lcd_clear()
        lcd.lcd_puts(gv.ver_date, 1)
        self.add_status(gv.ver_date)
      elif report == 104:
        lcd.lcd_clear()
        lcd.lcd_puts("My IP is:", 1)
        self.add_status('My IP is:')
      elif report == 105:
        lcd.lcd_clear()
        ip = get_ip()
        lcd.lcd_puts(str(ip), 1)
        self.add_status(str(ip))
      elif report == 106:
        lcd.lcd_clear()
        lcd.lcd_puts("Port IP:", 1)
        self.add_status('Port IP:')
      elif report == 107:
        lcd.lcd_clear()
        lcd.lcd_puts("8080", 1)
        self.add_status('8080')
      elif report == 108:
        lcd.lcd_clear()
        lcd.lcd_puts("CPU temperature:", 1)
        self.add_status('CPU temperature:')
      elif report == 109:
        lcd.lcd_clear()
        temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
        lcd.lcd_puts(temp, 1)
        self.add_status(temp)
      elif report == 110:
        lcd.lcd_clear()
        da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
        lcd.lcd_puts("Date: " + da, 1)
        self.add_status('Date: ' + da)
      elif report == 111:
        lcd.lcd_clear()
        ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
        lcd.lcd_puts("Time: " + ti, 1)
        self.add_status('Time: ' + ti)
      elif report == 112:
        lcd.lcd_clear()
        lcd.lcd_puts("System run time:", 1)
        self.add_status('System run time:')
      elif report == 113:
        lcd.lcd_clear()
        up = uptime()
        lcd.lcd_puts(up, 1)
        self.add_status(up)
      elif report == 114:
        lcd.lcd_clear()
        lcd.lcd_puts("Rain sensor:", 1)
        self.add_status('Rain sensor:')
      elif report == 115:
        lcd.lcd_clear()
        if gv.sd['rs']:
            rain_sensor = "Active"
        else:
            rain_sensor = "Inactive"
        lcd.lcd_puts(rain_sensor, 1)
        self.add_status(rain_sensor)
      elif report == 116:
        lcd.lcd_clear()
        lcd.lcd_puts('Last program', 1)
        self.add_status('Last program')
      elif report == 117:
        lcd.lcd_clear()
        if gv.lrun[1] == 98:
           pgr = 'Run-once'
        elif gv.lrun[1] == 99:
           pgr = 'Manual'
        else:
           pgr = str(gv.lrun[1])
        stop = time.gmtime(gv.lrun[2])
        if pgr != '0':
             logline2 = 'P' + pgr + ' ' + timestr(gv.lrun[2])
        else:
             logline2 = 'none' 
        lcd.lcd_puts(logline2, 1)
        self.add_status(logline2)
      elif report == 118:
        lcd.lcd_clear()
        lcd.lcd_puts("Pressure sensor:", 1)
        self.add_status('Pressure sensor:')
      elif report == 119:
        lcd.lcd_clear()
        try: 
            from pressure_adj import get_check_pressure
            state_press = get_check_pressure()
            if state_press: 
                lcd.lcd_puts("GPIO is HIGH", 1)
                self.add_status('GPIO is HIGH')

            else:
                lcd.lcd_puts("GPIO is LOW", 1)
                self.add_status('GPIO is LOW')

        except:
                lcd.lcd_puts("Not used", 1)
                self.add_status('Not used')
 

    else:
      self.add_status('No find PCF8574 controller.')
Exemple #9
0
    logger = logging.getLogger('sip_monitor')
    logger.addHandler(fh)
    gv.logger.addHandler(fh)
    logger.setLevel(level)
    if len(sys.argv) > 1:
        level_name = sys.argv[1]
        if level_name in log_levels:
            level = log_levels[level_name]
            logger.setLevel(level)
        else:
            logger.critical('Bad parameter to sip_monitor: ' + level_name)

    logger.critical('Starting')
    light_vsb_boards()
    time.sleep(15)  # give time for network to come up
    light_ip(get_ip())
    pi = pigpio.pi()
    button_pin = 21
    pi.set_mode(button_pin, pigpio.INPUT)
    pi.set_pull_up_down(button_pin, pigpio.PUD_UP)

    reset_skip = 10
    sip_restart_skip = 2
    sip_net_finish_skip = 2
    last_net_reset = timegm(time.localtime())

    cmds = [
        ['rm', 'data/substation_proxy_pause'],
        ['/etc/init.d/bind9', 'stop'],  # only run with master radio
        ['update-rc.d', 'sip', 'remove'],
        ['update-rc.d', 'sip_net_finish', 'remove'],
Exemple #10
0
    def POST(self):
        self.logger.debug('in Net POST')
        save_last_get('Net POST')
        form = web.input()
        outdata = []

        net = 'eth0' if 'Use Hardwired eth0' in form else 'wlan0'
        # use hidden SSID if provided
        using_hidden_ssid = False
        if 'Hidden SSID' in form and form['Hidden SSID'].strip() != '':
            using_hidden_ssid = True
            form['SSID'] = form['Hidden SSID']
            self.logger.info('using Hidden SSID')

        use_eth0 = 'SSID' not in form

        if not use_eth0:
            form['SSID'] = form['SSID'].strip()
            form['Password'] = form['Password'].strip()
        else:
            form['SSID'] = 'using eth0'
        self.logger.debug('in Net POST: ' + form['SSID'])

        try:
            drop = 0
            with open('/etc/network/interfaces','r') as infile:
                iface = infile.readlines()
            for line in iface:
                did_iface_wlan0 = False
                if drop > 0:
                    drop -= 1
                    continue
                if 'iface ' + net + ' inet' in line:
                    if net == 'wlan0':
                        did_iface_wlan0 = True
                    if 'Use DHCP' in form:
                        self.logger.debug('Using dhcp: ' + form['SSID'])
                        if 'static' in line:
                            drop = 3
                            line = 'iface ' + net + ' inet manual\n'
                    else:
                        self.logger.debug('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway'])
                        if 'static' in line:
                            drop = 3
                        outdata.append('iface ' + net + ' inet static\n')
                        outdata.append('        address ' + form['Static IP'] + '\n')
                        outdata.append('        netmask ' + form['Netmask'] + '\n')
                        line = '        gateway ' + form['Gateway'] +'\n'
                outdata.append(line)
                if did_iface_wlan0:
                    outdata.append('        wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n')


        except Exception as ex:
            self.logger.exception('Unexpected exception trying to configure network: ' + str(ex))
            raise web.seeother('/cn')

        if len(outdata) == 0:
            self.logger.error('Expected data in /etc/network/interfaces')
            raise web.seeother('/cn')

        self.logger.debug('stopping daemons before updating network interfaces')
#        if not use_eth0:
#            stop_daemons()

        try:
            with open('/etc/network/interfaces','w') as outfile:
                outfile.writelines(outdata)

            if not use_eth0:
                wpa_supp_lines = ['ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n']
                wpa_supp_lines.append('update_config=1\n\n')
                if form['SSID'] != '' and form['Password'] != '':
                    # wpa_passphrase cannot handle blanks
                    cmd = 'wpa_passphrase ' + form['SSID'] + ' ' + form['Password'] + ' > passphrase'
                    subprocess.call(cmd, shell=True)
                    with open('passphrase', 'r') as f:
                        pl = f.readlines()
                        for line in pl:
                            wpa_supp_lines.append(line)
                            if using_hidden_ssid and 'ssid' in line:
                                wpa_supp_lines.append('\tscan_ssid=1\n')
                    subprocess.call(['rm', 'passphrase'])
                else:
                    self.logger.warning('missing ssid or password')

                with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile:
                    outfile.writelines(wpa_supp_lines)

                # check if network connection was made
                self.logger.debug('wpa_action stopping wlan0')
                rc = subprocess.call(['wpa_action', 'wlan0', 'stop'])
                self.logger.debug( 'wpa_action return: ' + str(rc))
                time.sleep(1)
                self.logger.debug('ifup wlan0')
                rc = subprocess.call(['ifup', net])
                self.logger.debug( 'ifup return: ' + str(rc))
                time.sleep(2)

            if network_up(net):
                #successful network connection.   Finalize
                # copy the current versions to the save version
                if gv.sd['enable_upnp']: # was enabled?  Then cleanup
                    cur_ip = get_ip(net)
                    deletes = []
                    if gv.sd['external_htp'] != 0:
                        deletes.append(gv.sd['external_htp'])
                    if gv.sd['remote_support_port'] != 0:
                        deletes.append(gv.sd['remote_support_port'])
                    update_upnp(cur_ip, deletes)
                gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0
                if gv.sd['enable_upnp']:
                    if 'UPnP Refresh Rate' in form:
                        gv.sd['upnp_refresh_rate'] = int(form['UPnP Refresh Rate'])

                if 'System Name' in form:
                    gv.sd['name'] = form['System Name']
                    jsave(gv.sd, 'sd')
                if 'System Port' in form:
                    gv.sd['htp'] = int(form['System Port'])
                    jsave(gv.sd, 'sd')
                if 'External System Port' in form:
                    gv.sd['external_htp'] = int(form['External System Port'])
                self.logger.info('success....copying back interfaces and wpa')
                shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save')
                shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save')
#                self.logger.info('success....enabling boiler')
#                subprocess.call(['update-rc.d', 'boiler', 'defaults'])
#                self.logger.info('disabling boiler_net_finish')
#                subprocess.call(['update-rc.d', 'boiler_net_finish', 'remove'])
                self.logger.info('rebooting')
                subprocess.call(['reboot', '-h'])
                exit(0)
            else:
                raise Exception('Network Inaccessible')

        except Exception as ex:
            self.logger.exception('failed: ' + str(ex))
            # restore saved /etc/network/interfaces and wpa_suplicant.conf
            self.logger.info('restore network files and exit.  Exception: ' + str(ex))
            shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces')
            shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf')
            exit(1)

        self.logger.error('boiler_net_config: should have exited above.  boiler_monitor will restart')
        raise web.seeother('/')
Exemple #11
0
    def _lcd_print(self, report, txt=None):
        self._lcd_lock.acquire()
        #  Print messages to LCD 16x2
        datalcd = get_lcd_options()
        adr = int(datalcd[u"adress"], 0)
        if adr not in self._addresses:
            self.status = ""
            self.add_status(
                u"Error: Address is not range 0x20-0x27 or 0x38-0x3F!")
            self._lcd_lock.release()
            self._sleep(5)
            return

        # If the address has changed: Turn off the backlight and clear the LCD then forget the pylcd object.
        if self._lcd is not None and self._lcd.lcd_device.addr != adr:
            self._lcd.backlight = 0  # takes effect during next update call on self._lcd
            self._lcd.lcd_clear()
            self._lcd = None

        # Create a pylcd object if necessary
        if self._lcd is None:
            self._lcd = pylcd.lcd(
                adr, (1 if get_rpi_revision() >= 2 else 0), 1
            )  # Address for PCF8574 = example 0x20, Bus Raspi = 1 (0 = 256MB, 1=512MB)
            if self._lcd.error is not None:
                self.status = u""
                self.add_status(u"Error: [Errno " +
                                str(self._lcd.error.errno) +
                                u"] Display not found at address " +
                                datalcd[u"adress"])
                self._lcd = None
                self._lcd_lock.release()
                self._sleep(5)
                return

        if report == u"name":
            self._lcd.lcd_clear()
            self._lcd.lcd_puts(gv.sd[u"name"], 1)
            self._lcd.lcd_puts(u"Irrigation syst.", 2)
            self.add_status(u"SIP. / Irrigation syst.")
        elif report == u"d_sw_version":
            self._lcd.lcd_clear()
            self._lcd.lcd_puts(u"Software SIP:", 1)
            self._lcd.lcd_puts(gv.ver_date, 2)
            self.add_status(u"Software SIP: / " + gv.ver_date)
        elif report == u"d_ip":
            self._lcd.lcd_clear()
            ip = get_ip()
            self._lcd.lcd_puts(u"My IP is:", 1)
            self._lcd.lcd_puts(str(ip), 2)
            self.add_status(u"My IP is: / " + str(ip))
        elif report == u"d_port":
            self._lcd.lcd_clear()
            self._lcd.lcd_puts(u"Port IP:", 1)
            self._lcd.lcd_puts(str(gv.sd[u"htp"]), 2)
            self.add_status(u"Port IP: / {}".format(gv.sd[u"htp"]))
        elif report == u"d_cpu_temp":
            self._lcd.lcd_clear()
            temp = str(get_cpu_temp()) + u" " + gv.sd[u"tu"]
            self._lcd.lcd_puts(u"CPU temperature:", 1)
            self._lcd.lcd_puts(temp, 2)
            self.add_status(u"CPU temperature: / " + temp)
        elif report == u"d_date_time":
            self._lcd.lcd_clear()
            da = time.strftime(u"%d.%m.%Y", time.gmtime(gv.now))
            ti = time.strftime(u"%H:%M:%S", time.gmtime(gv.now))
            self._lcd.lcd_puts(da, 1)
            self._lcd.lcd_puts(ti, 2)
            self.add_status(da + " " + ti)
        elif report == u"d_uptime":
            self._lcd.lcd_clear()
            up = uptime()
            self._lcd.lcd_puts(u"System run time:", 1)
            self._lcd.lcd_puts(up, 2)
            self.add_status(u"System run time: / " + up)
        elif report == u"d_rain_sensor":
            self._lcd.lcd_clear()
            if gv.sd[u"rs"]:
                rain_sensor = u"Active"
            else:
                rain_sensor = u"Inactive"
            self._lcd.lcd_puts(u"Rain sensor:", 1)
            self._lcd.lcd_puts(rain_sensor, 2)
            self.add_status(u"Rain sensor: / " + rain_sensor)
        elif report == u"d_running_stations":  # Report running Stations
            self._lcd.lcd_clear()
            if gv.pon is None:
                prg = u"Idle"
            elif gv.pon == 98:  # something is running
                prg = u"Run-once"
            elif gv.pon == 99:
                prg = u"Manual Mode"
            else:
                prg = u"Prog: {}".format(gv.pon)

            s = ""
            if prg != u"Idle":
                # Get Running Stations from gv.ps
                for i in range(len(gv.ps)):
                    p, d = gv.ps[i]
                    if p != 0:
                        s += u"S{} ".format(str(i + 1))
            self._lcd.lcd_puts(prg, 1)
            self._lcd.lcd_puts(s, 2)

        elif report == u"d_alarm_signal":  # ALARM!!!!
            self._lcd.lcd_clear()
            self._lcd.lcd_puts(u"ALARM", 1)
            self._lcd.lcd_puts(txt, 2)
            self.add_status(u"Alarm! / " + txt)

        elif report == u"d_stat_schedule_signal":  # A program has been scheduled
            self._lcd.lcd_clear()
            self._lcd.lcd_puts(u"New Program", 1)
            txt = u"Running"  # Do not Know what else to display
            self._lcd.lcd_puts(txt, 2)
            self.add_status(u"New Program Running / " + txt)

        self._lcd_lock.release()
Exemple #12
0
    def run(self):
        if disable_substations:
            return        

        gv.logger.info('Substation plugin started')        
        time.sleep(7) # let things wake up, but keep less than delay for sending email

        last_message_base = gv.now - 60
        while True:
            try:
                if gv.sd['slave'] and gv.now - last_message_base >= 60:
                    try:
                        last_message_base = gv.now
                        data = message_base('suslj')
                        if 'unreachable' in data:
                            raise IOError, 'UnreachableMaster'
                        force_reboot = False
                        # update common data that has changed on the master
                        for grouping in data:
                            if gv.sd['master']:
                                continue
                            for key in data[grouping]:
                                if grouping == 'sd':
                                    if key in gv.sd:
                                        if gv.sd[key] != data['sd'][key]:
                                            gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key]))
                                            if key == 'remote_support_port' and gv.sd['enable_upnp']:
                                                gv.logger.critical('substation_run: Unexpected key of remote_support_port')
                                                if gv.sd[key] != 0: # delete old
                                                    update_upnp(get_ip(), [gv.sd[key]])
                                                if data['sd'][key] != 0:
                                                    update_upnp(get_ip(), [], [[22, data['sd'][key]]])
                                            gv.sd[key] = data['sd'][key]
                                            if key == 'tza':
                                                with open('/etc/timezone','w') as file:
                                                    file.write(qdict['o'+f]+'\n')
                                                subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata'])
                                                force_reboot = True
                                            elif key == 'loc' or key == 'lang':
                                                force_reboot = True
                                    else:
                                        gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key]))
                                        gv.sd[key] = data['sd'][key]
                                elif grouping in gv.plugin_data:
                                    if key in gv.plugin_data[grouping]:
                                        if gv.plugin_data[grouping][key] != data[grouping][key]:
                                            gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key]))
                                            gv.plugin_data[grouping][key] = data[grouping][key]
                                    else:
                                        gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key]))
                                        gv.plugin_data[grouping][key] = data[grouping][key]
                                elif grouping == 'other':
                                    if key == 'websession':
                                        web.config._session.user = data[grouping][key]
                                    elif key == 'datetime':
                                        try:
                                            pass
#                                            subprocess.call(['date', '--set='+data[grouping][key]])
                                        except:
                                            gv.logger.exception('Could not set datetime to ' + data[grouping][key])
                            if grouping == 'sd':
                                jsave(gv.sd, 'sd')
                            elif grouping != 'other':
                                pass
                        if force_reboot:
                            reboot(5) # give a few seconds before reboot

                    except Exception as ex:
                        gv.logger.info('No master response.  ip: ' + get_ip_to_base() + \
                                       ' port: ' + str(gv.sd['master_port']) + \
                                       ' Exception: ' + str(ex))
                        try:
                            iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                            lines = iwout.split('\n')
                            for l in lines:
                                if 'ESSID:' in l:
                                    gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):])
                        except Exception as ex:
                            gv.logger.info('slave could not check iwconfig: ' + str(ex))

                if gv.sd['master']:
                    for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                        sub = gv.plugin_data['su']['subinfo'][subid]
                        try:
                            if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out
                                qd = {'substation':subid}
                                load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive
                        except Exception as ex:
                            gv.logger.info('substations reach out to slave: No response from slave: ' +
                                           sub['name'] + ' Exception: ' + str(ex))
                            sub['status'] = 'unreachable'
                            try:
                                iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                                lines = iwout.split('\n')
                                for l in lines:
                                    if 'ESSID:' in l:
                                        gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):])
                            except Exception as ex:
                                gv.logger.info('master could not check iwconfig: ' + str(ex))

            except Exception as ex:
                self.start_status('', 'Substation encountered error: ' + str(ex))

            self._sleep(30)
Exemple #13
0
def get_LCD_print(self, report):
    """Print messages to LCD 16x2"""
    datalcd = get_lcd_options()
    adr = 0x20
    if datalcd['adress'] == '0x20':  # range adress from PCF8574 or PCF 8574A
        adr = 0x20
    elif datalcd['adress'] == '0x21':
        adr = 0x21
    elif datalcd['adress'] == '0x22':
        adr = 0x22
    elif datalcd['adress'] == '0x23':
        adr = 0x23
    elif datalcd['adress'] == '0x24':
        adr = 0x24
    elif datalcd['adress'] == '0x25':
        adr = 0x25
    elif datalcd['adress'] == '0x26':
        adr = 0x26
    elif datalcd['adress'] == '0x27':
        adr = 0x27
    elif datalcd['adress'] == '0x38':
        adr = 0x38
    elif datalcd['adress'] == '0x39':
        adr = 0x39
    elif datalcd['adress'] == '0x3a':
        adr = 0x3a
    elif datalcd['adress'] == '0x3b':
        adr = 0x3b
    elif datalcd['adress'] == '0x3c':
        adr = 0x3c
    elif datalcd['adress'] == '0x3d':
        adr = 0x3d
    elif datalcd['adress'] == '0x3e':
        adr = 0x3e
    elif datalcd['adress'] == '0x3f':
        adr = 0x3f
    else:
        self.status = ''
        self.add_status('Error: Address is not range 0x20-0x27 or 0x38-0x3F!')
        self._sleep(5)
        return

    import pylcd2  # Library for LCD 16x2 PCF8574
    lcd = pylcd2.lcd(adr, 1 if get_rpi_revision() >= 2 else 0)  # Address for PCF8574 = example 0x20, Bus Raspi = 1 (0 = 256MB, 1=512MB)

    if report == 0:
        lcd.lcd_clear()
        lcd.lcd_puts("Open Sprinkler", 1)
        lcd.lcd_puts("Irrigation syst.", 2)
        self.add_status('Open Sprinkler. / Irrigation syst.')
    elif report == 1:
        lcd.lcd_clear()
        lcd.lcd_puts("Software ospi:", 1)
        lcd.lcd_puts(gv.ver_date, 2)
        self.add_status('Software ospi: / ' + gv.ver_date)
    elif report == 2:
        lcd.lcd_clear()
        ip = get_ip()
        lcd.lcd_puts("My IP is:", 1)
        lcd.lcd_puts(str(ip), 2)
        self.add_status('My IP is: / ' + str(ip))
    elif report == 3:
        lcd.lcd_clear()
        lcd.lcd_puts("Port IP:", 1)
        lcd.lcd_puts("8080", 2)
        self.add_status('Port IP: / 8080')
    elif report == 4:
        lcd.lcd_clear()
        temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
        lcd.lcd_puts("CPU temperature:", 1)
        lcd.lcd_puts(temp, 2)
        self.add_status('CPU temperature: / ' + temp)
    elif report == 5:
        lcd.lcd_clear()
        da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
        ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
        lcd.lcd_puts(da, 1)
        lcd.lcd_puts(ti, 2)
        self.add_status(da + ' ' + ti)
    elif report == 6:
        lcd.lcd_clear()
        up = uptime()
        lcd.lcd_puts("System run time:", 1)
        lcd.lcd_puts(up, 2)
        self.add_status('System run time: / ' + up)
    elif report == 7:
        lcd.lcd_clear()
        if gv.sd['rs']:
            rain_sensor = "Active"
        else:
            rain_sensor = "Inactive"
        lcd.lcd_puts("Rain sensor:", 1)
        lcd.lcd_puts(rain_sensor, 2)
        self.add_status('Rain sensor: / ' + rain_sensor)
Exemple #14
0
    cmds = [['rm', 'data/substation_proxy_pause'],
            ['rm', 'data/hostapd.conf'],
            ['rm', 'data/dnsmasq.conf'],
            ['chattr', '-i', '/etc/resolv.conf'], # allow overwriting resolv.conf
            ['/etc/init.d/bind9', 'stop'], # only run with master radio
            ['./dnsmasq', 'stop'],
            ['./hostapd', 'stop'],
            ['update-rc.d', 'sip', 'remove'],
            ['update-rc.d', 'sip_net_finish', 'remove'],
            ['update-rc.d', 'sip_monitor', 'defaults'],
            ['sysctl', '/net/ipv4/ip_forward=1'],
           ]
    run_commands(logger, cmds)

    time.sleep(15) # give time for network to come up
    light_ip(get_ip())

    if not config_mode:
        cmds = [
                ['sysctl', 'net.ipv4.tcp_thin_linear_timeouts=1'], # not proven necessary (or problematic)
                ['iw', 'dev', 'wlan0', 'interface', 'add', 'uap0', 'type', '__ap'],
                ['ifup', 'uap0'],
                ['/etc/init.d/bind9', 'start'],
               ]
        run_commands(logger, cmds)

    pi = pigpio.pi()
    button_pin = 21
    pi.set_mode(button_pin, pigpio.INPUT)
    pi.set_pull_up_down(button_pin, pigpio.PUD_UP)
Exemple #15
0
    def POST(self):
        self.logger.debug('in Net POST')
        save_last_get('Net POST')
        form = web.input()
        outdata = []

        net = 'eth0' if 'Use Hardwired eth0' in form else 'wlan0'
        # use hidden SSID if provided
        using_hidden_ssid = False
        if 'Hidden SSID' in form and form['Hidden SSID'].strip() != '':
            using_hidden_ssid = True
            form['SSID'] = form['Hidden SSID']
            self.logger.info('using Hidden SSID')

        use_eth0 = 'SSID' not in form

        if not use_eth0:
            form['SSID'] = form['SSID'].strip()
            form['Password'] = form['Password'].strip()
        else:
            form['SSID'] = 'using eth0'
        self.logger.debug('in Net POST: ' + form['SSID'])

        try:
            drop = 0
            with open('/etc/network/interfaces', 'r') as infile:
                iface = infile.readlines()
            for line in iface:
                did_iface_wlan0 = False
                if drop > 0:
                    drop -= 1
                    continue
                if 'iface ' + net + ' inet' in line:
                    if net == 'wlan0':
                        did_iface_wlan0 = True
                    if 'Use DHCP' in form:
                        self.logger.debug('Using dhcp: ' + form['SSID'])
                        if 'static' in line:
                            drop = 3
                            line = 'iface ' + net + ' inet manual\n'
                    else:
                        self.logger.debug('Using static ip: ' +
                                          form['Static IP'] + ' ' +
                                          form['Netmask'] + ' ' +
                                          form['Gateway'])
                        if 'static' in line:
                            drop = 3
                        outdata.append('iface ' + net + ' inet static\n')
                        outdata.append('        address ' + form['Static IP'] +
                                       '\n')
                        outdata.append('        netmask ' + form['Netmask'] +
                                       '\n')
                        line = '        gateway ' + form['Gateway'] + '\n'
                outdata.append(line)
                if did_iface_wlan0:
                    outdata.append(
                        '        wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n'
                    )

        except Exception as ex:
            self.logger.exception(
                'Unexpected exception trying to configure network: ' + str(ex))
            raise web.seeother('/cn')

        if len(outdata) == 0:
            self.logger.error('Expected data in /etc/network/interfaces')
            raise web.seeother('/cn')

        self.logger.debug(
            'stopping daemons before updating network interfaces')
        #        if not use_eth0:
        #            stop_daemons()

        try:
            with open('/etc/network/interfaces', 'w') as outfile:
                outfile.writelines(outdata)

            if not use_eth0:
                wpa_supp_lines = [
                    'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'
                ]
                wpa_supp_lines.append('update_config=1\n\n')
                if form['SSID'] != '' and form['Password'] != '':
                    # wpa_passphrase cannot handle blanks
                    cmd = 'wpa_passphrase ' + form['SSID'] + ' ' + form[
                        'Password'] + ' > passphrase'
                    subprocess.call(cmd, shell=True)
                    with open('passphrase', 'r') as f:
                        pl = f.readlines()
                        for line in pl:
                            wpa_supp_lines.append(line)
                            if using_hidden_ssid and 'ssid' in line:
                                wpa_supp_lines.append('\tscan_ssid=1\n')
                    subprocess.call(['rm', 'passphrase'])
                else:
                    self.logger.warning('missing ssid or password')

                with open('/etc/wpa_supplicant/wpa_supplicant.conf',
                          'w') as outfile:
                    outfile.writelines(wpa_supp_lines)

                # check if network connection was made
                self.logger.debug('wpa_action stopping wlan0')
                rc = subprocess.call(['wpa_action', 'wlan0', 'stop'])
                self.logger.debug('wpa_action return: ' + str(rc))
                time.sleep(1)
                self.logger.debug('ifup wlan0')
                rc = subprocess.call(['ifup', net])
                self.logger.debug('ifup return: ' + str(rc))
                time.sleep(2)

            if network_up(net):
                #successful network connection.   Finalize
                # copy the current versions to the save version
                if gv.sd['enable_upnp']:  # was enabled?  Then cleanup
                    cur_ip = get_ip(net)
                    deletes = []
                    if gv.sd['external_htp'] != 0:
                        deletes.append(gv.sd['external_htp'])
                    if gv.sd['remote_support_port'] != 0:
                        deletes.append(gv.sd['remote_support_port'])
                    update_upnp(cur_ip, deletes)
                gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0
                if gv.sd['enable_upnp']:
                    if 'UPnP Refresh Rate' in form:
                        gv.sd['upnp_refresh_rate'] = int(
                            form['UPnP Refresh Rate'])

                if 'System Name' in form:
                    gv.sd['name'] = form['System Name']
                    jsave(gv.sd, 'sd')
                if 'System Port' in form:
                    gv.sd['htp'] = int(form['System Port'])
                    jsave(gv.sd, 'sd')
                if 'External System Port' in form:
                    gv.sd['external_htp'] = int(form['External System Port'])
                self.logger.info('success....copying back interfaces and wpa')
                shutil.copy('/etc/network/interfaces',
                            '/etc/network/interfaces.save')
                shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf',
                            '/etc/wpa_supplicant/wpa_supplicant.conf.save')
                #                self.logger.info('success....enabling boiler')
                #                subprocess.call(['update-rc.d', 'boiler', 'defaults'])
                #                self.logger.info('disabling boiler_net_finish')
                #                subprocess.call(['update-rc.d', 'boiler_net_finish', 'remove'])
                self.logger.info('rebooting')
                subprocess.call(['reboot', '-h'])
                exit(0)
            else:
                raise Exception('Network Inaccessible')

        except Exception as ex:
            self.logger.exception('failed: ' + str(ex))
            # restore saved /etc/network/interfaces and wpa_suplicant.conf
            self.logger.info('restore network files and exit.  Exception: ' +
                             str(ex))
            shutil.move('/etc/network/interfaces.save',
                        '/etc/network/interfaces')
            shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save',
                        '/etc/wpa_supplicant/wpa_supplicant.conf')
            exit(1)

        self.logger.error(
            'boiler_net_config: should have exited above.  boiler_monitor will restart'
        )
        raise web.seeother('/')
Exemple #16
0
    def POST(self):
        global error_msg

        if not been_through_subconfig:
            self.logger.info('tried Net POST....back to /su')
            raise web.seeother('/su')

        self.logger.debug('in Net POST')
        save_last_get('Net POST')
        form = web.input()
        error_msg = ''
        outdata = []

        for f in ['Static IP', 'Netmask', 'Gateway', 'DNS Nameservers', 'SSID', 'Password', 'Hidden SSID', 'UPnP Refresh Rate', 'Station Name', 'Station Port', 'External Station Port', 'Remote Substation Access Port', 'Extender SSID', 'Extender Password']:
            if f in form:
                form[f] = form[f].strip()

        # use hidden SSID if provided
        using_hidden_ssid = False
        if 'Hidden SSID' in form and form['Hidden SSID'] != '':
            using_hidden_ssid = True
            form['SSID'] = form['Hidden SSID']
            self.logger.info('using Hidden SSID')

        use_eth0 = 'SSID' not in form or form['SSID'] == 'ethernet'

        if gv.sd['remote_radio_substation']:
            form['SSID'] = 'using radio'
            net = 'radio'
        elif not use_eth0:
            net = 'wlan0'
        else:
            form['SSID'] = 'using eth0'
            net = 'eth0'

        self.logger.debug('in Net POST: ' + form['SSID'])
        gv.sd['light_ip'] = 1
        try:
            if form['DNS Nameservers'][0:1] == 'X' and \
                   (len(form['DNS Nameservers']) == 1 or form['DNS Nameservers'][1:2] == ' '):
                gv.sd['light_ip'] = 0 # hack to disable blinking led on startup with leading X in nameservers
                form['DNS Nameservers'] = form['DNS Nameservers'][1:].strip()
        except:
            pass

        if not gv.sd['remote_radio_substation'] and 'Use DHCP' in form:
            for d in ['DNS Search', 'DNS Nameservers']:
                if d in form and form[d] != '':
                    error_msg = 'Error:  "' + d + '" must be blank with "Use DHCP".'
                    raise web.seeother('/cn') # back to form

        pass_len = 0 if 'Extender Password' not in form else len(form['Extender Password'])
        if 'Extender SSID' in form and form['Extender SSID'] != '':
            if pass_len < 8 or pass_len > 63:
                error_msg = 'Error:  "Extender Password" must be between 8 and 63 characters.'
                raise web.seeother('/cn') # back to form
        else: # force data to be present and safe
            form['Extender SSID'] = ''
            form['Extender Password'] = ''

        pass_len = 0 if 'Password' not in form else len(form['Password'])
        if not gv.sd['remote_radio_substation'] and not using_eth0 and (pass_len < 8 or pass_len > 63):
            error_msg = 'Error:  "Password" must be between 8 and 63 characters.'
            raise web.seeother('/cn') # back to form

        if 'Station Name' in form:
            sn = validate_fqdn(form['Station Name'])
            if sn == 'Irricloud': # error condition
                error_msg = 'Error:  "Station Name" must have only letter and numbers.'
                raise web.seeother('/cn') # back to form
            elif len(sn) > 50 or len(sn) < 1:
                error_msg = 'Error:  "Station Name" must be at most 50 characters.'
                raise web.seeother('/cn') # back to form
            form['Station Name'] = sn

        for portn in ['Station Port', 'External Station Port', 'Remote Substation Access Port', 'UPnP Refresh Rate']:
            if portn in form:
                try:
                    port = int(form[portn])
                except:
                    error_msg = 'Error:  "' + portn + '" must be integer.'
                    raise web.seeother('/cn') # back to form
                if port < 0 or port > 65535:
                    error_msg = 'Error:  "' + portn + '" must be between 0 and 65535.'
                    raise web.seeother('/cn') # back to form
                if portn == 'Station Port' and port == 9080: # specially reserved for proxy
                    error_msg = 'Error:  "' + portn + '" cannot be 9080.'
                    raise web.seeother('/cn') # back to form

        try:
            drop = 0
            with open('/etc/network/interfaces','r') as infile:
                iface = infile.readlines()
            for line in iface:
                if 'dns-nameservers' in line:
                    continue # delete any old dns stuff
                did_iface_wlan0 = False
                if drop > 0:
                    drop -= 1
                    continue
                if 'iface ' + net + ' inet' in line:
                    if net == 'wlan0':
                        did_iface_wlan0 = True
                    if 'Use DHCP' in form:
                        self.logger.info('Using dhcp: ' + form['SSID'])
                        if 'static' in line:
                            drop = 3
                            line = 'iface ' + net + ' inet manual\n'
                    else:
                        self.logger.info('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway'])
                        if 'static' in line:
                            drop = 3
                        outdata.append('iface ' + net + ' inet static\n')
                        outdata.append('        address ' + form['Static IP'] + '\n')
                        outdata.append('        netmask ' + form['Netmask'] + '\n')
                        line = '        gateway ' + form['Gateway'] +'\n'
                        outdata.append(line)
                        if 'DNS Nameservers' in form and form['DNS Nameservers'] != '':
                            line = '        dns-nameservers ' + form['DNS Nameservers'] +'\n'
                        else: # use gateway
                            line = '        dns-nameservers ' + form['Gateway'] +'\n'
                elif 'iface ' + 'wlan0' + ' inet' in line: # using eth0 or radio only, but need to clean up 10.0.0.1 entry
                    if 'static' in line:
                        drop = 3
                        line = 'iface ' + 'wlan0' + ' inet manual\n'
                        did_iface_wlan0 = True

                outdata.append(line)
                if did_iface_wlan0:
                    outdata.append('        wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n')

        except Exception as ex:
            self.logger.exception('Unexpected exception trying to configure network: ' + str(ex))
            raise web.seeother('/cn')

        if len(outdata) == 0:
            self.logger.error('Expected data in /etc/network/interfaces')
            raise web.seeother('/cn')

        self.logger.info('stopping daemons before updating network interfaces')
        stop_daemons()

        try:
            with open('/etc/network/interfaces','w') as outfile:
                outfile.writelines(outdata)

            # Do not let dhcpcd get a dhcp address (and dns info?) if we are using a static config
            if 'Use DHCP' in form:
                shutil.copy2('/etc/dhcpcd.conf.yeswlan0', '/etc/dhcpcd.conf')
            else:
                shutil.copy2('/etc/dhcpcd.conf.nowlan0', '/etc/dhcpcd.conf')

            # if we are going to broadcast our own ssid to extend reach, save ssid and password
            broad_wpa_info = wpa_passphrase(form['Extender SSID'], form['Extender Password'])
            if len(broad_wpa_info['ssid']) > 2 and broad_wpa_info['ssid'][0] == '"': # strip off quotes for hostapd.conf
                broad_wpa_info['ssid'] = broad_wpa_info['ssid'][1:len(broad_wpa_info['ssid'])-1]
            gv.sd['extender_ssid'] = broad_wpa_info['ssid']
            gv.sd['extender_psk'] = broad_wpa_info['psk']

            if not gv.sd['remote_radio_substation'] and not use_eth0:
                wpa_supp_lines = ['ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n']
                wpa_supp_lines.append('update_config=1\n\n')
                if form['SSID'] != '' and form['Password'] != '':
                    wpa_info = wpa_passphrase(form['SSID'], form['Password'])
                    wpa_supp_lines.append('network={\n')
                    wpa_supp_lines.append('\tssid=' + wpa_info['ssid'] + '\n')
                    if using_hidden_ssid:
                        wpa_supp_lines.append('\tscan_ssid=1\n')
                    wpa_supp_lines.append('\tpsk=' + wpa_info['psk'] + '\n')
                    wpa_supp_lines.append('}\n')
                else:
                    self.logger.warning('missing ssid or password')

                with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile:
                    outfile.writelines(wpa_supp_lines)

                # check if network connection was made
#                self.logger.debug('wpa_action stopping wlan0')
#                rc = subprocess.call(['wpa_action', 'wlan0', 'stop'])
#                self.logger.debug( 'wpa_action wlan0 stop return: ' + str(rc))
#                time.sleep(1)
#                self.logger.debug('ifup wlan0')
#                rc = subprocess.call(['ifup', 'wlan0'])
#                self.logger.debug( 'ifup return: ' + str(rc))
#                time.sleep(1)
#                rc = subprocess.call(['wpa_action', 'wlan0', 'reload'])
#                self.logger.debug( 'wpa_action wlan0 reload return: ' + str(rc))
#                time.sleep(1)
#                reset_networking()

            if True or 'Do not validate network connection' in form or network_up(net, self.logger):
                #successful network connection.   Finalize
                # copy the current versions to the save version
                cur_ip = get_ip(net)
                self.logger.info('success...cur_ip: ' + cur_ip)
                if gv.sd['enable_upnp']: # was enabled?  Then cleanup.  If network still points to 10.0.0.1 network cant cleanup!
                    deletes = []
                    if gv.sd['external_htp'] != 0:
                        deletes.append(gv.sd['external_htp'])
                    if gv.sd['remote_support_port'] != 0:
                        deletes.append(gv.sd['remote_support_port'])
                    if gv.sd['external_proxy_port'] != 0:
                        deletes.append(gv.sd['external_proxy_port'])
                    update_upnp(cur_ip, self.logger, deletes)
                gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0
                if gv.sd['enable_upnp']:
                    if 'UPnP Refresh Rate' in form:
                        gv.sd['upnp_refresh_rate'] = int(form['UPnP Refresh Rate'])
                if 'Station Name' in form:
                    gv.sd['name'] = form['Station Name']
                    update_hostname(gv.sd['name'])
                if 'Station Port' in form:
                    gv.sd['htp'] = int(form['Station Port'])
                if gv.sd['master']:
                    gv.sd['master_ip'] = 'localhost' # update local master_port 
                    gv.sd['master_port'] == gv.sd['htp']
                else:
                    gv.sd['master_port'] = 0
                gv.sd['external_htp'] = int(form['External Station Port']) if 'External Station Port' in form else 0
                gv.sd['external_proxy_port'] = int(form['Remote Substation Access Port']) if 'Remote Substation Access Port' in form else 0
                jsave(gv.sd, 'sd')
                self.logger.info('success....copying back interfaces and wpa')
                try:
                    os.remove('/etc/resolv.conf')
                except:
                    pass
                shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save')
                shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save')
#                self.logger.info('success....enabling sip')
#                subprocess.call(['systemctl', 'enable', 'sip.service'])
##                subprocess.call(['update-rc.d', 'sip', 'enable'])
##                subprocess.call(['update-rc.d', 'sip', 'defaults'])
##                self.logger.info('disabling sip_net_finish')
#                subprocess.call(['systemctl', 'disable', 'sip_net_finish.service'])
##                subprocess.call(['update-rc.d', '-f', 'sip_net_finish', 'remove'])
#                light_ip(cur_ip)
                self.logger.info('rebooting')
                subprocess.call(['reboot', '-h'])
                exit(0)
            else:
                raise Exception('Network Inaccessible')

        except Exception as ex:
            self.logger.exception('failed: ' + str(ex))
            # restore saved /etc/network/interfaces and wpa_suplicant.conf
            self.logger.info('restore network files and exit.  Exception: ' + str(ex))
            shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces')
            shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf')
            exit(1)

        self.logger.error('sip_net_config: should have exited above.  sip_monitor will restart')
        raise web.seeother('/cn')
Exemple #17
0
    def _lcd_print(self, report, txt=None):
        self._lcd.acquire()
        """Print messages to LCD 16x2"""
        datalcd = get_lcd_options()
        adr = 0x20
        if datalcd[
                'adress'] == '0x20':  # range adress from PCF8574 or PCF 8574A
            adr = 0x20
        elif datalcd['adress'] == '0x21':
            adr = 0x21
        elif datalcd['adress'] == '0x22':
            adr = 0x22
        elif datalcd['adress'] == '0x23':
            adr = 0x23
        elif datalcd['adress'] == '0x24':
            adr = 0x24
        elif datalcd['adress'] == '0x25':
            adr = 0x25
        elif datalcd['adress'] == '0x26':
            adr = 0x26
        elif datalcd['adress'] == '0x27':
            adr = 0x27
        elif datalcd['adress'] == '0x38':
            adr = 0x38
        elif datalcd['adress'] == '0x39':
            adr = 0x39
        elif datalcd['adress'] == '0x3a':
            adr = 0x3a
        elif datalcd['adress'] == '0x3b':
            adr = 0x3b
        elif datalcd['adress'] == '0x3c':
            adr = 0x3c
        elif datalcd['adress'] == '0x3d':
            adr = 0x3d
        elif datalcd['adress'] == '0x3e':
            adr = 0x3e
        elif datalcd['adress'] == '0x3f':
            adr = 0x3f
        else:
            self.status = ''
            self.add_status(
                'Error: Address is not range 0x20-0x27 or 0x38-0x3F!')
            self._sleep(5)
            return

        import pylcd2  # Library for LCD 16x2 PCF8574
        lcd = pylcd2.lcd(
            adr, 1 if get_rpi_revision() >= 2 else 0
        )  # Address for PCF8574 = example 0x20, Bus Raspi = 1 (0 = 256MB, 1=512MB)

        if report == 'name':
            lcd.lcd_clear()
            lcd.lcd_puts(gv.sd['name'], 1)
            lcd.lcd_puts("Irrigation syst.", 2)
            self.add_status('SIP. / Irrigation syst.')
        elif report == 'd_sw_version':
            lcd.lcd_clear()
            lcd.lcd_puts("Software SIP:", 1)
            lcd.lcd_puts(gv.ver_date, 2)
            self.add_status('Software SIP: / ' + gv.ver_date)
        elif report == 'd_ip':
            lcd.lcd_clear()
            ip = get_ip()
            lcd.lcd_puts("My IP is:", 1)
            lcd.lcd_puts(str(ip), 2)
            self.add_status('My IP is: / ' + str(ip))
        elif report == 'd_port':
            lcd.lcd_clear()
            lcd.lcd_puts("Port IP:", 1)
            lcd.lcd_puts(str(gv.sd['htp']), 2)
            self.add_status('Port IP: / {}'.format(gv.sd['htp']))
        elif report == 'd_cpu_temp':
            lcd.lcd_clear()
            temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
            lcd.lcd_puts("CPU temperature:", 1)
            lcd.lcd_puts(temp, 2)
            self.add_status('CPU temperature: / ' + temp)
        elif report == 'd_date_time':
            lcd.lcd_clear()
            da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
            ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))
            lcd.lcd_puts(da, 1)
            lcd.lcd_puts(ti, 2)
            self.add_status(da + ' ' + ti)
        elif report == 'd_uptime':
            lcd.lcd_clear()
            up = uptime()
            lcd.lcd_puts("System run time:", 1)
            lcd.lcd_puts(up, 2)
            self.add_status('System run time: / ' + up)
        elif report == 'd_rain_sensor':
            lcd.lcd_clear()
            if gv.sd['rs']:
                rain_sensor = "Active"
            else:
                rain_sensor = "Inactive"
            lcd.lcd_puts("Rain sensor:", 1)
            lcd.lcd_puts(rain_sensor, 2)
            self.add_status('Rain sensor: / ' + rain_sensor)
        elif report == 'd_running_stations':  # Report running Stations
            lcd.lcd_clear()
            if gv.pon is None:
                prg = 'Idle'
            elif gv.pon == 98:  # something is running
                prg = 'Run-once'
            elif gv.pon == 99:
                prg = 'Manual Mode'
            else:
                prg = "Prog: {}".format(gv.pon)

            s = ""
            if prg != "Idle":
                # Get Running Stations from gv.ps
                for i in range(len(gv.ps)):
                    p, d = gv.ps[i]
                    if p != 0:
                        s += "S{} ".format(str(i))
            lcd.lcd_puts(prg, 1)
            lcd.lcd_puts(s, 2)

        elif report == 'd_alarm_signal':  # ALARM!!!!
            lcd.lcd_clear()
            lcd.lcd_puts("ALARM", 1)
            lcd.lcd_puts(txt, 2)
            self.add_status('Alarm! / ' + txt)

        elif report == 'd_stat_schedule_signal':  # A program has been scheduled
            lcd.lcd_clear()
            lcd.lcd_puts("New Program", 1)
            txt = "Running"  # Do not Know what else to display
            lcd.lcd_puts(txt, 2)
            self.add_status('New Program Running / ' + txt)

        self._lcd.release()
Exemple #18
0
def sms_check(self):
    """Control and processing SMS"""
    data = get_sms_options()  # Load data from json file
    tel1 = data['tel1']
    tel2 = data['tel2']
    comm1 = data['txt1']
    comm2 = data['txt2']
    comm3 = data['txt3']
    comm4 = data['txt4']
    comm5 = data['txt5']
    comm6 = data['txt6']

    sm = gammu.StateMachine()
    sm.ReadConfig()
    try:
        sm.Init()
        print "Checking SMS..."
    except:
        print "Error: SMS modem fault"

    status = sm.GetSMSStatus()
    remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed']
    sms = []
    start = True
    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)
    data = gammu.LinkSMS(sms)
    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        print '%-15s: %s' % ('Sender', m['Number'])
        print '%-15s: %s' % ('Date', str(m['DateTime']))
        print '%-15s: %s' % ('State', m['State'])
        print '%-15s: %s' % ('SMS command', m['Text'])
        if (m['Number'] == tel1) or (m['Number'] == tel2):  # If telephone is admin 1 or admin 2
            self.add_status(time.strftime("%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) + ' SMS from admin')
            if m['State'] == "UnRead":          # If SMS is unread
                if m['Text'] == comm1:           # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    self.add_status('Command ' + comm1 + ' is processed')
                    if gv.lrun[1] == 98:
                        pgr = 'Run-once'
                    elif gv.lrun[1] == 99:
                        pgr = 'Manual'
                    else:
                        pgr = str(gv.lrun[1])
                    start = time.gmtime(gv.now - gv.lrun[2])
                    if pgr != '0':
                        logline = ' {program: ' + pgr + ',station: ' + str(gv.lrun[0]) + ',duration: ' + timestr(
                            gv.lrun[2]) + ',start: ' + time.strftime("%H:%M:%S - %Y-%m-%d", start) + '}'
                    else:
                        logline = ' Last program none'
                    revision = ' Rev: ' + gv.ver_date
                    datastr = ('On ' + time.strftime("%d.%m.%Y at %H:%M:%S", time.localtime(
                        time.time())) + '. Run time: ' + uptime() + ' IP: ' + get_ip() + logline + revision)
                    message = {
                        'Text': datastr,
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm1 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    self.add_status('SMS text: ' + datastr)

                    sm.DeleteSMS(m['Folder'], m['Location'])  # SMS deleted
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm2:        # If command = comm2 (stop - system SIP off)
                    self.add_status('Command ' + comm2 + ' is processed')
                    gv.sd['en'] = 0            # disable system SIP
                    jsave(gv.sd, 'sd')         # save en = 0
                    message = {
                        'Text': 'Command: ' + comm2 + ' was processed',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm2 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm3:         # If command = comm3 (start - system SIP on)
                    self.add_status('Command ' + comm3 + ' is processed')
                    gv.sd['en'] = 1             # enable system SIP
                    jsave(gv.sd, 'sd')          # save en = 1
                    message = {
                        'Text': 'Command: ' + comm3 + ' was processed',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm3 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm4:        # If command = comm4 (reboot system)
                    self.add_status('Command ' + comm4 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm4 + ' was processed',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm4 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted and system is now reboot')
                    self._sleep(10)
                    reboot()                    # restart linux system

                elif m['Text'] == comm5:        # If command = comm5 (poweroff system)
                    self.add_status('Command ' + comm5 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm5 + ' was processed',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm5 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted and system is now poweroff')
                    self._sleep(10)
                    poweroff()                  # poweroff linux system

                elif m['Text'] == comm6:        # If command = comm6 (update SIP system)
                    self.add_status('Command ' + comm6 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm6 + ' was processed',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm6 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    try:
                        from plugins.system_update import perform_update

                        perform_update()
                        self.add_status('Received SMS was deleted, update was performed and program will restart')
                    except ImportError:
                        self.add_status('Received SMS was deleted, but could not perform update')

                    sm.DeleteSMS(m['Folder'], m['Location'])

                else:                            # If SMS command is not defined
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received command ' + m['Text'] + ' is not defined!')

            else:                                # If SMS was read
                sm.DeleteSMS(m['Folder'], m['Location'])
                self.add_status('Received SMS was deleted - SMS was read')
        else:                          # If telephone number is not admin 1 or admin 2 phone number
            sm.DeleteSMS(m['Folder'], m['Location'])
            self.add_status('Received SMS was deleted - SMS was not from admin')
Exemple #19
0
def sms_check(self):
    """Control and processing SMS"""
    data = get_sms_options()  # Load data from json file
    tel1 = data['tel1']
    tel2 = data['tel2']
    comm1 = data['txt1']
    comm2 = data['txt2']
    comm3 = data['txt3']
    comm4 = data['txt4']
    comm5 = data['txt5']
    comm6 = data['txt6']

    sm = gammu.StateMachine()
    sm.ReadConfig()
    try:
        sm.Init()
        print "Checking SMS..."
    except:
        print "Error: SMS modem fault"

    status = sm.GetSMSStatus()
    remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed']
    sms = []
    start = True
    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)
    data = gammu.LinkSMS(sms)
    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        print '%-15s: %s' % ('Sender', m['Number'])
        print '%-15s: %s' % ('Date', str(m['DateTime']))
        print '%-15s: %s' % ('State', m['State'])
        print '%-15s: %s' % ('SMS command', m['Text'])
        if (m['Number']
                == tel1) or (m['Number']
                             == tel2):  # If telephone is admin 1 or admin 2
            self.add_status(
                time.strftime("%d.%m.%Y at %H:%M:%S",
                              time.localtime(time.time())) + ' SMS from admin')
            if m['State'] == "UnRead":  # If SMS is unread
                if m['Text'] == comm1:  # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    self.add_status('Command ' + comm1 + ' is processed')
                    if gv.lrun[1] == 98:
                        pgr = 'Run-once'
                    elif gv.lrun[1] == 99:
                        pgr = 'Manual'
                    else:
                        pgr = str(gv.lrun[1])
                    start = time.gmtime(gv.now - gv.lrun[2])
                    if pgr != '0':
                        logline = ' {program: ' + pgr + ',station: ' + str(
                            gv.lrun[0]) + ',duration: ' + timestr(
                                gv.lrun[2]) + ',start: ' + time.strftime(
                                    "%H:%M:%S - %Y-%m-%d", start) + '}'
                    else:
                        logline = ' Last program none'
                    revision = ' Rev: ' + gv.ver_date
                    datastr = ('On ' + time.strftime(
                        "%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) +
                               '. Run time: ' + uptime() + ' IP: ' + get_ip() +
                               logline + revision)
                    message = {
                        'Text': datastr,
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm1 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    self.add_status('SMS text: ' + datastr)

                    sm.DeleteSMS(m['Folder'], m['Location'])  # SMS deleted
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm2:  # If command = comm2 (stop - system OSPi off)
                    self.add_status('Command ' + comm2 + ' is processed')
                    gv.sd['en'] = 0  # disable system OSPi
                    jsave(gv.sd, 'sd')  # save en = 0
                    message = {
                        'Text': 'Command: ' + comm2 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm2 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm3:  # If command = comm3 (start - system ospi on)
                    self.add_status('Command ' + comm3 + ' is processed')
                    gv.sd['en'] = 1  # enable system OSPi
                    jsave(gv.sd, 'sd')  # save en = 1
                    message = {
                        'Text': 'Command: ' + comm3 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm3 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm4:  # If command = comm4 (reboot system)
                    self.add_status('Command ' + comm4 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm4 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm4 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status(
                        'Received SMS was deleted and system is now reboot')
                    self._sleep(10)
                    reboot()  # restart linux system

                elif m['Text'] == comm5:  # If command = comm5 (poweroff system)
                    self.add_status('Command ' + comm5 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm5 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm5 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status(
                        'Received SMS was deleted and system is now poweroff')
                    self._sleep(10)
                    poweroff()  # poweroff linux system

                elif m['Text'] == comm6:  # If command = comm6 (update ospi system)
                    self.add_status('Command ' + comm6 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm6 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm6 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    try:
                        from plugins.system_update import perform_update

                        perform_update()
                        self.add_status(
                            'Received SMS was deleted, update was performed and program will restart'
                        )
                    except ImportError:
                        self.add_status(
                            'Received SMS was deleted, but could not perform update'
                        )

                    sm.DeleteSMS(m['Folder'], m['Location'])

                else:  # If SMS command is not defined
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received command ' + m['Text'] +
                                    ' is not defined!')

            else:  # If SMS was read
                sm.DeleteSMS(m['Folder'], m['Location'])
                self.add_status('Received SMS was deleted - SMS was read')
        else:  # If telephone number is not admin 1 or admin 2 phone number
            sm.DeleteSMS(m['Folder'], m['Location'])
            self.add_status(
                'Received SMS was deleted - SMS was not from admin')
Exemple #20
0
    def _lcd_print(self, report, txt=None):
        self._lcd.acquire()
        """Print messages to OLED 128x32"""
        dataoled = get_oled_options()

        #define RST pin
        adr = dataoled['adress']
        #configure display settings
        disp = Adafruit_SSD1306.SSD1306_128_32(
            rst=int(adr), gpio=GPIO.get_platform_gpio(mode=RPi.GPIO.BOARD))

        disp.begin()
        disp.clear()
        disp.display()
        width = disp.width
        height = disp.height
        image = Image.new('1', (width, height))
        draw = ImageDraw.Draw(image)
        draw.rectangle((0, 0, width, height), outline=0, fill=0)
        padding = -2
        top = padding
        bottom = height - padding
        x = 0
        font = ImageFont.load_default()

        if report == 'name':
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Name: ", font=font, fill=255)
            draw.text((x, top + 8), str(gv.sd['name']), font=font, fill=255)
            draw.text((x, top + 16), "Irrigation syst.", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('SIP. / Irrigation syst.')
        elif report == 'd_sw_version':
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Software SIP: ", font=font, fill=255)
            draw.text((x, top + 8), str(gv.ver_date), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('Software SIP: / ' + gv.ver_date)
        elif report == 'd_ip':
            ip = get_ip()
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "My IP is: ", font=font, fill=255)
            draw.text((x, top + 8), str(ip), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('My IP is: / ' + str(ip))
        elif report == 'd_port':
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Port IP: ", font=font, fill=255)
            draw.text((x, top + 8), str(gv.sd['htp']), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('Port IP: / {}'.format(gv.sd['htp']))
        elif report == 'd_cpu_temp':
            temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "CPU temperature: ", font=font, fill=255)
            draw.text((x, top + 8), str(temp), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('CPU temperature: / ' + temp)
        elif report == 'd_date_time':
            da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
            ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))

            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Date Time: ", font=font, fill=255)
            draw.text((x, top + 8), str(da), font=font, fill=255)
            draw.text((x, top + 16), str(ti), font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status(da + ' ' + ti)
        elif report == 'd_uptime':
            up = uptime()
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "System run Time: ", font=font, fill=255)
            draw.text((x, top + 8), str(up), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('System run time: / ' + up)
        elif report == 'd_rain_sensor':
            if gv.sd['rs']:
                rain_sensor = "Active"
            else:
                rain_sensor = "Inactive"
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Rain sensor: ", font=font, fill=255)
            draw.text((x, top + 8), str(rain_sensor), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('Rain sensor: / ' + rain_sensor)
        elif report == 'd_running_stations':  # Report running Stations
            if gv.pon is None:
                prg = 'Idle'
            elif gv.pon == 98:  # something is running
                prg = 'Run-once'
            elif gv.pon == 99:
                prg = 'Manual Mode'
            else:
                prg = "Prog: {}".format(gv.pon)

            s = ""
            if prg != "Idle":
                # Get Running Stations from gv.ps
                for i in range(len(gv.ps)):
                    p, d = gv.ps[i]
                    if p != 0:
                        s += "S{} ".format(str(i + 1))
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Running Stations: ", font=font, fill=255)
            draw.text((x, top + 8), str(prg), font=font, fill=255)
            draw.text((x, top + 16), str(s), font=font, fill=255)
            disp.image(image)
            disp.display()
        elif report == 'd_alarm_signal':  # ALARM!!!!
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "ALARM!: ", font=font, fill=255)
            draw.text((x, top + 8), str(txt), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
        elif report == 'd_stat_schedule_signal':  # A program has been scheduled
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "New program: ", font=font, fill=255)
            draw.text((x, top + 8), "Running", font=font, fill=255)
            draw.text((x, top + 16), "...", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('New Program Running / ')
        self._lcd.release()