예제 #1
0
def update_lcd(line1, line2=None):
    """Print messages to LCD 16x2"""

    if lcd_options['address'] == 0:
        find_lcd_address()

    if lcd_options['address'] != 0:
        import pylcd  # Library for LCD 16x2 PCF8574

        lcd = pylcd.lcd(lcd_options['address'], 0 if helpers.get_rpi_revision() == 1 else 1, lcd_options['hw_PCF8574']) # (address, bus, hw version for expander)
        # DF - alter RPi version test fallback to value that works on BBB
    else:
        lcd = dummy_lcd

    lcd.lcd_clear()
    sleep_time = 1
    while line1 is not None:
        lcd.lcd_puts(line1[:16], 1)

        if line2 is not None:
           lcd.lcd_puts(line2[:16], 2)

        if max(len(line1), len(line2)) <= 16:
           break
 
        if line1 is not None:
           if len(line1) > 16:
              line1 = line1[1:]

        if line2 is not None:
            if len(line2) > 16:
                line2 = line2[1:]

        time.sleep(sleep_time)
        sleep_time = 0.25
예제 #2
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.'))
예제 #3
0
def get_overview():
    """Returns the info data as a list of lines."""
    result = []
    log.clear(NAME)
    meminfo = helpers.get_meminfo()
    netdevs = helpers.get_netdevs()

    result.append('System release: ' + platform.release())
    result.append('System name:    ' + platform.system())
    result.append('Node:           ' + platform.node())
    result.append('Machine:        ' + platform.machine())
    result.append('Total memory:   ' + meminfo['MemTotal'])
    result.append('Free memory:    ' + meminfo['MemFree'])
    if netdevs:
        for dev, info in netdevs.items():
            result.append('%-16s %s MiB %s MiB' %
                          (dev + ':', info['rx'], info['tx']))
    else:
        result.append('Network:        Unknown')
    result.append('Uptime:         ' + helpers.uptime())
    result.append('CPU temp:       ' +
                  helpers.get_cpu_temp(options.temp_unit) + ' ' +
                  options.temp_unit)
    result.append('MAC adress: ' + helpers.get_mac())
    try:
        result.append('I2C HEX Adress:')
        rev = str(0 if helpers.get_rpi_revision() == 1 else 1)
        cmd = 'sudo i2cdetect -y ' + rev
        result.append(process(cmd))
    except Exception:
        log.error(NAME, 'System info plug-in:\n' + traceback.format_exc())
    log.info(NAME, result)
    return result
예제 #4
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.'))
예제 #5
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
예제 #6
0
파일: api.py 프로젝트: teodoryantcheff/OSPy
 def GET(self):
     logger.debug('GET ' + self.__class__.__name__)
     return {
         'version': version.ver_str,
         'CPU_temperature': helpers.get_cpu_temp(),
         'release_date': version.ver_date,
         'uptime': helpers.uptime(),
         'platform': helpers.determine_platform(),
         'rpi_revision': helpers.get_rpi_revision()
     }
예제 #7
0
파일: api.py 프로젝트: Rimco/OSPy
 def GET(self):
     logger.debug('GET ' + self.__class__.__name__)
     return {
         'version': version.ver_str,
         'CPU_temperature': helpers.get_cpu_temp(),
         'release_date': version.ver_date,
         'uptime': helpers.uptime(),
         'platform': helpers.determine_platform(),
         'rpi_revision': helpers.get_rpi_revision(),
         'total_adjustment': level_adjustments.total_adjustment()
     }
예제 #8
0
def led_outputs(led):
    try:
        import smbus  
        bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
 
        bus.write_byte_data(0x27,0x01,0x00)
        bus.write_byte_data(0x27,0x13,led)
        
    except Exception:
        log.error(NAME, _('Button plug-in') + ':' + _('Set LED - FAULT'))
        log.error(NAME, '\n' + traceback.format_exc())
        pass
