On Friday, 20 September 2019 12:04:33 UTC+1, Andrew Milner wrote:
>
> perhaps it would help us if you attached a copy of your weewx.conf
>
>
>
> On Friday, 20 September 2019 13:34:25 UTC+3, Laurent Lasne wrote:
>>
>> Hi Everyone,
>>
>> Weather station : Raspberry pi3, running Raspbian buster
>>                             Adafruit PCF8523 Real Time Clock Assembled 
>> Breakout Board [ADA3295] 
>> <https://thepihut.com/products/adafruit-pcf8523-real-time-clock-assembled-breakout-board>
>> Driver for weewx: jardiamj/BYOWS_RPi 
>> <https://github.com/jardiamj/BYOWS_RPi>
>>                            
>> Tutorial             : Build your own weather station_Raspberry pi 
>> project 
>> <https://projects.raspberrypi.org/en/projects/build-your-own-weather-station>
>>   
>>  (Uploading data to weather underground)
>>
>>
>>      After getting my station up and running perfectly using the python3 
>> code from the tutorial: SQLite, all sensors reading and upload to weather 
>> underground, I decided to give a go to weewx, but I have an issue. When I 
>> start weewx manually 
>> sudo weewxd /etc/weewx/weewx.conf
>>
>> I got that in my /var/log/Syslog when debug = 1 in  : weewx.conf
>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Initializing weewx 
>>>> version 3.9.2
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Using Python 2.7.16 
>>>> (default, Apr  6 2019, 01:42:57) #012[GCC 8.2.0]
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Platform 
>>>> Linux-4.19.66-v7+-armv7l-with-debian-10.1
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Locale is 'en_GB.UTF-8'
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Using configuration 
>>>> file /etc/weewx/weewx.conf
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Debug is 1
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Initializing engine
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Loading station type 
>>>> BYOWS (user.byows_rpi)
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Import of driver 
>>>> failed: int() can't convert non-string with explicit base (<type 
>>>> 'exceptions.TypeError'>)
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]: engine: Unable to load driver: 
>>>> int() can't convert non-string with explicit base
>>>
>>> Sep 20 11:17:52 raspberrypi weewx[4040]:     ****  Exiting...
>>>
>>>
>> I know that wiring is ok because working with python3
>> I did reinstall libraries for python 2.7 
>> I made some research but come empty-handed
>> I am not a programmer, just in learning phase python3 (first language for 
>> me).
>> Not bad knowledge of Linux, Debian ubuntu Knoppix, etc...
>> I don't know what to do next, I hope I will get help.
>> Thank you for your time 
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"weewx-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/weewx-user/a518d36b-63ee-4a55-ba48-0effd90d31c3%40googlegroups.com.
# WEEWX CONFIGURATION FILE
#
# Copyright (c) 2009-2019 Tom Keffer <[email protected]>
# See the file LICENSE.txt for your rights.

##############################################################################

# This section is for general configuration information.

# Set to 1 for extra debug info, otherwise comment it out or set to zero
debug = 1

# Root directory of the weewx data file hierarchy for this station
WEEWX_ROOT = /

# Whether to log successful operations
log_success = True

# Whether to log unsuccessful operations
log_failure = True

# How long to wait before timing out a socket (FTP, HTTP) connection
socket_timeout = 20

# Do not modify this. It is used when installing and updating weewx.
version = 3.9.2

##############################################################################

#   This section is for information about the station.

[Station]
    
    # Description of the station location
    location = "Grove Hill Kilkeel Down NI"
    
    # Latitude and longitude in decimal degrees
    latitude = 54.065
    longitude = -6.028
    
    # Altitude of the station, with unit it is in. This is downloaded from
    # from the station if the hardware supports it.
    altitude = 44, meter
    
    # Set to type of station hardware. There must be a corresponding stanza
    # in this file with a 'driver' parameter indicating the driver to be used.
    station_type = BYOWS
    
    # If you have a website, you may specify an URL
    #station_url = http://www.example.com
    
    # The start of the rain year (1=January; 10=October, etc.). This is
    # downloaded from the station if the hardware supports it.
    rain_year_start = 1
    
    # Start of week (0=Monday, 6=Sunday)
    week_start = 6

