예제 #1
0
 def _extract_common_weather_data(self, datapoint: Any, temperatures: dict) -> dict:
     """Extracts common (unchanging from hourly/daily methods) weather data
     from a given data point"""
     wind = datapoint.wind('meters_sec').get('speed')
     hum = datapoint.humidity
     # Apply 'feels like' temperature
     feels = {f'feels-{k.lower()}': round(feels_like(Temp(v, 'c'), hum, wind).c, 2)
              for k, v in temperatures.items() if 'feels' not in k}
     dew_pt = datapoint.dewpoint if datapoint.dewpoint is not None \
         else dew_point(temperatures['temp-avg'], hum).c
     pt_dict = {
         'date': pd.to_datetime(datapoint.reference_time('iso')).tz_convert(self.tz).strftime('%F %T'),
         'summary': datapoint.detailed_status,
         'precip-intensity': datapoint.rain.get('3h', 0),
         'dewpoint': round(dew_pt, 2),
         'humidity': hum / 100,
         'pressure': datapoint.pressure.get('press'),
         'wind-speed': wind,
         'wind-bearing': datapoint.wind('meters_sec').get('deg'),
         'cloud-cover': datapoint.clouds / 100,
         'visibility': datapoint.visibility_distance
     }
     pt_dict.update(temperatures)
     pt_dict.update(feels)
     return pt_dict
예제 #2
0
def process_data_payload(data: dict) -> dict:
    """Process incoming data from an Ecowitt device."""
    for ignore_key in ("dateutc", "freq", "model", "stationtype"):
        data.pop(ignore_key, None)

    humidity = int(data[DATA_POINT_HUMIDITY])
    temperature = meteocalc.Temp(data[DATA_POINT_TEMPF], "f")
    wind_speed = float(data[DATA_POINT_WINDSPEEDMPH])

    dew_point = meteocalc.dew_point(temperature, humidity)
    data[DATA_POINT_DEWPOINT] = dew_point.f

    heat_index = meteocalc.heat_index(temperature, humidity)
    data[DATA_POINT_HEATINDEX] = heat_index.f

    try:
        wind_chill = meteocalc.wind_chill(temperature, wind_speed)
    except ValueError as err:
        LOGGER.debug(
            "%s (temperature: %s, wind speed: %s)",
            err,
            temperature.f,
            wind_speed,
        )
    else:
        data[DATA_POINT_WINDCHILL] = wind_chill.f

    feels_like = meteocalc.feels_like(temperature, humidity, wind_speed)
    data[DATA_POINT_FEELSLIKEF] = feels_like.f

    return data
예제 #3
0
파일: air.py 프로젝트: ben700/droneponics
    def payload(self, __payload):
        try:
            __payload["deviceTime"] = int(time.time())
            if (self.bme680 is not None):
                __payload["sensorType"] = "bme680"
                __payload["voc"] = "{0:.0f}".format(self.bme680.gas)
                __payload["temperature"] = "{0:.1f}".format(
                    self.bme680.temperature)
                __payload["humidity"] = "{0:.0f}".format(self.bme680.humidity)
                __payload["pressure"] = "{0:.0f}".format(self.bme680.pressure)
                __payload["altitude"] = "{0:.0f}".format(self.bme680.altitude)
                t = Temp(self.bme680.temperature, 'c')
                dewPoint = dew_point(temperature=t,
                                     humidity=self.bme680.humidity)
                __payload["dewPoint"] = "{0:.1f}".format(float(dewPoint))
            elif (self.bme280 is not None):
                print("payload for BME280")
                __payload["sensorType"] = "bme280"
                __payload["temperature"] = "{0:.1f}".format(
                    self.bme280.temperature)
                __payload["humidity"] = "{0:.0f}".format(self.bme280.humidity)
                __payload["pressure"] = "{0:.0f}".format(self.bme280.pressure)
                __payload["altitude"] = "{0:.0f}".format(self.bme280.altitude)
                t = Temp(self.bme280.temperature, 'c')
                dewPoint = dew_point(temperature=t,
                                     humidity=self.bme280.humidity)
                __payload["dewPoint"] = "{0:.1f}".format(float(dewPoint))
        except:
            pass

        try:
            if (self.tsl is not None):
                __payload["lux"] = "{0:.0f}".format(self.tsl.lux)
                __payload["infrared"] = "{0:d}".format(self.tsl.infrared)
                __payload["visible"] = "{0:d}".format(self.tsl.visible)
                __payload["full_spectrum"] = "{0:d}".format(
                    self.tsl.full_spectrum)
        except:
            pass

        try:
            drone.noSUDO()
            mhz19b = mh_z19.read()
            if mhz19b is not None:
                __payload["CO2"] = '{0:d}'.format(mhz19b['co2'])
        except:
            pass
예제 #4
0
 def do_GET(s):
     global muestras
     global separador
     datosValidos = 0
     """Respond to a GET request."""
     #Muestra valores por consola
     while (datosValidos == 0):
         result = instance.read()
         datosValidos = result.is_valid()
     print("Ultima peticion: " + str(datetime.datetime.now()))
     print("Temperatura: %.2f C" % result.temperature)
     print("Humedad: %.2f %%" % result.humidity)
     timestamp = time.strftime("%d/%m/%y %H:%M:%S")
     #Content-type html
     s.send_response(200)
     s.send_header("Content-type", "text/plain")
     s.end_headers()
     ffile1 = open(fichero, "r")
     lineas = len(ffile1.readlines())
     #Muestra actual
     temperatura = result.temperature
     humedad = result.humidity
     t = Temp(temperatura, 'c')
     pdr = dew_point(temperature=t, humidity=humedad)
     #Si las muestras capturadas no llegan al numero de muestras configuradas
     #Eniva todas
     if lineas < int(muestras):
         ffile1.seek(0)
         for linea in ffile1:
             s.wfile.write(linea)
         muestra = lineas - 1
         linea = (str(muestra) + separador + timestamp + separador +
                  str(temperatura) + separador + str(humedad) + separador +
                  str(round(pdr, 2)) + separador + numeroMaquina + "\n")
         s.wfile.write(linea)
         ffile1.close()
     #Descarta el envio de las muestras anteriores
     else:
         inicioLin = lineas - int(muestras)
         finLineas = lineas - 1
         s.wfile.write("muestra" + separador + "timestamp" + separador +
                       "temperatura" + separador + "humedad" + separador +
                       "pdr" + separador + "maquina\n")
         with open(fichero) as data:
             texto = itertools.islice(data, inicioLin, finLineas + 1)
             for linea in texto:
                 s.wfile.write(linea)
         muestra = lineas - 1
         linea = (str(muestra) + separador + timestamp + separador +
                  str(temperatura) + separador + str(humedad) + separador +
                  str(round(pdr, 2)) + separador + numeroMaquina + "\n")
         s.wfile.write(linea)
         ffile1.close()