예제 #9
0
def DS18B20_read_data():
    import smbus
    try:
        bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
        time.sleep(1)  #wait here to avoid 121 IO Error
        try:
            i2c_data = try_io(lambda: bus.read_i2c_block_data(0x03, 0))
        except:
            i2c_data = [255, 255, 255]
            pass

        # Test recieved data byte 1 and 2
        if i2c_data[1] == 255 or i2c_data[2] == 255:
            log.debug(NAME, _(u'Data is not correct. Please try again later.'))
            return [-127, -127, -127, -127, -127, -127]  # data has error

        # Each float temperature from the hw board is 5 bytes long (5byte * 6 probe = 30 bytes).
        pom = 0
        teplota = [-127, -127, -127, -127, -127, -127]
        for i in range(0, plugin_options['ds_used']):
            priznak = 0
            jed = 0
            des = 0
            sto = 0
            tis = 0
            soucet = 0
            jed = i2c_data[pom + 4]  # 4 byte
            des = i2c_data[pom + 3] * 10  # 3
            sto = i2c_data[pom + 2] * 100  # 2
            tis = i2c_data[pom + 1] * 1000  # 1
            priznak = i2c_data[pom]  # 0 byte
            pom += 5
            soucet = tis + sto + des + jed
            if (priznak == 1):
                soucet = soucet * -1  # negation number
            teplota[i] = soucet / 10.0
            if teplota[i] > 127:
                teplota[i] = -127
            tempDS[i] = teplota[i]  # global temperature for all probe DS18B20

    except Exception:
        log.debug(
            NAME,
            _(u'Air Temperature and Humidity Monitor plug-in') + ':\n' +
            traceback.format_exc())
        time.sleep(0.5)
        pass
        return [-127, -127, -127, -127, -127, -127]  # try data has error

    return teplota  # data is ok
예제 #10
0
def read_buttons():
    try:
        import smbus  
        bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
        
        # Set 8 GPA pins as input pull-UP
        bus.write_byte_data(0x27,0x0C,0xFF)
        # Read state of GPIOA register
        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, _('Switch 8 pressed'))
        if inBut == 64:
            button_number = 6
            log.debug(NAME, _('Switch 7 pressed'))
        if inBut == 32:
            button_number = 5
            log.debug(NAME, _('Switch 6 pressed'))
        if inBut == 16:
            button_number = 4
            log.debug(NAME, _('Switch 5 pressed'))
        if inBut == 8:
            button_number = 3
            log.debug(NAME, _('Switch 4 pressed'))
        if inBut == 4:
            button_number = 2
            log.debug(NAME, _('Switch 3 pressed'))
        if inBut == 2:
            button_number = 1
            log.debug(NAME, _('Switch 2 pressed'))
        if inBut == 1:
            button_number = 0
            log.debug(NAME, _('Switch 1 pressed'))
        return button_number #if button is not pressed return -1

    except Exception:
        log.clear(NAME)
        log.error(NAME, _('Button plug-in') + ':' + _('Read button - FAULT'))
        log.error(NAME, '\n' + traceback.format_exc())
        pass
        return -1
예제 #11
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
예제 #12
0
def notify_ospyupdate(name, **kw):
    ### OSPy new version availbale ###
    global blocker
    blocker = True
    log.info(NAME, datetime_string() + ': ' + _('System OSPy Has Update'))
    if lcd_options['address'] == 0:
        find_lcd_address()
    if lcd_options['address'] != 0:
        from . import pylcd  # Library for LCD 16x2 PCF8574
        lcd = pylcd.lcd(lcd_options['address'],
                        0 if helpers.get_rpi_revision() == 1 else 1,
                        lcd_options['hw_PCF8574']
                        )  # (address, bus, hw version for expander)
        # DF - alter RPi version test fallback to value that works on BBB
    else:
        lcd = dummy_lcd

    try_io(lambda: lcd.lcd_clear())
    try_io(lambda: lcd.lcd_puts(ASCI_convert(_('System OSPy')), 1))
    try_io(lambda: lcd.lcd_puts(ASCI_convert(_('Has Update')), 2))
