def fetch_temperatures(session): client = EvohomeClient(config.USERNAME, config.PASSWORD) #Setup the Temperature type Base = declarative_base() class Temperature(Base): __tablename__ = "temperatures" seq_id = Column(Integer, Sequence('temp_seq_id'), primary_key=True) timestamp = Column(DateTime) temp = Column(Float) setpoint = Column(Float) thermostat = Column(String) name = Column(String) id = Column(Integer) #Create the tables (if they don't exist) Base.metadata.create_all(engine) now = datetime.datetime.now() logger.debug(now) for zone in client.temperatures(): row = Temperature() for key in zone.keys(): setattr(row,key,zone[key]) if type(row.setpoint) == type(''): row.setpoint = float(0) row.timestamp = now session.add(row) logger.info("%s - %s: %s %s" % (row.thermostat,row.name,row.temp,row.setpoint)) session.commit()
def getCurrentValues(self): ec = EvohomeClient(self.login, self.password) temperatures=[] weather=None for device in ec.temperatures(): temperatures.append({'name':device['name'],'temperature':device['temp']}) if self.extemp=="True": import pyowm owm = pyowm.OWM(self.apikey) observation = owm.weather_at_place(self.city) w = observation.get_weather() weather={} weather['temperature']=w.get_temperature('celsius')['temp'] weather['min']=w.get_temperature('celsius')['temp_min'] weather['max']=w.get_temperature('celsius')['temp_max'] weather['rain']=w.get_rain() weather['cloud']=w.get_clouds() weather['wind']=w.get_wind() weather['humidity']=w.get_humidity() weather['pressure']=w.get_pressure() weather['status']=w.get_detailed_status() weather['icon']='https://openweathermap.org/img/w/'+w.get_weather_icon_name()+'.png' sunrise=datetime.datetime.fromtimestamp(w.get_sunrise_time()).strftime("%Hh%M") weather['sunrise']=sunrise sunset = datetime.datetime.fromtimestamp(w.get_sunset_time()).strftime("%Hh%M") weather['sunset']=sunset return (temperatures,weather)
def getCurrentValues(self): ec = EvohomeClient(self.login, self.password) temperatures = [] weather = None for device in ec.temperatures(): temperatures.append({ 'name': device['name'], 'temperature': device['temp'] }) if self.extemp == "True": import pyowm owm = pyowm.OWM(self.apikey) observation = owm.weather_at_place(self.city) w = observation.get_weather() weather = {} weather['temperature'] = w.get_temperature('celsius')['temp'] weather['min'] = w.get_temperature('celsius')['temp_min'] weather['max'] = w.get_temperature('celsius')['temp_max'] weather['rain'] = w.get_rain() weather['cloud'] = w.get_clouds() weather['wind'] = w.get_wind() weather['humidity'] = w.get_humidity() weather['pressure'] = w.get_pressure() weather['status'] = w.get_detailed_status() weather[ 'icon'] = 'https://openweathermap.org/img/w/' + w.get_weather_icon_name( ) + '.png' sunrise = datetime.datetime.fromtimestamp( w.get_sunrise_time()).strftime("%Hh%M") weather['sunrise'] = sunrise sunset = datetime.datetime.fromtimestamp( w.get_sunset_time()).strftime("%Hh%M") weather['sunset'] = sunset return (temperatures, weather)
def update_evohome(cur): client = EvohomeClient(os.environ['EVOHOME_USER'], os.environ['EVOHOME_PASSWORD']) actual_sql = "INSERT INTO data (data_source_id, date_added, field, is_target, value) VALUES (1, current_timestamp, %s, false, %s)" target_sql = "INSERT INTO data (data_source_id, date_added, field, is_target, value) VALUES (1, current_timestamp, %s, true, %s)" for device in client.temperatures(): if device['thermostat'] == 'DOMESTIC_HOT_WATER': cur.execute(actual_sql, ("Hot Water", "%d" % (device['temp'] * 100))) if device['thermostat'] == 'EMEA_ZONE': cur.execute(actual_sql, (device['name'], "%d" % (device['temp'] * 100))) cur.execute(target_sql, (device['name'], "%d" % (device['setpoint'] * 100)))
def _setup_round(username, password, config, add_devices): """Set up the rounding function.""" from evohomeclient2 import EvohomeClient away_temp = config.get(CONF_AWAY_TEMPERATURE) client = EvohomeClient(username, password) try: for device in client.temperatures(): add_devices([RoundThermostat(client, device['id'], True, 10)], True) except socket.error: _LOGGER.error( "Connection error logging into the honeywell evohome web service") return False return True
def obtain_zone_details(): try: client = EvohomeClient(username, password, debug=False) except ValueError: print("\nEvoHome API error - aborting\n") exit(1) zone_details = [] for zone in client.temperatures(): # normalise response for DHW to be consistent with normal zones if zone['thermostat'] == 'DOMESTIC_HOT_WATER': zone['name'] = '_DHW' zone['setpoint'] = dhw_target zone_details.append(zone) return zone_details
#!/usr/bin/env python import sys from datetime import datetime from evohomeclient2 import EvohomeClient try: from config import username, password, filename except: print "Please configure config.py" sys.exit() client = EvohomeClient(username, password, debug=True) today = datetime.today().date() filename = './backup-%d-%02d-%02d.json' % (today.year, today.month, today.day) client.zone_schedules_backup(filename)
def setup(hass, hass_config): """Create a (EMEA/EU-based) Honeywell evohome system. Currently, only the Controller and the Zones are implemented here. """ # CC; pylint: disable=too-many-branches, too-many-statements evo_data = hass.data[DATA_EVOHOME] = {} evo_data['timers'] = {} # use a copy, since scan_interval is rounded up to nearest 60s evo_data['params'] = dict(hass_config[DOMAIN]) scan_interval = evo_data['params'][CONF_SCAN_INTERVAL] scan_interval = timedelta(minutes=(scan_interval.total_seconds() + 59) // 60) if _LOGGER.isEnabledFor(logging.DEBUG): # then redact username, password tmp = dict(evo_data['params']) tmp[CONF_USERNAME] = 'REDACTED' tmp[CONF_PASSWORD] = 'REDACTED' _LOGGER.debug("setup(): Configuration parameters: %s", tmp) from evohomeclient2 import EvohomeClient _LOGGER.warn("setup(): API call [4 request(s)]: client.__init__()...") # noqa: E501; pylint: disable=line-too-long; ZXDEL try: client = evo_data['client'] = EvohomeClient( evo_data['params'][CONF_USERNAME], evo_data['params'][CONF_PASSWORD], # debug=False ) except requests.exceptions.ConnectionError as err: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "This is a networking error, possibly at the vendor's end. " "Unable to continue. Resolve any errors and restart HA.") _LOGGER.error("setup(): The error message is: %s", err) _LOGGER.error( "setup(): For more help, see: https://github.com/zxdavb/evohome") return False # unable to continue except requests.exceptions.HTTPError as err: if err.response.status_code == HTTP_BAD_REQUEST: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "Check your username (%s), and password are correct. " "Unable to continue. Resolve any errors and restart HA.", evo_data['params'][CONF_USERNAME]) elif err.response.status_code == HTTP_SERVICE_UNAVAILABLE: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "The server is not contactable. Unable to continue. " "Resolve any errors and restart HA.") elif err.response.status_code == HTTP_TOO_MANY_REQUESTS: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "You have exceeded the API rate limit. Unable to continue. " "Try waiting a while (say 10 minutes) and restart HA.") else: raise # we don't expect/handle any other HTTPErrors _LOGGER.error("setup(): The error message is: %s", err) _LOGGER.error( "setup(): For more help, see: https://github.com/zxdavb/evohome") return False # unable to continue finally: # Redact username, password as no longer needed evo_data['params'][CONF_USERNAME] = 'REDACTED' evo_data['params'][CONF_PASSWORD] = 'REDACTED' evo_data['schedules'] = {} evo_data['status'] = {} # Redact any installation data we'll never need for loc in client.installation_info: loc['locationInfo']['locationId'] = 'REDACTED' loc['locationInfo']['locationOwner'] = 'REDACTED' loc['locationInfo']['streetAddress'] = 'REDACTED' loc['locationInfo']['city'] = 'REDACTED' loc[GWS][0]['gatewayInfo'] = 'REDACTED' # Pull down the installation configuration loc_idx = evo_data['params'][CONF_LOCATION_IDX] try: evo_data['config'] = client.installation_info[loc_idx] except IndexError: _LOGGER.error( "setup(): Parameter '%s' = %s , is outside its permissible range " "(0-%s). Unable to continue. " "Check your configuration, resolve any errors and restart HA.", CONF_LOCATION_IDX, loc_idx, len(client.installation_info) - 1) _LOGGER.error( "setup(): For more help, see: https://github.com/zxdavb/evohome") return False # unable to continue if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( "setup(): The location (temperature control system) " "used is: %s [%s] (%s [%s])", evo_data['config']['locationInfo']['locationId'], evo_data['config']['locationInfo']['name'], evo_data['config'][GWS][0][TCS][0]['systemId'], evo_data['config'][GWS][0][TCS][0]['modelType']) # Some of this data needs further redaction before being logged tmp_loc = dict(evo_data['config']) tmp_loc['locationInfo']['postcode'] = 'REDACTED' _LOGGER.debug("setup(): evo_data['config']=%s", tmp_loc) if evo_data['params'][CONF_USE_HEURISTICS]: _LOGGER.warning( "setup(): '%s' = True. This feature is best efforts, and may " "return incorrect state data.", CONF_USE_HEURISTICS) load_platform(hass, 'climate', DOMAIN, {}, hass_config) if 'dhw' in evo_data['config'][GWS][0][TCS][0]: # if this location has DHW load_platform(hass, 'water_heater', DOMAIN, {}, hass_config) @callback def _first_update(event): # noqa: E501; pylint: disable=line-too-long, unused-argument # When HA has started, the hub knows to retrieve it's first update pkt = {'sender': 'setup()', 'signal': 'refresh', 'to': EVO_PARENT} async_dispatcher_send(hass, DISPATCHER_EVOHOME, pkt) hass.bus.listen(EVENT_HOMEASSISTANT_START, _first_update) return True
#!/usr/bin/python import sys import requests from evohomeclient2 import EvohomeClient client = EvohomeClient('email', 'password') for device in client.temperatures(): requests.put('http://localhost:8080/rest/items/CV_Temperature/state', data=str(device['temp'])) requests.put('http://localhost:8080/rest/items/CV_Setpoint/state', data=str(device['setpoint']))
def setup(hass, config): """Create a Honeywell (EMEA/EU) evohome CH/DHW system. One controller with 0+ heating zones (e.g. TRVs, relays) and, optionally, a DHW controller. Does not work for US-based systems. """ evo_data = hass.data[DATA_EVOHOME] = {} evo_data['timers'] = {} evo_data['params'] = dict(config[DOMAIN]) evo_data['params'][CONF_SCAN_INTERVAL] = SCAN_INTERVAL_DEFAULT from evohomeclient2 import EvohomeClient _LOGGER.debug("setup(): API call [4 request(s)]: client.__init__()...") try: # There's a bug in evohomeclient2 v0.2.7: the client.__init__() sets # the root loglevel when EvohomeClient(debug=?), so remember it now... log_level = logging.getLogger().getEffectiveLevel() client = EvohomeClient(evo_data['params'][CONF_USERNAME], evo_data['params'][CONF_PASSWORD], debug=False) # ...then restore it to what it was before instantiating the client logging.getLogger().setLevel(log_level) except HTTPError as err: if err.response.status_code == HTTP_BAD_REQUEST: _LOGGER.error( "Failed to establish a connection with evohome web servers, " "Check your username (%s), and password are correct." "Unable to continue. Resolve any errors and restart HA.", evo_data['params'][CONF_USERNAME]) return False # unable to continue raise # we dont handle any other HTTPErrors finally: # Redact username, password as no longer needed. evo_data['params'][CONF_USERNAME] = 'REDACTED' evo_data['params'][CONF_PASSWORD] = 'REDACTED' evo_data['client'] = client # Redact any installation data we'll never need. if client.installation_info[0]['locationInfo']['locationId'] != 'REDACTED': for loc in client.installation_info: loc['locationInfo']['streetAddress'] = 'REDACTED' loc['locationInfo']['city'] = 'REDACTED' loc['locationInfo']['locationOwner'] = 'REDACTED' loc[GWS][0]['gatewayInfo'] = 'REDACTED' # Pull down the installation configuration. loc_idx = evo_data['params'][CONF_LOCATION_IDX] try: evo_data['config'] = client.installation_info[loc_idx] except IndexError: _LOGGER.warning( "setup(): Parameter '%s' = %s , is outside its range (0-%s)", CONF_LOCATION_IDX, loc_idx, len(client.installation_info) - 1) return False # unable to continue evo_data['status'] = {} if _LOGGER.isEnabledFor(logging.DEBUG): tmp_loc = dict(evo_data['config']) tmp_loc['locationInfo']['postcode'] = 'REDACTED' tmp_tcs = tmp_loc[GWS][0][TCS][0] if 'zones' in tmp_tcs: tmp_tcs['zones'] = '...' if 'dhw' in tmp_tcs: tmp_tcs['dhw'] = '...' _LOGGER.debug("setup(), location = %s", tmp_loc) load_platform(hass, 'climate', DOMAIN, {}, config) return True
def setup(hass, hass_config): """Create a (EMEA/EU-based) Honeywell evohome system. Currently, only the Controller and the Zones are implemented here. """ evo_data = hass.data[DATA_EVOHOME] = {} evo_data['timers'] = {} # use a copy, since scan_interval is rounded up to nearest 60s evo_data['params'] = dict(hass_config[DOMAIN]) scan_interval = evo_data['params'][CONF_SCAN_INTERVAL] scan_interval = timedelta(minutes=(scan_interval.total_seconds() + 59) // 60) from evohomeclient2 import EvohomeClient try: client = EvohomeClient(evo_data['params'][CONF_USERNAME], evo_data['params'][CONF_PASSWORD], debug=False) except HTTPError as err: if err.response.status_code == HTTP_BAD_REQUEST: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "Check your username (%s), and password are correct." "Unable to continue. Resolve any errors and restart HA.", evo_data['params'][CONF_USERNAME]) elif err.response.status_code == HTTP_SERVICE_UNAVAILABLE: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "The server is not contactable. Unable to continue. " "Resolve any errors and restart HA.") elif err.response.status_code == HTTP_TOO_MANY_REQUESTS: _LOGGER.error( "setup(): Failed to connect with the vendor's web servers. " "You have exceeded the api rate limit. Unable to continue. " "Wait a while (say 10 minutes) and restart HA.") else: raise # we dont expect/handle any other HTTPErrors return False # unable to continue finally: # Redact username, password as no longer needed evo_data['params'][CONF_USERNAME] = 'REDACTED' evo_data['params'][CONF_PASSWORD] = 'REDACTED' evo_data['client'] = client evo_data['status'] = {} # Redact any installation data we'll never need for loc in client.installation_info: loc['locationInfo']['locationId'] = 'REDACTED' loc['locationInfo']['locationOwner'] = 'REDACTED' loc['locationInfo']['streetAddress'] = 'REDACTED' loc['locationInfo']['city'] = 'REDACTED' loc[GWS][0]['gatewayInfo'] = 'REDACTED' # Pull down the installation configuration loc_idx = evo_data['params'][CONF_LOCATION_IDX] try: evo_data['config'] = client.installation_info[loc_idx] except IndexError: _LOGGER.warning( "setup(): Parameter '%s'=%s, is outside its range (0-%s)", CONF_LOCATION_IDX, loc_idx, len(client.installation_info) - 1) return False # unable to continue if _LOGGER.isEnabledFor(logging.DEBUG): tmp_loc = dict(evo_data['config']) tmp_loc['locationInfo']['postcode'] = 'REDACTED' if 'dhw' in tmp_loc[GWS][0][TCS][0]: # if this location has DHW... tmp_loc[GWS][0][TCS][0]['dhw'] = '...' _LOGGER.debug("setup(): evo_data['config']=%s", tmp_loc) load_platform(hass, 'climate', DOMAIN, {}, hass_config) @callback def _first_update(event): # When HA has started, the hub knows to retreive it's first update pkt = {'sender': 'setup()', 'signal': 'refresh', 'to': EVO_PARENT} async_dispatcher_send(hass, DISPATCHER_EVOHOME, pkt) hass.bus.listen(EVENT_HOMEASSISTANT_START, _first_update) return True
def run_quickstart(): otgwDebug("otgwset BEGIN") # # get OTGW values in json format from the gateway # try: otgwDebug("read otgw vals") otgwData = json.loads(urlopen(os.environ["OTGWURL"] + "/json").read()) except HTTPError as e: otgwDebug("get otgwData failed: ", "code = ", e.code, " reason = ", e.reason) except IOError as e: print("I/O error({0}): {1}".format(e.errno, e.strerror)) otgwExit(1) else: # success .. write otgw data with open(os.environ["OTGWVALS"], "w") as f: json.dump(otgwData, f) f.close() if otgwData['dhwmode']['value'] == "1": # shower on, leave alone otgwExit(2) otgwDebug("read weather data") # update wether data older than 17 minutes, restrict number of API calls if os.path.exists(os.environ["OUTTEMP"]) == False or ( time.time() - os.path.getmtime(os.environ["OUTTEMP"])) > (17 * 60): weatherRequest = (os.environ["OTGWCITY"] + "&APPID=" + os.environ["APIKEYOT"] + "&units=metric") try: json_data = urlopen( "http://api.openweathermap.org/data/2.5/weather?q=" + weatherRequest).read() except HTTPError as e: otgwDebug("get weatherData failed: ", "code = ", e.code, " reason = ", e.reason) except OSError as e: print("OS error({0}): {1}".format(e.errno, e.strerror)) otgwExit(3) else: # success .. write weather data otgwDebug("write weather data") weatherData = json.loads(json_data) with open(os.environ["OUTTEMP"], "w") as f: json.dump(weatherData, f) f.close() else: # read weather data with open(os.environ["OUTTEMP"], "r") as f: weatherData = json.load(f) f.close() # reply timeout Evohome backend portal TCCTimeout = 113 # if changed more than 5 minutes (Evohome 6 switchpoints per hour) if os.path.exists(os.environ["EVOHOMEZ"]) == False or ( time.time() - os.path.getmtime(os.environ["EVOHOMEZ"])) > ( 9 * 60 - 2 * TCCTimeout): # load Evohome module sys.path.insert(0, os.environ["HOME"] + "/evohome-client") from evohomeclient2 import EvohomeClient # get Evohome zone temperature data try: otgwDebug("retrieve Evohome data") #login to Evohome backend evoClient = EvohomeClient(os.environ["EVOLOGIN"], os.environ["EVOPASSWD"], debug=False, timeout=TCCTimeout) except (requests.HTTPError, requests.Timeout, Exception) as e: # except (requests.HTTPError, requests.Timeout) as e: otgwDebug("EvohomeClient error: ", str(e)) # in case of error assume no demand evoWimm = [{ "id": "999999999", "name": "EvohomeERR", "temp": 99.0, "setpoint": 99.0 }] else: # succes .. write Evohome data otgwDebug("Evohome TCC connected") evoWimm = [] for evoData in evoClient.temperatures(): evoWimm.append(evoData) if len(evoWimm) <= 0: otgwDebug("Evohome data, no zones") otgwExit(33) else: otgwDebug("write Evohome data, zones: ", len(evoWimm)) with open(os.environ["EVOHOMEZ"], "w") as f: json.dump(evoWimm, f) f.close() otgwDebug("read Evohome data") with open(os.environ["EVOHOMEZ"], "r") as f: evoWimm = json.load(f) f.close() # # 2. calculate central heating settings # i = 0 # zones request y = 0 # zones over setpoint totalDiff = 0 for evoZone in evoWimm: zoneDiff = evoZone['setpoint'] - evoZone['temp'] otgwDebug("evoData zone", evoZone['name'], "dif =", zoneDiff) if zoneDiff > 0: totalDiff = totalDiff + zoneDiff i = i + 1 if zoneDiff < 0: y = y + 1 # average heating demand otgwDebug("totallDiff =", totalDiff, ", i =", i) if i > 0: # some zones request heat AVGDIF = totalDiff / i else: if (y == 0): # all zones at setpoint AVGDIF = 0 else: # all zones over setpoint AVGDIF = -1 # heating mode HM = int(otgwData['chmode']['value']) # outside temperature OT = float(weatherData['main']['temp']) if (AVGDIF > 0) and (HM == 1): # Evohome requests heating, set current setpoint # min/max values of heating curve OTCSMIN = float(os.environ["OTCSMIN"]) OTCSMAX = float(os.environ["OTCSMAX"]) # linear -20 > +20 outside temperature CS = OTCSMIN + AVGDIF + ((20 - OT) / (20 - -20)) * (OTCSMAX - OTCSMIN) otgwDebug("CS heating curve = ", CS) # see cv manual pendelMax = 15 PT = float(otgwData['boilertemp']['value']) if CS > PT + pendelMax: # gradual change at start otgwDebug("pendelmax", pendelMax, "active") CS = PT + pendelMax CS = math.ceil(CS) SH = (math.floor(CS / 5) + 1) * 5 # maximum modulation (show override) MM = '99' # temporary setpoint TT = '0' else: # pass along thermostat value CS = 0 # 'buffer bottom' temperature SH = float(os.environ["BUFTEMP"]) #SH = float(otgwData['chwsetpoint']['value']) # reset override MM = '93' # lower temporary setpoint TT = '17' # # 3. set central heating parameters # otgwDebug("AVGDIF =", AVGDIF, "HM =", HM) otgwDebug("CS =", CS, "returntemp =", otgwData['returntemp']['value'], "SH =", SH) # Evohome demand return hotter than setpoint if (HM == 1) and ((AVGDIF >= 0) or (float(otgwData['returntemp']['value']) > SH)): # wait until gateway mode while str(otgwCmd("PR", 'M')).find('M=M') > 0: otgwCmd("GW", '1') time.sleep(3) # outside (ambient) temperature try: type(otgwData["outside"]["value"]) except: # doesn't exist yet otgwCmd("OT", OT) else: # set OT if different if OT != float(otgwData["outside"]["value"]): otgwCmd("OT", OT) if (float(otgwData['chwsetpoint']['value']) != float( os.environ["BUFTEMP"])) or (SH != float( os.environ["BUFTEMP"])): # set current setpoint otgwCmd("CS", CS) # (re)set maximum modulation otgwCmd("MM", MM) # (re)set temporary setpoint otgwCmd("TT", TT) # set max. setpoint if SH != float(otgwData['chwsetpoint']['value']): otgwCmd("SH", SH) else: # no Evohome demand while str(otgwCmd("PR", 'M')).find('M=M') < 0: # set OTGW to monitoring (if not already) otgwCmd("GW", '0') time.sleep(3)
#!/usr/bin/python import sys import requests from evohomeclient2 import EvohomeClient client = EvohomeClient('*****@*****.**', 'somePassword') for device in client.temperatures(): requests.post('http://localhost:8086/rest/items/CV_Temperature', data=str(device['temp'])) requests.post('http://localhost:8086/rest/items/CV_Setpoint', data=str(device['setpoint']))
from dotenv import load_dotenv from evohomeclient2 import EvohomeClient import os import time load_dotenv(dotenv_path="./.env") client = EvohomeClient(os.getenv("EMAIL"), os.getenv("PW"), debug=True) client.zone_schedules_backup('backup_zone_schedules_%s.json' % time.time()) client.zone_schedules_restore('new_zone_schedules.json')
["id"], states=[ "Auto", "AutoWithEco", "AutoWithReset", "Away", "DayOff", "HeatingOff", "Custom", ], ) upd = prom.Gauge("evohome_updated", "Evohome client last updated") up = prom.Gauge("evohome_up", "Evohome client status") prom.start_http_server(8082) try: client = EvohomeClient(username, password) except Exception as e: print( "ERROR: can't create EvohomeClient\n{}: {}".format( type(e).__name__, str(e)), file=sys.stderr, ) sys.exit(1) loggedin = True lastupdated = 0 tcsalerts = set() zonealerts = dict() oldids = set() labels = {} lastup = False
py.sign_in(Username, APIkey) stream_ids_array = [] for name, value in Config.items('Rooms'): stream_ids_array.append(value) # Stream tokens from plotly tls.set_credentials_file(stream_ids=stream_ids_array) stream_ids = tls.get_credentials_file()['stream_ids'] # Set your login details in the 2 fields below USERNAME = Config.get('Evohome', 'Username') PASSWORD = Config.get('Evohome', 'Password') try: client = EvohomeClient(USERNAME, PASSWORD) except ValueError: try: client = EvohomeClient(USERNAME, PASSWORD) except ValueError: print "Error when connecting to internet, please try again" # We make a plot for every room for device in client.temperatures(): stream_id = Config.get('Rooms', device['name']) stream = Stream(token=stream_id, maxpoints=288) trace1 = Scatter(x=[], y=[], mode='lines+markers', line=Line(shape='spline'), stream=stream)
#!/usr/bin/env python import sys from evohomeclient2 import EvohomeClient try: from config import username, password, filename except: print "Please configure config.py" sys.exit() client = EvohomeClient(username, password, debug=True) filename = './schedule-to-restore.json' client.zone_schedules_restore(filename)
from evohomeclient2 import EvohomeClient import evohomeclient from influx import * # Set your login details in the 2 fields below USERNAME = get_string_or_default('Evohome', 'Username', '') PASSWORD = get_string_or_default('Evohome', 'Password', '') DEBUG = get_boolean_or_default('Evohome', 'Debug', False) # Infinite loop every 5 minutes while True: # Get current time and all thermostat readings try: client = evohomeclient.EvohomeClient(USERNAME, PASSWORD) client2 = EvohomeClient(USERNAME, PASSWORD, debug=DEBUG) temps = [] if DEBUG: print(client2.locations[0]._gateways[0]._control_systems[0]. systemModeStatus) print(client2.locations[0]._gateways[0]._control_systems[0]. activeFaults) for device in client.temperatures(): temperatures = Temperature(device['name'], float(device['temp']), float(device['setpoint'])) if DEBUG: print temperatures temps.append(temperatures) timestamp = datetime.utcnow() timestamp = timestamp.replace(microsecond=0) write(timestamp, temps)
extemp=config.get("EVOHOME", "extemp") date = time.time() conn = sqlite3.connect(dbname) cursor = conn.cursor() if extemp=="True": apikey=config.get("EVOHOME", "apikey") city=config.get("EVOHOME", "city") import pyowm owm = pyowm.OWM(apikey) observation = owm.weather_at_place(city) w = observation.get_weather() temperature=w.get_temperature('celsius')['temp'] print temperature cursor.execute("INSERT INTO data(name,temp,time) VALUES(?,?,?)",("Ext",temperature,date)) ec = EvohomeClient(login, password) for device in ec.temperatures(): #cursor.execute("""INSERT INTO users(name, age) VALUES(?, ?)""", ("olivier", 30)) name=device['name'] temp=device['temp']+0.0 #print name+" "+str(temp)+" "+str(date) cursor.execute("INSERT INTO data(name,temp,time) VALUES(?,?,?)",(name,temp,date)) conn.commit()
password = os.environ['EH-PASSWORD'] starttime = time.time() if __name__ == "__main__": while True: # Connect to Influxdb try: client = InfluxDBClient(host='influxdb', port=8086) print("Connected to InfluxDB") client.create_database("EH-TEMPS") print("Database EH-TEMPS exists") client.get_list_database() # Collect and store evohome temperatures print("Collect and store evohome temperatures") eclient = EvohomeClient({username}, {password}) for device in eclient.temperatures(): # Hot Water has null strings for name and setpoint so manually add them if device['thermostat'] == "DOMESTIC_HOT_WATER": device['setpoint'] = 55.0 device['name'] = "Hot Water" print([{"measurement": "Temperatures", "fields": device}]) client.write_points([{ "measurement": "Temperatures", "fields": device }], database='EH-TEMPS') # Collect and store OH temperatures print("Collect and store OH temperatures") if "OW" in os.environ:
def main(): logger.info("Evohome exporter for Prometheus") try: username = environ[username_env_var] password = environ[password_env_var] except KeyError: logger.error("Missing environment variables for Evohome credentials:") logger.error(f"\t{username_env_var} - Evohome username") logger.error(f"\t{password_env_var} - Evohome password") exit(1) else: logger.info( f"Evohome credentials read from environment variables ({username})" ) poll_interval = int(environ.get(poll_interval_env_var, 300)) scrape_port = int(environ.get(scrape_port_env_var, 8082)) eht = prom.Gauge( "evohome_temperature_celcius", "Evohome temperatuur in celsius", ["name", "thermostat", "id", "type"], ) zavail = prom.Gauge( "evohome_zone_available", "Evohome zone availability", ["name", "thermostat", "id"], ) zfault = prom.Gauge( "evohome_zone_fault", "Evohome zone has active fault(s)", ["name", "thermostat", "id"], ) zmode = prom.Enum( "evohome_zone_mode", "Evohome zone mode", ["name", "thermostat", "id"], states=["FollowSchedule", "TemporaryOverride", "PermanentOverride"], ) tcsperm = prom.Gauge( "evohome_temperaturecontrolsystem_permanent", "Evohome temperatureControlSystem is in permanent state", ["id"], ) tcsfault = prom.Gauge( "evohome_temperaturecontrolsystem_fault", "Evohome temperatureControlSystem has active fault(s)", ["id"], ) tcsmode = prom.Enum( "evohome_temperaturecontrolsystem_mode", "Evohome temperatureControlSystem mode", ["id"], states=[ "Auto", "AutoWithEco", "AutoWithReset", "Away", "DayOff", "HeatingOff", "Custom", ], ) upd = prom.Gauge("evohome_updated", "Evohome client last updated") up = prom.Gauge("evohome_up", "Evohome client status") prom.start_http_server(scrape_port) try: client = EvohomeClient(username, password) except Exception as e: logger.error( f"ERROR: can't create EvohomeClient\n{type(e).__name__}: {e}") sys.exit(1) logger.info("Logged into Evohome API") loggedin = True lastupdated = 0 tcsalerts = set() zonealerts = dict() oldids = set() labels = {} lastup = False while True: temps = [] newids = set() try: temps = list(client.temperatures()) get_schedules(client) loggedin = True updated = True lastupdated = time.time() except Exception as e: print("{}: {}".format(type(e).__name__, str(e)), file=sys.stderr) temps = [] updated = False loggedin = loginEvohome(client) if loggedin: continue if loggedin and updated: up.set(1) upd.set(lastupdated) tcs = client._get_single_heating_system() sysmode = tcs.systemModeStatus tcsperm.labels(client.system_id).set( float(sysmode.get("isPermanent", True))) tcsmode.labels(client.system_id).state(sysmode.get("mode", "Auto")) if tcs.activeFaults: tcsfault.labels(client.system_id).set(1) for af in tcs.activeFaults: afhd = hashabledict(af) if afhd not in tcsalerts: tcsalerts.add(afhd) logger.warn(f"fault in temperatureControlSystem: {af}") else: tcsfault.labels(client.system_id).set(0) tcsalerts = set() for d in temps: newids.add(d["id"]) labels[d["id"]] = [d["name"], d["thermostat"], d["id"]] if d["temp"] is None: zavail.labels(d["name"], d["thermostat"], d["id"]).set(0) eht.remove(d["name"], d["thermostat"], d["id"], "measured") else: zavail.labels(d["name"], d["thermostat"], d["id"]).set(1) eht.labels(d["name"], d["thermostat"], d["id"], "measured").set(d["temp"]) eht.labels(d["name"], d["thermostat"], d["id"], "setpoint").set(d["setpoint"]) eht.labels(d["name"], d["thermostat"], d["id"], "planned").set( calculate_planned_temperature(schedules[d["id"]])) zmode.labels(d["name"], d["thermostat"], d["id"]).state( d.get("setpointmode", "FollowSchedule")) if d["id"] not in zonealerts.keys(): zonealerts[d["id"]] = set() if d.get("activefaults"): zonefault = 1 for af in d["activefaults"]: afhd = hashabledict(af) if afhd not in zonealerts[d["id"]]: zonealerts[d["id"]].add(afhd) print( "fault in zone {}: {}".format(d["name"], af), file=sys.stderr, ) else: zonefault = 0 zonealerts[d["id"]] = set() zfault.labels(d["name"], d["thermostat"], d["id"]).set(zonefault) lastup = True else: up.set(0) if lastup: tcsperm.remove(client.system_id) tcsfault.remove(client.system_id) tcsmode.remove(client.system_id) lastup = False for i in oldids: if i not in newids: eht.remove(*labels[i] + ["measured"]) eht.remove(*labels[i] + ["setpoint"]) eht.remove(*labels[i] + ["planned"]) zavail.remove(*labels[i]) zmode.remove(*labels[i]) zfault.remove(*labels[i]) oldids = newids time.sleep(poll_interval)
password = config.get("EVOHOME", "password") dbname = config.get("EVOHOME", "dbname") extemp = config.get("EVOHOME", "extemp") date = time.time() conn = sqlite3.connect(dbname) cursor = conn.cursor() if extemp == "True": apikey = config.get("EVOHOME", "apikey") city = config.get("EVOHOME", "city") import pyowm owm = pyowm.OWM(apikey) observation = owm.weather_at_place(city) w = observation.get_weather() temperature = w.get_temperature('celsius')['temp'] print temperature cursor.execute("INSERT INTO data(name,temp,time) VALUES(?,?,?)", ("Ext", temperature, date)) ec = EvohomeClient(login, password) for device in ec.temperatures(): #cursor.execute("""INSERT INTO users(name, age) VALUES(?, ?)""", ("olivier", 30)) name = device['name'] temp = device['temp'] + 0.0 #print name+" "+str(temp)+" "+str(date) cursor.execute("INSERT INTO data(name,temp,time) VALUES(?,?,?)", (name, temp, date)) conn.commit()