예제 #5
0
def processTemperature(feed, aggregate):
    value = getSensorValue(feed, "Temperature")
    tempC = value['s']
    tempVal = Temp(tempC, 'c')

    lastTemp = temperature_config["last_temp_c"]
    # occassionally the temperature sensor flakes out and this is an attempt to filter that flake
    if lastTemp == None or abs(lastTemp - tempC) < 20:
        if "humidity" in aggregate:
            aggregate["dewptf"] = (dew_point(temperature=tempVal,
                                             humidity=aggregate["humidity"]) *
                                   1.8) + 32
        aggregate["tempf"] = (value['s'] * 1.8 + 32)
        print("--> Got temp [" + str(aggregate["tempf"]) + "F]")
        temperature_config["last_temp_c"] = tempC
예제 #6
0
def calculate_dew_point(
        temperature: float,
        humidity: float,
        *,
        input_unit_system: str = UNIT_SYSTEM_IMPERIAL,
        output_unit_system: str = UNIT_SYSTEM_IMPERIAL) -> float:
    """Calculate dew point in the appropriate unit system."""
    temp_obj = _get_temperature_object(temperature, input_unit_system)
    dew_point_obj = meteocalc.dew_point(temp_obj, humidity)

    if output_unit_system == UNIT_SYSTEM_IMPERIAL:
        value = round(dew_point_obj.f, 1)
    else:
        value = round(dew_point_obj.c, 1)
    return cast(float, value)
예제 #7
0
def insert_by_esp():
    '''method when calling with esp32'''
    db = get_db()
    print("JSON %s" % request.get_json())
    request_dict = request.get_json()
    values = [
        calendar.timegm(time.gmtime()), request_dict['temperature'],
        request_dict['pressure'], request_dict['humidity'],
        dew_point(Temp(request_dict['temperature'], 'c'),
                  request_dict['humidity']).c,
        heat_index(Temp(request_dict['temperature'], 'c'),
                   request_dict['humidity']).c
    ]

    db.execute(
        'insert into weather_history (timestamp, temperature, '
        'pressure, humidity, dew_point, heat_index) values '
        '(?,?,?,?,?,?)', values)

    if request_dict.get('cloud_coverage', False):
        cloudy = request_dict['cloud_coverage']
        cloudy = str(cloudy)[1:]
        db.execute(
            'insert into cloud_history (cloud_coverage,timestamp)'
            'values (?,?)', [cloudy, calendar.timegm(time.gmtime())])

    if request_dict.get('rain', False) is not False:
        rain = request_dict['rain']
        db.execute('insert into rain_history (rain,timestamp)'
                   'values (?,?)', [rain, calendar.timegm(time.gmtime())])

    if request_dict.get('wind', False):
        vector = request_dict['wind']
        vector = vector[1:]
        vector = vector.split(',')
        vector = [float(el) for el in vector]
        wind_speed = int(length(vector))
        wind_direction = int(inner_angle(vector, [0, 0]))

        db.execute(
            'insert into wind_history (wind_direction, wind_speed, '
            'timestamp) values (?,?,?)',
            [wind_direction, wind_speed,
             calendar.timegm(time.gmtime())])

    db.commit()
    return 'OK'
예제 #8
0
def setDHTEnvironmentData(sensorPin, sensorType,):
    humidity, temperature_c = Adafruit_DHT.read_retry(sensorType, sensorPin)
    if(temperature_c is not None and -20 <= temperature_c <= 100 and humidity is not None and 1 <= humidity <= 100):
        humidity = round(humidity,2)
        temperature_c = round(temperature_c,2)
        temp_c_meteocalc = Temp(temperature_c, 'c')
        sensorData = {
                "temp": temperature_c,
                "humidity": humidity,
                "dewPoint" : round(dew_point(temperature=temp_c_meteocalc, humidity=humidity).c, 2),
                "heatIndex" : round(heat_index(temperature=temp_c_meteocalc, humidity=humidity).c, 2),
                "sensorData": 1
                }
    else:
        sensorData = {
                "sensorData": 0
                }
    return sensorData