##############################################################################

[BYOWS]
    # This section is for the Raspberry Pi Bring Your Own Weather Station 
driver.
    
    # [REQUIRED]
    # The driver to use.
    driver = user.byows_rpi



[Simulator]
    # This section is for the weewx weather station simulator
    
    # The time (in seconds) between LOOP packets.
    loop_interval = 2.5
    
    # The simulator mode can be either 'simulator' or 'generator'.
    # Real-time simulator. Sleep between each LOOP packet.
    mode = simulator
    # Generator.  Emit LOOP packets as fast as possible (useful for testing).
    #mode = generator
    
    # The start time. Format is YYYY-mm-ddTHH:MM. If not specified, the default 
    # is to use the present time.
    #start = 2011-01-01T00:00
    
    # The driver to use:
    driver = weewx.drivers.simulator

##############################################################################

#   This section is for uploading data to Internet sites

[StdRESTful]
    
    [[StationRegistry]]
        # To register this weather station with weewx, set this to true
        register_this_station = false
    
    [[AWEKAS]]
        # This section is for configuring posts to AWEKAS.
        
        # If you wish to do this, set the option 'enable' to true,
        # and specify a username and password.
        # To guard against parsing errors, put the password in quotes.
        enable = false
        username = replace_me
        password = replace_me
    
    [[CWOP]]
        # This section is for configuring posts to CWOP.
        
        # If you wish to do this, set the option 'enable' to true,
        # and specify the station ID (e.g., CW1234).
        enable = false
        station = replace_me
    
    # If this is an APRS (radio amateur) station, uncomment
    # the following and replace with a passcode (e.g., 12345).
    #passcode = replace_me (APRS stations only)
    
    [[PWSweather]]
        # This section is for configuring posts to PWSweather.com.
        
        # If you wish to do this, set the option 'enable' to true,
        # and specify a station and password.
        # To guard against parsing errors, put the password in quotes.
        enable = false
        station = replace_me
        password = replace_me
    
    [[WOW]]
        # This section is for configuring posts to WOW.
        
        # If you wish to do this, set the option 'enable' to true,
        # and specify a station and password.
        # To guard against parsing errors, put the password in quotes.
        enable = false
        station = replace_me
        password = replace_me
    
    [[Wunderground]]
        # This section is for configuring posts to the Weather Underground.
        
        # If you wish to do this, set the option 'enable' to true,
        # and specify a station (e.g., 'KORHOODR3') and password.
        # To guard against parsing errors, put the password in quotes.
        enable = false
        station = replace_me
        password = replace_me
        
        # Set the following to True to have weewx use the WU "Rapidfire"
        # protocol. Not all hardware can support it. See the User's Guide.
        rapidfire = False

##############################################################################

#   This section specifies what reports, using which skins, to generate.

