예제 #1
0
    def test_validate_api(self):
        """ Test Python API validate_api. """
        self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api))

        self.assertEqual(remote.APIStatus.INVALID_PASSWORD,
                         remote.validate_api(
                             remote.API("127.0.0.1", API_PASSWORD + "A")))
예제 #2
0
    def __init__(self, ha_ip, ha_passw, tg_token):
        self.alive = True
        self.bot = telegram.Bot(token=tg_token)
        self.api = remote.API(ha_ip, ha_passw)

        try:
            remote.validate_api(self.api)
            self.bot.getMe()
        except:
            self.teardown()

        try:
            self.last_update_id = self.bot.getUpdates()[-1].update_id
        except IndexError:
            self.last_update_id = None
        #except telegram.TelegramError:
        #self.last_update_id = None
        self.sensors = self.get_homeassistant_sensors()

        # access control
        self.trusted_users = []
        self.admins = []
        self.token = ''.join(
            random.choice(string.ascii_lowercase + string.ascii_uppercase +
                          string.digits) for x in range(10))
예제 #3
0
    def test_validate_api(self):
        """ Test Python API validate_api. """
        self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api))

        self.assertEqual(
            remote.APIStatus.INVALID_PASSWORD,
            remote.validate_api(remote.API("127.0.0.1", API_PASSWORD + "A")))
예제 #4
0
    def test_validate_api(self):
        """Test Python API validate_api."""
        self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api))

        self.assertEqual(
            remote.APIStatus.INVALID_PASSWORD,
            remote.validate_api(remote.API("127.0.0.1", API_PASSWORD + "A", MASTER_PORT)),
        )

        self.assertEqual(remote.APIStatus.CANNOT_CONNECT, remote.validate_api(broken_api))
    def test_validate_api(self):
        """Test Python API validate_api."""
        self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api))

        self.assertEqual(
            remote.APIStatus.INVALID_PASSWORD,
            remote.validate_api(
                remote.API("127.0.0.1", API_PASSWORD + "A", MASTER_PORT)))

        self.assertEqual(remote.APIStatus.CANNOT_CONNECT,
                         remote.validate_api(broken_api))
예제 #6
0
 def connect(self):
     self.api = remote.API(self.host,
                           api_password=self.password,
                           port=self.port,
                           use_ssl=self.use_ssl)
     print('Connecting to Home Assistant instance...')
     print(remote.validate_api(self.api))
예제 #7
0
    def __init__(self, config, args):
        self.args = args
        self.nodes = Nodes()
        self.json = {'nodes': [], 'edges': []}

        self.haconf = homeassistant.config.load_yaml_config_file(config)

        self.directory = os.path.join(os.path.dirname(config), 'www')
        self.filename = 'z-wave-graph.json'

        # API connection necessities.
        api_password = None
        base_url = 'http://localhost'
        port = homeassistant.const.SERVER_PORT

        if self.haconf['http'] is not None and 'base_url' in self.haconf[
                'http']:
            base_url = self.haconf['http']['base_url']

        if self.haconf['http'] is not None and 'api_password' in self.haconf[
                'http']:
            api_password = str(self.haconf['http']['api_password'])

        # If the base_url ends with a port, then strip it and set the port.
        # remote.API adds the default port if port= is not set.
        m = re.match(r'(^.*)(:(\d+))$', base_url)
        if m:
            base_url = m.group(1)
            port = m.group(3)

        self.api = remote.API(base_url, api_password, port=port)
        if remote.validate_api(self.api).value != 'ok':
            print("Error, unable to connect to the API: %s" %
                  remote.validate_api(self.api))
            sys.exit(1)

        self._get_entities()

        if self.args.debug:
            self.dump_nodes()

        self._build_dot()
예제 #8
0
def cli(ctx, verbose, host, password, ssl, port):
    """A command line interface for Home Assistant."""
    import requests

    ctx.verbose = verbose
    ctx.password = password
    ctx.ssl = ssl
    if host is not None:
        ctx.host = host
    if port is not None:
        ctx.port = port        
    ctx.api = remote.API(ctx.host, ctx.password, ctx.port, ctx.ssl)
    if str(remote.validate_api(ctx.api)) == 'invalid_password':
        ctx.log("Your API password for %s was not provided or is wrong. "
                "Use '--password/-p'", ctx.host)
        sys.exit(1)
