예제 #1
0
    def GET(self):
        qdict = web.input()
        errorCode = qdict.get('errorCode', 'none')

        if 'delete' in qdict:
            delete = qdict['delete']
            if len(plugin_options['sounds']) > 0:
                del_file = os.path.join(plugin_data_dir(),
                                        plugin_options['sounds'][int(delete)])
                if os.path.isfile(del_file):
                    os.remove(del_file)
                    errorCode = qdict.get('errorCode', 'DelOK')
                    read_folder()
                    log.debug(
                        NAME,
                        datetime_string() + ': ' +
                        _(u'Deleting file has sucesfully.'))
                else:
                    errorCode = qdict.get('errorCode', 'DelNex')
                    log.error(
                        NAME,
                        datetime_string() + ': ' +
                        _(u'File for deleting not found!'))

        return self.plugin_render.voice_station_sounds(plugin_options,
                                                       errorCode)
예제 #2
0
    def GET(self):
        global must_stop
        qdict = web.input()

        if checker is not None:
            stop = helpers.get_input(qdict, 'stop', False, lambda x: True)
            clear = helpers.get_input(qdict, 'clear', False, lambda x: True)

            if 'test' in qdict:
                command = -1
                data = {}
                if 'state' in qdict and int(qdict['state']) == 1:
                    command = plugin_options['on'][int(qdict['test'])]
                if 'state' in qdict and int(qdict['state']) == 0:
                    command = plugin_options['off'][int(qdict['test'])]

                if len(plugin_options['sounds']) > 0 and command != -1:
                    data['song'] = plugin_options['sounds'][command]
                    path = os.path.join(plugin_data_dir(), data['song'])
                    if os.path.isfile(path):
                        log.info(
                            NAME,
                            datetime_string() + u': ' +
                            _(u'Button test, song {}.').format(data['song']))
                        update_song_queue(data)  # save song name to song queue
                    else:
                        log.info(
                            NAME,
                            datetime_string() + u': ' + _(u'File not exists!'))
                else:
                    log.info(
                        NAME,
                        datetime_string() + u': ' + _(u'File not exists!'))

            if stop:
                must_stop = True
                log.info(NAME, datetime_string() + u': ' + _(u'Button Stop.'))

            if clear:
                must_stop = True
                song_queue = read_song_queue()
                while len(song_queue) > 0:
                    song_queue = read_song_queue()
                    del song_queue[0]
                    write_song_queue(song_queue)
                log.clear(NAME)
                log.info(
                    NAME,
                    datetime_string() + u': ' + _(u'Button clear playlist.'))

        try:
            return self.plugin_render.voice_station(plugin_options,
                                                    log.events(NAME))
        except Exception:
            log.error(
                NAME,
                _(u'Voice Station plug-in') + ':\n' + traceback.format_exc())
            set_to_default()
            return self.plugin_render.voice_station(plugin_options,
                                                    log.events(NAME))
예제 #3
0
    def GET(self):
        global wind_sender

        qdict = web.input()
        reset = helpers.get_input(qdict, 'reset', False, lambda x: True)
        delete = helpers.get_input(qdict, 'delete', False, lambda x: True)
        show = helpers.get_input(qdict, 'show', False, lambda x: True)

        if wind_sender is not None and reset:
            wind_sender.status['max_meter'] = 0
            wind_sender.status['log_date_maxspeed'] = datetime_string()
            log.clear(NAME)
            log.info(
                NAME,
                datetime_string() + ' ' + _(u'Maximal speed has reseted.'))
            raise web.seeother(plugin_url(settings_page), True)

        if wind_sender is not None and delete:
            write_log([])
            create_default_graph()
            log.info(NAME,
                     datetime_string() + ' ' + _(u'Deleted all log files OK'))
            raise web.seeother(plugin_url(settings_page), True)

        if wind_sender is not None and 'history' in qdict:
            history = qdict['history']
            wind_options.__setitem__('history', int(history))

        if wind_sender is not None and show:
            raise web.seeother(plugin_url(log_page), True)

        return self.plugin_render.wind_monitor(wind_options,
                                               wind_sender.status,
                                               log.events(NAME))
