def updated(config_dir): """ Send 'ns-notifcations was updated' message after (automatic) upgrade """ settings = get_config(config_dir) openhab = OpenHAB(settings.openhab_url) item_ns_notification = openhab.get_item(settings.openhab_item_notifications) local_version = get_local_version() item_ns_notification.command('Notifier was updated to ' + local_version + ', details might be in your (cron) email')
def check_connections(departure, destination, time, config_dir): """ Send 'ns-notifcations was updated' message after (automatic) upgrade """ settings = get_config(config_dir) nsapi = ns_api.NSAPI( settings['General'].get('apikey','')) print(departure + " " + destination + " " + str(time)) openhab = OpenHAB(settings['Openhab'].get('openhab_url')) item_ns_routeName = openhab.get_item(settings['Openhab'].get('openhab_item_route_name')) item_ns_routeName.command(departure + "->" + destination + " (" + str(time)+")") current_trips = nsapi.get_trips(time, departure, None, destination, True) ns_trains = json.loads(settings['Openhab'].get('openhab_item_trains',[])) for index, trip in enumerate(current_trips): print(index) if(trip.status == "NORMAL"): text = "🟢 " else: text = "🔴 " text = text + str(trip.product_shortCategoryName) + " " text = text + " " + str(ns_api.simple_time(trip.departure_time_planned)) text = text + " ➡ " + str(ns_api.simple_time(trip.arrival_time_planned)) text = text + " ⏱ " + (str(datetime.timedelta(minutes=(trip.travel_time_actual))))[:-3] if(trip.status == "NORMAL"): print("according to plan captain!") else: print(trip.disruptions_head) print(trip.disruptions_text) #print(trip.delay) print(trip.status) print(trip.departure_platform_actual) item_ns_train = openhab.get_item(ns_trains[index]) item_ns_train.command(text)
from openhab import OpenHAB from pydbus import SystemBus from gi.repository import GLib import requests r = requests.put('http://192.168.1.92:8080/rest/items/AlarmBuero', 'ON') base_url = 'http://localhost:8080/rest' openhab = OpenHAB(base_url) # fetch all items items = openhab.fetch_all_items() AlarmBuero = items.get('AlarmBuero') print(AlarmBuero.state) item = openhab.get_item('AlarmBuero') item.command('ON')
import os BASE_URL='https://api.geotogether.com/' LOGIN_URL='usersservice/v2/login' DEVICEDETAILS_URL='api/userapi/v2/user/detail-systems?systemDetails=true' LIVEDATA_URL = 'api/userapi/system/smets2-live-data/' PERIODICDATA_URL = 'api/userapi/system/smets2-periodic-data/' USERNAME= '******' PASSWORD = '******' LOG_DIRECTORY = 'xxxxxxxxxx'' openhab_URL = 'xxxxxxxxxxxx openhab = OpenHAB(openhab_URL) HouseElectricityPower = openhab.get_item('HouseElectricityPower') HouseGasMeterReading = openhab.get_item('HouseGasMeterReading') HouseGasPower = openhab.get_item('HouseGasPower') class GeoHome(threading.Thread): # Thread class with a _stop() method. # The thread itself has to check # regularly for the stopped() condition. def __init__(self, varUserName, varPassword): log = "Start Intalising: " + str(datetime.now()) super(MyThread, self).__init__() self._stop = threading.Event() self.varUserName = varUserName
def get_RVTemp(): sendEmail = False config_settings = ReadConfigini('/RVmonitor/rvmonitor.ini') logger = setup_logger(config_settings) logger.critical('**') logger.critical('Starting the RV Temp Monitor') logger.critical('**') logger.debug(config_settings) email_Address = config_settings['notification_address'] base_url = config_settings['base_url'] openhab = OpenHAB(base_url + '/rest') try: response = requests.get(base_url + '/rest/things') except: o365Text.send_email(email_Address, 'Connection Error', 'Could Not Connect to One Control - Things', '', config_settings['email_sender'], config_settings['server_userName'], config_settings['server_Password'], logger) logger.error('Could not connect to One Control things') if (response.status_code != 200): o365Text.send_email(email_Address, 'Connection Error', 'Could Not Connect to One Control - Request Failed', '', config_settings['email_sender'], config_settings['server_userName'], config_settings['server_Password'], logger) logger.error('Request Failed - Could not connect to One Control') try: json_data = response.json() hvac_devices = {} generator_details = {} temp = 0 for k in json_data: if (k["thingTypeUID"] == "idsmyrv:hvac-thing"): for c in k["channels"]: linkedItem = c["linkedItems"] linkedItem = (str(linkedItem).strip('[]')).strip("''") if c['id'] == 'inside-temperature': temp = openhab.get_item(linkedItem) hvac_devices.update({k["label"] : {"UID":k["UID"], "Thing" : linkedItem, "Temp" : temp.state}}) if (k["thingTypeUID"] == 'idsmyrv:generator-thing'): for c in k["channels"]: if c['id'] == 'battery-voltage': linkedItem = c['uid'].replace(':','_') linkedItem = linkedItem.replace('-','_') temp = openhab.get_item(linkedItem) generator_details.update({'Battery Voltage' : str(temp.state)}) if c['id'] == 'state': linkedItem = c['uid'].replace(':','_') linkedItem = linkedItem.replace('-','_') state = openhab.get_item(linkedItem) generator_details.update({'Running State' : state.state}) message = '' tempHi = config_settings['temp_hi'] tempLow = config_settings['temp_low'] useGarageTemp = (config_settings['use_garage_temp']).lower() == 'true' for room in hvac_devices: spc = room.find(' ') if (spc > 0): name = room[0:spc] else: name = room #numTemp is the temp in floating point form numTemp = hvac_devices[room]["Temp"] if ((numTemp > float(tempHi)) or (numTemp < float(tempLow))) : if name.lower() == 'garage' : if useGarageTemp : sendEmail = True else : sendEmail = True temperature = "{:.0f}".format(numTemp,1) message += name + ' ' + temperature + '\n' message += "Batt V " + str(generator_details['Battery Voltage']) + '\n' message += 'Gen State ' + generator_details['Running State'] + '\n' message += "Hi limit " + tempHi + '\n' message += "Low limit " + tempLow except: message = 'Error, could not read temperatures' logger.error('Could not read temperatures') # If we can't get temps, let's notify the user sendEmail = True finally: if sendEmail: o365Text.send_email(email_Address, 'Temp in Mo', message, '', config_settings['email_senderName'], config_settings['email_userName'], config_settings['email_password'], logger) logger.info('Gathered temps and emailed\n' + message) else: logger.info("No need to send email, temps are acceptable") logger.info("\n" + message) logAddress = config_settings['log_address'] if ( logAddress.lower() != 'none') and (logAddress): o365Text.send_email(config_settings['log_address'], 'Temp in Mo', message, '', config_settings['email_senderName'], config_settings['email_userName'], config_settings['email_password'], logger) logger.info('Gathered temps and emailed to log address :' + logAddress) logger.critical('**') logger.critical('Ending run of the RV Temp Monitor') logger.critical('**\n')
from openhab import OpenHAB from screens import Heos1Screen from inky import InkyWHAT from PIL import Image, ImageFont, ImageDraw from font_fredoka_one import FredokaOne base_url = 'http://192.168.1.20:5080/rest' openhab = OpenHAB(base_url) # fetch a single item item = openhab.get_item('LocalWeatherAndForecastForecastHours06IconId') print(item.state) item = openhab.get_item('HEOS1Control') print(item.state) item = openhab.get_item('HEOS1Album') print(item.state) item = openhab.get_item('HEOS1Artist') print(item.state) # turn a switch on # item.command('OFF') screen = Heos1Screen(openhab)
class MercedesBenzAPI(object): """ A wrapper for the Mercedes Benz Connect API https://developer.mercedes-benz.com for connection your vehicle data to your openHAB system """ def __init__(self): """ Check all requirements, get item states from openHAB and initialize the api connection. """ self.oh = OpenHAB(REDIRECT_URL.split('/static/')[0] + '/rest') self.client_id = self.oh.get_item(ITEM_PREFIX + 'client_id').state self.client_secret = self.oh.get_item(ITEM_PREFIX + 'client_secret').state self.vehicle_id = self.oh.get_item(ITEM_PREFIX + 'vehicle_id').state self.api_key = self.oh.get_item(ITEM_PREFIX + 'api_key').state self.auth_code = self.oh.get_item(ITEM_PREFIX + 'auth_code').state self.auth_code_trigger = self.oh.get_item(ITEM_PREFIX + 'auth_code_trigger').state self.auth_state = self.oh.get_item(ITEM_PREFIX + 'auth_state').state self.access_token = self.oh.get_item(ITEM_PREFIX + 'access_token').state self.refresh_token = self.oh.get_item(ITEM_PREFIX + 'refresh_token').state self.token_issued = self.oh.get_item(ITEM_PREFIX + 'token_issued').state self.token_expiry = self.oh.get_item(ITEM_PREFIX + 'token_expiry').state self.scope_fuelstatus = self.oh.get_item(ITEM_PREFIX + 'scope_fuelstatus').state self.scope_evstatus = self.oh.get_item(ITEM_PREFIX + 'scope_evstatus').state self.scope_vehiclelock = self.oh.get_item(ITEM_PREFIX + 'scope_vehiclelock').state self.scope_vehiclestatus = self.oh.get_item(ITEM_PREFIX + 'scope_vehiclestatus').state self.scope_payasyoudrive = self.oh.get_item(ITEM_PREFIX + 'scope_payasyoudrive').state self.imageoption_night = self.oh.get_item(ITEM_PREFIX + 'data_imageoption_night').state self.imageoption_roofOpen = self.oh.get_item(ITEM_PREFIX + 'data_imageoption_roofOpen').state self.imageoption_background = self.oh.get_item(ITEM_PREFIX + 'data_imageoption_background').state self.imageoption_cropped = self.oh.get_item(ITEM_PREFIX + 'data_imageoption_cropped').state self.imageoption_jpeg = self.oh.get_item(ITEM_PREFIX + 'data_imageoption_jpeg').state if self.auth_code is None: print('# No authorization code found. Visit "' + REDIRECT_URL + '" to get authorization code.') sys.exit() if self.client_id is None: print('# No CLIENT ID found. Please fill the openHAB item "' + ITEM_PREFIX + 'client_id" with data.') sys.exit() if self.client_secret is None: print('# No CLIENT SECRET found. Please fill the openHAB item "' + ITEM_PREFIX + 'client_secret" with data.') sys.exit() if self.vehicle_id is None: print('# No VEHICLE ID found. Please fill the openHAB item "' + ITEM_PREFIX + 'vehicle_id" with data.') sys.exit() self.auth_base64 = base64.b64encode(bytes(self.client_id + ':' + self.client_secret, 'utf-8'), altchars=None).decode('ascii') if self.auth_code_trigger is None or self.refresh_token is None or self.token_expiry is None or self.access_token is None or self.token_expiry is None: self._generateCredentials() if self.auth_code_trigger == 'ON': # New Auth Code in openHAB self.oh.get_item(ITEM_PREFIX + 'auth_code_trigger').command('OFF') else: if (datetime.datetime.now().timestamp() > float(self.token_expiry)): self._refreshCredentials() def _generateCredentials(self): """ Generate access token for the API connection. """ if len(self.auth_code) > 15: # Request to exchange the authorization code with an access token headers = {'Authorization': 'Basic ' + self.auth_base64, 'content-type': 'application/x-www-form-urlencoded'} payload = 'grant_type=authorization_code&code=' + self.auth_code + '&redirect_uri=' + REDIRECT_URL print("# Exchange the authorization code with an access token") try: r = requests.post(API_TOKEN_URL, headers=headers, params=payload) if (DEBUG): print(r.json()) except: print("# Token request failed") sys.exit() if list(r.json().keys())[0] == 'error_description': print('# Error get new token: ' + r.json()['error_description']) print('# Visit "' + REDIRECT_URL + '" to get a new authorization code.') sys.exit() resp = r.json() if(r.status_code == 200): access_token = resp['access_token'] refresh_token = resp['refresh_token'] expires_in = resp['expires_in'] # Set and Save the access token self.access_token = access_token self.refresh_token = refresh_token self.token_expiry = str(datetime.datetime.now().timestamp() + float(expires_in)) self.token_issued = datetime.datetime.now() self._saveCredentials() else: print('# Error get new token: ' + r.json()) sys.exit() else: print('# No Auth Code found in openHAB item!') def _refreshCredentials(self): """ If previous access token expired, get a new one with refresh token. """ # Send OAuth2 payload to get access_token headers = {'Authorization': 'Basic ' + self.auth_base64, 'content-type': 'application/x-www-form-urlencoded'} payload = 'grant_type=refresh_token&refresh_token=' + self.refresh_token print("# The access token has expired, use the refresh token to get a new one.") try: r = requests.post(API_TOKEN_URL, headers=headers, params=payload) resp = r.json() if (DEBUG): print(resp) if(r.status_code == 200): access_token = resp['access_token'] expires_in = resp['expires_in'] if('refresh_token' in resp): refresh_token = resp['refresh_token'] self.refresh_token = refresh_token # Set and Save the access token self.access_token = access_token self.token_expiry = str(datetime.datetime.now().timestamp() + float(expires_in)) self.token_issued = datetime.datetime.now() self._saveCredentials() else: print('# Error get new token: ' + r.json()) except: print('# Error refreshing token:' + str(sys.exc_info()[1])) def _saveCredentials(self): """ Save the new token data to openHAB. """ self.oh.get_item(ITEM_PREFIX + 'access_token').command(self.access_token) self.oh.get_item(ITEM_PREFIX + 'refresh_token').command(self.refresh_token) self.oh.get_item(ITEM_PREFIX + 'token_expiry').command(self.token_expiry) self.oh.get_item(ITEM_PREFIX + 'token_issued').command(self.token_issued) def _helper_data_switch(self, switch): """ Translate Mercedes Benz API values to openHAB switch item definition. "true"="ON", "false"="OFF". """ if switch == 'true': return 'ON' else: return 'OFF' def _helper_data_contact(self, contact): """ Translate Mercedes Benz API values to openHAB contact item definition. "true"="OPEN", "false"="CLOSED". """ if contact == 'true': return 'OPEN' else: return 'CLOSED' def _helper_data_number(self, number): """ Translate Mercedes Benz API values to openHAB number item definition. Check for float or int value. """ if '.' in str(number): return float(number) else: return int(number) def _helper_oh_switch_state(self, switch): """ Check the state of an openhab switch item and return True or False. """ if switch == 'ON': return True else: return False def call(self): """ Call the available resources of the API's and check for data. """ print('# Mercedes Benz API connection successfully established!') print('# Searching resources for selected scopes:') url = API_DATA_URL + self.vehicle_id + '/resources' headers = {'accept': 'application/json;charset=utf-8', 'authorization': 'Bearer ' + self.access_token} r = requests.get(url, headers=headers) if(r.status_code < 200 and r.status_code > 299): if (DEBUG): print('# Response Code = ' + str(r.status_code)) if (DEBUG): print(r.content) print('# Error: ' + r.content) sys.exit() if r.status_code == 200: for resources in range(len(r.json())): self._get_endpoint(r.json()[resources]['href']) else: print('# Response Error') sys.exit() print('# All available data has been sent to openHAB!') self._done() def _transform_data(self, data): """ Check the underlying openHAB item, transform the value to match it and send the value to openHAB. Args: data (dict): requested endpoint data """ key = list(data.keys())[0] value_raw = data[key]['value'] ts = data[key]['timestamp'] item_value = self.oh.get_item(ITEM_PREFIX + 'data_' + key) if 'Switch' in str(item_value): value = self._helper_data_switch(value_raw) elif 'Contact' in str(item_value): value = self._helper_data_contact(value_raw) elif 'Number' in str(item_value): value = self._helper_data_number(value_raw) elif 'String' in str(item_value): value = value_raw else: print('# Error: ' + data) return item_value.update(value) try: item_ts = self.oh.get_item(ITEM_PREFIX + 'data_' + key + '_ts') item_ts.update(datetime.datetime.utcfromtimestamp(ts / 1000)) ts_text = 'and' except: ts_text = 'without' print('# Update data "' + key + '" with value "' + str(value) + '" ' + ts_text + ' timestamp "' + str(datetime.datetime.utcfromtimestamp(ts / 1000)) + '" to openHAB item "' + ITEM_PREFIX + 'data_' + key + '".') def _get_endpoint(self, endpoint): """ Retrieve the individual resources and extract the data. Args: endpoint (dict): a single endpoint from the resources dict Returns: [dict]: requested entpoint whit name, value, timestamp """ if (DEBUG): print('# try Call Endpoint') url = API_DATA_URL + endpoint[10:] headers = {'accept': 'application/json;charset=utf-8', 'authorization': 'Bearer ' + self.access_token} r = requests.get(url, headers=headers) if(r.status_code < 200 and r.status_code > 204): print('# Response Code = ' + str(r.status_code)) if (DEBUG): print(r.content) if (DEBUG): print('# Error') return str(r.reason) if r.status_code == 200: if (DEBUG): print(r.json()) self._transform_data(r.json()) return r.json() if r.status_code == 204: print('# No data available for "' + endpoint.split('/')[-1] + '".') else: if (DEBUG): print(r) if (DEBUG): print('# Error') return str(r.reason) def get_images(self): """ Retrieve the available resources of the image api. """ print('# Mercedes Benz API connection successfully established!') def confirm_prompt(question: str) -> bool: reply = None while reply not in ("y", "n"): reply = input(f"{question} (y/n): ").lower() if reply.lower() == 'n': print('# Cancel image download!') sys.exit() if reply.lower() == 'y': return reply = confirm_prompt("# There is a call limit of 5 for the vehicle image trail. Confirm?") if self.api_key is None: print('# No API KEY found. Please fill the openHAB item "' + ITEM_PREFIX + 'api_key" with data.') sys.exit() print('# Searching image resources') url = API_IMAGE_URL + 'vehicles/' + self.vehicle_id + '?roofOpen=' + str(self._helper_oh_switch_state(self.imageoption_roofOpen)).lower() + '&night=' + str(self._helper_oh_switch_state(self.imageoption_night)).lower() + '&background=' + str(self._helper_oh_switch_state(self.imageoption_background)).lower() + '&cropped=' + str(self._helper_oh_switch_state(self.imageoption_cropped)).lower() + '&jpeg=' + str(self._helper_oh_switch_state(self.imageoption_jpeg)).lower() + '&apikey=' + self.api_key headers = {'accept': 'application/json;charset=utf-8'} r = requests.get(url, headers=headers) if(r.status_code < 200 and r.status_code > 299): if (DEBUG): print('# Response Code = ' + str(r.status_code)) if (DEBUG): print(r.content) print('# Error: ' + r.content) sys.exit() if r.status_code == 200: img_counter = 0 print('Found ' + str(len(r.json())) + ' image IDs') print('Start downloading') for key, value in r.json().items(): self._download_images(key,value) img_counter += 1 print('# Image ' + key + ' (' + str(img_counter) + ' of ' + str(len(r.json())) + ') downloaded successfully') print('the default location of your vehicle images are: "openHAB conf directory"/html/mb-connect/vehicle_images/') else: print('# Response Error') print('# Response Code = ' + str(r.status_code)) print('# Response Text = ' + str(r.text)) sys.exit() def _download_images(self, imageName, imageId): """ Download the received images. """ url = API_IMAGE_URL + 'images/' + imageId + '?apikey=' + self.api_key headers = {'accept': 'image/png'} r = requests.get(url, headers=headers) if(r.status_code < 200 and r.status_code > 299): if (DEBUG): print('# Response Code = ' + str(r.status_code)) if (DEBUG): print(r.text) print('# Error: ' + r.text) sys.exit() if r.status_code == 200: if self._helper_oh_switch_state(self.imageoption_roofOpen): img_option_roof = '_roofOpen' else: img_option_roof = '' if self._helper_oh_switch_state(self.imageoption_night): img_option_night = '_night' else: img_option_night = '' if self._helper_oh_switch_state(self.imageoption_background): img_option_background = '_background' else: img_option_background = '' if self._helper_oh_switch_state(self.imageoption_cropped): img_option_cropped = '_cropped' else: img_option_cropped = '' if self._helper_oh_switch_state(self.imageoption_jpeg): img_option_fileFormat = '.jpeg' else: img_option_fileFormat = '.png' with open(IMAGEPATH + IMAGNAME_PREFIX + imageName + img_option_roof + img_option_night + img_option_background + img_option_cropped + img_option_fileFormat, 'wb') as f: f.write(r.content) else: print('# Response Error') print('# Response Code = ' + str(r.status_code)) print('# Response Text = ' + str(r.text)) sys.exit() def _done(self): self.oh.get_item(ITEM_PREFIX + 'lastConnectionDateTime').command(datetime.datetime.now())
class OpenHABServer: """Get a handle to the OpenHAB Server""" def __init__(self, ip_addr, port, light_base): """ :param ip_addr: <string> :param port: <number> :param light_base: <string> base code for OpenHAB Thing that all of its items share. # TODO: Trim out the obv """ self._raw_base = light_base self._openhab = None self._is_open = None self._light_base = _base_transform(light_base) self._light_color_name = self._light_base + COLOR_NAME_ATTR self.color_name_item = None self.ip_addr = ip_addr self.port = port def __enter__(self): """ Dunder for context management open :return self: """ self.open() return self def __exit__(self, exc_type=None, exc_value=None, traceback=None): """ Dunder for context management close """ self.close(exc_type, exc_value, traceback) def open(self): """ Open the connection. # TODO: Not sure how long it can stay open yet. """ if self._is_open: log_.warning("Already Open!") else: log_.info("Opening connection to the OpenHAB Server.") log_.debug(" at %s:%s", self.ip_addr, self.port) server_path = SERVER_FORMAT(ip_addr=self.ip_addr, port=self.port) self._openhab = OpenHAB(server_path) self.color_name_item = self._openhab.get_item(self._light_color_name) self._is_open = True def close(self, exc_type=None, exc_value=None, traceback=None): """ Close the connection down. """ if self._is_open: log_.debug("Closing connection to the OpenHAB Server") self._is_open = False else: log_.warning("Already Closed!") log_.error( "Passing exception data: %s, %s, %s.", exc_type, exc_value, traceback ) def change_light_color(self, color): """ Post an update to the light. :param color: <string> """ # TODO: Hysteresis? Do we need this? log_.info("Posting update to Light") log_.debug(" color: %s", color) self.color_name_item.command(color)