Пример #1
0
def find_address(search_range, range=False):
    try:
        import smbus
        bus = smbus.SMBus(0 if helpers.get_rpi_revision() == 1 else 1)
        if range:
            for addr, type in search_range.items():
                try:
                    bus.read_byte(addr)
                    return True
                    break
                except Exception:
                    pass
                else:
                    return False
        else:
            try:
                bus.read_byte(search_range)
                return True
            except Exception:
                pass
            else:
                return False

    except ImportError:
        log.warning(NAME, _('Could not import smbus.'))
Пример #2
0
def find_lcd_address():
    search_range = {addr: 'PCF8574' for addr in range(32, 40)}
    search_range.update({addr: 'PCF8574A' for addr in range(56, 63)})

    try:
        import smbus

        bus = smbus.SMBus(0 if helpers.get_rpi_revision() == 1 else 1)
        # DF - alter RPi version test fallback to value that works on BBB

        for addr, pcf_type in search_range.items():
            try:
                # bus.write_quick(addr)
                try_io(
                    lambda: bus.read_byte(addr)
                )  #bus.read_byte(addr) # DF - write_quick doesn't work on BBB
                log.info(
                    NAME,
                    _('Found {} on address {}').format(pcf_type, hex(addr)))
                lcd_options['address'] = addr
                break
            except Exception:
                pass
        else:
            log.warning(NAME, _('Could not find any PCF8574 controller.'))

    except:
        log.warning(NAME, _('Could not import smbus.'))
Пример #3
0
def get_all_addr():
    find_adr = ''
    try:
        import smbus
        bus = smbus.SMBus(0 if helpers.get_rpi_revision() == 1 else 1)
        find_adr += _('Available addresses') + '\n'
        for addr in range(128):
            try:
                bus.read_byte(addr)
                find_adr += '{}\n'.format(hex(addr))
            except Exception:
                pass

    except ImportError:
        log.warning(NAME, _('Could not import smbus.'))

    return find_adr