[StdReport]
    
    # Where the skins reside, relative to WEEWX_ROOT
    SKIN_ROOT = /etc/weewx/skins
    
    # Where the generated reports should go, relative to WEEWX_ROOT
    HTML_ROOT = /var/www/html/weewx
    
    # The database binding indicates which data should be used in reports.
    data_binding = wx_binding
    
    # Whether to log a successful operation
    log_success = True
    
    # Whether to log an unsuccessful operation
    log_failure = False
    
    # Each of the following subsections defines a report that will be run.
    # See the customizing guide to change the units, plot types and line
    # colors, modify the fonts, display additional sensor data, and other
    # customizations. Many of those changes can be made here by overriding
    # parameters, or by modifying templates within the skin itself.
    
    [[SeasonsReport]]
        # The SeasonsReport uses the 'Seasons' skin, which contains the
        # images, templates and plots for the report.
        skin = Seasons
        enable = true
    
    [[SmartphoneReport]]
        # The SmartphoneReport uses the 'Smartphone' skin, and the images and
        # files are placed in a dedicated subdirectory.
        skin = Smartphone
        enable = false
        HTML_ROOT = /var/www/html/weewx/smartphone
    
    [[MobileReport]]
        # The MobileReport uses the 'Mobile' skin, and the images and files
        # are placed in a dedicated subdirectory.
        skin = Mobile
        enable = false
        HTML_ROOT = /var/www/html/weewx/mobile
    
    [[StandardReport]]
        # This is the old "Standard" skin. By default, it is not enabled.
        skin = Standard
        enable = false
    
    [[FTP]]
        # FTP'ing the results to a webserver is treated as just another report,
        # albeit one with an unusual report generator!
        skin = Ftp
        
        # If you wish to use FTP, set "enable" to "true", then
        # fill out the next four lines.
        # Use quotes around passwords to guard against parsing errors.
        enable = false
        user = replace_me
        password = replace_me
        server = replace_me    # The ftp server name, e.g, www.myserver.org
        path = replace_me    # The destination directory, e.g., /weather
        
        # Set to True for an FTP over TLS (FTPS) connection. Not all servers
        # support this.
        secure_ftp = False
        
        # To upload files from something other than what HTML_ROOT is set
        # to above, specify a different HTML_ROOT here.
        #HTML_ROOT = /var/www/html/weewx
        
        # Most FTP servers use port 21
        port = 21
        
        # Set to 1 to use passive mode, zero for active mode
        passive = 1
    
    [[RSYNC]]
        # rsync'ing to a webserver is treated as just another report
        skin = Rsync
        
        # If you wish to use rsync, you must configure passwordless ssh using
        # public/private key authentication from the user account that weewx
        # runs to the user account on the remote machine where the files
        # will be copied.
        #
        # If you wish to use rsync, set "enable" to "true", then
        # fill out server, user, and path.
        # The server should appear in your .ssh/config file.
        # The user is the username used in the identity file.
        # The path is the destination directory, such as /var/www/html/weather.
        # Be sure that the user has write permissions on the destination!
        enable = false
        server = replace_me
        user = replace_me
        path = replace_me
        
        # To upload files from something other than what HTML_ROOT is set
        # to above, specify a different HTML_ROOT here.
        #HTML_ROOT = /var/www/html/weewx
        
        # Rsync can be configured to remove files from the remote server if
        # they don't exist under HTML_ROOT locally. USE WITH CAUTION: if you
        # make a mistake in the remote path, you could could unintentionally
        # cause unrelated files to be deleted. Set to 1 to enable remote file
        # deletion, zero to allow files to accumulate remotely.
        delete = 0
    
    ####
    
    # Various options for customizing your reports.
    
    [[Defaults]]
        
        [[[Units]]]
            
            # The following section sets what unit to use for each unit group.
            # NB: The unit is always in the singular. I.e., 'mile_per_hour',
            # NOT 'miles_per_hour'
            [[[[Groups]]]]
                
                group_altitude = meter    # Options are 'foot' or 'meter'
                group_degree_day = degree_C_day    # Options are 'degree_F_day' 
or 'degree_C_day'
                group_pressure = mbar    # Options are 'inHg', 'mmHg', 'mbar', 
or 'hPa'
                group_rain = cm    # Options are 'inch', 'cm', or 'mm'
                group_rainrate = cm_per_hour    # Options are 'inch_per_hour', 
'cm_per_hour', or 'mm_per_hour'
                group_speed = km_per_hour    # Options are 'mile_per_hour', 
'km_per_hour', 'knot', or 'meter_per_second'
                group_speed2 = km_per_hour2    # Options are 'mile_per_hour2', 
'km_per_hour2', 'knot2', or 'meter_per_second2'
                group_temperature = degree_C    # Options are 'degree_F' or 