예제 #4
0
    def POST(self):
        global saved_emails
        
        email_options.web_update(web.input())
        qdict = web.input()
        test = get_input(qdict, 'test', False, lambda x: True)
        delete = get_input(qdict, 'del', False, lambda x: True)

        if email_sender is not None:
            email_sender.update()

            if test:
                regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')      # SMTP username
                if not re.fullmatch(regex, email_options['emlusr']):
                    log.clear(NAME)
                    log.info(NAME,datetime_string() + ': ' + _(u'Sender e-mail address appears to be invalid!'))
                    raise web.seeother(plugin_url(settings_page), True)  

                body = datetime_string() + ': ' + _(u'This is test e-mail from OSPy. You can ignore it.')
                logtext = _(u'This is test e-mail from OSPy. You can ignore it.')
                try_mail(body, logtext)
            
            if delete:
                log.info(NAME, datetime_string() + ': ' + _(u'Email Queue was deleted.'))         
                write_email([])
                saved_emails = 0

        raise web.seeother(plugin_url(settings_page), True)
예제 #5
0
def notify_station_off(name, **kw):
    if plugin_options['enabled']:
        current_time = datetime.datetime.now()
        try:
            if int(current_time.hour) >= int(
                    plugin_options['start_hour']) and int(
                        current_time.hour) <= int(plugin_options['stop_hour']):
                st_nr = int(kw[u"txt"])
                log.clear(NAME)
                log.info(
                    NAME,
                    datetime_string() + u': ' +
                    _(u'Stations {} OFF').format(str(st_nr + 1)))
                data = {}
                if len(plugin_options['sounds']) > 0:
                    data['song'] = plugin_options['sounds'][int(
                        plugin_options['off'][st_nr])]
                    path = os.path.join(plugin_data_dir(), data['song'])
                    if os.path.isfile(path):
                        update_song_queue(data)  # save song name to song queue
                    else:
                        log.info(
                            NAME,
                            datetime_string() + u': ' + _(u'File not exists!'))
        except Exception:
            log.error(
                NAME,
                _(u'Voice Station plug-in') + ':\n' + traceback.format_exc())
예제 #6
0
def get_client():
    if is_python2():
        if not os.path.exists("/usr/lib/python2.7/dist-packages/pip"):
            log.clear(NAME)
            log.info(NAME, _('PIP is not installed.'))
            log.info(NAME, _('Please wait installing python-pip...'))
            log.info(NAME, _('This operation takes longer (minutes)...'))
            cmd = "sudo apt-get install python-pip -y"
            proc_install(cmd)
    else:
        if not os.path.exists("/usr/lib/python3/dist-packages/pip"):
            log.clear(NAME)
            log.info(NAME, _('PIP3 is not installed.'))
            log.info(NAME, _('Please wait installing python3-pip...'))
            log.info(NAME, _('This operation takes longer (minutes)...'))
            cmd = "sudo apt-get install python3-pip -y"
            proc_install(cmd)                

    try:
        import paho.mqtt.client as mqtt
    except ImportError:
        log.error(NAME, _('MQTT Plugin requires paho mqtt.'))
        log.info(NAME, _('Paho-mqtt is not installed.'))
        log.info(NAME, _('Please wait installing paho-mqtt...'))
        log.info(NAME, _('This operation takes longer (minutes)...'))
        if is_python2():
            cmd = "sudo pip install paho-mqtt"
        else:
            cmd = "sudo pip3 install paho-mqtt"    
        proc_install(cmd)
    try:
        import paho.mqtt.client as mqtt
    except ImportError:      
        mqtt = None
        log.error(NAME, _('Error try install paho-mqtt manually.'))
        time.sleep(60)
 
    if mqtt is not None and plugin_options["use_mqtt"]:  
        try:
            _client = mqtt.Client(options.name)                  # Use system name as client ID 
            _client.on_connect = on_connect                      # flag = 1 is connected
            _client.on_disconnect = on_disconnect                # flag = 0 is disconnected
            _client.on_message = on_message                      # Attach function to callback            
            log.clear(NAME)
            log.info(NAME, datetime_string() + ' ' + _('Connecting to broker') + '...')
            _client.username_pw_set(plugin_options['user_name'], plugin_options['user_password'])
            _client.connect(plugin_options['broker_host'], plugin_options['broker_port'], 60)
            _client.loop_start()
            log.info(NAME, datetime_string() + ' ' + _('OK'))
            return _client
            
        except Exception:
            log.error(NAME, _('MQTT plugin couldnot initalize client') + ':\n' + traceback.format_exc())
            pass
            return None
