Esempio n. 1
0
    def test_get_state(self):
        """Test Python API get_state."""
        self.assertEqual(
            hass.states.get('test.test'),
            remote.get_state(master_api, 'test.test'))

        self.assertEqual(None, remote.get_state(broken_api, 'test.test'))
Esempio n. 2
0
def getalldoorstatus():
	frontdoor =  remote.get_state(api, 'sensor.frontdoor')
	backdoor =  remote.get_state(api, 'sensor.backdoor')
	sidedoor =  remote.get_state(api, 'sensor.sidedoor')
	msg = "yes"
       	
	doorlist = {"front":frontdoor.state ,"back": backdoor.state,"side": sidedoor.state}
	if doorlist["back"] == doorlist["front"] == doorlist["side"] == 'Open':
		return('OPEN')
	elif doorlist["back"] == doorlist["front"] == doorlist["side"] == 'Closed':
		return('CLOSE')
	else:
			
		if(doorlist["back"] == "Open"):
			msg =  " back"
		if(doorlist["front"] == "Open"):
			if(msg == "yes"):
				msg = "front"
			else:
				msg = msg +  "  and front"
		if(doorlist["side"] == "Open"):
			if(msg == "yes"):
				msg =  "side"
			else:
				msg = msg +  " and side"
		if(msg == "yes"):
			msg = "No"				
				

		return(msg)
Esempio n. 3
0
def checkHAStatus():
    #check if lecture status has changed, send update to telegram bot so it can react accordingly
    global lastLectureValue, breakAlert
    textlist = []
    lectureValue = remote.get_state(api, "input_boolean.breakrequest").state
    if lectureValue == lastLectureValue:
        pass
    else:
        if lectureValue == "on":
            lastLectureValue = lectureValue
            breakAlert = 0
            textlist.append('lectureStart')
        else:
            lastLectureValue = lectureValue
            textlist.append('lectureStop')
    #check if break score has exceeded limit, send update to telegram bot so it can notify users
    breakScore = int(remote.get_state(api, "sensor.breakscore").state)
    if breakScore < 100:
        breakAlert = 0
        pass
    elif breakScore > 100 and breakScore < 150:
        if breakAlert == 0:
            breakAlert = 1
            textlist.append('breakAlert')
    else:
        if breakAlert == 1:
            breakAlert = 2
            textlist.append('breakAlert')
        else:
            pass
    return textlist
Esempio n. 4
0
    def test_get_state(self):
        """ Test Python API get_state. """

        self.assertEqual(hass.states.get('test.test'),
                         remote.get_state(master_api, 'test.test'))

        self.assertEqual(None, remote.get_state(broken_api, 'test.test'))
Esempio n. 5
0
def checkHAStatus():
    #check if lecture status has changed, send update to telegram bot so it can react accordingly
    value = remote.get_state(
        api, XXX
    )  #replace by ID of lecture button - evtl oben id wie bei sensoren setzen(!)
    if response['state'] == response1:
        pass
    else:
        if response['state'] == "on":
            return 'lectureStop'
            break_requests.clear()
            al1 = 0
        else:
            return 'lectureStart'
        response1 = response['state']
    #check if break score has exceeded limit, send update to telegram bot so it can notify users
    value = remote.get_state(
        api, XXX
    )  #replace by ID of break score - evtl oben id wie bei sensoren setzen(!)
    if response['state'] < 100:
        pass
    else:
        if al1 == 0:
            al1 = 1
            return 'breakAlert'
        else:
            pass
Esempio n. 6
0
def getdoorstatus(door_name):
	door = {
		'front': remote.get_state(api, 'sensor.frontdoor'),
		'back' : remote.get_state(api, 'sensor.backdoor'),
		'side' : remote.get_state(api, 'sensor.sidedoor') 
	
		}
	
	return (door.get(door_name).state)
