Exemplo n.º 1
0
def FTP_upload(self):
    try:
        # create a file "stavy.php"
        cas = time.strftime('%d.%m.%Y (%H:%M:%S)', time.localtime(time.time()))

        text = "<?php\r\n$cas = \""  # actual time (ex: cas = dd.mm.yyyy (HH:MM:SS)
        text += cas + "\";\r\n"
        text += "$rain = \'"  # rain state (ex: rain = 0/1)
        text += str(1 if inputs.rain_sensed() else 0) + "\';\r\n"
        text += "$output = \'"  # use xx outputs count (ex: output = 8)
        text += str(options.output_count) + "\';\r\n"
        text += "$program = \'"  # use xx programs count (ex: program = 3)
        text += str(programs.count()) + "\';\r\n"

        text += "$masterstat = "  # master stations index
        for station in stations.get():
            if station.is_master:
                text += "\'" + str(station.index) + "\';\r\n"
        if stations.master is None:
            text += "\'\';\r\n"

        text += "$raindel = "  # rain delay
        if rain_blocks.seconds_left():
            m, s = divmod(int(rain_blocks.seconds_left()), 60)
            h, m = divmod(m, 60)
            text += "\'" + "%dh:%02dm:%02ds" % (h, m, s) + "\';\r\n"
        else:
            text += "\'\';\r\n"

        import unicodedata  # for only asci text in PHP WEB (stations name, program name...)

        namestations = []
        for num in range(0, options.output_count):  # stations name as array
            namestations.append(
                unicodedata.normalize('NFKD',
                                      stations.get(num).name).encode(
                                          'ascii', 'ignore'))
        text += "$name" + " = array"
        text += str(namestations) + ";\r\n"

        statestations = []
        for num in range(0, options.output_count):  # stations state as array
            statestations.append(1 if stations.get(num).active else 0)
        text += "$state" + " = array"
        text += str(statestations) + ";\r\n"

        progrname = []
        for program in programs.get():  # program name as array
            progrname.append(
                unicodedata.normalize('NFKD',
                                      program.name).encode('ascii', 'ignore'))
        text += "$progname" + " = array"
        text += str(progrname) + ";\r\n"

        text = text.replace('[', '(')
        text = text.replace(']', ')')

        text += "$schedul = \'"  # scheduller state (ex: schedul = 0 manual/ 1 scheduler)
        text += str(0 if options.manual_mode else 1) + "\';\r\n"
        text += "$system = \'"  # scheduller state (ex: system = 0 stop/ 1 scheduler)
        text += str(0 if options.scheduler_enabled else 1) + "\';\r\n"
        text += "$cpu = \'"  # cpu temp (ex: cpu  = 45.2)
        text += str(helpers.get_cpu_temp(options.temp_unit)) + "\';\r\n"
        text += "$unit = \'"  # cpu temp unit(ex: unit  = C/F) in Celsius or Fahrenheit
        text += str(options.temp_unit) + "\';\r\n"
        text += "$ver = \'"  # software version date (ex: ver  = 2016-07-30)
        text += str(version.ver_date) + "\';\r\n"
        text += "$id = \'"  # software OSPy ID (ex: id  = "opensprinkler")
        text += str(options.name) + "\';\r\n"
        text += "$ip = \'"  # OSPy IP address (ex: ip  = "192.168.1.1")
        text += str(helpers.get_ip()) + "\';\r\n"
        text += "$port = \'"  # OSPy port (ex: port  = "8080")
        text += str(options.web_port) + "\';\r\n"
        text += "$ssl = \'"  # OSPy use ssl port (ex: ssl  = "1" or "0")
        text += str(1 if options.use_ssl else 0) + "\';\r\n"

        tank = ''
        try:
            from plugins import tank_humi_monitor
            tank = tank_humi_monitor.get_sonic_tank_cm()
            if tank < 0:  # -1 is error I2C device for ping not found in tank_humi_monitor
                tank = ''
        except Exception:
            tank = ''

        text = text + "$tank = \'"  # from tank humi monitor plugins check water level (ex: tank  = "100" in cm or "")
        text = text + str(tank) + "\';\r\n"

        press = ''
        try:
            from plugins import pressure_monitor
            press = pressure_monitor.get_check_pressure()
        except Exception:
            press = ''

        text = text + "$press = \'"  # from pressure plugins check press (ex: press  = "1" or "0")
        text = text + str(press) + "\';\r\n"

        ups = ''
        try:
            from plugins import ups_adj
            ups = ups_adj.get_check_power(
            )  # read state power line from plugin ups adj
        except Exception:
            ups = ''

        text = text + "$ups = \'"
        text = text + str(ups) + "\';\r\n"

        result = ''
        finished = [run for run in log.finished_runs() if not run['blocked']]
        if finished:
            result = finished[-1]['start'].strftime(
                '%d-%m-%Y v %H:%M:%S program: ') + finished[-1]['program_name']
        else:
            result = ''

        text = text + "$lastrun = \'"  # last run program (ex: start d-m-r v h:m:s program: jmemo programu)
        text = text + str(result) + "\';\r\n"

        text = text + "$up = \'"  # system run uptime
        text = text + str(helpers.uptime()) + "\';\r\n"

        text = text + "?>\r\n"
        #print text
        """ example php code -----------
      <?php
      $cas = "09.08.2016 (15:28:10)";
      $rain = '0';
      $output = '3';
      $program = '3';
      $masterstat = '0';
      $raindel = '1:26:22'; // hod:min:sec
      $name = array('cerpadlo','test','out2');
      $state = array('0', '0', '0');
      $progname = array('cerpadlo v 5','test','out2');   
      $schedul = '1';
      $system = '1';
      $cpu = '40.1';
      $unit = 'C';
      $ver = '2016-07-30';
      $id = 'Zalevac chata';
      $ip = '192.168.1.253';
      $port = '80';
      $ssl = '1';
      $tank = '20';
      $press = '0';
      $ups = '1';
      $lastrun = '09.08.2016 v 15:28:10 program: bezi 5 minut)';
      $up = '6 days, 0:48:01'
      ?>
      ------------------------------- """

        try:
            fs = file("/home/pi/ramdisk/stavy.php", 'w')
            fs.write(text)
            fs.close()

        except:
            log.error(NAME, _(u'Could not save stavy.php to ramdisk!'))
            pass

        self.ftp.storbinary("STOR " + plugin_options['loc'] + 'stavy.php',
                            open("/home/pi/ramdisk/stavy.php", 'rb'))
        log.info(
            NAME,
            _(u'Data file stavy.php has send on to FTP server') + ': ' +
            str(cas))

        self.ftp.storbinary("STOR " + plugin_options['loc'] + 'data.txt',
                            open("/home/pi/ramdisk/data.txt", 'rb'))
        log.info(
            NAME,
            _(u'Data file data.txt has send on to FTP server') + ': ' +
            str(cas))

        self.ftp.close  # FTP end

    except Exception:
        log.info(
            NAME,
            _(u'Remote FTP control settings') + ':\n' + traceback.format_exc())