예제 #7
0
    def run(self):
        last_rain = False
        finished_count = len(
            [run for run in log.finished_runs() if not run['blocked']])

        if email_options[
                "emlpwron"]:  # if eml_power_on send email is enable (on)
            body = (datetime_string() + ': System was powered on.')

            if email_options["emllog"]:
                self.try_mail(body, EVENT_FILE)
            else:
                self.try_mail(body)

        while not self._stop_event.is_set():
            try:
                # Send E-amil if rain is detected
                if email_options["emlrain"]:
                    if inputs.rain_sensed() and not last_rain:
                        body = (datetime_string() + ': System detected rain.')
                        self.try_mail(body)
                    last_rain = inputs.rain_sensed()

                # Send E-mail if a new finished run is found
                if email_options["emlrun"]:
                    finished = [
                        run for run in log.finished_runs()
                        if not run['blocked']
                    ]
                    if len(finished) > finished_count:
                        body = datetime_string() + ':\n'
                        for run in finished[finished_count:]:
                            duration = (run['end'] -
                                        run['start']).total_seconds()
                            minutes, seconds = divmod(duration, 60)
                            body += "Finished run:\n"
                            body += "  Program: %s\n" % run['program_name']
                            body += "  Station: %s\n" % stations.get(
                                run['station']).name
                            body += "  Start time: %s \n" % datetime_string(
                                run['start'])
                            body += "  Duration: %02d:%02d\n\n" % (minutes,
                                                                   seconds)

                        self.try_mail(body)

                    finished_count = len(finished)

                self._sleep(5)

            except Exception:
                log.error(NAME, 'E-mail plug-in:\n' + traceback.format_exc())
                self._sleep(60)
예제 #8
0
    def GET(self):
        global sender, status

        qdict = web.input()
        reset = helpers.get_input(qdict, 'reset', False, lambda x: True)
        if sender is not None and reset:
            plugin_options.__setitem__('sum_one', 0)
            plugin_options.__setitem__('sum_two', 0)
            plugin_options.__setitem__('last_reset', datetime_string())

            log.clear(NAME)
            log.info(NAME, datetime_string() + ': ' + _(u'Counter has reseted'))
            raise web.seeother(plugin_url(settings_page), True)

        return self.plugin_render.water_consumption_counter(plugin_options, log.events(NAME))
예제 #9
0
def on_stop():
    client = get_client()
    if client is not None:
        client.disconnect()
        client.loop_stop()
        client = None
        log.info(NAME, datetime_string() + ' ' + _('Client stop'))