예제 #9
0
ha_url = config['ha_url']
ha_key = config['ha_key']
ha_port = config['ha_port']
ha_ssl = config['ha_ssl']
ha_alarm_entity = config['ha_alarm_entity']
ha_alarm_code = config['ha_alarm_code']
bot_token = config['bot_token']
allowed_chat_ids = config['allowed_chat_ids']
fav_entities = config['fav_entities']
fav_entities = fav_entities.split()
show_maps = config['show_maps']

# instance the API connection to HASS
api = remote.API(ha_url, ha_key, ha_port, ha_ssl)
print(remote.validate_api(api))

# this prints out all the HASS services - mostly here for testing atm
print('-- Available Domains/Services:')
services = remote.get_services(api)
for service in services:
    print(service['domain'])
    print(service['services'])

# instance the Telegram bot
bot = telepot.Bot(bot_token)

# calls the HASS API to get the state of an entity
# need to change this so you can pass in entity type so we can get the right attributes for display
def get_state (entity_id, readable):
  print(entity_id)
예제 #10
0
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("/fireplace/exahust")


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    global currentTemp, newData
    print(msg.topic + " " + str(msg.payload))
    currentTemp = float(msg.payload)
    newData = True


api = remote.API(hiddenFields.HASSServer, hiddenFields.HASSPassword)
print(remote.validate_api(api))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(hiddenFields.MQTTServer, 1883, 60)

# Loop printing measurements every second.
print('Press Ctrl-C to quit.')
while True:
    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.
    if (newData):
