I add the var log and attach /usr/share/weewx/user file ans yes the driver is in user file
var/log/syslog: Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Initializing weewx version >> 3.9.2 > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Using Python 2.7.16 >> (default, Apr 6 2019, 01:42:57) #012[GCC 8.2.0] > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Platform >> Linux-4.19.66-v7+-armv7l-with-debian-10.1 > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Locale is 'en_GB.UTF-8' > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Using configuration file >> /etc/weewx/weewx.conf > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Debug is 1 > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Initializing engine > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Loading station type >> BYOWS (user.byows_rpi) > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Import of driver failed: >> int() can't convert non-string with explicit base (<type >> 'exceptions.TypeError'>) > > Sep 20 15:11:59 raspberrypi weewx[1509]: engine: Unable to load driver: >> int() can't convert non-string with explicit base > > Sep 20 15:11:59 raspberrypi weewx[1509]: **** Exiting... > > > On Friday, 20 September 2019 14:15:14 UTC+1, Andrew Milner wrote: > > now you have deleted the original post with the log etc!!! > > can you confirm that byows_rpi.py is in the user directory - perhaps a > listing of the user directory would be beneficial to check permissions etc > of the file > > > > On Friday, 20 September 2019 15:28:22 UTC+3, Laurent Lasne wrote: >> >> >> >> 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/bd9c4935-a625-42bb-882b-71316fffdf6d%40googlegroups.com.
__init__.pyc
Description: application/python-code
#!/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)
# # Copyright (c) 2009-2015 Tom Keffer <[email protected]> # # See the file LICENSE.txt for your full rights. # """User extensions module This module is imported from the main executable, so anything put here will be executed before anything else happens. This makes it a good place to put user extensions. """ import locale # This will use the locale specified by the environment variable 'LANG' # Other options are possible. See: # http://docs.python.org/2/library/locale.html#locale.setlocale locale.setlocale(locale.LC_ALL, '')
byows_rpi.pyc
Description: application/python-code
extensions.pyc
Description: application/python-code
# # Copyright (c) 2009-2015 Tom Keffer <[email protected]> # # See the file LICENSE.txt for your full rights. # """ Package of user extensions to weewx. This package is for your use. Generally, extensions to weewx go here. Any modules you add to it will not be touched by the upgrade process. """
#!/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)
# Introduction byows_rpi - This is an weeWX driver implementation of the Build Your Own Weather Station guide produced by the [Raspberry Pi Organization](https://projects.raspberrypi.org/en/projects/build-your-own-weather-station/) Copyright 2019 Jardi A. Martinez Jordan Distributed under terms of the GPLv3 # Installation Download the byows_rpi.py file and copy it to your weeWX user directory. In Debian it is: /usr/share/weewx/user ``` wget https://github.com/jardiamj/BYOWS_RPi/blob/master/byows_rpi.py -O /usr/share/weewx/user/byows_rpi.py ``` You could install the driver by using git to clone the project into the weewx user folder: git clone https://github.com/jardiamj/BYOWS_RPI.git . That will also copy a directory named "files", those files are not necessary for the driver to work, they are there for my own documenting purposes. ## Configuration To enable the byows_rpi driver modify the /etc/weewx/weewx.conf file and change the "station_type" variable to "BYOWS" in the "[Station]" section. Below is a snippet of the configured station section. ```plaintext [Station] ... # 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 ``` Then add an new section called "[BYOWS]" preferably below the "[Station]" section. ```plaintext [BYOWS] # This section is for the Raspberry Pi Bring Your Own Weather Station driver. # [REQUIRED] # The driver to use. driver = user.byows_rpi ``` If you are using different hardware or connecting them to a different pin or port, you are able to add additional variables in the "[BYOWS]" section and thereby overwriting the default values in the byows_rpi driver. Please see ```plaintext [BYOWS] # This section is for the Raspberry Pi Bring Your Own Weather Station driver. # [REQUIRED] # The driver to use. driver = user.byows_rpi # [OPTIONAL] # How often should the driver generate packets in seconds loop_interval = 2.5 # [OPTIONAL] # Pin to which anemometer is connected, the DEFAULT is pin 5. anemometer_pin = 5 # [OPTIONAL] # Pin to which rain bucket is connected, the DEFAULT is pin 6. rain_bucket_pin = 6 # [OPTIONAL] # Port and address for sensor bme280, the DEFAULT are port=1 address=0x77 bme280_port = 1 bme280_address = 0x77 # [OPTIONAL] # Channel to which wind vane is connected to on MCP3008, The DEFAULT is channel 0 mcp3008_channel = 0 # [OPTIONAL] # Anemometer adjustment value, the DEFAULT is 1.18 anemometer_adjustment = 1.18 # [OPTIONAL] # Bucket Size in mm, the DEFAULT is 0.2794 mm. bucket_size = 0.2794 # [OPTIONAL] # Anemometer radious in cm, the DEFAULT is 9.0 cm. anemometer_radius_cm = 9.0 ```
LICENSE
Description: Binary data
Driver_Options_Section
Description: Binary data
import bme280
import smbus2
from time import sleep
port = 1
address = 0x76
bus = smbus2.SMBus(port)
bme280.load_calibration_params(bus,address)
def read_all():
bme280_data = bme280.sample(bus,address)
return bme280_data.humidity, bme280_data.pressure, bme280_data.temperature
import math
from gpiozero import MCP3008
import time
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}
class WindVane(object):
""" Object that represents a Wind Vane sensor. """
def __init__(self,channel=0):
# pass channel of MCP3008 where wind vane is connected to
self.count = 0
self.adc = MCP3008(channel)
def get_value(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:
wind =round(self.adc.value*3.3,1)
if not wind in WIND_VANE_VOLTS: # keep only good measurements
print('unknown value ' + str(wind))
else:
data.append(WIND_VANE_VOLTS[wind])
return self.get_average(data)
def get_average(self, angles):
# Function that returns the average angle from a list of values
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
while True:
wind_vane = WindVane(0)
wind_direction = wind_vane.get_value(2)
from gpiozero import Button
import time
import math
import bme280_sensor_2
import wind_direction_byo_5
import statistics
import ds18b20_therm
import datetime
import database
wind_interval = 1 # How often (secs) to sample speed
interval = 5 # measurements recorded every 5 seconds
CM_IN_A_KM = 100000.0
SECS_IN_AN_HOUR = 3600
ADJUSTMENT = 1.18
BUCKET_SIZE = 0.2794
class BYO_RPi_Station(object):
""" Object that represents a BYO_Station. """
def __init__(self):
""" Initialized Onject. """
self.wind_count = 0 # Counts how many half-rotations
self.radius_cm = 9.0 # Radius of your anemometer
self.rain_count = 0
self.gust = 0
self.wind_speed_sensor = Button(5)
self.wind_speed_sensor.when_pressed = self.spin
self.rain_sensor = Button(6)
self.rain_sensor.when_pressed = self.bucket_tipped
# Every half-rotations, add 1 to count
def spin(self):
self.wind_count = self.wind_count + 1
#print("spin" + str(wind_count))
def calculate_speed(self, time_sec):
circumference_cm = (2 * math.pi) * self.radius_cm
rotations = self.wind_count / 2.0
# Calculate distance travelled by a cup in km
dist_km = (circumference_cm * rotations) / CM_IN_A_KM
# Speed = distance / time
km_per_sec = dist_km / time_sec
km_per_hour = km_per_sec * SECS_IN_AN_HOUR
# Calculate Speed
final_speed = km_per_hour * ADJUSTMENT
return final_speed
def get_rainfall(self):
rainfall = self.rain_count * BUCKET_SIZE
self.reset_rainfall()
return rainfall
def bucket_tipped(self):
self.rain_count = self.rain_count + 1
#print (rain_count * BUCKET_SIZE)
def reset_rainfall(self):
self.rain_count = 0
def reset_wind(self):
self.wind_count = 0
def reset_gust(self):
self.gust = 0
station = BYO_RPi_Station() #This is how we'll pass our station object into the weeWX driver
temp_probe = ds18b20_therm.DS18B20()
db = database.weather_database()
store_speeds = []
store_directions = []
while True:
start_time = time.time()
while time.time() - start_time <= interval:
wind_start_time = time.time()
station.reset_wind()
while time.time() - wind_start_time <= wind_interval:
store_directions.append(wind_direction_byo_5.get_value())
final_speed = station.calculate_speed(wind_interval)# Add this speed to the list
store_speeds.append(final_speed)
wind_average = wind_direction_byo_5.get_average(store_directions)
wind_gust = max(store_speeds)
wind_speed = statistics.mean(store_speeds)
rainfall = station.get_rainfall()
store_speeds = []
store_directions = []
ground_temp = temp_probe.read_temp()
# ground_temp =45
humidity, pressure, ambient_temp = bme280_sensor_2.read_all()
# db.insert(ambient_temp, ground_temp, 0, pressure, humidity, wind_average, wind_speed, wind_gust, rainfall)
db.insert(ambient_temp, ground_temp, 0, pressure, humidity, wind_average, wind_speed, wind_gust, rainfall, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print()
print('Wind direction: ' + str(wind_average) +' /', 'Wind speed: ' + str(wind_speed) +' /', 'Wind gust: ' + str(wind_gust) +' /', 'Rainfall: ' + str(rainfall) +' /', 'Humidity: ' + str(humidity) +' /', 'Pressure: ' + str(pressure) +' /', 'Ambient Temperature: ' + str(ambient_temp) +' /', 'Ground Temperature: ' +str(ground_temp) +';')
print()
# WEEWX CONFIGURATION FILE # # Copyright (c) 2009-2015 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 = 0 # Root directory of the weewx data file hierarchy for this station WEEWX_ROOT = /home/weewx # 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.8.2 ############################################################################## # This section is for information about the station. [Station] # Description of the station location location = "Le Rotoir, Essonne FRANCE" # Latitude and longitude in decimal degrees latitude = 48.4667 longitude = 2.0833 # Altitude of the station, with unit it is in. This is downloaded from # from the station if the hardware supports it. altitude = 147, meter # Choose 'foot' or 'meter' for unit # 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 = Simulator station_type = BYOWS # If you have a website, you may specify an URL station_url = 192.168.0.150 # 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 ############################################################################## [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 = skins # Where the generated reports should go, relative to WEEWX_ROOT HTML_ROOT = /var/www/html/weewx #HTML_ROOT = public_html # The database binding indicates which data should be used in reports. data_binding = wx_binding # Each of the following subsections defines a report that will be run. [[StandardReport]] # 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. # The StandardReport uses the 'Standard' skin, which contains the # images, templates and plots for the report. skin = Standard [[[Units]]] [[[[Groups]]]] group_altitude = meter group_speed2 = km_per_hour group_pressure = mbar group_rain = cm group_rainrate = cm_per_hour group_temperature = degree_C group_degree_day = degree_C_day group_speed = km_per_hour [[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, uncomment and fill out the next four lines. # Use quotes around passwords to guard against parsing errors. #user = replace with the ftp username #password = replace with the ftp password #server = replace with the ftp server name, e.g, www.threefools.org #path = replace with the ftp 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 = public_html # 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 as to the user account on the remote machine where the files # will be copied. # # The server, user, and path determine where files will be sent. # The server is the server name, such as www.threefools.org # The user is the username, such as weewx # The path is the destination directory, such as /var/www/html/weather # Be sure that the user has write permissions on the destination! #server = replace_me #user = replace_me #path = replace_me # 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 ############################################################################## # 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 outTemp = -40, 120, degree_F inTemp = 10, 120, degree_F outHumidity = 0, 100 inHumidity = 0, 100 windSpeed = 0, 120, mile_per_hour pressure = 24, 34.5, inHg ############################################################################## # This section controls the origin of derived values. [StdWXCalculate] ignore_zero_wind = False [[Calculations]] # Derived quantities are calculated by this service. 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_type = SQLite database_name = weewx.sdb # MySQL [[archive_mysql]] database_type = MySQL database_name = weewx ############################################################################## # 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 = %(WEEWX_ROOT)s/archive # 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 ################################################################################# [BYOWS] # This section is for the Raspberry Pi Bring Your Own Weather Station driver. # The driver to use driver = user.byows
#!/usr/bin/python3
import os, glob, time
# add the lines below to /etc/modules (reboot to take effect)
# w1-gpio
# w1-therm
class DS18B20(object):
def __init__(self):
self.device_file = glob.glob("/sys/bus/w1/devices/28*")[0] + "/w1_slave"
def read_temp_raw(self):
f = open(self.device_file, "r")
lines = f.readlines()
f.close()
return lines
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()
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
if __name__ == "__main__":
obj = DS18B20()
print("Temp: %s C" % obj.read_temp())
[BYOWS]
# Driver to be used by weeWX
driver = user.byows-pi
# How often should driver generate packets in seconds
loop_interval = 2.5
# List of sensors attached to the station, the available options are:
# rain, wind_vane, anemometer, ds18b20, bme280
# the settings for each sensor are under sections like: [[rain]]
# sensors not listed here will be ignored.
sensors = rain, wind_vane, anemometer, ds18b20, bme280
[[rain]]
pin = 6
bucket_size = 0.189
[[wind_vane]]
mcp3008_channel = 0
[[anemometer]]
pin = 5
# anemometer radius in cm
radius = 2.0
adjustment = 1.896
[[ds18b20]]
w1_id = 28-xxxxxxx
[[bme280]]
port = 1
i2c_address = 0x76