예제 #10
0
def update_log():
    """Update data in json files."""
    global status

    ### Data for log ###
    try:
        log_data = read_log()
    except:
        write_log([])
        log_data = read_log()

    from datetime import datetime

    data = {'datetime': datetime_string()}
    data['date'] = str(datetime.now().strftime('%d.%m.%Y'))
    data['time'] = str(datetime.now().strftime('%H:%M:%S'))
    data['minimum'] = str(status['minlevel'])
    data['maximum'] = str(status['maxlevel'])
    data['actual'] = str(get_all_values()[0])
    data['volume'] = str(get_all_values()[3])

    log_data.insert(0, data)
    if tank_options['log_records'] > 0:
        log_data = log_data[:tank_options['log_records']]

    try:
        write_log(log_data)
    except:
        write_log([])

    ### Data for graph log ###
    try:
        graph_data = read_graph_log()
    except:
        create_default_graph()
        graph_data = read_graph_log()

    timestamp = int(time.time())

    try:
        minimum = graph_data[0]['balances']
        minval = {'total': status['minlevel']}
        minimum.update({timestamp: minval})

        maximum = graph_data[1]['balances']
        maxval = {'total': status['maxlevel']}
        maximum.update({timestamp: maxval})

        actual = graph_data[2]['balances']
        actval = {'total': get_all_values()[0]}
        actual.update({timestamp: actval})

        volume = graph_data[3]['balances']
        volumeval = {'total': get_all_values()[3]}
        volume.update({timestamp: volumeval})

        write_graph_log(graph_data)
        log.info(NAME, _(u'Saving to log  files OK'))
    except:
        create_default_graph()
예제 #11
0
def update_debug_log(byte_0=0, byte_1=0, val=0, byte_2=0, byte_3=0):
    """Update data in debug json files."""

    ### Data for log ###
    try:
        log_data = read_debug_log()
    except:
        write_log([])
        log_data = read_debug_log()

    from datetime import datetime

    data = {'datetime': datetime_string()}
    data['date'] = str(datetime.now().strftime('%d.%m.%Y'))
    data['b0'] = str(byte_0)
    data['b1'] = str(byte_1)
    data['b2'] = str(byte_2)
    data['b3'] = str(byte_3)
    data['val'] = str(val)

    log_data.insert(0, data)

    try:
        write_debug_log(log_data)
    except:
        write_debug_log([])
예제 #12
0
def read_buttons():
    try:
        import smbus

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

        # Set 8 GPA pins as input pull-UP
        try_io(lambda: bus.write_byte_data(plugin_options[
            'i2c_addr'], 0x0C, 0xFF))  #bus.write_byte_data(0x27,0x0C,0xFF)

        # Wait for device
        time.sleep(0.2)

        # Read state of GPIOA register
        MySwitch = try_io(
            lambda: bus.read_byte_data(plugin_options[
                'i2c_addr'], 0x12))  # MySwitch = bus.read_byte_data(0x27,0x12)

        inBut = 255 - MySwitch
        # inversion number for led off if button is not pressed

        led_outputs(inBut)  # switch on actual led if button is pressed

        button_number = -1
        if inBut == 128:
            button_number = 7
            log.debug(NAME, _(u'Switch 8 pressed'))
        if inBut == 64:
            button_number = 6
            log.debug(NAME, _(u'Switch 7 pressed'))
        if inBut == 32:
            button_number = 5
            log.debug(NAME, _(u'Switch 6 pressed'))
        if inBut == 16:
            button_number = 4
            log.debug(NAME, _(u'Switch 5 pressed'))
        if inBut == 8:
            button_number = 3
            log.debug(NAME, _(u'Switch 4 pressed'))
        if inBut == 4:
            button_number = 2
            log.debug(NAME, _(u'Switch 3 pressed'))
        if inBut == 2:
            button_number = 1
            log.debug(NAME, _(u'Switch 2 pressed'))
        if inBut == 1:
            button_number = 0
            log.debug(NAME, _(u'Switch 1 pressed'))
        return button_number  #if button is not pressed return -1

    except Exception:
        log.clear(NAME)
        log.error(NAME, datetime_string() + ': ' + _(u'Read button - FAULT'))
        log.error(
            NAME,
            _(u'Is hardware connected? Is bus address corectly setuped?'))
        #log.error(NAME, '\n' + traceback.format_exc())
        pass
        return -1