Esempio n. 7
0
    async def hass(self, task: str):
        """Other HASS Commands"""
        if task == 'help':
            await self.bot.say(
                "**Home Assistant Bot!**\n\n**The commands are:**\n\n**[p]hass help** - Print this Help\n**[p]hass climate** - output climate infromations\n**[p]hass lights** - output state of all lights\n**[p]on** - Turn on a light\n**[p]off** - Turn off a light"
            )
        elif task == 'climate':
            ent = remote.get_state(api, 'group.climate')
            entstr = '{}'.format(ent)
            # regex help provided by Python help discord server
            ents = re.findall(r"\W(s[e,u].[^']+)", entstr)
            embed = discord.Embed(title="HASS climate",
                                  url=url,
                                  description="Climate at home",
                                  color=3447003)
            for i in ents:
                climate = remote.get_state(api, '{}'.format(i))
                try:
                    embed.add_field(
                        name='{}'.format(climate.name),
                        value='{} {}'.format(
                            climate.state,
                            climate.attributes['unit_of_measurement']),
                        inline=False)
                except:
                    break
            embed.set_footer(text="HASS")
            await self.bot.say(embed=embed)
        elif task == 'lights':
            ent = remote.get_state(api, 'group.all_lights')
            entstr = '{}'.format(ent)
            # regex help provided by Python help discord server
            ents = re.findall(r"\W(light\.[^']+)", entstr)
            embed = discord.Embed(title="HASS lights",
                                  url=url,
                                  description="Lights at home",
                                  color=3447003)
            for i in ents:
                lights = remote.get_state(api, '{}'.format(i))
                try:
                    # zero width char to to get around lack of support for no value field
                    embed.add_field(name='{} {}'.format(
                        lights.name, lights.state),
                                    value='\u200b',
                                    inline=False)
                except:
                    break
            embed.set_footer(text="HASS")
            await self.bot.say(embed=embed)

        else:
            await self.bot.say(
                "**Home Assistant Bot!**\n\n**The commands are:**\n\n**[p]hass help** - Print this Help\n**[p]hass climate** - output climate infromations\n**[p]hass lights** - output state of all lights\n**[p]on** - Turn on a light\n**[p]off** - Turn off a light"
            )
Esempio n. 8
0
def isdoorsopen():
  frontdoor =  remote.get_state(api, 'sensor.frontdoor')
  backdoor =  remote.get_state(api, 'sensor.backdoor')
  sidedoor =  remote.get_state(api, 'sensor.sidedoor')
  print(frontdoor.state)
  doorstatus = [frontdoor.state, backdoor.state, sidedoor.state]
  	
  if doorstatus[0] == 'Closed' and doorstatus[1]  == 'Closed'  and  doorstatus[2] == 'Closed':
	  return('false')
  else:
	  return('true')	
Esempio n. 9
0
def get_state (entity_id):
  print(entity_id)
  entity = remote.get_state(api, entity_id)
  state = format('{} is {}.'.format(entity.attributes['friendly_name'], entity.state))

  print(state)
  return state
Esempio n. 10
0
 async def state(self, entity: str):
     """Get the state of a light"""
     try:
         domain = 'light'
         ent = remote.get_state(api, domain + '.{}'.format(entity))
         await self.bot.say('{} is {}.'.format(ent.name, ent.state))
     except:
         await self.bot.say("There was an error!")
Esempio n. 11
0
 def get_entity_states(self, entity_id):
     """
     获取设备状态
     :param entity_id:
     :return:
     """
     state_obj = remote.get_state(self._api, entity_id)
     return {'state': state_obj.state, 'attributes': state_obj.attributes}
Esempio n. 12
0
	def mute(self):
		#get the mute state of sonos, will be used in media_mute api.
		sonos_state = remote.get_state(api,'media_player.{0}'.format(self.device_name)) 
		mute_state  = "false" if sonos_state.attributes['is_volume_muted'] else "true"

		remote.call_service(api,'media_player','volume_mute',\
		{'entity_id':'media_player.{0}'.format(self.device_name),\
		"is_volume_muted":"{}".format(mute_state)})
