示例#1
0
 def calculate_inside_temperature(self):
     """Use stored sensor values to calculate the 'feels like' temperature inside."""
     self.last_inside_temperature = self.inside_temperature
     temperatures = []
     humidities = []
     for sensor in self.sensors.values():
         if sensor.is_enabled() and sensor.location != "outside":
             temperature = sensor.get_measure("temperature")
             if temperature is not None:
                 temperatures.append(temperature)
             humidity = sensor.get_measure("humidity")
             if humidity is not None:
                 humidities.append(humidity)
     self.inside_temperature = round(
         heat_index(
             temperature=Temp(
                 sum(temperatures) / len(temperatures),
                 "c",
             ),
             humidity=sum(humidities) / len(humidities),
         ).c,
         1,
     )
     if self.last_inside_temperature != self.inside_temperature:
         self.controller.log(
             f"Inside temperature calculated as {self.inside_temperature} degrees",
             level="DEBUG",
         )
         self.controller.handle_temperatures()
示例#2
0
 def status(self):
     w = self.obs.get_weather()
     l = self.obs.get_location()
     
     name = l.get_name()
     humidity = w.get_humidity()
     
     #get rainfall, in mm. If no value returned, assume zero (0).
     r = w.get_rain()
     
     if ('3h' in r):
         rainfall = r['3h']
     else:
         rainfall = 0
     
     if (self.unit == "f"):
         temp = w.get_temperature(unit='fahrenheit')['temp']
     elif (self.unit == "k"):
         temp = w.get_temperature(unit='kelvin')['temp']
     else:
         temp = w.get_temperature(unit='celsius')['temp']
          
     t = mc.Temp(temp, self.unit)	    
     hi = mc.heat_index(temperature=t, humidity=humidity)
      
     if (self.unit == "f"):
         heatIndex = round(hi.f,2)
     elif (self.unit == "k"):
         heatIndex = round(hi.k,2)
     else:
         heatIndex = round(hi.c,2)
         
     return (name, temp, humidity, heatIndex, rainfall)
示例#3
0
def DealCsv(name='hello'):
    r = open(name, "rt")
    w = open(name.replace('2017122', '1'), 'w', newline='')
    read = csv.reader(r)
    write = csv.writer(w)
    head_row = next(read)
    head_row.append('E_WGBT(F)')
    head_row.append('E_WGBT(C)')
    head_row.append('AE_WGBT(C)')
    head_row.append('AE_WGBT(F)')
    write.writerow(head_row)
    for line in read:
        at = Temp(float(line[1]), 'c')
        fa = float(line[1]) * 1.8 + 32
        hum = float(line[5])
        # print(fa,hum)
        e_H = CalcuateHeatindex(fa, hum)
        e_C = Cal2(float(line[1]), hum)
        e_A = heat_index(at, hum)
        line[0] = line[0][-8:]
        line.append(e_H)
        line.append(e_C)
        line.append(e_A.c)
        line.append(e_A.f)
        write.writerow(line)

    r.close()
    w.close()
示例#4
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
示例#5
0
def sendWebAlert():
    humidity = sensors.humidity.read().humidity
    temperature = sensors.pressure.read().temperature - 8
    hi = heat_index(temperature=temperature, humidity=humidity)
    uri = "https://shellhacks2019-1f061.appspot.com/addMarker"
    x = requests.post(uri,
                      json={
                          'humid': int(humidity),
                          'heatindex': int(hi),
                          'bodytext': 'SOS',
                          'fallenAlert': 'true',
                          'temp': int(temperature)
                      })
    print(x)
示例#6
0
def calculate_heat_index(
        temperature: float,
        humidity: float,
        *,
        input_unit_system: str = UNIT_SYSTEM_IMPERIAL,
        output_unit_system: str = UNIT_SYSTEM_IMPERIAL) -> float:
    """Calculate heat index in the appropriate unit system."""
    temp_obj = _get_temperature_object(temperature, input_unit_system)
    heat_index_obj = meteocalc.heat_index(temp_obj, humidity)

    if output_unit_system == UNIT_SYSTEM_IMPERIAL:
        value = round(heat_index_obj.f, 1)
    else:
        value = round(heat_index_obj.c, 1)
    return cast(float, value)