'degree_C'
            
            # The following section sets the formatting for each type of unit.
            [[[[StringFormats]]]]
                
                centibar = %.0f
                cm = %.2f
                cm_per_hour = %.2f
                degree_C = %.1f
                degree_F = %.1f
                degree_compass = %.0f
                foot = %.0f
                hPa = %.1f
                hour = %.1f
                inHg = %.3f
                inch = %.2f
                inch_per_hour = %.2f
                km_per_hour = %.0f
                km_per_hour2 = %.1f
                knot = %.0f
                knot2 = %.1f
                mbar = %.1f
                meter = %.0f
                meter_per_second = %.1f
                meter_per_second2 = %.1f
                mile_per_hour = %.0f
                mile_per_hour2 = %.1f
                mm = %.1f
                mmHg = %.1f
                mm_per_hour = %.1f
                percent = %.0f
                second = %.0f
                uv_index = %.1f
                volt = %.1f
                watt_per_meter_squared = %.0f
                NONE = "   N/A"
            
            # The following section sets the label for each type of unit
            [[[[Labels]]]]
                
                day = " day", " days"
                hour = " hour", " hours"
                minute = " minute", " minutes"
                second = " second", " seconds"
                NONE = ""
            
            # The following section sets the format for each time scale.
            # The values below will work in every locale, but they may not look
            # particularly attractive.
            [[[[TimeFormats]]]]
                
                hour = %H:%M
                day = %X
                week = %X (%A)
                month = %x %X
                year = %x %X
                rainyear = %x %X
                current = %x %X
                ephem_day = %X
                ephem_year = %x %X
            
            [[[[Ordinates]]]]
                
                # Ordinal directions. The last one is for no wind direction
                directions = N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, 
W, WNW, NW, NNW, N/A
                
                # The following section sets the base temperatures used for the
                #  calculation of heating and cooling degree-days.
                [[[[[DegreeDays]]]]]
                    
                    # Base temperature for heating days, with unit:
                    heating_base = 65, degree_F
                    # Base temperature for cooling days, with unit:
                    cooling_base = 65, degree_F
                
                # A trend takes a difference across a time period. The following
                # section sets the time period, and how big an error is allowed 
to
                # still be counted as the start or end of a period.
                [[[[[Trend]]]]]
                    
                    time_delta = 10800    # 3 hours
                    time_grace = 300    # 5 minutes
        
        # The labels to be used for each observation type
        [[[Labels]]]
            
            # Set to hemisphere abbreviations suitable for your location:
            hemispheres = N, S, E, W
            
            # Formats to be used for latitude whole degrees, longitude whole
            # degrees, and minutes:
            latlon_formats = %02d, %03d, %05.2f
            
            # Generic labels, keyed by an observation type.
            [[[[Generic]]]]
                barometer = Barometer
                dewpoint = Dew Point
                ET = ET
                heatindex = Heat Index
                inHumidity = Inside Humidity
                inTemp = Inside Temperature
                outHumidity = Humidity
                outTemp = Outside Temperature
                radiation = Radiation
                rain = Rain
                rainRate = Rain Rate
                UV = UV Index
                windDir = Wind Direction
                windGust = Gust Speed
                windGustDir = Gust Direction
                windSpeed = Wind Speed
                windchill = Wind Chill
                windgustvec = Gust Vector
                windvec = Wind Vector
                extraTemp1 = Temperature1
                extraTemp2 = Temperature2
                extraTemp3 = Temperature3
                
                # Sensor status indicators
                
                rxCheckPercent = Signal Quality
                txBatteryStatus = Transmitter Battery
                windBatteryStatus = Wind Battery
                rainBatteryStatus = Rain Battery
                outTempBatteryStatus = Outside Temperature Battery
                inTempBatteryStatus = Inside Temperature Battery
                consBatteryVoltage = Console Battery
                heatingVoltage = Heating Battery
                supplyVoltage = Supply Voltage
                referenceVoltage = Reference Voltage
        
        [[[Almanac]]]
            
            # The labels to be used for the phases of the moon:
            moon_phases = New, Waxing crescent, First quarter, Waxing gibbous, 