def weatherStationUploader(event):
    weatherStationUploader.log.setLevel(weatherStationUploader_configuration['logLevel'])
    global wu_second_count
    if (not weatherStationUploader_configuration['stationdata']['weather_upload']) \
    or (weatherStationUploader_configuration['stationdata']['weather_upload'] and wu_second_count%weatherStationUploader_configuration['stationdata']['upload_frequency_seconds'] == 0):
        if weatherStationUploader_configuration['stationdata']['weather_upload']:
            weatherStationUploader.log.debug('Uploading data to Weather Underground')
        else:
            weatherStationUploader.log.debug('No data to will be upladed to Weather Underground')

        sdf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
        dateutc = sdf.print(DateTime.now((DateTimeZone.UTC)))

        tempf = None
        temp = None
        sensorName = getTheSensor('tempc', getLowest=True)
        if sensorName is not None:
            temp = Temp(getItemValue(sensorName, 0.0), 'c') # Outdoor temp, c - celsius, f - fahrenheit, k - kelvin
            tempf = str(round(temp.f, 1))

        soiltempf = None
        sensorName = getTheSensor('soiltempc')
        if sensorName is not None:
            _temp = Temp(getItemValue(sensorName, 0.0), 'c') # Soil temp, c - celsius, f - fahrenheit, k - kelvin
            soiltempf = str(round(_temp.f, 1))

        humidity = None
        sensorName = getTheSensor('humidity')
        if sensorName is not None:
            humidity = getItemValue(sensorName, 0.0)

        dewptf = None
        heatidxf = None
        if humidity is not None and temp is not None:
            dewptf = str(round(dew_point(temperature=temp, humidity=humidity).f, 1)) # calculate Dew Point
            heatidxf = str(round(heat_index(temperature=temp, humidity=humidity).f, 1)) # calculate Heat Index

        pressure = None
        sensorName = getTheSensor('pressurembar')
        if sensorName is not None:
            _mbar = getItemValue(sensorName, 0)
            if ((_mbar < 1070) and (_mbar > 920)): 
                pressure = str(mbar_to_inches_mercury(_mbar))

        rainin = None
        sensorName = getTheSensor('rainhour', never_assume_dead=True)
        if sensorName is not None:
            rainin = str(mm_to_inch(getItemValue(sensorName, 0.0)))

        dailyrainin = None
        sensorName = getTheSensor('raintoday', never_assume_dead=True)
        if sensorName is not None:
            dailyrainin = str(mm_to_inch(getItemValue(sensorName, 0.0)))

        soilmoisture = None
        sensorName = getTheSensor('soilmoisture')
        if sensorName is not None:
            soilmoisture = str(int(round(getItemValue(sensorName, 0.0) * 100 / 1023)))

        winddir = None
        sensorName = getTheSensor('winddir')
        if sensorName is not None:
            winddir = str(getItemValue(sensorName, 0))

        windspeedmph = None
        sensorName = getTheSensor('windspeedms')
        if sensorName is not None:
            windspeedmph = str(ms_to_mph(getItemValue(sensorName, 0.0)))

        windgustmph = None
        sensorName = getTheSensor('windgustms')
        if sensorName is not None:
            windgustmph = str(ms_to_mph(getItemValue(sensorName, 0.0)))

        windgustdir = None
        sensorName = getTheSensor('windgustdir')
        if sensorName is not None:
            windgustdir = str(getItemValue(sensorName, 0))

        windspdmph_avg2m = None
        sensorName = getTheSensor('windspeedms_avg2m')
        if sensorName is not None:
            windspdmph_avg2m = str(ms_to_mph(getItemValue(sensorName, 0.0)))

        winddir_avg2m = None
        sensorName = getTheSensor('winddir_avg2m')
        if sensorName is not None:
            winddir_avg2m = str(getItemValue(sensorName, 0))

        windgustmph_10m = None
        sensorName = getTheSensor('windgustms_10m')
        if sensorName is not None:
            windgustmph_10m = str(ms_to_mph(getItemValue(sensorName, 0.0)))

        windgustdir_10m = None
        sensorName = getTheSensor('windgustdir_10m')
        if sensorName is not None:
            windgustdir_10m = str(getItemValue(sensorName, 0))

        solarradiation = None
        sensorName = getTheSensor('solarradiation', getHighest=True)
        if sensorName is not None:
            solarradiation = str(lux_to_watts_m2(getItemValue(sensorName, 0)))

        # From http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol

        cmd = 'curl -s -G "' + WU_URL + '" ' \
            + '--data-urlencode "action=updateraw" ' \
            + ('--data-urlencode "realtime=1" ' if weatherStationUploader_configuration['stationdata']['rapid_fire_mode'] else '') \
            + ('--data-urlencode "rtfreq='+str(weatherStationUploader_configuration['stationdata']['upload_frequency_seconds'])+'" ' if weatherStationUploader_configuration['stationdata']['rapid_fire_mode'] else '') \
            + '--data-urlencode "ID='+weatherStationUploader_configuration['stationdata']['station_id']+'" ' \
            + '--data-urlencode "PASSWORD='******'stationdata']['station_key']+'" ' \
            + '--data-urlencode "dateutc='+dateutc+'" ' \
            + '--data-urlencode "softwaretype=openHAB" '
        weatherStationUploader.log.debug("")

        if weatherStationUploader_configuration['stationdata']['weather_upload']:
            weatherStationUploader.log.debug("Below is the weather data that we will send:")
        else:
            weatherStationUploader.log.debug("Below is the weather data that we would send (if weather_upload was enabled):")

        if tempf is not None:
            cmd += '--data-urlencode "tempf='+tempf+'" '
            weatherStationUploader.log.debug("tempf: "+tempf)
        if humidity is not None:
            cmd += '--data-urlencode "humidity='+str(humidity)+'" '
            weatherStationUploader.log.debug("humidity: "+str(humidity))
        if dewptf is not None:
            cmd += '--data-urlencode "dewptf='+dewptf+'" '
            weatherStationUploader.log.debug("dewptf: "+dewptf)
        if heatidxf is not None:
            cmd += '--data-urlencode "heatidxf='+heatidxf+'" '
            weatherStationUploader.log.debug("heatidxf: "+heatidxf)
        if soiltempf is not None:
            cmd += '--data-urlencode "soiltempf='+soiltempf+'" '
            weatherStationUploader.log.debug("soiltempf: "+soiltempf)
        if soilmoisture is not None:
            cmd += '--data-urlencode "soilmoisture='+soilmoisture+'" '
            weatherStationUploader.log.debug("soilmoisture: "+soilmoisture)
        if pressure is not None:
            cmd += '--data-urlencode "baromin='+pressure+'" '
            weatherStationUploader.log.debug("baromin: "+pressure)
        if rainin is not None:
            cmd += '--data-urlencode "rainin='+rainin+'" '
            weatherStationUploader.log.debug("rainin: "+rainin)
        if dailyrainin is not None:
            cmd += '--data-urlencode "dailyrainin='+dailyrainin+'" '
            weatherStationUploader.log.debug("dailyrainin: "+dailyrainin)
        if winddir is not None:
            cmd += '--data-urlencode "winddir='+winddir+'" '
            weatherStationUploader.log.debug("winddir: "+winddir)
        if windspeedmph is not None:
            cmd += '--data-urlencode "windspeedmph='+windspeedmph+'" '
            weatherStationUploader.log.debug("windspeedmph: "+windspeedmph)
        if windgustmph is not None:
            cmd += '--data-urlencode "windgustmph='+windgustmph+'" '
            weatherStationUploader.log.debug("windgustmph: "+windgustmph)
        if windgustdir is not None:
            cmd += '--data-urlencode "windgustdir='+windgustdir+'" '
            weatherStationUploader.log.debug("windgustdir: "+windgustdir)
        if windspdmph_avg2m is not None:
            cmd += '--data-urlencode "windspdmph_avg2m='+windspdmph_avg2m+'" '
            weatherStationUploader.log.debug("windspdmph_avg2m: "+windspdmph_avg2m)
        if winddir_avg2m is not None:
            cmd += '--data-urlencode "winddir_avg2m='+winddir_avg2m+'" '
            weatherStationUploader.log.debug("winddir_avg2m: "+winddir_avg2m)
        if windgustmph_10m is not None:
            cmd += '--data-urlencode "windgustmph_10m='+windgustmph_10m+'" '
            weatherStationUploader.log.debug("windgustmph_10m: "+windgustmph_10m)
        if windgustdir_10m is not None:
            cmd += '--data-urlencode "windgustdir_10m='+windgustdir_10m+'" '
            weatherStationUploader.log.debug("windgustdir_10m: "+windgustdir_10m)
        if solarradiation is not None:
            cmd += '--data-urlencode "solarradiation='+solarradiation+'" '
            weatherStationUploader.log.debug("solarradiation: "+solarradiation)
        cmd += ' 1>/dev/null 2>&1 &'
        weatherStationUploader.log.debug("")

        if weatherStationUploader_configuration['stationdata']['weather_upload']:
            weatherStationUploader.log.debug("WeatherUpload version {}, performing an upload. (second count is: {})".format(__version__, wu_second_count))
            weatherStationUploader.log.debug("cmd: {}".format(cmd))
            os.system(cmd)
    else:
        weatherStationUploader.log.debug("WeatherUpload version {}, skipping upload. (second count is: {})".format(__version__, wu_second_count))

    if (wu_second_count%weatherStationUploader_configuration['stationdata']['upload_frequency_seconds'] == 0):
        wu_second_count = 0
    wu_second_count = wu_second_count + 10 # Corresponding to CronTrigger(EVERY_10_SECONDS)