예제 #13
0
def led_outputs(led):
    try:
        import smbus

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

        try_io(lambda: bus.write_byte_data(plugin_options[
            'i2c_addr'], 0x01, 0x00))  # bus.write_byte_data(0x27,0x01,0x00)

        # Wait for device
        time.sleep(0.2)

        try_io(lambda: bus.write_byte_data(plugin_options[
            'i2c_addr'], 0x13, led))  # bus.write_byte_data(0x27,0x13,led)

    except Exception:
        log.error(NAME, datetime_string() + ': ' + _(u'Set LED - FAULT'))
        log.error(
            NAME,
            _(u'Is hardware connected? Is bus address corectly setuped?'))
        #log.error(NAME, '\n' + traceback.format_exc())
        pass
예제 #14
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)
예제 #15
0
    def run(self):
        log.clear(NAME)
        error_check = False  # error signature
        relay_pins = [0]
        relay_count = -1
        msg_debug_err = True
        msg_debug_on = [
            True, True, True, True, True, True, True, True, True, True, True,
            True, True, True, True, True
        ]
        msg_debug_off = [
            True, True, True, True, True, True, True, True, True, True, True,
            True, True, True, True, True
        ]
        time_cleaner = 0

        if not plugin_options['enabled']:
            log.info(NAME, _('Relay 16 plug-in') + ': ' + _('is disabled.'))

        while not self._stop_event.is_set():
            try:
                if relay_count != plugin_options['relays'] and plugin_options[
                        'enabled']:
                    relay_count = plugin_options['relays']
                    log.clear(NAME)
                    log.info(
                        NAME,
                        _('Relay 16 plug-in') + ': ' + datetime_string() +
                        ' ' + str(plugin_options['relays']) + ' ' +
                        _('Outputs set.'))

                    #### define the GPIO pins that will be used ####
                    try:
                        if determine_platform(
                        ) == 'pi':  # If this will run on Raspberry Pi:

                            import RPi.GPIO as GPIO  # RPi hardware
                            GPIO.setmode(
                                GPIO.BOARD
                            )  #IO channels are identified by header connector pin numbers. Pin numbers are

                            if get_rpi_revision() >= 2:

                                relay_pins = [
                                    22, 24, 26, 32, 36, 38, 40, 21, 23, 29, 31,
                                    33, 35, 37, 18, 19
                                ]  ### associations for outputs HW connector PINs

                                log.info(
                                    NAME,
                                    _('Relay 16 plug-in') + ': ' +
                                    _('Possible GPIO pins') + str(relay_pins) +
                                    '.')
                                for i in range(
                                        plugin_options['relays']
                                ):  # count 1 or 2, 4, 8, 16 outputs
                                    try:
                                        GPIO.setup(
                                            relay_pins[i],
                                            GPIO.OUT)  # set pin as outputs
                                    except:
                                        error_check = True  # not set pins -> this is error
                                        log.error(
                                            NAME,
                                            _('Relay 16 plug-in') + ':\n' +
                                            traceback.format_exc())
                            else:
                                log.info(
                                    NAME,
                                    _('Relay 16 plug-in') + ': ' +
                                    _('Sorry Raspberry Pi 1 is old version.'))
                                error_check = True
                        else:
                            log.info(
                                NAME,
                                _('Relay 16 plug-in') + ': ' +
                                _('Relay board plugin only supported on Raspberry Pi.'
                                  ))

                    except:
                        if msg_debug_err:
                            log.error(
                                NAME,
                                _('Relay 16 plug-in') + ':\n' +
                                traceback.format_exc())
                            msg_debug_err = False
                        error_check = False
                        pass

                #### plugin
                if plugin_options['enabled']:  # if plugin is enabled
                    if error_check == False:  # if not check error
                        for station in stations.get():
                            if station.index + 1 <= plugin_options[
                                    'relays']:  # only if station count is < count relay outputs

                                ### ON
                                if station.active:  # stations is on
                                    if plugin_options[
                                            'active'] == 'high':  # normal high logic
                                        # relay output on to 3.3V
                                        GPIO.output(relay_pins[station.index],
                                                    GPIO.HIGH)
                                        if msg_debug_on[station.index]:
                                            log.info(
                                                NAME,
                                                _('Relay 16 plug-in') + ': ' +
                                                datetime_string() + ' ' +
                                                _('Setings Relay Output') +
                                                ' ' +
                                                str(relay_pins[station.index])
                                                + ' ' + _('to HIGH') + ' (' +
                                                _('Station') + ' ' +
                                                str(station.index + 1) + ' ' +
                                                _('ON') + ').')
                                            msg_debug_on[station.index] = False
                                            msg_debug_off[station.index] = True
                                    else:  # inversion low logic
                                        # relay output on to 0V
                                        GPIO.output(relay_pins[station.index],
                                                    GPIO.LOW)
                                        if msg_debug_on[station.index]:
                                            log.info(
                                                NAME,
                                                _('Relay 16 plug-in') + ': ' +
                                                datetime_string() + ' ' +
                                                _('Setings Relay Output') +
                                                ' ' +
                                                str(relay_pins[station.index])
                                                + ' ' + _('to LOW') + ' (' +
                                                _('Station') + ' ' +
                                                str(station.index + 1) + ' ' +
                                                _('ON') + ').')
                                            msg_debug_on[station.index] = False
                                            msg_debug_off[station.index] = True

                                ### OFF
                                else:  # stations is off
                                    if plugin_options[
                                            'active'] == 'high':  # normal high logic
                                        # relay output off to 0V
                                        GPIO.output(relay_pins[station.index],
                                                    GPIO.LOW)
                                        if msg_debug_off[station.index]:
                                            log.info(
                                                NAME,
                                                _('Relay 16 plug-in') + ': ' +
                                                datetime_string() + ' ' +
                                                _('Setings Relay Output') +
                                                ' ' +
                                                str(relay_pins[station.index])
                                                + ' ' + _('to LOW') + ' (' +
                                                _('Station') + ' ' +
                                                str(station.index + 1) + ' ' +
                                                _('OFF') + ').')
                                            msg_debug_off[
                                                station.index] = False
                                            msg_debug_on[station.index] = True
                                    else:  # inversion low logic
                                        # relay output off to 3.3V
                                        GPIO.output(relay_pins[station.index],
                                                    GPIO.HIGH)
                                        if msg_debug_off[station.index]:
                                            log.info(
                                                NAME,
                                                _('Relay 16 plug-in') + ': ' +
                                                datetime_string() + ' ' +
                                                _('Setings Relay Output') +
                                                ' ' +
                                                str(relay_pins[station.index])
                                                + ' ' + _('to HIGH') + ' (' +
                                                _('Station') + ' ' +
                                                str(station.index + 1) + ' ' +
                                                _('OFF') + ').')
                                            msg_debug_off[
                                                station.index] = False
                                            msg_debug_on[station.index] = True

                time.sleep(0.5)

                time_cleaner += 1

                if time_cleaner >= 120:  # 60 sec timer (ex: 120 * time.sleep(0.5) is 60 sec)
                    time_cleaner = 0
                    relay_count = -1
                    msg_debug_err = True
                    msg_debug_on = [
                        True, True, True, True, True, True, True, True, True,
                        True, True, True, True, True, True, True
                    ]
                    msg_debug_off = [
                        True, True, True, True, True, True, True, True, True,
                        True, True, True, True, True, True, True
                    ]

            except Exception:
                log.error(
                    NAME,
                    _('Relay 16 plug-in') + ':\n' + traceback.format_exc())
                msg = -1
                self._sleep(60)