示例#7
0
 def calculate_heat_index(self, humidity, temperature, sun=0):
     # Heat Index Calculation
     # Make sure that humidity is a ratio. NOT A PERCENTAGE
     if humidity > 1 or humidity < 0:
         raise ValueError(
             "Humidity: %f is not in range [0, 1]. Don't use percentages")
     temp = meteocalc.Temp(temperature, 'c')
     heat_index = meteocalc.heat_index(
         temperature=temp,
         humidity=100 * humidity)  # Stupid meteocalc likes percentages
     # Wikipedia: Exposure to full sunshine can increase heat index values by up to 8 °C (14 °F)[7]
     # Heat Index on the website of the Pueblo, CO United States National Weather Service.
     # Link: http://web.archive.org/web/20110629041320/http://www.crh.noaa.gov/pub/heat.php
     heat_index += meteocalc.Temp(8, 'c') * sun
     return heat_index
示例#8
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'
示例#9
0
def get_forecast():
    #unix_tstamp=calendar.timegm(pendulum.now().utctimetuple())

    #adding this is a time machine request avoid for realtime forecasts, no need for unix timestmap
    #url='https://api.darksky.net/forecast//40.7829,-73.9654,'+str(unix_tstamp)
    url = 'https://api.darksky.net/forecast/YOURDARKSKYAPIGOESHERE/40.7829,-73.9654'

    response = urllib.urlopen(url)
    d = json.loads(response.read())
    #with open('https://api.darksky.net/forecast//40.7829,-73.9654,141105960') as json_data:
    #with open('40.7829,-73.9654,1489503600') as json_data:
    #d = json.load(json_data)
    #print(d)
    forecasts = d['hourly']['data']
    forecasts = forecasts[0:24]

    #temperature,rh,rain
    #timestamp=[]
    #temperature=[] #in F
    #rh=[] #0-1
    ##rain=[] #in/hr
    #fractionalhour,dayofweek,month1505962085
    values = []
    #need to get into this format
    #keys=['day_of_week','weeks','hr','stop_id','heat_index']
    for forecast in forecasts:
        T = pendulum.from_timestamp(forecast['time'], 'America/New_York')
        #print T
        day_of_week = T.weekday()
        month = T.month
        fractionalhour = T.hour + (T.minute / 60.) + (T.second / 3600.)
        temperature = (float(forecast['temperature']))
        rh = (float(forecast['humidity']))
        rain = (float(forecast['precipIntensity']))
        HI = float(heat_index(temperature, rh))
        #bug in t.week_of_year
        values.append([
            day_of_week,
            T.week_of_year,
            fractionalhour,
            1,
            HI,
        ])
        #this has been customized for h

    return np.array(values)
def heatIndex():
	temperatureHI = (sensors.pressure.read().temperature) - 5
	humidityHI = sensors.humidity.read().humidity
	hi = heat_index(temperature=temperatureHI, humidity= humidityHI)

	ledSet = []

	for x in range(1, int(hi)):
		ledSet.append((25,0,25,0))
		led.set(ledSet)
		time.sleep(0.1)

	if (int(hi) >= 40):
		phoneContact()
		dangerAlert()

	print(hi)
	time.sleep(5)
示例#11
0
def get_weather(url, key):
    city = raw_input('Input city: ')
    r = requests.get(url % (city, key))
    json_r = r.json()
    temp_kel = json_r['main']['temp']
    precipitation = json_r['weather'][0]['description']
    wind = json_r['wind']['speed']
    temp_cel = round(temp_kel - 273.15)
    humidity = json_r['main']['humidity']
    t = Temp(temp_cel, 'c')
    hi = heat_index(temperature=t, humidity=humidity)

    print("Current temperature in " + city + ' : ' + str(temp_cel))
    print("Precipitation: " + precipitation)
    print("Wind speed: %s meters per second" % wind)
    print("Humidity: %s" % str(humidity) + '%')
    print("Feel\'s like: %s" % str(round((hi.c))) + 'C')
    print('==========================================')