예제 #11
0
def main():
	whereami = os.path.dirname(os.path.realpath(__file__))
	# Parse arguments
	p = argparse.ArgumentParser(description="A pygame GUI for Home Assistant.")
	p_config = p.add_argument_group('Configuration')
	p_config.add_argument('-c','--config',help="config file to use",required=True,type=argparse.FileType('r'))
	p_config.add_argument('-f','--framebuffer',help="Use this framebuffer as output for the UI (defaults to window mode)",
												default=None,type=str,metavar="/dev/fbX")
	p_config.add_argument('-t','--touchscreen',help="Enable touchscreen integration. Use this as event input",
												default=None,type=str,metavar="/dev/input/eventX")
	p_config.add_argument('-n','--no-display',help="We don't have a display. Sets the SDL_VIDEODRIVER to \"dummy\". Usefull for testing",dest="dummy",action="store_true",
												default=False)
	p_homeassistant = p.add_argument_group('HomeAssistant'," (optional) Parameters to override the config file")
	p_homeassistant.add_argument('-H','--homeassistant',default=None,help="The location of home-assistant",metavar="host.name")
	p_homeassistant.add_argument('-p','--port',default=None,help="the port to use for home-assistant (default: 8123)",type=int)
	p_homeassistant.add_argument('-k','--key',default=None,help="The api password to use (default: None)",type=str)
	p_homeassistant.add_argument('-s','--ssl',help="Use ssl (default false)",default=False,action="store_true")
	p_logging = p.add_argument_group('Logging'," (optional) Logging settings")
	p_logging.add_argument('-v','--verbose',help="Log output",default=False,action="store_true")
	p_logging.add_argument('-L','--logLevel',dest="logLevel",help="Log level to use (default: ERROR)",choices=["INFO","WARNING","ERROR","CRITICAL","DEBUG"],default="ERROR",type=str)
	p_logging.add_argument('-l','--logfile',help="Instead of logging to stdout, log to this file",default=None)
	args = p.parse_args();
	
	
	# Setup logger
	logFormatter = logging.Formatter("%(asctime)s [%(threadName)s:%(name)s] [%(levelname)-5.5s]  %(message)s")
	log = logging.getLogger("HUD")
	log.setLevel(getattr(logging, args.logLevel.upper()))
	if args.verbose:
		if not args.logfile:
			consoleHandler = logging.StreamHandler(sys.stdout)
			consoleHandler.setFormatter(logFormatter)
			log.addHandler(consoleHandler)
		else:
			fileHandler = logging.FileHandler(str(args.logfile))
			fileHandler.setFormatter(logFormatter)
			log.addHandler(fileHandler)
	# Setup Home assistant config
	log.info("Startup: Load config")
	config = configparser.ConfigParser()
	config.read(args.config.name)
	print((config.sections()))
	try:
		haconfig = {
			"host" : (args.homeassistant if args.homeassistant else config["HomeAssistant"]["Host"]),
			"port" : (args.port if args.port else config["HomeAssistant"]["Port"]),
			"ssl" : (args.ssl if args.ssl else config["HomeAssistant"]["SSL"]),
			"key": (args.key if args.key else config["HomeAssistant"]["Password"])
		}
	except KeyError as e:
		log.error("Cannot find section [{}] in config file '{}'!".format(str(e),str(args.config.name)))
		exit(1)
	
	# Setup home assistant connection
	log.info("Startup: Create EventHandler")
	hass = remote.API(haconfig['host'],haconfig['key'],haconfig['port'],haconfig['ssl'])
	HAE = HAEventHandler(hass,settings=haconfig)
	try:
		validation = remote.validate_api(hass)
		if str(validation) != "ok":
			log.info("Startup: Successfully connected to HomeAssistant!")
			raise Exception(validation)
	
	except Exception as e:
		log.error("hass connection verification failed: {}".format(str(validation)))
		exit(1)
	
	log.info("Startup: Setting screen")
	if args.framebuffer:
		log.info("Startup: Setting framebuffer")
		os.putenv('SDL_VIDEODRIVER', 'fbcon')
		os.putenv('SDL_FBDEV'      , args.framebuffer)
	if args.touchscreen:
		log.info("Startup: Setting up touchscreen support")
		os.putenv('SDL_MOUSEDRV'   , 'TSLIB')
		os.putenv('SDL_MOUSEDEV' , args.touchscreen)
	if args.dummy:
		os.putenv('SDL_VIDEODRIVER', 'dummy')
	if args.framebuffer:
		pygame_opts = FULLSCREEN | HWSURFACE | DOUBLEBUF
		#                         ^UNTESTED!^
	else:
		pygame_opts = SWSURFACE
	screen = pygame.display.set_mode((320,480),pygame_opts)
	
	if args.touchscreen:
		## Hide the mouse cursor if we have a touchscreen
		pygame.mouse.set_visible(False)
	
	
	log.info("Startup: Load Theme")
	app = gui.Desktop(theme=gui.Theme(whereami+"/pgu.theme"))
	app.connect(gui.QUIT,app.quit,None)
	
	container=gui.Table(width=230,vpadding=0, hpadding=0)
	
	for section in config.sections():
		if section != "HomeAssistant":
			log.info("Startup: Loading section {}".format(str(section)))
			c = container
			c.tr()
			state = remote.get_state(hass,"group.{}".format(str(config[section]["group"])))
			header = elements.rowHeader(hass,state,table=c)
			HAE.add_listener(state.entity_id,header.set_hass_event)
			c.td(header.draw(),align=-1)
			c.tr()
			if state == None:
				log.warning("Startup: Unable to find group.{}".format(str(config[section]["group"])))
				c.td(gui.Label("Startup: Unable to find group.{}".format(str(config[section]["group"]))))
			else:
				log.info("Startup: Fetching entity statusses")
				# get all states from entities & add to the list if entity is not None (eg. not found)
				entities =  [e for e in [remote.get_state(hass,eid) for eid in state.attributes['entity_id']] if e != None]
				for entity in entities:
					log.info("Startup: Loading entity {}".format(entity.entity_id))
					# Changeable, lights are hmmMMmmm
					if (entity.domain == "light"):
						row = elements.rowLight(hass,entity,last=(True if entity == entities[-1] else False),table=c)
						log.info("Startup: Adding Event listener for {}".format(entity.entity_id))
						HAE.add_listener(entity.entity_id,row.set_hass_event)
						 #row.draw()
						c.td(row.draw(),align=-1)
					elif (entity.domain in ('sensor','device_tracker')):
						# widget = gui.Label("{} : {}".format(str(entity.name),str(entity.state)))
						# c.td(widget)
						row = elements.rowSensor(hass,entity,last=(True if entity == entities[-1] else False))
						log.info("Startup: Adding Event listener for {}".format(entity.entity_id))
						HAE.add_listener(entity.entity_id,row.set_hass_event)
						c.td(row.draw(),align=-1)
					c.tr()
	
			container.td(gui.Spacer(height=4,width=320))
	log.info("Startup: Load elements onto surface")
	main = gui.Container(width=320,height=480)
	header = elements.Header("Home Assistant",width=320,height=40)
	
	
	main.add(header,0,0)
	main.add(container,0,60)
	
	# Start the EventDaemon
	log.info("Startup: start HAEventHandler")
	HAE.start()
	RunPlease = True
	while RunPlease:
		try:
			log.info("Start screen")
			app.run(main,screen=screen )
		except (KeyboardInterrupt, SystemExit):
			log.warning("Got Exit or Ctrl-C. Stopping.")
			RunPlease = False
			pass
		except AttributeError as e:
			log.error("AttributeError, restarting")
			pass
	
	HAE.stop()
	sys.exit(0)