Пример #4
0
    def run(self):
        try:
            import smbus  # for PCF 8591

            self.adc = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
        except ImportError:
            log.warning(NAME, _(u'Could not import smbus.'))

        while not self._stop_event.is_set():
            log.clear(NAME)
            try:
                if self.adc is not None and pcf_options['enabled']:  # if pcf plugin is enabled
                    for i in range(4):
                        val = read_AD(self.adc, i + 1)
                        self.status['ad%d_raw' % i] = val
                        self.status['ad%d' % i] = get_temp(val) if pcf_options['ad%d_temp' % i] else get_volt(val)

                    log.info(NAME, datetime_string())
                    for i in range(4):
                        log.info(NAME, pcf_options['ad%d_label' % i] + ': ' + format(self.status['ad%d' % i],
                                                                                     pcf_options['ad%d_temp' % i]))

                    if pcf_options['enable_log']:
                        update_log(self.status)

                try:
                    write_DA(self.adc, pcf_options['da_value'])
                except Exception:
                    self.adc = None
                    
                self._sleep(max(60, pcf_options['log_interval'] * 60))

            except Exception:
                self.adc = None
                log.error(NAME, _(u'Voltage and Temperature Monitor plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)
Пример #5
0
def on_message(client, userdata, message):
    log.clear(NAME) 
    log.info(NAME, datetime_string() + ' ' + _('Message received') + ': ' + str(message.payload.decode("utf-8")))
    #print("Message topic=",message.topic)
    #print("Message qos=",message.qos)
    #print("Message retain flag=",message.retain)

    try:
        cmd = json.loads(message.payload)
    except:
        cmd = []
        status = "RunOnce Error"
        client.publish(plugin_options['publish_up_down'], status)
        pass

    try:
        log.info(NAME, datetime_string() + ' ' + _(u'Try-ing to processing command.'))
        num_sta = options.output_count
        if type(cmd) is list:            # cmd is list
            if len(cmd) < num_sta:
                log.info(NAME, datetime_string() + ' ' + _(u'Not enough stations specified, assuming first {} of {}').format(len(cmd), num_sta))
                rovals = cmd + ([0] * (num_sta - len(cmd)))              
            elif len(cmd) > num_sta:
                log.info(NAME, datetime_string() + ' ' + _(u'Too many stations specified, truncating to {}').format(num_sta))
                rovals = cmd[0:num_sta]
            else:
                rovals = cmd

        elif type(cmd) is dict:          # cmd is dictionary
            rovals = [0] * num_sta
            snames = station_names()     # Load station names from file
            jnames = json.loads(snames)  # Load as json
                                                
            for k, v in list(cmd.items()):
                if k not in snames:      # station name in dict is not in OSPy stations name (ERROR)
                    log.warning(NAME, _(u'No station named') + (u': %s') % k)
                                                    
                else:                    # station name in dict is in OSPy stations name (OK)
                    # v is value for time, k is station name in dict
                    rovals[jnames.index(k)] = v         

        else:
            log.error(NAME, datetime_string() + ' ' + _(u'Unexpected command') + (u': %s') % message.payload)
            rovals = None
            status = "RunOnce Error"
            client.publish(plugin_options['publish_up_down'], status)

        if rovals is not None and any(rovals):  
            for i in range(0, len(rovals)):     
                sid = i                                                                                
                start = datetime.datetime.now()
                try:
                    end = datetime.datetime.now() + datetime.timedelta(seconds=int(rovals[i]))
                except:
                    end = datetime.datetime.now()
                    log.error(NAME, _(u'MQTT Run-once plug-in') + ':\n' + traceback.format_exc())
                    pass

                new_schedule = {
                    'active': True,
                    'program': -1,
                    'station': sid,
                    'program_name': _(u'MQTT Run-once'),
                    'fixed': True,
                    'cut_off': 0,
                    'manual': True,
                    'blocked': False,
                    'start': start,
                    'original_start': start,
                    'end': end,
                    'uid': '%s-%s-%d' % (str(start), "Manual", sid),
                    'usage': stations.get(sid).usage
                }
                log.start_run(new_schedule)
                stations.activate(new_schedule['station'])

                if int(rovals[i]) < 1:                 # station has no time for run (stoping)
                    stations.deactivate(sid)
                    active = log.active_runs()
                    for interval in active:
                        if interval['station'] == sid:
                            log.finish_run(interval)

            status = "RunOnce Processing"
            client.publish(plugin_options['publish_up_down'], status)                                                                    

    except Exception:
        log.clear(NAME)
        log.error(NAME, _(u'MQTT Run-once plug-in') + ':\n' + traceback.format_exc())
        status = "RunOnce Error"
        client.publish(plugin_options['publish_up_down'], status)
        pass
Пример #6
0
    def run(self):
        millis = int(round(time_.time() * 1000))

        last_millis = millis  # timer for save log
        last_clear_millis = millis  # last clear millis for timer
        last_24h_millis = millis  # deleting maximal spead after 24 hour

        send = False  # send email
        disable_text = True
        val = 0
        en_del_24h = True
        wind_mon = None

        if wind_options['use_footer']:
            wind_mon = showInFooter(
            )  #  instantiate class to enable data in footer
            wind_mon.label = _(u'Wind Speed')  # label on footer
            wind_mon.val = '---'  # value on footer
            wind_mon.button = "wind_monitor/settings"  # button redirect on footer

        while not self._stop_event.is_set():
            try:
                if wind_options[
                        'use_wind_monitor']:  # if wind plugin is enabled
                    disable_text = True
                    try:
                        import smbus  # for PCF 8583
                        self.bus = smbus.SMBus(
                            0 if helpers.get_rpi_revision() == 1 else 1)

                    except ImportError:
                        log.warning(NAME, _(u'Could not import smbus.'))

                    if self.bus is not None:
                        set_counter(self.bus)  # set pcf8583 as counter
                        puls = counter(self.bus)  # read pulses

                    if puls is not None and puls < 1000:  # limiter for maximal pulses from counter (error filter)
                        puls = counter(
                            self.bus) / 10.0  # counter value is value/10sec
                        val = puls / (wind_options['pulses'] * 1.0)
                        val = val * wind_options['metperrot']

                        self.status['meter'] = round(val * 1.0, 2)
                        self.status['kmeter'] = round(val * 3.6, 2)

                        if self.status['meter'] > self.status['max_meter']:
                            self.status['max_meter'] = self.status['meter']
                            self.status['log_date_maxspeed'] = datetime_string(
                            )
                            if wind_options['enable_log_change']:
                                update_log()

                        log.info(NAME, datetime_string())
                        if wind_options['use_kmh']:
                            log.info(
                                NAME,
                                _(u'Speed') + ': ' +
                                u'%.1f' % round(self.status['meter'] * 3.6, 2)
                                + ' ' + _(u'km/h') + ', ' + _(u'Pulses') +
                                ': ' + u'%s' % puls + ' ' + _(u'pulses/sec'))
                        else:
                            log.info(
                                NAME,
                                _(u'Speed') + ': ' +
                                u'%.1f' % round(self.status['meter'], 2) +
                                ' ' + _(u'm/sec') + ', ' + _(u'Pulses') +
                                ': ' + u'%s' % puls + ' ' + _(u'pulses/sec'))

                        if wind_options['use_kmh']:
                            log.info(
                                NAME,
                                u'%s' % self.status['log_date_maxspeed'] +
                                ' ' + _(u'Maximal speed') + ': ' + u'%s' %
                                round(self.status['max_meter'] * 3.6, 2) +
                                ' ' + _(u'km/h'))
                        else:
                            log.info(
                                NAME,
                                u'%s' % self.status['log_date_maxspeed'] +
                                ' ' + _(u'Maximal speed') + ': ' +
                                u'%s' % round(self.status['max_meter'], 2) +
                                ' ' + _(u'm/sec'))

                        if self.status['meter'] >= 42:
                            log.error(
                                NAME,
                                datetime_string() + ' ' +
                                _(u'Wind speed > 150 km/h (42 m/sec)'))

                        if self.status['meter'] >= int(
                                wind_options['maxspeed']
                        ):  # if wind speed is > options max speed
                            log.clear(NAME)
                            if wind_options[
                                    'sendeml']:  # if enabled send email
                                send = True
                                log.info(
                                    NAME,
                                    datetime_string() + ' ' +
                                    _(u'Sending E-mail with notification.'))

                            if wind_options[
                                    'stoperr']:  # if enabled stoping for running stations in scheduler
                                set_stations_in_scheduler_off(
                                )  # set selected stations to stop in scheduler

                        millis = int(round(time_.time() * 1000))

                        if wind_options['enable_log']:  # if logging
                            interval = (wind_options['log_interval'] * 60000)
                            if (millis - last_millis) >= interval:
                                last_millis = millis
                                update_log()

                        if (
                                millis - last_clear_millis
                        ) >= 120000:  # after 120 second deleting in status screen
                            last_clear_millis = millis
                            log.clear(NAME)

                        if wind_options[
                                'delete_max_24h']:  # if enable deleting max after 24 hours (86400000 ms)
                            is_interval = True
                            if wind_options[
                                    'delete_max'] == '1':  # after one minute
                                int_ms = 60000
                            elif wind_options[
                                    'delete_max'] == '10':  # after 10 minutes
                                int_ms = 600000
                            elif wind_options[
                                    'delete_max'] == '30':  # after 30 minutes
                                int_ms = 1800000
                            elif wind_options[
                                    'delete_max'] == '1h':  # after one hours
                                int_ms = 3600000
                            elif wind_options[
                                    'delete_max'] == '2h':  # after two hours
                                int_ms = 7200000
                            elif wind_options[
                                    'delete_max'] == '10h':  # after 10 hours
                                int_ms = 36000000
                            elif wind_options[
                                    'delete_max'] == '24h':  # after 24 hours
                                int_ms = 86400000
                            else:
                                is_interval = False

                            if (
                                    millis - last_24h_millis
                            ) >= int_ms and is_interval:  # after xx minutes or hours deleting maximal speed
                                last_24h_millis = millis
                                self.status['meter'] = 0
                                self.status['kmeter'] = 0
                                self.status['max_meter'] = 0
                                self.status[
                                    'log_date_maxspeed'] = datetime_string()
                                log.info(
                                    NAME,
                                    datetime_string() + ' ' +
                                    _(u'Deleting maximal speed after selected interval.'
                                      ))
                                update_log()

                        tempText = ""
                        if wind_options['use_kmh']:
                            tempText += u'%s' % self.status[
                                'kmeter'] + ' ' + _(u'km/h')
                        else:
                            tempText += u'%s' % self.status['meter'] + ' ' + _(
                                u'm/s')
                        if wind_options['use_footer']:
                            if wind_mon is not None:
                                wind_mon.val = tempText.encode('utf8').decode(
                                    'utf8')  # value on footer
                    else:
                        self._sleep(1)

                else:
                    if disable_text:
                        log.clear(NAME)
                        log.info(NAME,
                                 _(u'Wind speed monitor plug-in is disabled.'))
                        disable_text = False
                    self._sleep(1)

                if send:
                    msg = '<b>' + _(
                        u'Wind speed monitor plug-in'
                    ) + '</b> ' + '<br><p style="color:red;">' + _(
                        u'System detected error: wind speed monitor. All stations set to OFF. Wind is'
                    ) + ': ' + u'%.1f' % (round(
                        val * 3.6, 2)) + ' ' + _(u'km/h') + '. </p>'
                    msglog = _(
                        u'System detected error: wind speed monitor. All stations set to OFF. Wind is'
                    ) + ': ' + u'%.1f' % (round(val, 2) *
                                          3.6) + ' ' + _(u'km/h') + '.'
                    send = False
                    try:
                        try_mail = None
                        if wind_options['eplug'] == 0:  # email_notifications
                            from plugins.email_notifications import try_mail
                        if wind_options[
                                'eplug'] == 1:  # email_notifications SSL
                            from plugins.email_notifications_ssl import try_mail
                        if try_mail is not None:
                            try_mail(
                                msg,
                                msglog,
                                attachment=None,
                                subject=wind_options['emlsubject']
                            )  # try_mail(text, logtext, attachment=None, subject=None)

                    except Exception:
                        log.error(
                            NAME,
                            _(u'Wind Speed monitor plug-in') + ':\n' +
                            traceback.format_exc())

            except Exception:
                log.clear(NAME)
                log.error(
                    NAME,
                    _(u'Wind Speed monitor plug-in') + ':\n' +
                    traceback.format_exc())
                self._sleep(60)
Пример #7
0
    def run(self):
        try:
            import smbus  # for PCF 8583

            self.bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
        except ImportError:
            log.warning(NAME, _('Could not import smbus.'))

        if self.bus is not None:
            self.pcf = set_counter(self.bus)  # set pcf8583 as counter

        log.clear(NAME)
        send = False  # send email
        disable_text = True
        val = 0.0
        maxval = 0.0
        timer_reset = 0

        while not self._stop.is_set():
            try:
                if self.bus is not None and wind_options[
                        'use_wind_monitor']:  # if wind plugin is enabled
                    disable_text = True

                    puls = counter(
                        self.bus) / 10.0  # counter value is value/10sec

                    val = puls / (wind_options['pulses'] * 1.0)
                    val = val * wind_options['metperrot']

                    if val > maxval:
                        maxval = val

                    if timer_reset >= 86400:  # 1 day
                        timer_reset = 0
                        maxval = 0.0

                    self.status['meter'] = round(val, 2)
                    self.status['kmeter'] = round(val * 3.6, 2)

                    log.clear(NAME)
                    log.info(NAME, _('Please wait 10 sec...'))
                    log.info(
                        NAME,
                        _('Speed') + ' ' + str(round(val, 2)) + ' ' +
                        _('m/sec'))
                    log.info(
                        NAME,
                        _('Speed Peak 24 hour') + ' ' + str(round(maxval, 2)) +
                        ' ' + _('m/sec'))
                    log.info(
                        NAME,
                        _('Pulses') + ' ' + str(puls) + ' ' + _('pulses/sec'))

                    if val >= 42:
                        log.error(NAME, _('Wind speed > 150 km/h (42 m/sec)'))

                    if get_station_is_on():  # if station is on
                        if val >= int(
                                wind_options['maxspeed']
                        ):  # if wind speed is > options max speed
                            log.clear(NAME)
                            log.finish_run(None)  # save log
                            stations.clear()  # set all station to off
                            log.clear(NAME)
                            log.info(
                                NAME,
                                _('Stops all stations and sends email if enabled sends email.'
                                  ))
                            if wind_options[
                                    'sendeml']:  # if enabled send email
                                send = True

                else:
                    # text on the web if plugin is disabled
                    if disable_text:
                        log.clear(NAME)
                        log.info(NAME,
                                 _('Wind speed monitor plug-in is disabled.'))
                        disable_text = False

                if send:
                    TEXT = (datetime_string() + ': ' + _(
                        'System detected error: wind speed monitor. All stations set to OFF. Wind is'
                    ) + ': ' + str(round(val * 3.6, 2)) + ' km/h.')
                    try:
                        from plugins.email_notifications import email
                        email(TEXT)  # send email without attachments
                        log.info(NAME, _('Email was sent') + ': ' + TEXT)
                        send = False
                    except Exception:
                        log.clear(NAME)
                        log.error(
                            NAME,
                            _('Email was not sent') + '! ' +
                            traceback.format_exc())

                timer_reset += 10  # measure is 10 sec long

            except Exception:
                log.clear(NAME)
                log.error(
                    NAME,
                    _('Wind Speed monitor plug-in') + ':\n' +
                    traceback.format_exc())
                self._sleep(60)
                self.pcf = set_counter(self.bus)  # set pcf8583 as counter
Пример #8
0
    def run(self):
        try:
            import smbus  # for PCF 8583
            self.bus = smbus.SMBus(0 if helpers.get_rpi_revision() == 1 else 1)

        except ImportError:
            log.warning(NAME, _(u'Could not import smbus.'))

        if self.bus is not None:
            self.pcf = set_counter(self.bus)     # set pcf8583 as counter

        log.clear(NAME)
        once_text = True  # text enabled plugin
        two_text = True   # text disabled plugin

        val = 0                     # actual water per second
        sum_water = options['sum']  # saved value of summary water 
        minute_water = 0            # actual water per minutes
        hour_water = 0              # actual water per hours

        last_minute_time = int(time.time())
        last_hour_time = int(time.time())
        actual_time = int(time.time())

        while not self._stop_event.is_set():
            try:
                if self.bus is not None and options['enabled']:  # if water meter plugin is enabled
                    val = counter(self.bus) / options['pulses']
                    self.status['meter'] = round(val, 2)

                    if once_text:
                        log.clear(NAME)
                        log.info(NAME, _(u'Water Meter plug-in is enabled.'))
                        once_text = False
                        two_text = True
                        if self.pcf is None:
                            log.warning(NAME, _(u'Could not find PCF8583.'))
                        else:
                            log.info(NAME, _(u'Please wait for minutes/hours data...'))
                            log.info(NAME, '________________________________')
                            log.info(NAME, _(u'Measured from') + ' {}'.format(options['log_date_last_reset']) + u'\n'+ _(u'Total sum') + u': {}'.format(round(sum_water, 2)) + u' ' + _(u'liters'))

                    if self.pcf is not None:
                        sum_water = sum_water + val
                        minute_water = minute_water + val
                        hour_water = hour_water + val

                        actual_time = int(time.time())
                        if actual_time - last_minute_time >= 60:          # minute counter
                            last_minute_time = actual_time
                            log.clear(NAME)
                            log.info(NAME, _(u'Water per minutes') + ': {}'.format(round(minute_water, 2)) + u' ' + _(u'liters'))
                            log.info(NAME, _(u'Water per hours') + ': {}'.format(round(hour_water, 2)) + u' ' + _(u'liters'))
                            log.info(NAME, _(u'Measured from') + ' {}'.format(options['log_date_last_reset']) + u'\n'+ _(u'Total sum') + u': {}'.format(round(sum_water, 2)) + u' ' + _(u'liters'))
                            minute_water = 0

                            # save summary water to options only 1 minutes
                            # options.__setitem__('sum', sum_water)  
                            qdict = {}       
                            if options['enabled']:
                                qdict['enabled'] = u'on' 
                            if options['address']:
                                qdict['address']  = u'on'
                            qdict['sum'] = round(sum_water, 2)
                            options.web_update(qdict)   

                        if actual_time - last_hour_time >= 3600:          # hour counter
                            last_hour_time = actual_time
                            hour_water = 0

                else:
                    if two_text:
                        self.status['meter'] = '0.0'
                        log.clear(NAME)
                        log.info(NAME, _(u'Water Meter plug-in is disabled.'))
                        two_text = False
                        once_text = True

                self._sleep(1)

            except Exception:
                self.bus = None
                log.error(NAME, _(u'Water Meter plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)
Пример #9
0
    def run(self):
        try:
            import smbus  # for PCF 8583

            self.bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
        except ImportError:
            log.warning(NAME, _('Could not import smbus.'))

        if self.bus is not None:
            self.pcf = set_counter(self.bus)  # set pcf8583 as counter

        log.clear(NAME)
        once_text = True  # text enabled plugin
        two_text = True  # text disabled plugin

        val = 0  # actual water per second
        sum_water = options['sum']  # saved value of summary water
        minute_water = 0  # actual water per minutes
        hour_water = 0  # actual water per hours

        last_minute_time = int(time.time())
        last_hour_time = int(time.time())
        actual_time = int(time.time())

        while not self._stop.is_set():
            try:
                if self.bus is not None and options[
                        'enabled']:  # if water meter plugin is enabled
                    val = counter(self.bus) / options['pulses']
                    self.status['meter'] = val

                    if once_text:
                        log.clear(NAME)
                        log.info(NAME, _('Water Meter plug-in is enabled.'))
                        once_text = False
                        two_text = True
                        if self.pcf is None:
                            log.warning(NAME, _('Could not find PCF8583.'))
                        else:
                            log.info(NAME,
                                     _('Please wait for min/hour data...'))
                            log.info(NAME, '________________________________')
                            log.info(NAME, _('Water in liters'))
                            log.info(
                                NAME,
                                _('Saved water summary') + ': ' +
                                str(sum_water))

                    if self.pcf is not None:
                        sum_water = sum_water + val
                        minute_water = minute_water + val
                        hour_water = hour_water + val

                        actual_time = int(time.time())
                        if actual_time - last_minute_time >= 60:  # minute counter
                            last_minute_time = actual_time
                            log.clear(NAME)
                            log.info(NAME, _('Water in liters'))
                            log.info(
                                NAME,
                                _('Water per minutes') + ': ' +
                                str(minute_water))
                            log.info(
                                NAME,
                                _('Water per hours') + ': ' + str(hour_water))
                            log.info(
                                NAME,
                                _('Water summary') + ': ' + str(sum_water))
                            minute_water = 0

                            options.__setitem__(
                                'sum', sum_water
                            )  # save summary water to options only 1 minutes

                        if actual_time - last_hour_time >= 3600:  # hour counter
                            last_hour_time = actual_time
                            hour_water = 0

                else:
                    if two_text:
                        self.status['meter'] = '0.0'
                        log.clear(NAME)
                        log.info(NAME, _('Water Meter plug-in is disabled.'))
                        two_text = False
                        once_text = True

                self._sleep(1)

            except Exception:
                self.bus = None
                log.error(
                    NAME,
                    _('Water Meter plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)