示例#1
0
    def settings(self, s):
        user = self.getSessionUser()
        if user is None or user.get('uid', '') == '':
            s.redirect('login?redirect_uri={0}'.format('settings'))
            return

        update = checkupdate()
        confJSON = json.dumps(configuration)
        public_url = getTunnelUrl()
        message = ''
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
        code = readFile(os.path.join(FILE_DIR, CONFIGFILE))
        logs = readFile(os.path.join(logfilepath, LOGFILE))
        template = TEMPLATE.format(message=message,
                                   uptime=uptime(),
                                   list=deviceList,
                                   meta=meta,
                                   code=code,
                                   conf=confJSON,
                                   public_url=public_url,
                                   logs=logs,
                                   update=update,
                                   branch=branch,
                                   dzversion=settings['dzversion'])

        s.send_message(200, template)
    def settings(self, s):
        public_url = PUBLIC_URL
        try:
            getDevices()
        except Exception as e:
            logger.error(
                'Connection to Domoticz refused!. Check configuration')

        if 'ngrok_tunnel' in configuration and configuration['ngrok_tunnel']:
            tunnels = getTunnelUrl()
            tunnel = tunnels[0].public_url
            if 'https' not in tunnel:
                public_url = tunnel.replace('http', 'https')
            else:
                public_url = tunnel

        user = self.getSessionUser()
        if user == None or user.get('uid', '') == '':
            s.redirect('/login?redirect_uri={0}'.format('/settings'))
            return
        message = ''
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
        code = readFile(CONFIGFILE)
        logs = readFile(LOGFILE)
        template = TEMPLATE.format(message=message,
                                   uptime=uptime(),
                                   list=deviceList,
                                   meta=meta,
                                   code=code,
                                   conf=confJSON,
                                   public_url=public_url,
                                   logs=logs,
                                   update=update)

        s.send_message(200, template)
    def settings(self, s):
        try:
            getDevices()
        except Exception as e:
            logger.error(
                'Connection to Domoticz refused! Check configuration.')

        user = self.getSessionUser()
        if user == None or user.get('uid', '') == '':
            s.redirect('/login?redirect_uri={0}'.format('/settings'))
            return

        update = checkupdate()
        confJSON = json.dumps(configuration)
        public_url = getTunnelUrl()
        message = ''
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
        code = readFile(CONFIGFILE)
        logs = readFile(LOGFILE)
        template = TEMPLATE.format(message=message,
                                   uptime=uptime(),
                                   list=deviceList,
                                   meta=meta,
                                   code=code,
                                   conf=confJSON,
                                   public_url=public_url,
                                   logs=logs,
                                   update=update)

        s.send_message(200, template)
示例#4
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)
示例#5
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)
示例#6
0
 def _info_data(self):
     """Returns the info data."""
     self.add_status('System release: ' + platform.release())
     self.add_status('System name: ' + platform.system())
     self.add_status('Node: ' + platform.node())
     self.add_status('Machine: ' + platform.machine())
     self.add_status('Distribution: ' + (platform.linux_distribution()[0]) + ' ' + (platform.linux_distribution()[1]))
     meminfo = get_meminfo()
     self.add_status('Total memory: {0}'.format(meminfo['MemTotal']))
     self.add_status('Free memory: {0}'.format(meminfo['MemFree']))
     netdevs = get_netdevs()
     for dev in netdevs.keys():
         self.add_status('{0}: {1} MiB {2} MiB'.format(dev, netdevs[dev].rx, netdevs[dev].tx))
     self.add_status('Up time: ' + uptime())
     self.add_status('CPU temp: ' + get_cpu_temp() + 'C')
     self.add_status('MAC adress: ' + get_mac())