예제 #12
0
    def __init__(self, port, hasshost, password, haport, ssl, retrycount,
                 waittime):
        self._port = port
        self._hasshost = hasshost
        self._password = password
        self._haport = haport
        self._ssl = ssl
        self._retrycount = retrycount
        self._waittime = waittime
        msg = "Sleeping to give Home Assistant a moment to start"
        _LOGGER.info(msg)
        print(msg)
        time.sleep(waittime)
        try:
            validationresult = "init"
            numretries = 0
            while validationresult != "ok" and numretries <= self._retrycount:
                self._api = remote.API(self._hasshost, self._password,
                                       self._haport, self._ssl)
                validationresult = str(remote.validate_api(self._api))
                numretries = numretries + 1
                if validationresult != "ok":
                    msg = "Connecting to Home Assistant failed, "
                    msg = msg + "retrying..."
                    _LOGGER.info(msg)
                    print(msg)
                    time.sleep(5)
            if validationresult != "ok":
                msg = "Error connection to Home Assistant: "
                msg = msg + validationresult
                _LOGGER.error(msg)
                print(msg)
                sys.exit(2)
            else:
                msg = "Succesfully connected to Home Assistant"
                print(msg)
                _LOGGER.info(msg)
        except:
            e = sys.exc_info()[0]
            msg = "Error connecting to Home Assistant: "
            msg = msg + str(e) + ", please check settings."
            print(msg)
            _LOGGER.error(msg)
            sys.exit(2)
        listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            listen_socket.bind(('', self._port))
            listen_socket.listen(1)
        except:
            msg = "Permission error, make sure to run "
            msg = msg + "this as root or in sudo mode"
            print(msg)
            _LOGGER.error(msg)
            sys.exit(2)
        msg = "EgardiaServer listening on port " + str(port)
        _LOGGER.info(msg)
        print(msg)
        self._status = ""
        while True:
            client_connection, client_address = listen_socket.accept()
            request = client_connection.recv(1024)

            http_response = """\
HTTP/1.1 200 OK

Hello, World!
"""
            requestdecoded = request.decode('utf8')
            if requestdecoded.startswith("["):
                newstatus = requestdecoded[requestdecoded.index(' ') + 1:]
                newstatus = newstatus[:len(newstatus) - 1]
                msg = "[" + str(datetime.datetime.now()) + "] Received new "
                msg = msg + "statuscode from alarm system: " + newstatus
                _LOGGER.info(msg)
                print(msg)
                if newstatus != self._status:
                    self._status = newstatus
                    payload = {"status": self._status}
                    try:
                        remote.fire_event(self._api,
                                          'egardia_system_status',
                                          data=payload)
                        msg = "egardia_system_status event fired with payload: "
                        msg = msg + str(payload)
                        _LOGGER.info(msg)
                        print(msg)
                    except:
                        e = sys.exc_info()[0]
                        msg = "Could not fire event, is your "
                        msg = msg + "HASS server running?"
                        _LOGGER.error(msg)
                        print(msg)
                        _LOGGER.error(str(e))
                        print(str(e))
            client_connection.sendall(http_response.encode('utf8'))
            client_connection.close()
예제 #13
0
    config = configparser.ConfigParser()
    home_dir = os.path.expanduser('~')
    configfile = os.path.join(home_dir, '.telehome/config.txt')
    if not os.path.exists(configfile):
        raise Exception('Expected configuration file: ' + configfile)
    config.read(configfile)
    return config

config = _read_config()
hass_ip = config['homeAssistant']['ip']
hass_pass = config['homeAssistant']['password']
hass_port = config['homeAssistant']['port']
hass_ssl = config.getboolean('homeAssistant', 'ssl')

api = remote.API(hass_ip, hass_pass, port = hass_port, use_ssl = hass_ssl)
status = remote.validate_api(api)
if status.value != 'ok':
    pprint(status)
    exit();

telegram_bot_id = config['telegram']['botKey']
telegram_chat_whitelist = [int(config['telegram']['chatIdWhitelist'])]

print('Configured with hass_ip=%s bot_id=%s allowed_chat=%s' % (hass_ip, telegram_bot_id, telegram_chat_whitelist))
bot = telepot.Bot(telegram_bot_id)
if status != remote.APIStatus.OK:
    print('Failed to connect to home assistant')
    exit()

print ('starting loop')
bot.message_loop(handle)