Full, Waning gibbous, Last quarter, Waning crescent

##############################################################################

#   This service acts as a filter, converting the unit system coming from
#   the hardware to a unit system in the database.

[StdConvert]
    
    # The target_unit affects only the unit system in the database. Once
    # chosen it cannot be changed without converting the entire database.
    # Modification of target_unit after starting weewx will result in
    # corrupt data - the database will contain a mix of US and METRIC data.
    #
    # The value of target_unit does not affect the unit system for
    # reporting - reports can display US, Metric, or any combination of units.
    #
    # In most cases, target_unit should be left as the default: US
    #
    # In particular, those migrating from a standard wview installation
    # should use US since that is what the wview database contains.
    
    # DO NOT MODIFY THIS VALUE UNLESS YOU KNOW WHAT YOU ARE DOING!
    target_unit = US    # Options are 'US', 'METRICWX', or 'METRIC'

##############################################################################

#   This section can adjust data using calibration expressions.

[StdCalibrate]
    
    [[Corrections]]
        # For each type, an arbitrary calibration expression can be given.
        # It should be in the units defined in the StdConvert section.
        # Example:
        foo = foo + 0.2

##############################################################################

#   This section is for quality control checks. If units are not specified,
#   values must be in the units defined in the StdConvert section.

[StdQC]
    
    [[MinMax]]
        barometer = 26, 32.5, inHg
        pressure = 24, 34.5, inHg
        outTemp = -40, 120, degree_F
        inTemp = 10, 120, degree_F
        outHumidity = 0, 100
        inHumidity = 0, 100
        windSpeed = 0, 120, mile_per_hour
        rain = 0, 10, inch

##############################################################################

#   This section controls the origin of derived values.

[StdWXCalculate]
    
    [[Calculations]]
        # How to calculate derived quantities.  Possible values are:
        #  hardware        - use the value provided by hardware
        #  software        - use the value calculated by weewx
        #  prefer_hardware - use value provide by hardware if available,
        #                      otherwise use value calculated by weewx
        
        pressure = prefer_hardware
        barometer = prefer_hardware
        altimeter = prefer_hardware
        windchill = prefer_hardware
        heatindex = prefer_hardware
        dewpoint = prefer_hardware
        inDewpoint = prefer_hardware
        rainRate = prefer_hardware

##############################################################################

#   For hardware that supports it, this section controls how often the
#   onboard clock gets updated.

[StdTimeSynch]
    
    # How often to check the weather station clock for drift (in seconds)
    clock_check = 14400
    
    # How much it can drift before we will correct it (in seconds)
    max_drift = 5

##############################################################################

#   This section is for configuring the archive service.

[StdArchive]
    
    # If the station hardware supports data logging then the archive interval
    # will be downloaded from the station. Otherwise, specify it (in seconds).
    archive_interval = 300
    
    # If possible, new archive records are downloaded from the station
    # hardware. If the hardware does not support this, then new archive
    # records will be generated in software.
    # Set the following to "software" to force software record generation.
    record_generation = hardware
    
    # Whether to include LOOP data in hi/low statistics
    loop_hilo = True
    
    # The data binding used to save archive records
    data_binding = wx_binding

##############################################################################

#   This section binds a data store to a database.

[DataBindings]
    
    [[wx_binding]]
        # The database must match one of the sections in [Databases].
        # This is likely to be the only option you would want to change.
        database = archive_sqlite
        # The name of the table within the database
        table_name = archive
        # The manager handles aggregation of data for historical summaries
        manager = weewx.wxmanager.WXDaySummaryManager
        # The schema defines the structure of the database.
        # It is *only* used when the database is created.
        schema = schemas.wview.schema

##############################################################################

#   This section defines various databases.

[Databases]
    
    # A SQLite database is simply a single file
    [[archive_sqlite]]
        database_name = weewx.sdb
        database_type = SQLite
    
    # MySQL
    [[archive_mysql]]
        database_name = weewx
        database_type = MySQL