예제 #10
0
 def cal_dp(self):
     return dew_point(temperature=self.tempc, humidity=self.rh).f
예제 #11
0
#AM2303
import Adafruit_DHT
sensor = Adafruit_DHT.AM2302
pin = 17
humidityDHT, tempDHT = Adafruit_DHT.read_retry(sensor, pin)

#Calcs
import time
from datetime import datetime
from time import strftime, localtime
from meteocalc import dew_point, heat_index
tBMP = tempBMP * 9 / 5 + 32
tDHT = tempDHT * 9 / 5 + 32
hDHT = humidityDHT
dpBMPc = dew_point(temperature=tempBMP, humidity=hDHT)
hiBMPc = heat_index(temperature=tempBMP, humidity=hDHT)
dpDHTc = dew_point(temperature=tempDHT, humidity=hDHT)
hiDHTc = heat_index(temperature=tempDHT, humidity=hDHT)
dpBMP = dpBMPc * 9 / 5 + 32
dpDHT = dpDHTc * 9 / 5 + 32
hiBMP = hiBMPc * 9 / 5 + 32
hiDHT = hiDHTc * 9 / 5 + 32

pBMP = pressureBMP * 0.00029529980164712
hpBMP = pressureBMP / 100

calti = (44330.0 * (1.0 - pow(pressureBMP / (sealevel * 100), 1.0 / 5.255)))
caltitude = calti * 3.28084
maltitude = altitudeBMP * 3.28084
예제 #12
0
from meteocalc import Temp, dew_point, heat_index

# create input temperature in different units
t = Temp(20, 'c')  # c - celsius, f - fahrenheit, k - kelvin
t2 = Temp(60, 'f')

# calculate Dew Point
dp = dew_point(temperature=t, humidity=56)

# calculate Heat Index
hi = heat_index(temperature=t2, humidity=42)

print('Dew Point in celsius:', dp.c)
print('Dew Point in fahrenheit:', dp.f)
print('Heat Index in kelvin:', hi.k)
예제 #13
0
pascals = sensor.read_pressure()

#AM2303
import Adafruit_DHT
sensor = Adafruit_DHT.AM2302
pin = 17
humidity, temp = Adafruit_DHT.read_retry(sensor, pin)

#Calcs
from datetime import datetime
from meteocalc import dew_point, heat_index
now = datetime.now()
temp = degrees*9/5+32 
hectopascals = pascals / 100
baro = 0.02952998751*hectopascals
dewpoint = dew_point(temperature=degrees, humidity=humidity)
heatindex = heat_index(temperature=degrees, humidity=humidity)

#format to print
import csv,sys
td = '%s/%s/%s' % (now.month, now.day, now.year)
th = '%s:%s' % (now.hour, now.minute)
t = format(temp, '0.2f')
b = format(baro, '0.2f')
h = format(humidity, '0.2f')
d = format(dewpoint.f, '0.2f')
hi = format(heatindex.f, '0.2f')
stamp = td, th 

#print 'Temp,',format(temp, '0.2f')
#print 'Baro,',format(baro, '0.2f')
예제 #14
0
import shlex
import json
import urllib
import urllib.parse
import urllib.request
from meteocalc import Temp, dew_point

