def notification_loop(self): api = remote.API('brixpro.lan', haPass) while True: try: v = self.char_read_hnd(0x21) # objT = (v[1]<<8)+v[0] ambT = (v[3] << 8) + v[2] ambT = tosigned(ambT) c_tmpAmb = ambT / 128.0 f_tmpAmb = 9.0 / 5.0 * c_tmpAmb + 32 remote.set_state(api, 'sensor.bedroom_temp', new_state=f_tmpAmb, attributes={'unit_of_measurement': '°F'}) # targetT = calcTmpTarget(objT, ambT) # self.data['t006'] = targetT # print "T006 %.1f" % c_tmpAmb v = self.char_read_hnd(0x29) rawT = (v[1] << 8) + v[0] rawH = (v[3] << 8) + v[2] (t, rh) = calcHum(rawT, rawH) remote.set_state(api, 'sensor.bedroom_humidity', new_state=rh, attributes={'unit_of_measurement': '%'}) #print ("%s -- %.1f %.1f" % (time.strftime('%l:%M:%S%p %Z on %b %d, %Y'), f_tmpAmb, rh)) time.sleep(120) # save battery on sensortag? except pexpect.TIMEOUT: print("TIMEOUT exception!") break
def setalaram(alaramstatus): switch = {'arm home': 'armed_home', 'arm away': 'armed_away', 'disarmed': 'disarmed'} Status = switch.get(alaramstatus) print('in alaram') if Status in alaram_valid: if isdoorsopen() == 'false': if getalaram() == alaramstatus: return('ALREADY') else: if alaramstatus == 'disarm' or alaramstatus == 'arm home': remote.set_state(api, 'alarm_control_panel.security_alarm' , new_state = Status) setswitchstatus('off') print('Alaram Set Successfully' + alaramstatus) return('DONE') else: threadObj = threading.Thread(target = takeANap,args=[switch.get(alaramstatus),120]) #scheduling thread after two minutes threadObj.start() return('DONE') else: return('DOOROPEN') else: print('invalid input') return('INVALID')
def test_set_state(self): """ Test Python API set_state. """ self.assertTrue(remote.set_state(master_api, 'test.test', 'set_test')) self.assertEqual('set_test', hass.states.get('test.test').state) self.assertFalse(remote.set_state(broken_api, 'test.test', 'set_test'))
def test_set_state(self): """Test Python API set_state.""" remote.set_state(master_api, "test.test", "set_test") state = hass.states.get("test.test") self.assertIsNotNone(state) self.assertEqual("set_test", state.state) self.assertFalse(remote.set_state(broken_api, "test.test", "set_test"))
def _turn_on_raw_sensor_on_change(self, entity, attribute, old, new, kwargs): _, last_st = self._raw_sensors_last_states[entity] self._raw_sensors_last_states[entity] = [self.datetime(), True] if not last_st: name, attrs = self._raw_sensors_attributes[entity] remote.set_state(self._master_ha_api, name + self._sufix, 'on', attributes=attrs)
def test_set_state(self): """Test Python API set_state.""" remote.set_state(master_api, 'test.test', 'set_test') state = hass.states.get('test.test') self.assertIsNotNone(state) self.assertEqual('set_test', state.state) self.assertFalse(remote.set_state(broken_api, 'test.test', 'set_test'))
def _turn_off_raw_sensor_if_not_updated(self, *kwargs): now = self.datetime() for s, (ts, st) in self._raw_sensors_last_states.copy().items(): if st and ceil( (now - ts).total_seconds()) >= self._raw_sensors_seconds_to_off: name, attrs = self._raw_sensors_attributes[s] self._raw_sensors_last_states[s] = [now, False] remote.set_state(self._master_ha_api, name + self._sufix, 'off', attributes=attrs)
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)
def _update_states(self, kwargs): """Update states in master if they are not changed.""" now = self.datetime() s_states = self.get_state('sensor') bs_states = self.get_state('binary_sensor') sensors = dict(**s_states) sensors.update(bs_states) for entity_id, state_atts in sensors.items(): key = entity_id + self._sufix if key not in self._sensor_updates \ or (now - self._sensor_updates[key]).total_seconds() > 60: remote.set_state(self._master_ha_api, key, state_atts['state'], attributes=state_atts['attributes']) self._sensor_updates[key] = now
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())
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)
def notification_loop(self): api = remote.API('brixpro.lan', haPass) while True: try: v = self.char_read_hnd(0x21) # objT = (v[1]<<8)+v[0] ambT = (v[3] << 8) + v[2] ambT = tosigned(ambT) c_tmpAmb = ambT / 128.0 f_tmpAmb = 9.0 / 5.0 * c_tmpAmb + 32 remote.set_state(api, 'sensor.bedroom_temp', new_state=f_tmpAmb, attributes={'unit_of_measurement': '°F'}) # targetT = calcTmpTarget(objT, ambT) # self.data['t006'] = targetT # print "T006 %.1f" % c_tmpAmb v = self.char_read_hnd(0x29) rawT = (v[1] << 8) + v[0] rawH = (v[3] << 8) + v[2] (t, rh) = calcHum(rawT, rawH) remote.set_state(api, 'sensor.bedroom_humidity', new_state=rh, attributes={'unit_of_measurement': '%'}) #print ("%s -- %.1f %.1f" % (time.strftime('%l:%M:%S%p %Z on %b %d, %Y'), f_tmpAmb, rh)) time.sleep(120) # save battery on sensortag? except pexpect.TIMEOUT: print ("TIMEOUT exception!") break
def test_set_state_with_push(self): """Test Python API set_state with push option.""" events = [] hass.bus.listen(EVENT_STATE_CHANGED, lambda ev: events.append(ev)) remote.set_state(master_api, "test.test", "set_test_2") remote.set_state(master_api, "test.test", "set_test_2") hass.block_till_done() self.assertEqual(1, len(events)) remote.set_state(master_api, "test.test", "set_test_2", force_update=True) hass.block_till_done() self.assertEqual(2, len(events))
def test_set_state_with_push(self): """TestPython API set_state with push option.""" events = [] hass.bus.listen(EVENT_STATE_CHANGED, events.append) remote.set_state(master_api, 'test.test', 'set_test_2') remote.set_state(master_api, 'test.test', 'set_test_2') hass.bus._pool.block_till_done() self.assertEqual(1, len(events)) remote.set_state( master_api, 'test.test', 'set_test_2', force_update=True) hass.bus._pool.block_till_done() self.assertEqual(2, len(events))
def test_set_state_with_push(self): """Test Python API set_state with push option.""" events = [] hass.bus.listen(EVENT_STATE_CHANGED, lambda ev: events.append(ev)) remote.set_state(master_api, 'test.test', 'set_test_2') remote.set_state(master_api, 'test.test', 'set_test_2') hass.block_till_done() self.assertEqual(1, len(events)) remote.set_state( master_api, 'test.test', 'set_test_2', force_update=True) hass.block_till_done() self.assertEqual(2, len(events))
def setMonitorState(outgoingSMSTopic, phoneNumber, remote, api, newState): print("Set monitor....") print(phoneNumber) print(newState) if phoneNumber == "JordanB": remote.set_state(api, 'switch.jordan_fireplace_monitor', new_state=newState) elif phoneNumber == "BrendanM": remote.set_state(api, 'switch.brendan_fireplace_monitor', new_state=newState) elif phoneNumber == "JoelD": remote.set_state(api, 'switch.joel_fireplace_monitor', new_state=newState) client.publish(outgoingSMSTopic + phoneNumber, "State set.")
import time import RPi.GPIO as io io.setmode(io.BCM) import homeassistant.remote as remote from homeassistant.const import STATE_ON api = remote.API('127.0.0.1', '') if __name__ == "__main__": door_pin = 14 io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP) # activate input with PullUp status = 0 while True: if io.input(door_pin) and status == 0: remote.set_state(api, 'sensor.Switch_Frontdoor', new_state='Open') print("DOOR ALARM!") status = 1 elif not io.input(door_pin) and status == 1: remote.set_state(api, 'sensor.Switch_Frontdoor', new_state='Closed') status = 0 time.sleep(0.5)
def set_state(self, entity_id, new_state, **kwargs): "Updates or creates the current state of an entity." return remote.set_state(self.api, new_state, **kwargs)
def setSensorState(apiurl, password, sensorname, state): api = remote.API(apiurl, password) print("setting {0} to {1}".format(sensorname, state)) remote.set_state(api, sensorname, new_state=state)
def test_set_state(self): """ Test Python API set_state. """ remote.set_state(self.api, 'test.test', 'set_test') self.assertEqual(self.hass.states.get('test.test').state, 'set_test')
def initialize(self): """AppDaemon required method for app init.""" self._hass_master_url = self.args.get('master_ha_url') self._hass_master_key = self.args.get('master_ha_key', '') self._hass_master_port = int(self.args.get('master_ha_port', '8123')) self._sufix = self.args.get('slave_sufix', DEFAULT_SUFFIX) self._master_ha_api = remote.API(self._hass_master_url, self._hass_master_key, port=self._hass_master_port) # Raw binary sensors self._raw_sensors = self.args.get('raw_binary_sensors', None) if self._raw_sensors is not None: self._raw_sensors = self._raw_sensors.split(',') self._raw_sensors_sufix = self.args.get( 'raw_binary_sensors_sufijo', '_raw') # Persistencia en segundos de último valor hasta considerarlos 'off' self._raw_sensors_seconds_to_off = int( self.args.get('raw_binary_sensors_time_off', DEFAULT_RAWBS_SECS_OFF)) # Handlers de cambio en raw binary_sensors: l1, l2 = 'attributes', 'last_changed' for s in self._raw_sensors: self._raw_sensors_attributes[s] = (s.replace( self._raw_sensors_sufix, ''), self.get_state(s, l1)) self._raw_sensors_last_states[s] = [ parse(self.get_state(s, l2)).replace(tzinfo=None), False ] self.listen_state(self._turn_on_raw_sensor_on_change, s) self.log('seconds_to_off: {}'.format( self._raw_sensors_seconds_to_off)) self.log('attributes_sensors: {}'.format( self._raw_sensors_attributes)) self.log('last_changes: {}'.format(self._raw_sensors_last_states)) # [self.set_state(dev, state='off', attributes=attrs) for dev, attrs in .._raw_sensors_attributes.values()] [ remote.set_state(self._master_ha_api, dev + self._sufix, 'off', attributes=attrs) for dev, attrs in self._raw_sensors_attributes.values() ] next_run = self.datetime() + dt.timedelta( seconds=self._raw_sensors_seconds_to_off) self.run_every(self._turn_off_raw_sensor_if_not_updated, next_run, self._raw_sensors_seconds_to_off) # Publish slave states in master bs_states = self.get_state('binary_sensor') if self._raw_sensors is not None: [bs_states.pop(raw) for raw in self._raw_sensors] s_states = self.get_state('sensor') sensors = dict(**s_states) sensors.update(bs_states) now = self.datetime() sensor_updates = {} for entity_id, state_atts in sensors.items(): self.log('SENSOR: {}, ATTRS={}'.format(entity_id, state_atts)) remote.set_state(self._master_ha_api, entity_id + self._sufix, state_atts['state'], attributes=state_atts['attributes']) self.listen_state(self._ch_state, entity_id, attributes=state_atts['attributes']) sensor_updates.update({entity_id + self._sufix: now}) self._sensor_updates = sensor_updates self.run_minutely(self._update_states, None) self.log('Transfer states from slave to master in {} COMPLETE'.format( self._master_ha_api))
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
def setSensorState(apiurl, password, sensorname, state): api = remote.API(apiurl, password) remote.set_state(api, sensorname, new_state=state)
def _ch_state(self, entity, attribute, old, new, kwargs): remote.set_state(self._master_ha_api, entity + self._sufix, new, **kwargs) self._sensor_updates[entity + self._sufix] = self.datetime()
def takeANap(Status,nap): time.sleep(nap) print('Wake up!') remote.set_state(api, 'alarm_control_panel.security_alarm' , new_state = Status) print('Alaram Set Successfully' + Status) setswitchstatus('on')