Esempio n. 13
0
    def get_state(self, entity_id):
        # ./set_state.py set-state group.test_view unknown --entity_id=energy_asset.plant_dgf,switch.plant_dgf --view=true --order=3 --friendly_name='Test' --hidden='true'
        # ./set_state.py set-state energy_asset.xxxxxx not_assigned --lat=48.3 --lon=11 --status=_uninit --schedule=0,0 --max_flex=0,0 --min_flex=0,0

        self._print('Result', full=True)
        state = remote.get_state(api, entity_id)
        pprint(state.attributes)
        self._print('state', full=False)
        print(state.state)
Esempio n. 14
0
def get_state (entity_id, readable):
  print(entity_id)
  entity = remote.get_state(api, entity_id)
  if (readable == 'true'):
    state = format('{} is {}.'.format(entity.attributes['friendly_name'], entity.state))
  else:
    state = entity.state
  print(state)
  return state
Esempio n. 15
0
def send_location(chat_id, entity_id):
  entity = remote.get_state(api, entity_id)
  if (show_maps == 'true' and entity.state != 'home' and
      'latitude' in entity.attributes and
      'longitude' in entity.attributes):  
    latitude = float(entity.attributes['latitude'])
    longitude = float(entity.attributes['longitude'])

    bot.sendLocation(chat_id=chat_id,
                     latitude=latitude, longitude=longitude)
Esempio n. 16
0
    def update_state(self, entity_id, new_state=None, **kwargs):
        state = remote.get_state(api, entity_id)
        state.state = new_state or state.state
        attr = state.attributes.copy()
        for k, v in kwargs.items():
            attr[k] = v

        self._print('kwargs', full=True)
        pprint(kwargs)

        self._print('attr', full=False)
        pprint(attr)
        self._print('state', full=False)
        print(state.state)
        remote.set_state(api, entity_id, new_state=state.state, attributes=attr)

        self._print('Result', full=True)
        state = remote.get_state(api, entity_id)
        pprint(state.attributes)
        self._print('state', full=False)
        print(state.state)
Esempio n. 17
0
 def getStateAvg(self, api, list):
     i = 0
     sum = 0
     for list_item in list:
         value = remote.get_state(api, list_item)
         sum = sum + float(value.state)
         i = i + 1
     if (i > 0):
         avg = sum / i
     else:
         avg = 0
     return avg
Esempio n. 18
0
    def callback(self):

        if self.haevent.state == hasconst.STATE_OFF:
            status = remote.call_service(self.api, self.haevent.domain,
                                         'turn_on',
                                         {'entity_id': self.haevent.entity_id})
        else:
            status = remote.call_service(self.api, self.haevent.domain,
                                         'turn_off',
                                         {'entity_id': self.haevent.entity_id})

        # TODO: Fix time
        self.set_hass_event(remote.get_state(self.api, self.haevent.entity_id))
Esempio n. 19
0
    def set_state(self, e_id, new_state=None, **kwargs):
        # ./set_state.py set-state group.test_view unknown --entity_id=energy_asset.plant_dgf,switch.plant_dgf --view=true --order=3 --friendly_name='Test' --hidden='true'
        # ./set_state.py update-state energy_asset.plant_tw --min_flex=0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

        self._print('kwargs', full=False)
        pprint(kwargs)
        self._print('state', full=False)
        print(new_state)
        remote.set_state(api, e_id, new_state=new_state, attributes=kwargs)

        self._print('Result', full=True)
        state = remote.get_state(api, e_id)
        pprint(state.attributes)
        self._print('state', full=False)
        print(state.state)