RTL_COMMAND = shlex.split("rtl_433 -R 69 -F json -U -q")
RTL_PROCESS = subprocess.Popen(RTL_COMMAND, stdout=subprocess.PIPE)
while True:
    try:
        RTL_PROCESS_OUTPUT = RTL_PROCESS.stdout.readline().decode('utf-8')

        OUTPUT_AS_JSON = json.loads(RTL_PROCESS_OUTPUT)
        REPORTED_TEMP = Temp(OUTPUT_AS_JSON['temperature_C'], 'c')
        CALCULATED_DEW_POINT = dew_point(temperature=REPORTED_TEMP, humidity=OUTPUT_AS_JSON['humidity'])
        REQUEST_OBJECT = {
            "action": "updateraw",
            "ID": sys.argv[1],
            "PASSWORD": sys.argv[2],
            "dateutc": OUTPUT_AS_JSON['time'],
            "windspeedmph": OUTPUT_AS_JSON['speed'] / 1.609344,
            "windgustmph": OUTPUT_AS_JSON['gust'] / 1.609344,
            "humidity": OUTPUT_AS_JSON['humidity'],
            "tempf": REPORTED_TEMP.f,
            "dewptf": CALCULATED_DEW_POINT.f
        }

        REQUEST_ENCODED = urllib.parse.urlencode(REQUEST_OBJECT)
        REQUEST_URL = \
            "https://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?%s" \
예제 #15
0
#AM2303
import Adafruit_DHT
sensor = Adafruit_DHT.AM2302
pin = 17
humidity, temp = Adafruit_DHT.read_retry(sensor, pin)

#Calcs
import time
from datetime import datetime
from time import strftime, localtime
from meteocalc import dew_point, heat_index
tempf = temp*9/5+32
#temp = degrees*9/5+32
#hectopascals = pascals / 100
#baro = 0.02952998751*hectopascals
dewpoint = dew_point(temperature=tempf, humidity=humidity)
#dewpoint = dew_point(temperature=degrees, humidity=humidity)
heatindex = heat_index(temperature=tempf, humidity=humidity)
#heatindex = heat_index(temperature=degrees, humidity=humidity)

#format to print
import os
import csv,sys
t = format(temp, '0.2f')
#b = format(baro, '0.2f')
h = format(humidity, '0.2f')
d = format(dewpoint.f, '0.2f')
hi = format(heatindex.f, '0.2f')