示例#12
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
示例#13
0
文件: trabalho.py 项目: Barca88/iata
def main(argv):
    size = len(argv)

    if size >= 2:
        imput_file = argv[0]
        output_file = argv[1]
    else:
        print('imput_file e output_file necessarios')
        return

    i = open(imput_file)
    csv_imput = csv.DictReader(i)
    o = open(output_file, 'a')

    csv_output = csv.writer(o,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_MINIMAL)
    c = 0
    for row in csv_imput:
        data = datetime.strptime(row['dt_iso'], "%Y-%m-%d %H:%M:%S")
        temperatura = Temp(row['temp'], 'c')
        humidade = int(row['humidity'])
        # Heat Index is an index that combines air temperature and relative
        # humidity in an attempt to determine the human-perceived equivalent temperature.
        hi = heat_index(temperatura, humidade)
        estacaoAno = estacao(data)
        tIdeal = tempIdeal(estacaoAno)

        diffTemp = tIdeal - hi.c
        if diffTemp > 0:
            r = 'airconditioning+{' + str(diffTemp) + '}'
        else:
            r = 'airconditioning{' + str(diffTemp) + '}'

        linha = [estacaoAno, str(tIdeal), r]
        csv_output.writerow(linha)
        c += 1
    print('Total de linhas tratadas: ' + str(c))
示例#14
0
	def status(self):
	
		instance = self.dht11.DHT11(pin=self.DHT11_PIN)
		
		self.outside.status()
		
		while True:
			result = instance.read()
			if result.is_valid():
				if (self.unit == "f"):
				    temperature = 9.0/5.0 * result.temperature + 32
				elif (self.unit == "k"):
				    temperature = result.temperature + 273
				else:
				    temperature = result.temperature
				humidity = result.humidity
				
				# based on these calculate the 'feels like' temp
				#t = mc.Temp(result.temperature, 'c')
				t = mc.Temp(temperature, self.unit)
				
				hi = mc.heat_index(temperature=t, humidity=humidity)
				
				
				if (self.unit == "f"):
				    heatIndex = round(hi.f,2)
				elif (self.unit == "k"):
				    heatIndex = round(hi.k,2)
				else:
				    heatIndex = round(hi.c,2)
				# want the value in Celsius, so hi.c
				#self.heatIndex = round(hi.c,2)
				
				return (temperature, humidity, heatIndex)
				break	
			time.sleep(0.1)	
示例#15
0
 def heat_index(self):
     return heat_index(temperature=self.temp, humidity=self.humidity).c
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)
示例#17
0
#    client.pod_change_ac_state(uid, ac_state, "on", not ac_state['on'])
#    Sensibo moved nativeTargetTemperature out of the acstate structure into device/acstate
#    print ac_state['result'][0]['device']['acState']['nativeTargetTemperature']

    url = 'https://api.openweathermap.org/data/2.5/onecall?lat=' + cityLat + \
        '&lon=' + cityLon + '&units=metric&exclude=hourly,daily&appid=' + weathAPIkey
    response = requests.get(url)
    response.raise_for_status()
    weather = response.json()
    outsideTemp = weather['current']['temp']
    fahrenheit = (outsideTemp * 9 / 5) + 32

    # create input temperature in different units
    t = Temp(sensibotemp, 'c')  # c - celsius, f - fahrenheit, k - kelvin
    # calculate Heat Index
    tRealFeel = heat_index(temperature=t, humidity=sensibohumidity)
    RealFeel = tRealFeel.c

    #    r = requests.get('http://wttr.in/' + cityName + '?format=%t')
    #    s = r.text[1:-2]
    #    outsideTemp = float(s)
    #    fahrenheit = (outsideTemp * 9/5) + 32

    g.write("{},{},{},{},{},{:.2f},{:.2f},{:.2f}\n".format(
        power, sensibotemp, sensibomode, fanlevel, targettemp, outsideTemp,
        RealFeel, sensibohumidity))
    f.write("--------Temps---------\n")
    f.write("Target Temp: {} {}\n".format(targettemp,
                                          to_fahrenheit(targettemp)))
    f.write(
        "Sensibo Power On: {} Temp: {} Humidity: {:.2f} % RealFeel: {:.2f} State: {}  Fan: {}\n"
示例#18
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

#format to write
示例#19
0
def calculate_heat_index(temp, humid):
    return float(heat_index(temp, humid))
示例#20
0
def calculate_heat_index(row):
    t = Temp(int(row['temperature']), 'c')
    rh = int(row['relative_humidity'])
    hi = heat_index(temperature=t, humidity=rh)
    return round(hi.c)
示例#21
0
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()
datetime = strftime("%H:%M:%S %m/%d/%y")
示例#22
0
 def o_hi(self):
     return heat_index(temperature=self.o_temp(), humidity=float(self.o_humidity))
示例#23
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,
                )
示例#24
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)
示例#25
0
#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')
#print 'Humi,',format(humidity, '0.2f')
    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