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()
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
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()
def kjiphet(data): # Get effective temperature temp = Temp(float(data["values"]["temperature"]), "c") windSpeed = 2.23694 * float(data["values"]["humidity"]) humidity = float(data["values"]["humidity"]) effTemp = feels_like(temperature=temp, humidity=humidity, wind_speed=windSpeed).c # Calc temperature kjiphet tempKjiphet = calcTempKjiphet(effTemp) # 20 m/s is max wind speed ish, everything above is about the same windKjiphet = float(8) / 20 * float(data["values"]["windSpeed"]) # gust of that are more than 10 m/s more than the wind speed really sucks (Does gust value work like this?) gust = float(data["values"]["windGust"]) gustKjiphet = 0 if gust > 0: gustKjiphet = float(10) / 8 * (gust - float(data["values"]["windSpeed"])) cloudKjiphet = calcCloudKjiphet(float(data["values"]["fog"]), float(data["values"]["lowClouds"]), float(data["values"]["mediumClouds"]), float(data["values"]["highClouds"])) # precipitation is mm/minute I believe, so the max value recorded in Norway is 4.3, normal amount seems to be under 1 precKjiphet = 2 * float(data["values"]["precipitation"]) # Variance kjiphet still not implemented # varianceKjiphet = 0 # Interplay kjiphet not implemented # interplayKjiphet = 0 # Typ drizzle er chill når det er horevarmt, regn er ekstra kjipt når det temp nær # Weight the different kjiphet's, summing weights to 1 return 100 * sigmoid( 0.1 * (0.40 * tempKjiphet + 0.05 * gustKjiphet + 0.05 * cloudKjiphet + 0.20 * precKjiphet + 0.2 * windKjiphet))
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
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'
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()
def calculate_fl(df): flike_final = [] flike = [] # calculate Feels Like temperature for i in range(len(df)): at = df['air_temperature'][i] rh = df['relative_humidity'][i] ws = df['wind_speed'][i] flike.append(feels_like(Temp(at, unit = 'C'), rh, ws)) for i in range(len(flike)): flike_final.append(flike[i].f) df['feels_like'] = flike_final del flike_final, flike, at, rh, ws
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
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('==========================================')
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 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))
def temp(self): return Temp(self.temperature, 'C')
# print ac_state # print(json.dumps(ac_state, indent=4, sort_keys=True)) # 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)))
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)
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)
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)
import subprocess 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 = \
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
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
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")