#time
start_time = time.time()
예제 #16
0
 def dew_point(self):
     return dew_point(temperature=self.temp, humidity=self.humidity).c
    def execute(self, modules, inputs):

        SCRIPT_VERSION = '2.3.1'
        WU_URL = "http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php"

        def ms_to_mph(input_speed):
            # convert input_speed from meter per second to miles per hour
            return round(input_speed / 0.44704, 2)

        def mm_to_inch(mm):
            # convert mm to inches
            return round(mm / 25.4, 2)

        def mbar_to_inches_mercury(input_pressure):
            # convert mbar to inches mercury
            return round(input_pressure * 0.02953, 2)

        def lux_to_watts_m2(lux):
            # Convert lux [lx] to watt/m² (at 555 nm)
            # Should typically be around 800-900 watt/m² at mid summer full sun diation at 13.00 h
            # return int(round(float(lux) * 0.01464128843))
            return int(round(float(lux) * 0.015454545))

        def getTheSensor(lbl,
                         never_assume_dead=False,
                         getHighest=False,
                         getLowest=False):
            # Each sensor entry in the configuration file can be a a single item name or a python list where you can
            # define multiple sensor names. The first sensor in that list that has reported within the value set in
            # sensor_dead_after_mins will be used. (Unless never_assume_dead is set to True)
            # When "getHighest" argument is set to True, the sensor name with the highest value is picked.
            # When "getlowest" argument is set to True, the sensor name with the lowest value is picked.

            def isSensorAlive(sName):
                if getLastUpdate(PersistenceExtensions,
                                 ir.getItem(sName)).isAfter(
                                     DateTime.now().minusMinutes(
                                         sensor_dead_after_mins)):
                    return True
                else:
                    self.log.warning('Sensor device ' + unicode(sName) +
                                     ' has not reported since: ' + str(
                                         getLastUpdate(PersistenceExtensions,
                                                       ir.getItem(sName))))
                    return False

            sensorName = None
            if lbl in self.config.wunderground[
                    'sensors'] and self.config.wunderground['sensors'][
                        lbl] is not None:
                tSens = self.config.wunderground['sensors'][lbl]
                if isinstance(tSens, list):
                    _highestValue = 0
                    _lowestValue = 999999999
                    for s in tSens:
                        if s is None:
                            break
                        # Get the first sensor that is not dead and find the sensor with the highest or the lowest value if requested
                        if never_assume_dead or isSensorAlive(s):
                            if getHighest:
                                _itemValue = getItemValue(s, 0)
                                if _itemValue > _highestValue:
                                    _highestValue = _itemValue
                                    sensorName = s
                            elif getLowest:
                                _itemValue = getItemValue(s, 0)
                                if _itemValue < _lowestValue:
                                    _lowestValue = _itemValue
                                    sensorName = s
                            else:
                                sensorName = s
                                break
                else:
                    if never_assume_dead or isSensorAlive(tSens):
                        sensorName = tSens

            if sensorName is not None:
                self.log.debug("Device used for " + unicode(lbl) + ": " +
                               sensorName)
            return sensorName

        self.log.setLevel(self.config.wunderground['logLevel'])

        global wu_loop_count
        sensor_dead_after_mins = self.config.wunderground[
            'sensor_dead_after_mins']  # The time after which a sensor is presumed to be dead
        if (not self.config.wunderground['stationdata']['weather_upload']) \
        or (self.config.wunderground['stationdata']['weather_upload'] and wu_loop_count%self.config.wunderground['stationdata']['upload_frequency'] == 0):
            if self.config.wunderground['stationdata']['weather_upload']:
                self.log.debug('Uploading data to Weather Underground')
            else:
                self.log.debug(
                    'No data to will be upladed to Weather Underground')

            sdf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
            dateutc = sdf.print(DateTime.now((DateTimeZone.UTC)))

            tempf = None
            temp = None
            sensorName = getTheSensor('tempc', getLowest=True)
            if sensorName is not None:
                temp = Temp(
                    getItemValue(sensorName, 0.0), 'c'
                )  # Outdoor temp, c - celsius, f - fahrenheit, k - kelvin
                tempf = str(round(temp.f, 1))

            soiltempf = None
            sensorName = getTheSensor('soiltempc')
            if sensorName is not None:
                _temp = Temp(
                    getItemValue(sensorName, 0.0),
                    'c')  # Soil temp, c - celsius, f - fahrenheit, k - kelvin
                soiltempf = str(round(_temp.f, 1))

            humidity = None
            sensorName = getTheSensor('humidity')
            if sensorName is not None:
                humidity = getItemValue(sensorName, 0.0)

            dewptf = None
            heatidxf = None
            if humidity is not None and temp is not None:
                dewptf = str(
                    round(dew_point(temperature=temp, humidity=humidity).f,
                          1))  # calculate Dew Point
                heatidxf = str(
                    round(
                        heat_index(temperature=temp, humidity=humidity).f,
                        1))  # calculate Heat Index

            pressure = None
            sensorName = getTheSensor('pressurembar')
            if sensorName is not None:
                _mbar = getItemValue(sensorName, 0)
                if ((_mbar < 1070) and (_mbar > 920)):
                    pressure = str(mbar_to_inches_mercury(_mbar))

            rainin = None
            sensorName = getTheSensor('rainhour', never_assume_dead=True)
            if sensorName is not None:
                rainin = str(mm_to_inch(getItemValue(sensorName, 0.0)))

            dailyrainin = None
            sensorName = getTheSensor('raintoday', never_assume_dead=True)
            if sensorName is not None:
                dailyrainin = str(mm_to_inch(getItemValue(sensorName, 0.0)))

            soilmoisture = None
            sensorName = getTheSensor('soilmoisture')
            if sensorName is not None:
                soilmoisture = str(
                    int(round(getItemValue(sensorName, 0.0) * 100 / 1023)))

            winddir = None
            sensorName = getTheSensor('winddir')
            if sensorName is not None:
                winddir = str(getItemValue(sensorName, 0))

            windspeedmph = None
            sensorName = getTheSensor('windspeedms')
            if sensorName is not None:
                windspeedmph = str(ms_to_mph(getItemValue(sensorName, 0.0)))

            windgustmph = None
            sensorName = getTheSensor('windgustms')
            if sensorName is not None:
                windgustmph = str(ms_to_mph(getItemValue(sensorName, 0.0)))

            windgustdir = None
            sensorName = getTheSensor('windgustdir')
            if sensorName is not None:
                windgustdir = str(getItemValue(sensorName, 0))

            windspdmph_avg2m = None
            sensorName = getTheSensor('windspeedms_avg2m')
            if sensorName is not None:
                windspdmph_avg2m = str(ms_to_mph(getItemValue(sensorName,
                                                              0.0)))

            winddir_avg2m = None
            sensorName = getTheSensor('winddir_avg2m')
            if sensorName is not None:
                winddir_avg2m = str(getItemValue(sensorName, 0))

            windgustmph_10m = None
            sensorName = getTheSensor('windgustms_10m')
            if sensorName is not None:
                windgustmph_10m = str(ms_to_mph(getItemValue(sensorName, 0.0)))

            windgustdir_10m = None
            sensorName = getTheSensor('windgustdir_10m')
            if sensorName is not None:
                windgustdir_10m = str(getItemValue(sensorName, 0))

            solarradiation = None
            sensorName = getTheSensor('solarradiation', getHighest=True)
            if sensorName is not None:
                solarradiation = str(
                    lux_to_watts_m2(getItemValue(sensorName, 0)))

            # From http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol

            cmd = 'curl -s -G "' + WU_URL + '" ' \
                + '--data-urlencode "action=updateraw" ' \
                + '--data-urlencode "ID='+self.config.wunderground['stationdata']['station_id']+'" ' \
                + '--data-urlencode "PASSWORD='******'stationdata']['station_key']+'" ' \
                + '--data-urlencode "dateutc='+dateutc+'" ' \
                + '--data-urlencode "softwaretype=openHAB" '
            self.log.debug("")

            if self.config.wunderground['stationdata']['weather_upload']:
                self.log.debug("Below is the weather data that we will send:")
            else:
                self.log.debug(
                    "Below is the weather data that we would send (if weather_upload was enabled):"
                )

            if tempf is not None:
                cmd += '--data-urlencode "tempf=' + tempf + '" '
                self.log.debug("tempf: " + tempf)
            if humidity is not None:
                cmd += '--data-urlencode "humidity=' + str(humidity) + '" '
                self.log.debug("humidity: " + str(humidity))
            if dewptf is not None:
                cmd += '--data-urlencode "dewptf=' + dewptf + '" '
                self.log.debug("dewptf: " + dewptf)
            if heatidxf is not None:
                cmd += '--data-urlencode "heatidxf=' + heatidxf + '" '
                self.log.debug("heatidxf: " + heatidxf)
            if soiltempf is not None:
                cmd += '--data-urlencode "soiltempf=' + soiltempf + '" '
                self.log.debug("soiltempf: " + soiltempf)
            if soilmoisture is not None:
                cmd += '--data-urlencode "soilmoisture=' + soilmoisture + '" '
                self.log.debug("soilmoisture: " + soilmoisture)
            if pressure is not None:
                cmd += '--data-urlencode "baromin=' + pressure + '" '
                self.log.debug("baromin: " + pressure)
            if rainin is not None:
                cmd += '--data-urlencode "rainin=' + rainin + '" '
                self.log.debug("rainin: " + rainin)
            if dailyrainin is not None:
                cmd += '--data-urlencode "dailyrainin=' + dailyrainin + '" '
                self.log.debug("dailyrainin: " + dailyrainin)
            if winddir is not None:
                cmd += '--data-urlencode "winddir=' + winddir + '" '
                self.log.debug("winddir: " + winddir)
            if windspeedmph is not None:
                cmd += '--data-urlencode "windspeedmph=' + windspeedmph + '" '
                self.log.debug("windspeedmph: " + windspeedmph)
            if windgustmph is not None:
                cmd += '--data-urlencode "windgustmph=' + windgustmph + '" '
                self.log.debug("windgustmph: " + windgustmph)
            if windgustdir is not None:
                cmd += '--data-urlencode "windgustdir=' + windgustdir + '" '
                self.log.debug("windgustdir: " + windgustdir)
            if windspdmph_avg2m is not None:
                cmd += '--data-urlencode "windspdmph_avg2m=' + windspdmph_avg2m + '" '
                self.log.debug("windspdmph_avg2m: " + windspdmph_avg2m)
            if winddir_avg2m is not None:
                cmd += '--data-urlencode "winddir_avg2m=' + winddir_avg2m + '" '
                self.log.debug("winddir_avg2m: " + winddir_avg2m)
            if windgustmph_10m is not None:
                cmd += '--data-urlencode "windgustmph_10m=' + windgustmph_10m + '" '
                self.log.debug("windgustmph_10m: " + windgustmph_10m)
            if windgustdir_10m is not None:
                cmd += '--data-urlencode "windgustdir_10m=' + windgustdir_10m + '" '
                self.log.debug("windgustdir_10m: " + windgustdir_10m)
            if solarradiation is not None:
                cmd += '--data-urlencode "solarradiation=' + solarradiation + '" '
                self.log.debug("solarradiation: " + solarradiation)
            cmd += ' 1>/dev/null 2>&1 &'
            self.log.debug("")

            if self.config.wunderground['stationdata']['weather_upload']:
                self.log.debug('WeatherUpload version ' + SCRIPT_VERSION +
                               ', performing an upload. (loop count is: ' +
                               str(wu_loop_count) + ')')
                self.log.debug('cmd: ' + cmd)
                os.system(cmd)
        else:
            self.log.debug('WeatherUpload version ' + SCRIPT_VERSION +
                           ', skipping upload. (loop count is: ' +
                           str(wu_loop_count) + ')')

        if (wu_loop_count %
                self.config.wunderground['stationdata']['upload_frequency'] ==
                0):
            wu_loop_count = 0
        wu_loop_count = wu_loop_count + 1