예제 #13
0
def update_log():
    """Update data in json files."""

    ### Data for log ###
    try:
        log_data = read_log()
    except:
        write_log([])
        log_data = read_log()

    from datetime import datetime

    data = {'datetime': datetime_string()}
    data['date'] = str(datetime.now().strftime('%d.%m.%Y'))
    data['time'] = str(datetime.now().strftime('%H:%M:%S'))
    data['maximum'] = str(get_all_values()[1])
    data['actual'] = str(get_all_values()[0])

    log_data.insert(0, data)
    if wind_options['log_records'] > 0:
        log_data = log_data[:wind_options['log_records']]

    write_log(log_data)

    ### Data for graph log ###
    try:
        graph_data = read_graph_log()
    except:
        create_default_graph()
        graph_data = read_graph_log()

    timestamp = int(time_.time())

    try:
        maximum = graph_data[0]['balances']
        maxval = {'total': get_all_values()[1]}
        maximum.update({timestamp: maxval})

        actual = graph_data[1]['balances']
        actval = {'total': get_all_values()[0]}
        actual.update({timestamp: actval})

        write_graph_log(graph_data)
        log.info(NAME, datetime_string() + ' ' + _(u'Saving to log  files OK'))
    except:
        create_default_graph()
예제 #14
0
    def GET(self):
        global sender, status, avg_lst, avg_cnt, avg_rdy

        qdict = web.input()
        reset = helpers.get_input(qdict, 'reset', False, lambda x: True)
        show = helpers.get_input(qdict, 'show', False, lambda x: True)
        debug = helpers.get_input(qdict, 'debug', False, lambda x: True)
        del_rain = helpers.get_input(qdict, 'del_rain', False, lambda x: True)
        log_now = helpers.get_input(qdict, 'log_now', False, lambda x: True)

        if sender is not None and reset:
            status['minlevel'] = status['level']
            status['maxlevel'] = status['level']
            tank_options['saved_max'] = status['level']
            tank_options['saved_min'] = status['level']
            status['minlevel_datetime'] = datetime_string()
            status['maxlevel_datetime'] = datetime_string()
            log.info(
                NAME,
                datetime_string() + ': ' +
                _(u'Minimum and maximum has reseted.'))
            raise web.seeother(plugin_url(settings_page), True)

        if sender is not None and log_now:
            update_log()

        if sender is not None and 'history' in qdict:
            history = qdict['history']
            tank_options.__setitem__('history', int(history))

        if sender is not None and show:
            raise web.seeother(plugin_url(log_page), True)

        if sender is not None and debug:
            raise web.seeother(plugin_url(log_debug_page), True)

        if sender is not None and del_rain:
            if NAME in rain_blocks:
                del rain_blocks[NAME]
                log.info(
                    NAME,
                    datetime_string() + ': ' + _(u'Removing Rain Delay') + '.')
            raise web.seeother(plugin_url(settings_page), True)

        return self.plugin_render.tank_monitor(tank_options, log.events(NAME))
예제 #15
0
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self._stop_event = Event()

        global status, avg_lst, avg_cnt, avg_rdy

        status['level'] = -1
        status['percent'] = -1
        status['ping'] = -1
        status['volume'] = -1
        status['maxlevel'] = tank_options['saved_max']
        status['minlevel'] = tank_options['saved_min']
        status['maxlevel_datetime'] = datetime_string()
        status['minlevel_datetime'] = datetime_string()

        self._sleep_time = 0
        self.start()
예제 #16
0
def on_restart():
    client = get_client()
    time.sleep(2)
    if client is not None:
        publish_status("DOWN")
        client.disconnect()
        client.loop_stop()
        client = None
        log.info(NAME, datetime_string() + ' ' + _('Client stop'))
예제 #17
0
def update_log(status):
    log_data = read_log()
    data = {'datetime': datetime_string()}
    for i in range(4):
        data['ad%d' % i] = format(status['ad%d' % i], pcf_options['ad%d_temp' % i])
    log_data.insert(0, data)
    if pcf_options['log_records'] > 0:
        log_data = log_data[:pcf_options['log_records']]
    write_log(log_data)