Exemplo n.º 2
0
    def run(self):
        send_msg = False  # send get data if change (rain, end program ....
        last_rain = False
        en_rain = True
        en_line = True
        en_line2 = True

        rain = 0  # rain status for rain=0 or rain=1 in get data
        lastrun = ""  # date and time for lastrun=xxxxx in get data
        tank = ""  # actual level cm in water tank
        percent = ""  # actual level % in water tank
        ping = ""  # actual level ping cm water level
        volume = ""  # actual level volume in m3 water level
        duration = ""  # duration in last program for duration=xx:yy in get data
        station = ""  # name end station for station=abcde in get data
        humi = ""  # humidity in station for humi=xx in get data
        line = ""  # actual state from UPS plugin for line=0 or line=1 in get data
        temp1 = ""  # temperature 1 from air temp plugin DS18B20
        temp2 = ""  # temperature 2 from air temp plugin DS18B20
        temp3 = ""  # temperature 3 from air temp plugin DS18B20
        temp4 = ""  # temperature 4 from air temp plugin DS18B20
        temp5 = ""  # temperature 5 from air temp plugin DS18B20
        temp6 = ""  # temperature 6 from air temp plugin DS18B20
        tempDHT = ""  # temperature  from air temp plugin DHT probe
        humiDHT = ""  # humidity from air temp plugin DHT probe

        finished_count = len(
            [run for run in log.finished_runs() if not run['blocked']])

        while not self._stop_event.is_set():
            try:

                # Send data if rain detected, power line state a new finished run is found
                if remote_options["use"]:
                    ### water tank level ###
                    try:
                        from plugins import tank_monitor
                        tank = tank_monitor.get_all_values()[0]
                        percent = tank_monitor.get_all_values()[1]
                        ping = tank_monitor.get_all_values()[2]
                        volume = tank_monitor.get_all_values()[3]

                    except Exception:
                        tank = ""
                        percent = ""
                        ping = ""
                        volume = ""

                    ### power line state ###
                    try:
                        from plugins import ups_adj
                        lin = ups_adj.get_check_power(
                        )  # read state power line from plugin
                        if lin == 1:
                            if en_line:  # send only if change
                                send_msg = True
                                en_line = False
                                en_line2 = True
                            line = 0  # no power on web

                        if lin == 0:
                            if en_line2:  # send only if change
                                send_msg = True
                                en_line2 = False
                                en_line = True
                            line = 1  # power ok on web

                    except Exception:
                        line = ""

                    ### rain state ###
                    if inputs.rain_sensed() and not last_rain:
                        send_msg = True
                        last_rain = inputs.rain_sensed()
                    if inputs.rain_sensed():
                        rain = 1
                        en_rain = True
                    else:
                        rain = 0
                        if en_rain:  # send data if no rain (only if change rain/norain...)
                            send_msg = True
                            en_rain = False

                    if not options.rain_sensor_enabled:  # if rain sensor not used
                        rain = ""

                    ### program and station ###
                    finished = [
                        run for run in log.finished_runs()
                        if not run['blocked']
                    ]
                    if len(finished) > finished_count:
                        las = datetime_string()
                        lastrun = re.sub(
                            " ", "_", las)  # eliminate gap in the title to _
                        send_msg = True
                        ### humidity in station ###
                        try:
                            from plugins import humi_monitor
                            humi = int(
                                humi_monitor.get_humidity(
                                    (stations.get(run['station']).index) +
                                    1))  # 0-7 to 1-8 humidity
                            if humi < 0:
                                humi = ""

                        except Exception:
                            humi = ""

                        ### temperature ###
                        try:
                            from plugins import air_temp_humi
                            temp1 = air_temp_humi.DS18B20_read_probe(0)
                            temp2 = air_temp_humi.DS18B20_read_probe(1)
                            temp3 = air_temp_humi.DS18B20_read_probe(2)
                            temp4 = air_temp_humi.DS18B20_read_probe(3)
                            temp5 = air_temp_humi.DS18B20_read_probe(4)
                            temp6 = air_temp_humi.DS18B20_read_probe(5)
                            tempDHT = air_temp_humi.DHT_read_temp_value()
                            humiDHT = air_temp_humi.DHT_read_humi_value()
                        except Exception:
                            temp1 = ""
                            temp2 = ""
                            temp3 = ""
                            temp4 = ""
                            temp5 = ""
                            temp6 = ""
                            tempDHT = ""
                            humiDHT = ""

                        for run in finished[finished_count:]:
                            dur = (run['end'] - run['start']).total_seconds()
                            minutes, seconds = divmod(dur, 60)
                            sta = "%s" % stations.get(run['station']).name
                            station = re.sub(
                                " ", "_",
                                sta)  # eliminate gap in the title to _
                            duration = "%02d:%02d" % (minutes, seconds)

                    finished_count = len(finished)

                if (send_msg):  # if enabled send data
                    body = ('tank=' + str(tank))
                    body += ('&percent=' + str(percent))
                    body += ('&ping=' + str(ping))
                    body += ('&volume=' + str(volume))
                    body += ('&rain=' + str(rain))
                    body += ('&humi=' + str(humi))
                    body += ('&line=' + str(line))
                    body += ('&lastrun=' + str(lastrun))
                    body += ('&station=' + sanity_msg(station))
                    body += ('&duration=' + str(duration))
                    body += ('&temp1=' + str(temp1))
                    body += ('&temp2=' + str(temp2))
                    body += ('&temp3=' + str(temp3))
                    body += ('&temp4=' + str(temp4))
                    body += ('&temp5=' + str(temp5))
                    body += ('&temp6=' + str(temp6))
                    body += ('&tempDHT=' + str(tempDHT))
                    body += ('&humiDHT=' + str(humiDHT))
                    body += ('&api=' + remote_options['api'])  # API password
                    log.clear(NAME)
                    log.info(NAME, _(u'Test data...'))
                    self.try_send(body)  # Send GET data to remote server
                    send_msg = False  # Disable send data

                self._sleep(2)

            except Exception:
                log.error(
                    NAME,
                    _(u'Remote plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)
Exemplo n.º 3
0
    def run(self):
        send_msg = False  # send get data if change (rain, end program ....
        last_rain = False 
        en_rain = True
        en_line = True
        en_line2 = True
  
        # ex: tank=100&rain=1&humi=55&line=1&lastrun=15.4.2016&station=kurnik&duration=5min 3sec&api=a1b2v5f4  
        rain = 0          # rain status for rain=0 or rain=1 in get data
        lastrun = ""      # date and time for lastrun=xxxxx in get data
        tank = ""         # actual %0-100 in water tank for tank=xx in get data
        duration = ""     # duration in last program for duration=xx:yy in get data
        station = ""      # name end station for station=abcde in get data
        humi = ""         # humidity in station for humi=xx in get data
        line = ""         # actual state from UPS plugin for line=0 or line=1 in get data
        temper = ""       # temperature  from air temp plugin 

        finished_count = len([run for run in log.finished_runs() if not run['blocked']]) 

        while not self._stop.is_set():
            try:
               
                # Send data if rain detected, power line state a new finished run is found
                if remote_options["use"]:   
                    ### water tank level ###
                    try:
                       from plugins import tank_humi_monitor
                       tank = tank_humi_monitor.get_tank()
                       if tank < 0: # -1 is error I2C device for ping not found in tank_humi_monitor
                         tank = ""
                    except Exception:
                       tank = ""

                    ### power line state ###
                    try:
                       from plugins import ups_adj
                       lin = ups_adj.get_check_power() # read state power line from plugin
                       if lin==1: 
                          if en_line:  # send only if change 
                              send_msg = True 
                              en_line = False
                              en_line2 = True 
                          line = 0 # no power on web
                           
                       if lin==0:
                          if en_line2: # send only if change
                             send_msg = True
                             en_line2 = False
                             en_line = True
                          line = 1 # power ok on web
       
                    except Exception:
                       line = ""

                    ### rain state ###
                    if inputs.rain_sensed() and not last_rain:
                        send_msg = True
                        last_rain = inputs.rain_sensed()
                    if inputs.rain_sensed():
                        rain = 1
                        en_rain = True
                    else:
                        rain = 0 
                        if en_rain: # send data if no rain (only if change rain/norain...)
                           send_msg = True
                           en_rain = False

                    if not options.rain_sensor_enabled: # if rain sensor not used
                        rain = ""
                                        
                    ### program and station ###
                    finished = [run for run in log.finished_runs() if not run['blocked']]                    
                    if len(finished) > finished_count:
                        las = datetime_string()
                        lastrun = re.sub(" ", "_", las) # eliminate gap in the title to _
                        send_msg = True
                        ### humidity in station ###
                        try:
                            from plugins import tank_humi_monitor
                            humi = int(tank_humi_monitor.get_humidity((stations.get(run['station']).index)+1)) # 0-7 to 1-8 humidity  
                            if humi < 0:
                               humi = "" 
                                
                        except Exception:
                            humi = ""

                        ### temperature ###
                        try:
                            from plugins import air_temp_humi
                            temper = air_temp_humi.DS18B20_read_string_data()
                        except Exception:
                            temper = " "
   
                        for run in finished[finished_count:]:
                            dur = (run['end'] - run['start']).total_seconds()
                            minutes, seconds = divmod(dur, 60)
                            sta = "%s" % stations.get(run['station']).name 
                            station = re.sub(" ", "_", sta)  # eliminate gap in the title to _
                            duration = "%02d:%02d" % (minutes, seconds)                       

                    finished_count = len(finished)

                if (send_msg): # if enabled send data
                    body = ('tank=' + str(tank))
                    body += ('&rain=' + str(rain))
                    body += ('&humi=' + str(humi))
                    body += ('&line=' + str(line))
                    body += ('&lastrun=' + str(lastrun)) 
                    body += ('&station=' + sanity_msg(station))
                    body += ('&duration=' + str(duration))
                    body += ('&temper=' + sanity_msg(temper))
                    body += ('&api=' + remote_options['api'])  # API password
                    self.try_send(body)                        # Send GET data to remote server 
                    send_msg = False                           # Disable send data    
                    
                self._sleep(2)

            except Exception:
                log.error(NAME, _('Remote plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)