예제 #18
0
def prepare_dew_point(record):
    temp = meteocalc.Temp(record['air_temperature_deg_c'], 'c')
    rh = record['relative_humidity']
    record['due_point_deg_c'] = meteocalc.dew_point(temp, rh).c
예제 #19
0
    def __post_init__(self):
        """Set up some additional attributes from passed-in data."""
        object.__setattr__(self, "unique_id",
                           self._input.pop("PASSKEY", DEFAULT_UNIQUE_ID))

        # Only store data keys that we explicitly care about:
        object.__setattr__(
            self,
            "_data",
            {k: v
             for k, v in self._input.items() if k not in KEYS_TO_IGNORE},
        )

        # Determine properties necessary for the calculated properties:
        if DATA_POINT_TEMPF in self._data:
            object.__setattr__(
                self,
                "_temperature_obj",
                meteocalc.Temp(self._data[DATA_POINT_TEMPF], "f"),
            )
        if DATA_POINT_HUMIDITY in self._data:
            object.__setattr__(
                self, "_humidity",
                round(float(self._data[DATA_POINT_HUMIDITY]), 1))
        if DATA_POINT_WINDSPEEDMPH in self._data:
            object.__setattr__(
                self, "_wind_speed",
                round(float(self._data[DATA_POINT_WINDSPEEDMPH])))

        # Determine calculated properties:
        if self._temperature_obj and self._humidity:
            object.__setattr__(
                self,
                "_dew_point_obj",
                meteocalc.dew_point(self._temperature_obj, self._humidity),
            )
            object.__setattr__(
                self,
                "_heat_index_obj",
                meteocalc.heat_index(self._temperature_obj, self._humidity),
            )
        if self._temperature_obj and self._wind_speed:
            if self._humidity:
                object.__setattr__(
                    self,
                    "_feels_like_obj",
                    meteocalc.feels_like(self._temperature_obj, self._humidity,
                                         self._wind_speed),
                )

            try:
                object.__setattr__(
                    self,
                    "_wind_chill_obj",
                    meteocalc.wind_chill(self._temperature_obj,
                                         self._wind_speed),
                )
            except ValueError as err:
                LOGGER.debug(
                    "%s (temperature: %s, wind speed: %s)",
                    err,
                    self._temperature_obj,
                    self._wind_speed,
                )
예제 #20
0
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    #Arranque Thread del servidor
    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
    #Carga hilos, servidor http y heartbreak
    subproceso.start()
    subproceso_led.start()
    #Programa principal
    while (1):
        #Captura muestra
        timestamp = time.strftime("%d/%m/%y %H:%M:%S")
        datosvalidos = 0
        while (datosvalidos == 0):
            result = instance.read()
            datosvalidos = result.is_valid()
        ffile = open(fichero, "r")
        muestra = len(ffile.readlines()) - 1
        ffile.close()
        temperatura = result.temperature
        humedad = result.humidity
        t = Temp(temperatura, 'c')
        pdr = dew_point(temperature=t, humidity=humedad)
        linea = (str(muestra) + separador + timestamp + separador +
                 str(temperatura) + separador + str(humedad) + separador +
                 str(round(pdr, 2)) + separador + numeroMaquina + "\n")
        print linea,
        ffile = open(fichero, "a")
        ffile.write(linea)
        ffile.close()
        #Temporizacion entre muestras segun intervalo configurado
        sleep(float(intervalo))
 def cal_dew_point(temp, humidity):         
     temp = Temp(temp, 'c')
     dewpoint = dew_point(temperature=temp, humidity = humidity).c
     
     return dewpoint