示例#7
0
    def settings(self, s):
        user = self.getSessionUser()
        if user is None or user.get('uid', '') == '':
            s.redirect('login?redirect_uri={0}'.format('settings'))
            return

        enableReport = ReportState.enable_report_state()
        update = checkupdate()
        public_url = getTunnelUrl()
        message = ''
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
        code = readFile(os.path.join(FILE_DIR, CONFIGFILE))

        templatepage = env.get_template('home.html')
        s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
    def settings_post(self, s):
        update = checkupdate()
        confJSON = json.dumps(configuration)
        public_url = getTunnelUrl()
        logs = readFile(LOGFILE)
        code = readFile(CONFIGFILE)
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'

        if (s.form.get("save")):
            textToSave = s.form.get("save", None)
            codeToSave = textToSave.replace("+", " ")
            saveFile(CONFIGFILE, codeToSave)
            message = 'Config saved'
            logger.info(message)

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)

        if (s.form.get("backup")):
            codeToSave = readFile(CONFIGFILE)
            saveFile('config.yaml.bak', codeToSave)
            message = 'Backup saved'
            logger.info(message)

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)

        if (s.form.get("restart")):
            message = 'Restart Server, please wait!'
            meta = '<meta http-equiv="refresh" content="5">'
            code = ''
            logs = ''

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)
            restartServer()

        if (s.form.get("sync")):
            if configuration[
                    'Homegraph_API_Key'] != 'ADD_YOUR HOMEGRAPH_API_KEY_HERE':
                r = self.forceDevicesSync()
                time.sleep(0.5)
                if r == True:
                    message = 'Devices syncronized'
                else:
                    message = 'Homegraph api key not valid!'
            else:
                message = 'Add Homegraph api key to sync devices here!'

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if (s.form.get("reload")):
            message = ''

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if (s.form.get("deletelogs")):
            logfile = os.path.join(FILE_DIR, LOGFILE)
            if os.path.exists(logfile):
                f = open(logfile, 'w')
                f.close()
            logger.info('Logs removed by user')
            message = ''

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if (s.form.get("update")):
            repo.git.reset('--hard')
            repo.remotes.origin.pull()
            message = 'Updated, Restarting Server, please wait!'
            meta = '<meta http-equiv="refresh" content="5">'

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)
            restartServer()
    def settings_post(self, s):

        if (s.form.get("save")):
            textToSave = s.form.get("save", None)
            codeToSave = textToSave.replace("+", " ")
            saveFile(CONFIGFILE, codeToSave)

            message = 'Config saved'
            logger.info(message)
            meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
            code = readFile(CONFIGFILE)
            logs = readFile(LOGFILE)
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)

        if (s.form.get("backup")):
            codeToSave = readFile(CONFIGFILE)
            saveFile('config.yaml.bak', codeToSave)

            message = 'Backup saved'
            logger.info(message)
            meta = '<!-- <meta http-equiv="refresh" content="5"> -->'
            code = readFile(CONFIGFILE)
            logs = readFile(LOGFILE)
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)

        if (s.form.get("restart")):
            message = 'Restart Server, please wait!'
            meta = '<meta http-equiv="refresh" content="5">'
            code = ''
            logs = ''
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)
            restartServer()

        if (s.form.get("sync")):
            r = self.forceDevicesSync()
            time.sleep(0.5)
            message = 'Devices syncronized'
            meta = '<!-- <meta http-equiv="refresh" content="10"> -->'
            code = readFile(CONFIGFILE)
            logs = readFile(LOGFILE)
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if (s.form.get("reload")):
            message = ''
            meta = '<!-- <meta http-equiv="refresh" content="10"> -->'
            code = readFile(CONFIGFILE)
            logs = readFile(LOGFILE)
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if (s.form.get("deletelogs")):
            logfile = os.path.join(FILE_DIR, LOGFILE)
            if os.path.exists(logfile):
                f = open(logfile, 'w')
                f.close()
            logger.info('Logs removed by user')
            message = ''
            meta = '<!-- <meta http-equiv="refresh" content="10"> -->'
            code = readFile(CONFIGFILE)
            logs = readFile(LOGFILE)
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if (s.form.get("update")):
            os.system('bash ~/Domoticz-Google-Assistant/scripts/update.sh')
            message = 'Updated, Restarting Server, please wait!'
            meta = '<meta http-equiv="refresh" content="5">'
            code = readFile(CONFIGFILE)
            logs = readFile(LOGFILE)
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)
            restartServer()
示例#10
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.')
                     uptime, getTunnelUrl, FILE_DIR, logger)

