#!/usr/bin/python
# Created by Pat O'Brien 2019 - https://obrienlabs.net
#
# This driver takes the sensors used in the Raspberry Pi
# build your own weather station project and converts it
# into a format that can be used with weewx.
#
# The Raspberry Pi project can be found here:
# https://projects.raspberrypi.org/en/projects/build-your-own-weather-station
#

import os # POB REMOVE
os.environ['GPIOZERO_PIN_FACTORY'] = os.environ.get('GPIOZERO_PIN_FACTORY', 'mock') # POB REMOVE
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 syslog






temp_probe = ds18b20_therm.DS18B20()

def logmsg(dst, msg):
    syslog.syslog(dst, 'BYOWS: %s' % msg)

def loginf(msg):
    logmsg(syslog.LOG_INFO, msg)

def logerror(msg):
    logmsg(syslog.LOG_ERROR, msg)

def logdebug(msg):
    logmsg(syslog.LOG_DEBUG, msg)

def loader(config_dict, engine):
    station = BYOWS(**config_dict['BYOWS'])
    return station


    """ Driver for the Raspberry Pi Bring Your Own Weather Station. """

    def __init__(self, **stn_dict) :
        """ Initialize object. """
        self.station_hardware = stn_dict.get('hardware')
        # TODO CONVERT TO WEEWX OPTIONS?
        self.interval = 60 # Measurements recorded every 1 minute
        self.wind_count = 0 # Counts how many half-rotations
        self.radius_cm = 9.0 # Radius of your anemometer
        self.wind_interval = 5 # How often (secs) to sample speed
        self.wind_gust = 0
        self.cm_in_a_km = 100000.0
        self.secs_in_an_hour = 3600
        self.adjustment = 1.18
        self.bucket_size = 0.2794 # mm
        self.rain_count = 0
        self.store_speeds = []
        self.store_directions = []
    self.wind_speed_sensor.when_pressed = self.spin() # is this a valid call for the below class function?
    self.rain_sensor = Button(6)
    self.rain_sensor.when_pressed = self.bucket_tipped() # is this a valid call for the below class function?

    def hardware_name(self):
        return self.station_hardware

    # Every half-rotations, add 1 to count
    def spin(self):
        self.wind_count = self.wind_count + 1
        #print("spin" + str(self.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) / 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.adjustment

        return final_speed

    def bucket_tipped(self):
        self.rain_count = self.rain_count + 1
        #print (self.rain_count * self.bucket_size)

    def reset_rainfall(self):
        self.rain_count = 0

    def reset_wind(self):
        self.wind_count = 0

    def reset_gust(self):
        self.wind_gust = 0


    #===============================================================================
    #                         LOOP record decoding functions
    #===============================================================================

    def genLoopPackets(self):
        """ Generator function that continuously returns loop packets """
        for _packet in self.genPackets():
            yield _packet

    def genPackets(self):
        """ Generate measurement packets. """
        global temp_probe
        while True:
            start_time = time.time()
            while time.time() - start_time <= self.interval:
                wind_start_time = time.time()
                self.reset_wind()
                while time.time() - wind_start_time <= self.wind_interval:
                    self.store_directions.append( wind_direction_byo_5.get_value() )
                    final_speed = self.calculate_speed( self.wind_interval ) # Add this speed to the list
                    self.store_speeds.append( final_speed )
            wind_average = wind_direction_byo_5.get_average( self.store_directions )
            self.wind_gust = max( self.store_speeds )
            wind_speed = statistics.mean( self.store_speeds )
            rainfall = self.rain_count * self.bucket_size # mm. if units are US, do we need to convert to inch?
            self.reset_rainfall()
            self.store_speeds = []
            self.store_directions = []
            ground_temp = temp_probe.read_temp()
            humidity, pressure, ambient_temp = bme280_sensor_2.read_all()

            # Build the weewx loop packet
            packet = { 'dateTime': int( time.time() ), 'usUnits': weewx.US }
            packet['outTemp'] = float( ambient_temp )
            packet['outHumidity'] = float( humidity )
            packet['soilTemp1'] = float( ground_temp )
            packet['pressure'] = float( pressure )
            packet['rain'] = rainfall
            packet['windDir'] = float( wind_average )
            packet['windSpeed'] = float( wind_speed )
            packet['windGust'] = float( self.wind_gust )

            # Send to the loop
            yield packet

            # Delay reading sensors for the interval time?
            #time.sleep( self.interval )