예제 #22
0
def blynk_data():
    #  try:
    #      _log.debug(bme680.gas)
    #  except:
    #      bme680 = None
    _log.debug("bme680 = " + str(bme680))
    _log.debug("bme280 = " + str(bme280))
    payload = drone.dronePayload(_log)

    _log.info("Start of timer.register fx")
    blynk.set_property(systemLED, 'color', colours[1])
    blynk.virtual_write(250, "Updating")
    _log.debug("Going to get timestamp")
    now = datetime.now()
    blynk.virtual_write(0, now.strftime("%d/%m/%Y %H:%M:%S"))
    blynk.set_property(0, 'color', colours['ONLINE'])
    _log.debug("Going to get openweather")
    openWeather.blynkOpenWeather(blynk, _log)
    _log.debug("Completed openweather")
    if (bme280 is None and bme680 is None):
        #drone.setBMEFormOfflineColours(blynkObj=blynk, loggerObj=_log)
        _log.debug("----------------------bme680 = " + str(bme680))
        _log.debug("----------------------bme280 = " + str(bme280))

    if (bme680 is not None):
        _log.debug("bme680 is not None so going to set pressure")
        payload.add("sensorType", "bme680")
        bme680.sea_level_pressure = openWeather.getPressure()
        _log.debug("Going to send bme680 data to blynk app")
        payload.add("voc", "{0:.4f}".format(bme680.gas))
        blynk.virtual_write(2, bme680.gas)
        _log.info("bme680.gas =" + str(bme680.gas))
        payload.add("temperature", "{0:.4f}".format(bme680.temperature))
        blynk.virtual_write(1, bme680.temperature)
        _log.info("bme680.temperature =" + str(bme680.temperature))
        payload.add("humidity", "{0:.4f}".format(bme680.gas))
        blynk.virtual_write(3, bme680.humidity)
        _log.info("bme680.humidity =" + str(bme680.humidity))
        payload.add("pressure", "{0:.4f}".format(bme680.pressure))
        blynk.virtual_write(4, bme680.pressure)
        _log.info("bme680.pressure =" + str(bme680.pressure))
        payload.add("altitude", "{0:.4f}".format(bme680.altitude))
        blynk.virtual_write(5, bme680.altitude)
        _log.info("bme680.altitude =" + str(bme680.altitude))
        _log.debug("Going to get dew point from bme680 data")
        t = Temp(bme680.temperature, 'c')
        dewPoint = dew_point(temperature=t, humidity=bme680.humidity)
        payload.add("dewPoint", dewPoint)
        blynk.virtual_write(11, dewPoint)
        _log.info("bme680.dew_point =" + str(dewPoint))
        drone.setBME680FormColours(bme680, blynkObj=blynk, loggerObj=_log)
    elif (bme280 is not None):
        _log.debug("Going to send bme280 data to blynk app")
        payload.add("sensorType", "bme280")
        blynk.virtual_write(2, "BME280")
        blynk.set_property(2, 'color', colours['OFFLINE'])
        payload.add("temperature", "{0:.4f}".format(bme280.temperature))
        blynk.virtual_write(1, bme280.temperature)
        _log.info("bme280.temperature" + str(bme280.temperature))
        payload.add("humidity", "{0:.4f}".format(bme280.humidity))
        blynk.virtual_write(3, bme280.humidity)
        _log.info("bme280.humidity" + str(bme280.humidity))
        payload.add("pressure", "{0:.4f}".format(bme280.pressure))
        blynk.virtual_write(4, bme280.pressure)
        _log.info("bme280.pressure" + str(bme280.pressure))
        payload.add("altitude", "{0:.4f}".format(bme280.altitude))
        blynk.virtual_write(5, bme280.altitude)
        _log.info("bme280.altitude" + str(bme280.altitude))
        _log.debug("Going to get dew point from bme280 data")
        t = Temp(bme280.temperature, 'c')
        dewPoint = dew_point(temperature=t, humidity=bme280.humidity)
        payload.add("dewPoint", dewPoint)
        blynk.virtual_write(11, dewPoint)
        _log.debug("set BME form display")
        drone.setBME280FormColours(bme280, blynkObj=blynk, loggerObj=_log)

    drone.pubEnviromentalReadingsToGoolgeCloud(payload)

    payload = drone.dronePayload(_log)

    _log.debug("Now work on TSL2591 sensor")
    if (tsl is not None):
        payload.add("sensorType", "TSL2591")
        payload.add("lux", "{0:.0f}".format(tsl.lux))
        payload.add("infrared", "{0:d}".format(tsl.infrared))
        payload.add("visible", "{0:d}".format(tsl.visible))
        payload.add("full_spectrum", "{0:d}".format(tsl.full_spectrum))
        drone.pubLightReadingsToGoolgeCloud(payload)

        _log.debug('Total light: {0:.2f}lux'.format(tsl.lux))
        _log.debug('Infrared light: {0:d}'.format(tsl.infrared))
        _log.debug('Visible light: {0:d}'.format(tsl.visible))
        _log.debug('Full spectrum (IR + visible) light: {0:d}'.format(
            tsl.full_spectrum))
        blynk.virtual_write(6, str("{0:.2f}".format(tsl.lux)))
        blynk.virtual_write(7, str("{0:d}".format(tsl.infrared)))
        blynk.virtual_write(8, ("{0:d}".format(tsl.visible)))
        blynk.virtual_write(9, ("{0:d}".format(tsl.full_spectrum)))
        _log.debug("Now drone.setTSLFormOnline")
        drone.setTSLFormOnlineColours(blynkObj=blynk, loggerObj=_log)
    else:
        drone.setTSLFormOfflineColours(blynkObj=blynk, loggerObj=_log)

    payload = drone.dronePayload(_log)
    _log.debug("Now work on mhz19b sensor")
    mhz19b = mh_z19.read()
    if mhz19b is not None:
        payload.add("sensorType", "mh_z19")
        payload.add("CO2", '{0:d}'.format(mhz19b['co2']))
        drone.pubGasiousReadingsToGoolgeCloud(payload)
        blynk.virtual_write(10, '{0:d}'.format(mhz19b['co2']))
        _log.info('CO2: {0:d}'.format(mhz19b['co2']))
        drone.setMHZFormOnlineColours(blynkObj=blynk, loggerObj=_log)
    else:
        blynk.virtual_write(98, 'Unexpected error: mhz19b' + '\n')
        _log.error('Unexpected error: mhz19b')
        drone.setMHZFormOfflineColours(blynkObj=blynk, loggerObj=_log)
    blynk.virtual_write(250, "Running")
    blynk.set_property(systemLED, 'color', colours[0])
    _log.debug("End of timer.register fx")