from const import (
    DOMOTICZ_TO_GOOGLE_TYPES, ERR_FUNCTION_NOT_SUPPORTED, ERR_PROTOCOL_ERROR,
    ERR_DEVICE_OFFLINE, TEMPLATE, ERR_UNKNOWN_ERROR, ERR_CHALLENGE_NEEDED,
    REQUEST_SYNC_BASE_URL, Auth, DOMOTICZ_URL, DOMOTICZ_GET_ALL_DEVICES_URL,
    DOMOTICZ_GET_SETTINGS_URL, DOMOTICZ_GET_ONE_DEVICE_URL,
    DOMOTICZ_GET_SCENES_URL, DOMOTICZ_GET_CAMERAS_URL, groupDOMAIN,
    sceneDOMAIN, lightDOMAIN, switchDOMAIN, blindsDOMAIN, screenDOMAIN,
    pushDOMAIN, climateDOMAIN, tempDOMAIN, lockDOMAIN, invlockDOMAIN,
    colorDOMAIN, mediaDOMAIN, speakerDOMAIN, cameraDOMAIN, securityDOMAIN,
    outletDOMAIN, sensorDOMAIN, doorDOMAIN, selectorDOMAIN, fanDOMAIN,
    ATTRS_BRIGHTNESS, ATTRS_THERMSTATSETPOINT, ATTRS_COLOR, ATTRS_COLOR_TEMP,
    ATTRS_PERCENTAGE, VERSION, PUBLIC_URL)

print("The system uptime is:", uptime())

try:
    r = requests.get(
        DOMOTICZ_URL +
        '/json.htm?type=command&param=addlogmessage&message=Connected to Google Assistant with DZGA v'
        + VERSION,
        auth=(configuration['Domoticz']['username'],
              configuration['Domoticz']['password']))
except Exception as e:
    logger.error('Connection to Domoticz refused!. Check configuration')

update = 0
confJSON = json.dumps(configuration)
public_url = PUBLIC_URL
示例#12
0
文件: lcd_adj.py 项目: alustig/OSPi
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)
示例#13
0
    def settings_post(self, s):
        enableReport = ReportState.enable_report_state()
        update = checkupdate()
        confJSON = json.dumps(configuration)
        public_url = getTunnelUrl()
        logs = readFile(os.path.join(logfilepath, LOGFILE))
        code = readFile(os.path.join(FILE_DIR, CONFIGFILE))
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'

        if s.form.get("save"):
            textToSave = s.form.get("save", None)
            codeToSave = textToSave.replace("+", " ")
            saveFile(CONFIGFILE, codeToSave)
            message = 'Config saved'
            logger.info(message)
            logs = readFile(os.path.join(logfilepath, LOGFILE))
            code = readFile(os.path.join(FILE_DIR, CONFIGFILE))
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)

        if s.form.get("backup"):
            codeToSave = readFile(os.path.join(FILE_DIR, CONFIGFILE))
            saveFile('config/config.yaml.bak', codeToSave)
            message = 'Backup saved'
            logger.info(message)
            logs = readFile(os.path.join(logfilepath, LOGFILE))
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)

        if s.form.get("restart"):
            message = 'Restart Server, please wait a minute!'
            meta = '<meta http-equiv="refresh" content="20">'
            code = ''
            logs = ''

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)

            s.send_message(200, template)
            restartServer()

        if s.form.get("sync"):
            if 'Homegraph_API_Key' in configuration and configuration[
                    'Homegraph_API_Key'] != 'ADD_YOUR HOMEGRAPH_API_KEY_HERE' or enableReport == True:
                r = self.forceDevicesSync()
                time.sleep(0.5)
                if r:
                    message = 'Devices syncronized'
                else:
                    message = 'Homegraph api key not valid!'
            else:
                message = 'Add Homegraph api key or a Homegraph Service Account json file to sync devices here!'
            logs = readFile(os.path.join(logfilepath, LOGFILE))
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if s.form.get("reload"):
            message = ''

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if s.form.get("deletelogs"):
            logfile = os.path.join(logfilepath, LOGFILE)
            if os.path.exists(logfile):
                f = open(logfile, 'w')
                f.close()
            logger.info('Logs removed by user')
            message = 'Logs removed'
            logs = readFile(os.path.join(logfilepath, LOGFILE))
            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

        if s.form.get("update"):
            repo.git.reset('--hard')
            repo.remotes.origin.pull()
            message = 'Updating to latest ' + repo.active_branch.name + ', please wait a minute!'
            meta = '<meta http-equiv="refresh" content="20">'

            template = TEMPLATE.format(message=message,
                                       uptime=uptime(),
                                       list=deviceList,
                                       meta=meta,
                                       code=code,
                                       conf=confJSON,
                                       public_url=public_url,
                                       logs=logs,
                                       update=update)
            s.send_message(200, template)

            subprocess.call([
                'pip', 'install', '-r',
                os.path.join(FILE_DIR, 'requirements/pip-requirements.txt')
            ])
            restartServer()