예제 #16
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)
예제 #17
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)
예제 #18
0
def get_sonic_cm():
    global last_data0, last_data1
    try:
        import smbus
        bus = smbus.SMBus(1 if get_rpi_revision() >= 2 else 0)
        try:
            data = try_io(lambda: bus.read_i2c_block_data(
                tank_options['address_ping'], 4))  # read bytes from I2C
            # data[0] is ultrasonic distance in overflow 255
            # data[1] is ultrasonic distance in range 0-255cm
            # ex: sonic is 180cm -> d0=0, d1=180
            # ex: sonic is 265cm -> d0=1, d1=10
            # data[2] is firmware version in CPU Atmega328 on board
            # data[3] is CRC sum

            val = data[1] + data[0] * 255

            ### logging ###
            if tank_options['input_byte_debug_log']:  # advanced bus logging
                if tank_options['byte_changed']:  # only if data changed
                    if (last_data0 != data[0]) or (last_data1 != data[1]):
                        last_data0 = data[0]
                        last_data1 = data[1]
                        update_debug_log(data[0], data[1], val, data[2],
                                         data[3])
                else:  # every 3 second log
                    update_debug_log(data[0], data[1], val, data[2], data[3])

            ### FW version on CPU atmega 328 processing ###
            # NO CRC init old version FW<1.4
            if data[2] == 0xFF or data[
                    2] == 0x00:  # not found version in atmega 328 (known version is 0x0D 13 FW1.3, 0x0E 14 FW1.4, 0x0F 15 FW1.5 ...)
                log.debug(NAME,
                          _(u'FW version in CPU (Atmega 328) is FW <= 1.3'))
                if data[1] == 0xFF or data[
                        0] == 0xFF:  # first check on buss error on sonic distance (byte 0 or byte 1 is 255 -> error skip)
                    return -1
                elif data[1] == 0x00 and data[
                        0] == 0x00:  # next check on buss error on sonic distance (byte 0 or byte 1 is 0 -> error skip)
                    return -1
                else:
                    if val > 400:  # 400 cm is max ping from ultrasonic sensor
                        return -1
                    else:
                        return val

            # WITH CRC check FW=1.4
            elif data[
                    2] == 14:  # 0x0E 14 is FW1.4 in Atmega 328 (with CRC8 check sum)
                from . import crc8  # online calc http://zorc.breitbandkatze.de/crc.html
                hash = crc8.crc8()
                bytes_val = repr(val).encode(
                    'utf8')  # convert int val to bytes ex: int 157 to b'157'
                hash.update(
                    bytes_val
                )  # val is calculated ping as sum from byte0 + byte1 (number ex: 0-65535)
                bytes_data = data[3].to_bytes(1, byteorder='big')
                hash_data = hash.digest()
                if hash_data == bytes_data:  # compare calculated ping in plugin and calculated ping on hw board
                    return val
                else:
                    return -1

            # UNKOWN VERSION
            else:
                log.debug(NAME, _(u'Unkown FW version in CPU (Atmega 328)'))
                return -1

        except:
            log.error(
                NAME,
                _(u'Water Tank Monitor plug-in') + ':\n' +
                traceback.format_exc())
            return -1
    except:
        log.error(
            NAME,
            _(u'Water Tank Monitor plug-in') + ':\n' + traceback.format_exc())
        return -1