예제 #18
0
def send_email(msg):
    """Send email"""
    message = datetime_string() + ': ' + msg
    try:
        from plugins.email_notifications import email
        email(message)
        log.info(NAME, _('Email was sent') + ': ' + message)
    except Exception:
        log.info(NAME, _('Email was not sent') + '! ' + traceback.format_exc())
예제 #19
0
def on_stop():
    client = get_client()
    if client is not None:
        status = "RunOnce Exit"
        client.publish(plugin_options['publish_up_down'], status)
        client.disconnect()
        client.loop_stop()
        client = None
        log.info(NAME, datetime_string() + ' ' +  _('Client on stop'))
예제 #20
0
def update_log():
    """Update data in json files."""
    global sender

    ### Data for log ###
    try:
        log_data = read_log()
    except:
        write_log([])
        log_data = read_log()

    from datetime import datetime

    data = {'datetime': datetime_string()}
    data['date'] = str(datetime.now().strftime('%d.%m.%Y'))
    data['time'] = str(datetime.now().strftime('%H:%M:%S'))
    data['down'] = str(sender.status['down'])
    data['up'] = str(sender.status['up'])
    data['ping'] = str(sender.status['ping'])

    log_data.insert(0, data)
    if speed_options['log_records'] > 0:
        log_data = log_data[:speed_options['log_records']]

    try:
        write_log(log_data)
    except:
        write_log([])

    ### Data for graph log ###
    try:
        graph_data = read_graph_log()
    except:
        create_default_graph()
        graph_data = read_graph_log()

    timestamp = int(time.time())

    try:
        downdata = graph_data[0]['balances']
        downval = {'total': sender.status['down']}
        downdata.update({timestamp: downval})

        updata = graph_data[1]['balances']
        upval = {'total': sender.status['up']}
        updata.update({timestamp: upval})

        pingdata = graph_data[2]['balances']
        pingval = {'total': sender.status['ping']}
        pingdata.update({timestamp: pingval})

        write_graph_log(graph_data)
        log.info(NAME, _('Saving to log files OK'))
    except:
        log.error(NAME,
                  _('Speed Monitor plug-in') + ':\n' + traceback.format_exc())
        pass
예제 #21
0
def publish_status(status="RunOnce Ready"):
    global last_status, flag_connected
    client = get_client()
    time.sleep(2)
    if client and plugin_options["use_mqtt"]:  # Publish message
        if status != last_status:
            last_status = status  
            log.info(NAME, datetime_string() + ' ' + _('Subscribing to topic') + ': ' + str(plugin_options['schedule_topic']))    
            client.subscribe(plugin_options['schedule_topic'])        
            client.publish(plugin_options['publish_up_down'], status)
예제 #22
0
    def POST(self):
        qdict = web.input(myfile={})
        errorCode = qdict.get('errorCode', 'none')

        #web.debug(qdict['myfile'].filename)    # This is the filename
        #web.debug(qdict['myfile'].value)       # This is the file contents
        #web.debug(qdict['myfile'].file.read()) # Or use a file(-like) object

        try:
            fname = qdict['myfile'].filename
            upload_type = fname[-4:len(fname)]
            types = ['.mp3', '.wav']
            if upload_type not in types:  # check file type is ok
                log.info(
                    NAME,
                    datetime_string() + ': ' +
                    _(u'Error. File must be in mp3 or wav format!'))
                errorCode = qdict.get('errorCode', 'Etype')
                return self.plugin_render.voice_station_sounds(
                    plugin_options, errorCode)
            else:
                fout = open(os.path.join(plugin_data_dir(), fname),
                            'wb')  # ASCI_convert(fname)
                fout.write(qdict['myfile'].file.read())
                fout.close()
                log.info(
                    NAME,
                    datetime_string() + ': ' +
                    _(u'Uploading file sucesfully.'))
                errorCode = qdict.get('errorCode', 'UplOK')
                read_folder()
                return self.plugin_render.voice_station_sounds(
                    plugin_options, errorCode)

        except Exception:
            log.error(
                NAME,
                _(u'Voice Station plug-in') + ':\n' + traceback.format_exc())
            errorCode = qdict.get('errorCode', 'Eupl')
            return self.plugin_render.voice_station_sounds(
                plugin_options, errorCode)

        raise web.seeother(plugin_url(sound_page), True)