示例#14
0
    def settings_post(self, s):
        enableReport = ReportState.enable_report_state()
        update = checkupdate()
        public_url = getTunnelUrl()
        code = readFile(os.path.join(FILE_DIR, CONFIGFILE))
        meta = '<!-- <meta http-equiv="refresh" content="5"> -->'

        if s.form.get("save"):
            textToSave = s.form.get("save", None)
            codeToSave = textToSave.replace("+", " ")
            saveFile(CONFIGFILE, codeToSave)
            message = 'Configuration saved. Restart DZGA for the settings to take effect'
            logger.info(message)
            logs = readFile(os.path.join(logfilepath, LOGFILE))
            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))

        if s.form.get("backup"):
            codeToSave = readFile(os.path.join(FILE_DIR, CONFIGFILE))
            saveFile('config/config.yaml.bak', codeToSave)
            message = 'Backup saved'
            logger.info(message)
            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))

        if s.form.get("restart"):
            meta = '<meta http-equiv="refresh" content="10">'
            message = 'Restarts DZGA server'

            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
            restartServer()

        if s.form.get("sync"):
            if 'Homegraph_API_Key' in configuration and configuration['Homegraph_API_Key'] != 'ADD_YOUR HOMEGRAPH_API_KEY_HERE' or enableReport == True:
                r = self.forceDevicesSync()
                time.sleep(0.5)
                if r:
                    message = 'Devices syncronized'
                else:
                    message = 'Homegraph api key not valid!'
            else:
                message = 'Add Homegraph api key or a Homegraph Service Account json file to sync devices in the UI! You can still sync by voice eg. "Hey Google, Sync my devices".'
            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))

        if s.form.get("reload"):
            message = ''

            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))

        if s.form.get("deletelogs"):
            logfile = os.path.join(logfilepath, LOGFILE)
            if os.path.exists(logfile):
                f = open(logfile, 'w')
                f.close()
            logger.info('Logs removed by user')
            message = 'Logs removed'
            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))

        if s.form.get("update"):
            repo.git.reset('--hard')
            repo.remotes.origin.pull()
            message = 'Updating to latest ' + branch + ', please wait a minute!'
            meta = '<meta http-equiv="refresh" content="20">'

            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
            
            subprocess.call(['pip3', 'install','-r', os.path.join(FILE_DIR, 'requirements/pip-requirements.txt')])
            restartServer()
            
        if s.form.get("saveSettings"):
            savedSettings = json.loads(s.form.get("saveSettings", None))
            with open(os.path.join(FILE_DIR, CONFIGFILE), 'r') as conf_file:
                newsettings = yaml.safe_load(conf_file)
                newsettings.update(savedSettings)
                
            saveFile(CONFIGFILE, yaml.safe_dump(newsettings, allow_unicode=True))
            logger.info(yaml.dump(savedSettings))
            message = 'Settings saved. Restart DZGA for the settings to take effect'
            logger.info(message)
            logs = readFile(os.path.join(logfilepath, LOGFILE))
            templatepage = env.get_template('home.html')
            s.send_message(200, templatepage.render(message=message, uptime=uptime(), meta=meta, code=code,
                                       conf=configuration, public_url=public_url, update=update, keyfile=enableReport,
                                       branch=branch, dzversion=settings['dzversion'], dzgaversion=VERSION))
示例#15
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")
示例#16
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')
示例#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()
示例#18
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()
示例#19
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)
示例#20
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')
示例#21
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()