Esempio n. 20
0
def handle_lights(args):
    if args == 'toggle':
        remote.call_service(api, DOMAIN_LIGHTS, 'toggle')
        return 'Toggled lights'
    if args == 'on':
        remote.call_service(api, DOMAIN_LIGHTS, 'turn_on')
        return 'Turned lights on'
    if args == 'off':
        remote.call_service(api, DOMAIN_LIGHTS, 'turn_off')
        return 'Turned lights off'

    light = 'light.made_lamp'
    lamp = remote.get_state(api, light)
    if args == '' or args == 'state':
        return 'Made Lamp is ' + lamp.state
    else:
        return 'Unknown command ' + args + '. Supported commands: state, on, off, toggle'
Esempio n. 21
0
def cli(ctx, entity, action, new_state, attributes):
    """Get, set or remove the state of entity."""
    import homeassistant.remote as remote

    if action == 'get':
        state = remote.get_state(ctx.api, entity)
        ctx.log('State of %s is %s', entity, state.state)

    if action == 'set':
        remote.set_state(ctx.api,
                         entity,
                         new_state,
                         attributes=json.loads(attributes))
        ctx.log('State of %s set to %s', entity, new_state)

    if action == 'remove':
        remote.remove_state(ctx.api, entity)
        ctx.log('Entitiy %s removed', entity)

    ctx.vlog('Entity: %s, Execute: %s', entity, timestamp())
Esempio n. 22
0
def gettemperature():
	temp = remote.get_state(api, 'sensor.philio_technology_corporation_pst02a_4_in_1_multisensor_temperature_16')
	return(temp.state)
Esempio n. 23
0
 def _check_powerpool(self):
     state = remote.get_state(self.API, 'group.all_powerpool')
     assert f"powerpool.{self.powerpool}" in state.attributes.get('entity_id', None), f"{self.powerpool} does not exist."
Esempio n. 24
0
    if alives > 3:
        return True

credentials = get_credentials()
api = remote.API(api_password=credentials['api_password'], port=443, use_ssl=True, host=credentials['host'])
previous = []
domain = 'light'
arguments = {
    "entity_id": 'light.desk',
    "color_temp": 375,
    "brightness": 107,
}

while True:
    alive = ping('192.168.0.60')
    desk = remote.get_state(api, 'light.desk')
    logger.debug('^^^^^^^^^^^')
    logger.debug("{previous} - {alive} - {state}".format(previous=previous, alive=alive, state=desk.state))

    if alive and desk.state == 'off':
        logger.info('alive and light is off, turning on')
        remote.call_service(api, domain, 'turn_on', arguments)
    if alive and desk.state == 'on':
        logger.debug('alive and light is on, pass')
        pass
    if not alive and desk.state == 'on':
        if just_died(previous):
            logger.info('just died and light is on, turning off')
            remote.call_service(api, domain, 'turn_off')
    if not alive and desk.state == 'off':
        logger.debug('not alive and light is off, pass')
Esempio n. 25
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)
Esempio n. 26
0
def getalaram() :
  Alaram = remote.get_state(api, 'alarm_control_panel.security_alarm')
  switch = {'armed_home': 'arm home', 'armed_away': 'arm away', 'disarmed': 'disarm'}
  
  return (switch.get(Alaram.state))
Esempio n. 27
0
 def get_state(self, entity_id):
     return remote.get_state(self.api, entity_id)
Esempio n. 28
0
#!/usr/bin/python3
import homeassistant.remote as remote
from sys import argv as argv
from sys import exit as exit
import yaml
from datetime import datetime as dt
from datetime import timedelta, timezone
from re import match

with open("/home/zgilburd/git/hass/app_config/secrets.yaml", "r") as stream:
    secrets = yaml.load(stream)

api = remote.API('127.0.0.1', secrets['http_password'])
yrno = remote.get_state(api, 'sensor.yr_symbol')
me = remote.get_state(api, 'sensor.command_sensor')
s = remote.get_state(api, 'sun.sun')
za = remote.get_state(api, 'device_tracker.zandra_v20')
zc = remote.get_state(api, 'device_tracker.zgilburd_zs8')
symb = yrno.as_dict()
sun = s.as_dict()
zandra = za.as_dict()
zack = zc.as_dict()
command = me.as_dict()