##############################################################################

#   This section defines defaults for the different types of databases.

[DatabaseTypes]
    
    # Defaults for SQLite databases
    [[SQLite]]
        driver = weedb.sqlite
        # Directory in which the database files are located
        SQLITE_ROOT = /var/lib/weewx
    
    # Defaults for MySQL databases
    [[MySQL]]
        driver = weedb.mysql
        # The host where the database is located
        host = localhost
        # The user name for logging in to the host
        user = weewx
        # The password for the user name (quotes guard against parsing errors)
        password = weewx

##############################################################################

#   This section configures the internal weewx engine.

[Engine]
    
    [[Services]]
        # This section specifies the services that should be run. They are
        # grouped by type, and the order of services within each group
        # determines the order in which the services will be run.
        prep_services = weewx.engine.StdTimeSynch
        data_services = ,
        process_services = weewx.engine.StdConvert, weewx.engine.StdCalibrate, 
weewx.engine.StdQC, weewx.wxservices.StdWXCalculate
        archive_services = weewx.engine.StdArchive
        restful_services = weewx.restx.StdStationRegistry, 
weewx.restx.StdWunderground, weewx.restx.StdPWSweather, weewx.restx.StdCWOP, 
weewx.restx.StdWOW, weewx.restx.StdAWEKAS
        report_services = weewx.engine.StdPrint, weewx.engine.StdReport
#!/usr/bin/env python
"""
Copyright 2019 Jardi A. Martinez Jordan <[email protected]>

This is an weeWX driver implementation of the Build Your OWN Weather
Station using the Raspberry Pi:
https://projects.raspberrypi.org/en/projects/build-your-own-weather-station/

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

"""
import math
import syslog
import time
import datetime

# Imports specific for ByowsRpiStation class
from gpiozero import Button, MCP3008
import os, glob
import bme280
import smbus2

import weewx.drivers

DRIVER_NAME = 'BYOWS'
DRIVER_VERSION = '0.51'

def loader(config_dict, _):
    return ByowsRpi(**config_dict[DRIVER_NAME])

"""
def confeditor_loader():
    return ByowsRpiConfEditor()
"""

def logmsg(level, msg):
    syslog.syslog(level, 'BYOWS RPi: %s' % msg)

def logdbg(msg):
    logmsg(syslog.LOG_DEBUG, msg)

def loginf(msg):
    logmsg(syslog.LOG_INFO, msg)

def logerr(msg):
    logmsg(syslog.LOG_ERR, msg)


class ByowsRpi(weewx.drivers.AbstractDevice):
    """weewx driver for the Build Your Own Weather Station - Raspberry Pi

    """
    def __init__(self, **stn_dict):
        self.hardware = stn_dict.get('hardware', "BYOWS - Raspberry Pi")
        self.loop_interval = float(stn_dict.get('loop_interval', 5))
        params = dict()
        params['anem_pin'] = int(stn_dict.get('anemometer_pin', 5))
        params['rain_bucket_pin'] = int(stn_dict.get('rain_bucket_pin', 6))
        params['bme280_port'] = int(stn_dict.get('bme280_port', 1))
        params['bme280_address'] = int(stn_dict.get('bme280_address', 0x77), 16)
        params['mcp3008_channel'] = int(stn_dict.get('mcp3008_channel', 0))
        params['anem_adjustment'] = float(stn_dict.get('anemometer_adjustment', 1.18))
        params['bucket_size'] = float(stn_dict.get('bucket_size', 0.2794))
        params['anem_radius_cm'] = float(stn_dict.get('anemometer_radius_cm', 9.0))
        loginf('using driver %s' % DRIVER_NAME)
        loginf('driver version is %s' % DRIVER_VERSION)
        self.station = ByowsRpiStation(**params)

    @property
    def hardware_name(self):
        return self.hardware

    def genLoopPackets(self):
        """ Function that generates packets for weeWX by looping through station
        data generator function. """
        while True:
            packet = {'dateTime': int(time.time() + 0.5),
                    'usUnits': weewx.METRIC}
            data = self.station.get_data()
            packet.update(data)
            yield packet
            time.sleep(self.loop_interval) # defaults to 5 seconds