예제 #19
0
    def run(self):
        Temperature = 0
        Humidity = 0  

        last_millis = 0 # timer for save log
        var1 = True     # Auxiliary variable for once on
        var2 = True     # Auxiliary variable for once off

        while not self._stop.is_set():
            try:
                if plugin_options['enabled']:  # if plugin is enabled   
                    try:
                       Temperature, Humidity = DHT11_read_data()
                    except:
                       self._sleep(0.3)                                     
                      
                    if Humidity and Temperature != 0:
                       log.clear(NAME)
                       self.status['temp'] = Temperature
                       self.status['humi'] = Humidity
                       log.info(NAME, datetime_string())
                       log.info(NAME, _('Temperature') + ' DHT: ' + u'%.1f \u2103' % Temperature)
                       log.info(NAME, _('Humidity') + ' DHT: ' + u'%.1f' % Humidity + ' %RH')
                       if plugin_options['enabled_reg']:
                          OT = _('ON') if self.status['outp'] is 1 else _('OFF') 
                          log.info(NAME, _('Output') + ': ' + u'%s' % OT)

                       if plugin_options['enable_log']:
                          millis = int(round(time.time() * 1000))
                          interval = (plugin_options['log_interval'] * 60000)
                          if (millis - last_millis) > interval:
                             last_millis = millis
                             update_log(self.status)

                       station = stations.get(plugin_options['control_output'])

                       if plugin_options['enabled_reg']:  # if regulation is enabled
                          if Humidity > (plugin_options['humidity_on'] + plugin_options['hysteresis']/2) and var1 is True:  
                             station.active = True
                             var1 = False
                             var2 = True
                             self.status['outp'] = 1
                             log.debug(NAME, _('Station output was turned on.'))
                             update_log(self.status)
                             
                          if Humidity < (plugin_options['humidity_off'] - plugin_options['hysteresis']/2) and var2 is True:  
                             station.active = False
                             var1 = True
                             var2 = False 
                             self.status['outp'] = 0
                             log.debug(NAME, _('Station output was turned off.'))
                             update_log(self.status)    

                       # Activate again if needed:
                       if station.remaining_seconds != 0:
                          station.active = True

 
                    if plugin_options['ds_enabled']:  # if in plugin is enabled DS18B20
                       try:
                          import smbus  
                          import struct

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

                          temp_data = bus.read_i2c_block_data(0x03, 0)
                          #log.info(NAME, _('Data: ') + str(temp_data))

                          # Each float from the hw board is 5 bytes long.
                          pom=0
                          for i in range(0, plugin_options['ds_used']):
                            priznak=0
                            jed=0
                            des=0
                            sto=0
                            tis=0
                            soucet=0
                            jed = temp_data[pom+4]        # 4 byte
                            des = temp_data[pom+3]*10     # 3
                            sto = temp_data[pom+2]*100    # 2
                            tis = temp_data[pom+1]*1000   # 1  
                            priznak = temp_data[pom]      # 0 byte

                            pom += 5

                            soucet = tis+sto+des+jed

                            if(soucet > 1270):
                               priznak=255 # error value not printing
                        
                            if(priznak==1):
                               soucet = soucet * -1  # negation number

                            teplota = soucet/10.0

                            if(priznak!=255):
                               self.status['DS%d' % i] = teplota
                               log.info(NAME, _('Temperature') + ' DS' + str(i) + ': ' + u'%.1f \u2103' % teplota)
                            else:
                               self.status['DS%d' % i] = -127
                               log.info(NAME, _('Temperature') + ' DS' + str(i) + ': Err')

                       except Exception:
                          log.error(NAME, '\n' + _('Can not read data from I2C bus.') + ':\n' + traceback.format_exc())
                          pass
                       
                    self._sleep(5)

            except Exception:
                log.error(NAME, _('Air Temperature and Humidity Monitor plug-in') + ':\n' + traceback.format_exc())
                self._sleep(60)
예제 #20
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
예제 #21
0
        'water_minimum': 6,  # default 6 cm water level <-> bottom tank
        'use_send_email': True,  # default send email
        'use_freq_1': False,  # default not use freq sensor 1
        'use_freq_2': False,  # default not use freq sensor 2
        'use_freq_3': False,  # default not use freq sensor 3
        'use_freq_4': False,  # default not use freq sensor 4
        'use_freq_5': False,  # default not use freq sensor 5
        'use_freq_6': False,  # default not use freq sensor 6
        'use_freq_7': False,  # default not use freq sensor 7
        'use_freq_8': False,  # default not use freq sensor 8
        'minimum_freq': 400000,  # default freq from sensor for 0% humi
        'maximum_freq': 100000,  # default freq from sensor for 100% humi
        'emlsubject': _('Report from OSPy TANK HUMI plugin')
    })

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

address_ping = 0x04  # device address for sonic ping HW board
address_humi = 0x05  # device address for humidity HW board

################################################################################
# Main function loop:                                                          #
################################################################################


class Sender(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self._stop = Event()
예제 #22
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)