set_time = dt.strptime(
    sun['attributes']['next_setting'].replace("+00:00", "+0000"),
    '%Y-%m-%dT%H:%M:%S%z')

rise_time = dt.strptime(
    sun['attributes']['next_rising'].replace("+00:00", "+0000"),
    '%Y-%m-%dT%H:%M:%S%z')
Esempio n. 29
0
    def test_get_state(self):
        """ Test Python API get_state. """

        self.assertEqual(
            remote.get_state(self.api, 'test.test'),
            self.hass.states.get('test.test'))
api = remote.API(hiddenFields.HASSServer, hiddenFields.HASSPassword)

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('Entering Loop; Press Ctrl-C to quit.')
while True:

    if currentTemp < 135.0 and prevTemp >= 135.0:  #if before it was optimal, and now its sub optimal
        if messageSent == 0:
            print("State Tranisiton")
            messageSent = 1
            if remote.get_state(
                    api, 'switch.jordan_fireplace_monitor').state == 'on':
                client.publish(
                    outgoingSMSTopic + "JordanB",
                    "Fireplace has dropped below optimal temperature at " +
                    str(datetime.now()))
            if remote.get_state(
                    api, 'switch.brendan_fireplace_monitor').state == 'on':
                client.publish(
                    outgoingSMSTopic + "BrendanM",
                    "Fireplace has dropped below optimal temperature at " +
                    str(datetime.now()))
            if remote.get_state(api,
                                'switch.joel_fireplace_monitor').state == 'on':
                client.publish(
                    outgoingSMSTopic + "JoelD",
                    "Fireplace has dropped below optimal temperature at " +
Esempio n. 31
0
import requests

url = "http://pegasus.cs.moravian.edu:8080/api/wemo"  #Enter url here
api = remote.API('http://homeassistant.cs.moravian.edu:8123/states',
                 'raspberry')

#Infinitely check status every 10 seconds
prevState = 10
while True:
    tm = time.strftime('%Y-%m-%d %H:%M:%S',
                       time.localtime(time.time()))  #Get time
    day = tm[0:10]  #Separate day
    clock = tm[11:19]  #Separate time
    # Get status
    status = False
    switch = remote.get_state(api,
                              'switch.aeotec_zw096_smart_switch_6_switch_3_0')
    st = switch.state
    if st == "on":
        status = True
    status = str(status).lower()
    #Print values
    print('date', day)
    print('time', clock)
    print('status', status)
    if prevState != status:  #If updated status
        #Send to API
        r = requests.post(url,
                          data={
                              'date': day,
                              'time': clock,
                              'status': status.lower()
Esempio n. 32
0
def sendStatusMessage(outgoingSMSTopic, phoneNumber, remote, api):
    message = "Current temp is: " + remote.get_state(
        api, 'sensor.fireplace_temperature').state
    message = message + "\nCurrent state is: " + remote.get_state(
        api, 'input_select.fireplace_burn_zone').state
    client.publish(outgoingSMSTopic + phoneNumber, message)
Esempio n. 33
0
radio.openReadingPipe(0, address[0])
radio.openWritingPipe(address[0])
radio.printDetails()

init = True

while True:

    if init:
        radio.stopListening()
        radio.write(sensor_orange[:len(sensor_orange)])
        time.sleep(1)
        radio.startListening()
        init = False

    switch_moteur = remote.get_state(api, 'switch.moteur')
    print('{} is {}.'.format(switch_moteur.name, switch_moteur.state))
    if switch_moteur.state == "on":
        radio.stopListening()
        radio.write(sensor_red[:len(sensor_red)])
        time.sleep(1)
        radio.startListening()
    elif switch_moteur.state == "off":
        radio.stopListening()
        radio.write(sensor_green[:len(sensor_green)])
        time.sleep(1)
        radio.startListening()
    if radio.available():
        print("radio is available")
        length = radio.getDynamicPayloadSize()
        receive_payload = radio.read(length)
def raspberry_connection():
    api = remote.API('http://172.16.230.225', 'tokyocommit')
    remote.get_state(api, 'binary_sensor.pir_office')
    state = remote.get_state(api, 'binary_sensor.pir_office').state  # on / off
Esempio n. 35
0
def getswitchstatus():
	Switch = remote.get_state(api, 'switch.ge_unknown_type5052_id3031_switch_11')
	return(Switch.state)
Esempio n. 36
0
def main():
    global tempAvg, humAvg, Co2Avg, lightAvg, fake_update, lastrun, api
    last_update_id = None
    response1 = None
    while True:
        #print('started loop')
        try:
            temp = remote.get_state(api, Config.get('Sensors', 'Temp')).state
            if temp != 'unknown':
                tempAvg = float(temp)
            hum = remote.get_state(api, Config.get('Sensors', 'Hum')).state
            if hum != 'unknown':
                humAvg = float(hum)
            Co2 = remote.get_state(api, Config.get('Sensors', 'Co2')).state
            if Co2 != 'unknown':
                Co2Avg = float(Co2)
            light = remote.get_state(api, Config.get('Sensors', 'Light')).state
            if light != 'unknown':
                lightAvg = float(light)
            #print(tempAvg, humAvg, Co2Avg, lightAvg)
        except Exception as e:
            #print("Getting states: "+str(e))
            pass
        try:
            updates = telegramBot.get_updates(last_update_id)
            if len(updates["result"]) > 0:
                last_update_id = telegramBot.get_last_update_id(updates) + 1
                infolist = telegramBot.handle_updates(updates)
                for info in infolist:
                    toggle_button(info)
                time.sleep(1)
        except Exception as e:
            #print("Telegram Msgs: "+str(e))
            pass
        try:
            currentrun = datetime.datetime.now()
            check = currentrun - lastrun
            if lastrun < currentrun and check > datetime.timedelta(minutes=2):
                #print("running FarbenFroh")
                textlist = farbenFroh.changeLightColor(Config, values, api,
                                                       tempAvg, humAvg, Co2Avg,
                                                       lightAvg)
                #print(textlist)
                for text in textlist:
                    fake_update['result'][0]['message']['text'] = text
                    telegramBot.handle_updates(fake_update)
                lastrun = datetime.datetime.now()
            else:
                #print("not running FarbenFroh this loop")
                pass
        except Exception as e:
            #print("Change Color: "+str(e))
            pass
        try:
            textlist = checkHAStatus()
            for text in textlist:
                fake_update['result'][0]['message']['text'] = text
                telegramBot.handle_updates(fake_update)
        except Exception as e:
            #print("Send status to TG: "+str(e))
            pass
Esempio n. 37
0
 def update_hass_event():
     self.set_hass_event(remote.get_state(self.api, self.haevent.entity_id))
Esempio n. 38
0
#!/srv/hass/bin/python3
import requests
import json
import datetime
import homeassistant.remote as remote

mindergas = "http://www.mindergas.nl/api/gas_meter_readings"
mindergas_token = 'hKzzx5FssNThX-J8zxw8'
hass_ip = '127.0.0.1'
hass_password = ''
hass_port = '8123'
gas_sensor = 'sensor.gas_consumption'
api = remote.API(hass_ip, hass_password, hass_port)
gas_usage = remote.get_state(api, 'sensor.gas_consumption')


def post():
    yesterday = datetime.date.today() - datetime.timedelta(days=1)
    data = {'date': yesterday.strftime("%Y%m%d"), 'reading': gas_usage.state}
    headers = {
        'Content-Type': 'application/json',
        'AUTH-TOKEN': mindergas_token
    }
    r = requests.post(mindergas, data=json.dumps(data), headers=headers)
    print(yesterday.strftime("%Y%m%d"))
    print(data)
    print(r)
    print('Ready')


post()
Esempio n. 39
0
import homeassistant.remote as remote
import time
import requests

url = "http://localhost:8080/api/zWaveDoor"  #Enter url here
#url = "http://pegasus.cs.moravian.edu:8080/api/zWaveDoor" #Enter url here
api = remote.API('http://homeassistant.cs.moravian.edu:8123/states',
                 'raspberry')

switch = remote.get_state(api, 'binary_sensor.__sensor_6_0')
print(switch.state)
prevState = True

while True:
    tm = time.strftime('%Y-%m-%d %H:%M:%S',
                       time.localtime(time.time()))  #Get time
    day = tm[0:10]  #Separate day
    clock = tm[11:19]  #Separate time
    # Get status
    status = False
    switch = remote.get_state(api, 'binary_sensor.__sensor_6_0')
    st = switch.state
    if st == "on":
        status = True
    status = str(status).lower()
    #Print values
    print('date', day)
    print('time', clock)
    print('status', status)
    if prevState != status:  #If updated status
        #Send to API
Esempio n. 40
0
def intent_request(session, user, request):
	if request['intent']['name'] == "LocateIntent":
                hass_devices = {}
                user = request['intent']['slots']['User']['value']
                allStates=remote.get_states(api)
                for state in allStates:
                    if get_entity_type(state) == "device_tracker":
                        hass_devices[state.attributes['friendly_name']]=state.state
                output_speech = user + " is at " + hass_devices[user]
                output_type = "PlainText"
                card_type = "Simple"
                card_title = "Location"
                card_content = hass_devices[user]
                print(output_speech)
                response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}	
                return response 

	elif request['intent']['name'] == "LockIntent":
                matched_lock = False
                action = request['intent']['slots']['Action']['value']
                requested_lock = request['intent']['slots']['LockName']['value']
                allStates = remote.get_states(api)
                for state in allStates:
                    if get_entity_type(state) == "lock":
                        friendly_name = state.attributes['friendly_name']
                        if friendly_name.lower() == requested_lock:
                            matched_lock = True
                            print(action)
                            if action == "lock":
                                remote.set_state(api, state.entity_id, new_state=STATE_LOCKED)
                                output_speech = "I have locked the " + requested_lock
                            elif action == "unlock":
                                remote.set_state(api, state.entity_id, new_state=STATE_UNLOCKED)
                                output_speech = "I have unlocked the " + requested_lock
                if matched_lock == False:
                    output_speech = "I'm sorry, I have not found a lock by that name."
                output_type = "PlainText"
                response = {"outputSpeech" : {"type":output_type, "text":output_speech}, 'shouldEndSession':True}
                return response
                        
	elif request['intent']['name'] == "CurrentEnergyIntent":
                energy_usage = remote.get_state(api, 'sensor.energy_usage')
                output_speech = 'Your {} is {} {}.'.format(energy_usage.attributes['friendly_name'], energy_usage.state, energy_usage.attributes['unit_of_measurement'])
                output_type = "PlainText"

                card_type = "Simple"
                card_title = "Energy Usage"
                card_content = output_speech
                response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':False}
                return response

	elif request['intent']['name'] == "MonthlyEnergyIntent":
                energy_cost = remote.get_state(api, 'sensor.energy_cost')
                output_speech = 'Your {} is ${}'.format(energy_cost.attributes['friendly_name'], energy_cost.state)
                output_type = "PlainText"

                card_type = "Simple"
                card_title = "Energy Cost"
                card_content = output_speech
                response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':False}
                return response
                
	elif request['intent']['name'] ==  "HelpIntent":
		output_speech = "This is the HomeAssistant app. Right now, you can only ask where someone is, or ask about your energy usage.  But I have big plans. "
		output_type = "PlainText"
		card_type = "Simple"
		card_title = "HelloWorld - Title"
		card_content = "HelloWorld - This is the Hello World help! Just say Hi"

		response = {"outputSpeech": {"type":output_type,"text":output_speech},'shouldEndSession':False}

		return response
	
		
	else:
		return launch_request(session, user, request) ##Just do the same thing as launch request