예제 #23
0
    def update_statistics(self):
        """Returns the statistics data."""

        try:
            import requests

            link = "https://pihrt.com/ospystats/statistics.json"
            req = requests.get(link)
            bodytext = req.text
            #log.debug(NAME, bodytext) # downloaded text

            import json

            jsonStr = json.loads(bodytext)
            IDlenght = len(jsonStr['user'])

            log.clear(NAME)
            for i in range(0, IDlenght - 1):
                log.info(NAME, _('ID') + ': ' + str(jsonStr['user'][i]['id']))
                log.info(NAME,
                         _('Log') + ': ' + str(jsonStr['user'][i]['log']))
                log.info(NAME,
                         _('OSPy') + ': ' + str(jsonStr['user'][i]['ospy']))
                log.info(NAME,
                         _('CPU') + ': ' + str(jsonStr['user'][i]['cpu']))
                log.info(
                    NAME,
                    _('Distribution') + ': ' +
                    str(jsonStr['user'][i]['distribution']))
                log.info(
                    NAME,
                    _('System') + ': ' + str(jsonStr['user'][i]['system']))
                log.info(
                    NAME,
                    _('Python') + ': ' + str(jsonStr['user'][i]['python']) +
                    '\n')

            self.status['pageOK'] = _(
                u'The data from') + ' www.pihrt.com ' + _(
                    u'was downloaded correctly.') + ' ' + datetime_string()
            self.status['pageOKstate'] = True

            try:
                f = open("./ospy/statistics/user_id", "r")
                userID = (f.read())
                self.status['pageID'] = _(u'Your ID is: ') + str(userID)
            except:
                #log.error(NAME, _('Usage statistics plug-in') + ':\n' + traceback.format_exc())
                pass

        except Exception:
            self.status['pageOK'] = _(
                u'Error: data cannot be downloaded from') + ' www.pihrt.com!'
            self.status['pageOKstate'] = False
            log.clear(NAME)
예제 #24
0
def subscribe(topic, callback, qos=0):
    "Subscribes to a topic with the given callback"
    global _subscriptions
    client = get_client()
    
    if client and plugin_options["use_mqtt"]:
        if topic not in _subscriptions:
            _subscriptions[topic] = [callback]
            client.subscribe(topic, qos)
            log.info(NAME, datetime_string() + ' ' + _('Subscribe topic') + ': ' + str(topic))
        else:
            _subscriptions[topic].append(callback)                
예제 #25
0
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self._stop_event = Event()

        self.status = {}
        self.status['meter'] = 0.0
        self.status['kmeter'] = 0.0
        self.status['max_meter'] = 0
        self.status['log_date_maxspeed'] = datetime_string()

        self._sleep_time = 0
        self.start()
예제 #26
0
    def POST(self):
        global saved_emails
        
        email_options.web_update(web.input())
        qdict = web.input()
        test = get_input(qdict, 'test', False, lambda x: True)
        delete = get_input(qdict, 'del', False, lambda x: True)

        if email_sender is not None:
            email_sender.update()

            if test:
                body = datetime_string() + ': ' + _(u'This is test e-mail from OSPy. You can ignore it.')
                logtext = _(u'This is test e-mail from OSPy. You can ignore it.')
                try_mail(body, logtext)
            
            if delete:
                log.info(NAME, datetime_string() + ': ' + _(u'Email Queue was deleted.'))         
                write_email([])
                saved_emails = 0

        raise web.seeother(plugin_url(settings_page), True)