class ByowsRpiStation(object):
    """ Object that represents a BYOWS_Station. """
    CM_IN_A_KM = 100000.0
    SECS_IN_AN_HOUR = 3600
    def __init__(self, **params):
        """ Initialize Object. """
        self.bme280_address = params.get('bme280_address')
        self.bme280_bus = smbus2.SMBus(params.get('bme280_port'))
        self.bme280_sensor = bme280
        self.bme280_sensor.load_calibration_params(self.bme280_bus,
                                                   self.bme280_address)
        self.bucket_size = params.get('bucket_size') # in mm
        self.rain_count = 0
        self.wind_gauge = WindGauge(params.get('mcp3008_channel'),
                                    params.get('anem_pin'),
                                    params.get('anem_radius_cm'),
                                    params.get('anem_adjustment'))
        self.rain_sensor = Button(params.get('rain_bucket_pin'))
        self.rain_sensor.when_pressed = self.bucket_tipped
        self.temp_probe = DS18B20()

    def bucket_tipped(self):
        self.rain_count = self.rain_count + 1

    def get_bme280_data(self):
        try:
            data = self.bme280_sensor.sample(self.bme280_bus,self.bme280_address)
            humidity, pressure, temperature = data.humidity, data.pressure, data.temperature
        except:
            logdbg("Error sampling sensor bme280, passing None as data.")
            humidity, pressure, temperature = None, None, None
            pass
        return humidity, pressure, temperature

    def get_soil_temp(self):
        return self.temp_probe.read_temp()

    def get_rainfall(self):
        """ Returns rainfall in cm. """
        rainfall = (self.rain_count * self.bucket_size)/10.0
        self.reset_rainfall()
        return rainfall

    def get_data(self):
        """ Generates data packets every time interval. """
        data = dict()
        anem_rotations = self.wind_gauge.wind_count/2.0
        time_interval = self.wind_gauge.last_wind_time - time.time()
        wind_speed, wind_dir = self.wind_gauge.get_wind()
        humidity, pressure, ambient_temp = self.get_bme280_data()
        data['outHumidity'] = humidity
        data['pressure'] = pressure
        data['outTemp'] = ambient_temp
        data['soilTemp1'] = self.get_soil_temp()
        data['windSpeed'] = float(wind_speed)
        data['windDir'] = wind_dir
        data['rain'] = float(self.get_rainfall())
        data['anemRotations'] = anem_rotations
        data['timeAnemInterval'] = time_interval
        return data

    def reset_rainfall(self):
        self.rain_count = 0

class DS18B20(object):
    """
    add the lines below to /etc/modules (reboot to take effect)
    w1-gpio
    w1-therm
    """
    def __init__(self):
        w1_devices = glob.glob("/sys/bus/w1/devices/28*")
        self.device_file = w1_devices[0] + '/w1_slave' if len(w1_devices) > 0 else None

    def read_temp_raw(self):
        if self.device_file != None:
            f = open(self.device_file, "r")
            lines = f.readlines()
            f.close()
            return lines
        else:
            return None

    def crc_check(self, lines):
        return lines[0].strip()[-3:] == "YES"

    def read_temp(self):
        temp_c = -255
        attempts = 0

        lines = self.read_temp_raw()

        if lines != None:
            success = self.crc_check(lines)

            while not success and attempts < 3:
                time.sleep(.2)
                lines = self.read_temp_raw()
                success = self.crc_check(lines)
                attempts += 1

            if success:
                temp_line = lines[1]
                equal_pos = temp_line.find("t=")
                if equal_pos != -1:
                    temp_string = temp_line[equal_pos+2:]
                    temp_c = float(temp_string)/1000.0

            return temp_c
        else:
            return None


