Example #1
0
def inject_items(hermes):
    conf = read_configuration_file(CONFIG_INI)
    openhab = OpenHAB(conf['secret']['openhab_server_url'])
    openhab.load_items()
    items, locations = openhab.get_injections()

    hermes.request_injection(
        InjectionRequestMessage([
            AddFromVanillaInjectionRequest(dict(device=items, room=locations))
        ]))
Example #2
0
    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 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')
Example #4
0
    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 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)
Example #6
0
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')
Example #7
0
from openhab import OpenHAB
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()
Example #8
0
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')
Example #9
0
    openhab.send_command_to_devices(items, command)
    return True, response


if __name__ == "__main__":
    with Assistant() as a:
        a.add_callback(user_intent("switchDeviceOn"), switch_on_off_callback)
        a.add_callback(user_intent("switchDeviceOff"), switch_on_off_callback)

        a.add_callback(user_intent("getTemperature"), get_temperature_callback)

        a.add_callback(user_intent("increaseItem"), increase_decrease_callback)
        a.add_callback(user_intent("decreaseItem"), increase_decrease_callback)

        a.add_callback(user_intent("setValue"), set_value_callback)

        a.add_callback(user_intent("playMedia"), player_callback)
        a.add_callback(user_intent("pauseMedia"), player_callback)
        a.add_callback(user_intent("nextMedia"), player_callback)
        a.add_callback(user_intent("previousMedia"), player_callback)

        a.add_callback(user_intent("repeatLastMessage"), repeat_last_callback)

        a.add_callback(user_intent("whatDoYouKnowAbout"),
                       what_do_you_know_about_callback)

        openhab = OpenHAB(a.conf['secret']['openhab_server_url'])

        inject_items(a)
        a.start()