예제 #27
0
def get_all_values():
    """Return all posible values for others use."""
    status = wind_sender.status
    try:
        if wind_options['use_kmh']:
            return round(status['meter'] * 3.6,
                         2), round(status['max_meter'] * 3.6,
                                   2), status['log_date_maxspeed']  # km/hod
        else:
            return round(status['meter'],
                         2), round(status['max_meter'],
                                   2), status['log_date_maxspeed']  # m/sec
    except:
        return -1, -1, datetime_string()
예제 #28
0
    def POST(self):
        email_options.web_update(web.input())
        qdict = web.input()
        test = get_input(qdict, 'test', False, lambda x: True)

        if email_sender is not None:
            email_sender.update()

            if test:
                body = (datetime_string() +
                        ': Test e-mail from e-mail notification plugin :-).')
                email_sender.try_mail(body)

        raise web.seeother(plugin_url(settings_page), True)
예제 #29
0
def notify_master_two_off(name, **kw):
    log.info(NAME, datetime_string() + ': ' + _(u'Master station 2 stopped, counter finished...')) 
    master_two_stop  = datetime.datetime.now()
    master_two_time_delta  = (master_two_stop - master_two_start).total_seconds() 
    difference = to_decimal(master_two_time_delta) * to_decimal(plugin_options['liter_per_sec_master_two'])

    _sum = round(to_decimal(plugin_options['sum_two']), 2) + round(difference, 2)  # to 2 places
    plugin_options.__setitem__('sum_two', _sum)
  
    msg = '<b>' + _(u'Water Consumption Counter plug-in') + '</b> ' + '<br><p style="color:green;">' + _(u'Water Consumption') + ' ' + str(round(difference,2)) + ' ' + _(u'liter') + '</p>'
    msglog = _(u'Water Consumption Counter plug-in') + ': ' + _(u'Water Consumption for master 2') + ': ' + str(round(difference,2)) + ' ' + _(u'liter')
    try:
        if plugin_options['sendeml']:
            send_email(msg, msglog)
    except Exception:
        log.error(NAME, _('Email was not sent') + '! '  + traceback.format_exc())
예제 #30
0
    def GET(self):
        global sender

        qdict = web.input()
        delete = helpers.get_input(qdict, 'delete', False, lambda x: True)
        show = helpers.get_input(qdict, 'show', False, lambda x: True)
        test = helpers.get_input(qdict, 'test', False, lambda x: True)

        if sender is not None and delete:
            write_log([])
            create_default_graph()
            raise web.seeother(plugin_url(settings_page), True)

        if sender is not None and test:
            log.clear(NAME)
            try:
                new_speeds = get_new_speeds()
                sender._sleep(2)
                tempText = _(
                    'Ping {} ms, Download {} Mb/s, Upload {} Mb/s').format(
                        sender.status['ping'], sender.status['down'],
                        sender.status['up'])
            except:
                new_speeds = 0, 0, 0
                tempText = _('Cannot be loaded')
                log.error(
                    NAME,
                    _('Speed Monitor plug-in') + ':\n' +
                    traceback.format_exc())
                pass
            sender.status['ping'] = new_speeds[0]  # Ping (ms)
            sender.status['down'] = new_speeds[1]  # Download (Mb/s)
            sender.status['up'] = new_speeds[2]  # Upload (Mb/s)
            log.info(
                NAME,
                datetime_string() + ' ' + _('Test button') + '\n' + tempText)
            raise web.seeother(plugin_url(settings_page), True)

        if sender is not None and 'history' in qdict:
            history = qdict['history']
            speed_options.__setitem__('history', int(history))

        if sender is not None and show:
            raise web.seeother(plugin_url(log_page), True)

        return self.plugin_render.speed_monitor(speed_options,
                                                log.events(NAME))