class WindGauge(object):
    """ Object that represents a Wind Vane sensor. """
    WIND_VANE_VOLTS = { 0.4: 0.0,   1.4: 22.5,  1.2: 45.0,  2.8: 67.5,
                    2.7: 90.0,  2.9: 112.5, 2.2: 135.0, 2.5: 157.5,
                    1.8: 180.0, 2.0: 202.5, 0.7: 225.0, 0.8: 247.5,
                    0.1: 270.0, 0.3: 292.5, 0.2: 315.0, 0.6: 337.5}
    CM_IN_A_KM = 100000.0
    SECS_IN_AN_HOUR = 3600
    def __init__(self,channel=0, anem_pin=5, anem_radius=9.0, anem_adjustment=1.18):
        # pass channel of MCP3008 where wind vane is connected to
        self.adc = MCP3008(channel)
        self.wind_count = 0 # Counts how many half-rotations
        self.last_wind_time = time.time()
        self.wind_speed_sensor = Button(anem_pin)
        self.wind_speed_sensor.when_pressed = self.spin
        self.anemometer_radius_cm = anem_radius # Radius of your anemometer
        self.anemometer_adjustment = anem_adjustment

    # Every half-rotations, add 1 to count
    def spin(self):
        self.wind_count = self.wind_count + 1

    def reset_wind(self):
        self.wind_count = 0
        self.last_wind_time = time.time()

    def get_wind_speed(self):
        """ Function that returns wind speed in km/hr. """
        wind_speed = self.calculate_speed(time.time() - self.last_wind_time)
        self.reset_wind() # reset wind_count and last time reading
        return wind_speed

    def get_wind(self, length=5):
        """ Function that returns wind as a vector: speed, direction."""
        return self.get_wind_speed(), self.read_direction()

    def calculate_speed(self, time_sec):
        circumference_cm = (2 * math.pi) * self.anemometer_radius_cm
        rotations = self.wind_count / 2.0
        # Calculate distance travelled by a cup in km
        dist_km = (circumference_cm * rotations) / self.CM_IN_A_KM
        # Speed = distance / time
        km_per_sec = dist_km / time_sec
        km_per_hour = km_per_sec * self.SECS_IN_AN_HOUR
        # Calculate Speed
        final_speed = km_per_hour * self.anemometer_adjustment
        return final_speed

    def read_direction(self):
        wind = round(self.adc.value*3.3,1)
        if not wind in self.WIND_VANE_VOLTS: # keep only good measurements
            logdbg('Unknown Wind Vane value: %s' % str(wind))
            return None
        else:
            return self.WIND_VANE_VOLTS[wind]

    def get_average_direction(self, length=5):
        # Get the average wind direction in a length of time in seconds
        data = []
        # print("Measuring wind direction for %d seconds..." % length)
        start_time = time.time()
        while time.time() - start_time <= length:
            direction = self.read_direction()
            if direction is not None:
                data.append(direction)
        return get_average(data)


def get_average(angles):
    # Function that returns the average angle from a list of angles
    sin_sum = 0.0
    cos_sum = 0.0

    for angle in angles:
        r = math.radians(angle)
        sin_sum += math.sin(r)
        cos_sum += math.cos(r)
    flen = float(len(angles))
    s = sin_sum / flen
    c = cos_sum / flen
    arc = math.degrees(math.atan(s / c))
    average = 0.0

    if s > 0 and c > 0:
        average = arc
    elif c < 0:
        average = arc + 180
    elif s < 0 and c > 0:
        average = arc + 360

    return 0.0 if average == 360 else average

""" Section for testing purposes, so file can be run outside of weeWX.
    invoke this as follows from the weewx root dir:
    PYTHONPATH=bin python bin/weewx/drivers/byows_rpi.py"""
if __name__ == '__main__':
    station = ByowsRpiStation()
    packet = {'dateTime': int(time.time() + 0.5),
              'usUnits': weewx.METRIC}

    interval = 5

    data = station.get_data(interval) # defaults to 5 seconds
    packet.update(data)
    print(packet)

Reply via email to