Example #10
0
def intent_callback(hermes, intent_message):
    intent_name = intent_message.intent.intent_name

    if intent_name not in (user_intent("switchDeviceOn"),
                           user_intent("switchDeviceOff"),
                           user_intent("getTemperature"),
                           user_intent("increaseItem"),
                           user_intent("decreaseItem"),
                           user_intent("setValue"), user_intent("playMedia"),
                           user_intent("pauseMedia"), user_intent("nextMedia"),
                           user_intent("previousMedia")):
        return

    conf = read_configuration_file(CONFIG_INI)
    openhab = OpenHAB(conf['secret']['openhab_server_url'])

    if intent_name in (user_intent("switchDeviceOn"),
                       user_intent("switchDeviceOff")):
        devices, room = get_items_and_room(intent_message)

        command = "ON" if intent_name == user_intent(
            "switchDeviceOn") else "OFF"

        if devices is None:
            hermes.publish_end_session(
                intent_message.session_id,
                UNKNOWN_DEVICE.format("einschalten" if command ==
                                      "ON" else "ausschalten"))
            return

        relevant_devices = openhab.get_relevant_items(devices,
                                                      room,
                                                      item_filter='or')

        # The user is allowed to ommit the room if the request matches exactly one device in the users home (e.g.
        # if there is only one tv) or if the request contains only devices of the current room
        if room is None and len(relevant_devices) > 1:
            print(
                "Request without room matched more than one item. Requesting again with current room."
            )

            room = get_room_for_current_site(
                intent_message, conf['secret']['room_of_device_default'])
            relevant_devices = openhab.get_relevant_items(devices,
                                                          room,
                                                          item_filter='or')

            if len(relevant_devices) == 0:
                hermes.publish_end_session(
                    intent_message.session_id,
                    "Deine Anfrage war nicht eindeutig genug")
                return

        if len(relevant_devices) == 0:
            hermes.publish_end_session(
                intent_message.session_id,
                "Ich habe kein Gerät gefunden, welches zu deiner Anfrage passt"
            )
            return

        openhab.send_command_to_devices(relevant_devices, command)
        result_sentence = generate_switch_result_sentence(
            relevant_devices, command)
        hermes.publish_end_session(intent_message.session_id, result_sentence)
    elif intent_name == user_intent("getTemperature"):
        # TODO: Generalize this case as get property

        if len(intent_message.slots.room) > 0:
            room = intent_message.slots.room.first().value
        else:
            room = get_room_for_current_site(
                intent_message, conf['secret']['room_of_device_default'])

        items = openhab.get_relevant_items(["temperatur", "messung"], room,
                                           "Number")

        if len(items) > 0:
            state = openhab.get_state(items[0])

            if state is None:
                hermes.publish_end_session(
                    intent_message.session_id,
                    UNKNOWN_TEMPERATURE.format(add_local_preposition(room)))
                return

            formatted_temperature = state.replace(".", ",")
            hermes.publish_end_session(
                intent_message.session_id,
                "Die Temperatur {} beträgt {} Grad.".format(
                    add_local_preposition(room), formatted_temperature))
        else:
            hermes.publish_end_session(
                intent_message.session_id,
                "Ich habe keinen Temperatursensor {} gefunden.".format(
                    add_local_preposition(room)))
    elif intent_name in (user_intent("increaseItem"),
                         user_intent("decreaseItem")):
        increase = intent_name == user_intent("increaseItem")

        if len(intent_message.slots.room) > 0:
            room = intent_message.slots.room.first().value
        else:
            room = get_room_for_current_site(
                intent_message, conf['secret']['room_of_device_default'])

        if len(intent_message.slots.property) == 0:
            hermes.publish_end_session(intent_message.session_id,
                                       UNKNOWN_PROPERTY)
            return

        device_property = intent_message.slots.property.first().value
        items = openhab.get_relevant_items([device_property, "sollwert"], room,
                                           "Dimmer")

        if len(items) > 0:
            openhab.send_command_to_devices(
                items, "INCREASE" if increase else "DECREASE")
            hermes.publish_end_session(
                intent_message.session_id, "Ich habe {} {} {}".format(
                    gd.get(device_property, Case.ACCUSATIVE),
                    add_local_preposition(room),
                    "erhöht" if increase else "verringert"))
        elif device_property == "Helligkeit":
            items = openhab.get_relevant_items("Licht", room, "Switch")

            if len(items) > 0:
                openhab.send_command_to_devices(items,
                                                "ON" if increase else "OFF")
                hermes.publish_end_session(
                    intent_message.session_id,
                    "Ich habe die Beleuchtung {} {}.".format(
                        add_local_preposition(room),
                        "eingeschaltet" if increase else "ausgeschaltet"))
        elif device_property == "Temperatur":
            items = openhab.get_relevant_items([device_property, "sollwert"],
                                               room, "Number")

            if len(items) > 0:
                temperature = float(openhab.get_state(items[0]))
                temperature = temperature + (1 if increase else -1)
                openhab.send_command_to_devices([items[0]], str(temperature))
                hermes.publish_end_session(
                    intent_message.session_id,
                    "Ich habe die gewünschte Temperatur {} auf {} Grad eingestellt"
                    .format(add_local_preposition(room), temperature))

        if len(items) == 0:
            hermes.publish_end_session(
                intent_message.session_id,
                "Ich habe keine Möglichkeit gefunden, um {} {} zu {}".format(
                    gd.get(device_property, Case.ACCUSATIVE),
                    add_local_preposition(room),
                    "erhöhen" if increase else "verringern"))
    elif intent_name == user_intent("setValue"):
        hermes.publish_end_session(intent_message.session_id,
                                   FEATURE_NOT_IMPLEMENTED)
    elif intent_name in [
            user_intent("playMedia"),
            user_intent("pauseMedia"),
            user_intent("nextMedia"),
            user_intent("previousMedia")
    ]:
        if len(intent_message.slots.room) > 0:
            room = intent_message.slots.room.first().value
        else:
            room = get_room_for_current_site(
                intent_message, conf['secret']['room_of_device_default'])

        items = openhab.get_relevant_items("fernbedienung", room, "Player")

        if len(items) == 0:
            hermes.publish_end_session(
                intent_message.session_id,
                "Ich habe kein Gerät gefunden, auf dem die Wiedergabe geändert werden kann."
            )
            return

        if intent_name == user_intent("playMedia"):
            command = "PLAY"
            response = "Ich habe die Wiedergabe {} fortgesetzt".format(
                add_local_preposition(room))
        elif intent_name == user_intent("pauseMedia"):
            command = "PAUSE"
            response = "Ich habe die Wiedergabe {} pausiert".format(
                add_local_preposition(room))
        elif intent_name == user_intent("nextMedia"):
            command = "NEXT"
            response = "Die aktuelle Wiedergabe wird im {} übersprungen".format(
                add_local_preposition(room))
        else:
            command = "PREVIOUS"
            response = "Im {} geht es zurück zur vorherigen Wiedergabe".format(
                add_local_preposition(room))

        openhab.send_command_to_devices(items, command)
        hermes.publish_end_session(intent_message.session_id, response)