Beispiel #1
0
    def pulsatingLightCall(self, api, exceeded, bright_max, color):
        #actual brightness
        bright = 1.0
        #when the maximum brigthness is reached
        reachedmax = False
        lamp = Config.get('Sensors', 'Lamp')
        global goodRoom

        #Loop to control the light
        while (exceeded == True):
            if bright <= bright_max and not reachedmax:
                bright = bright + 1
                if (bright == bright_max):
                    reachedmax = True
            else:
                if bright == 1:
                    exceeded = False
                    reachedmax = False
                    #Set global variable that one value is out of the defined borders
                    goodRoom = False

                bright = bright - 1

            #Call Home Assistant to set the light
            remote.call_service(api, 'light', 'turn_on', {
                'entity_id': lamp,
                'brightness': bright,
                'rgb_color': color
            })
            #Wait 0,1 seconds to make the brightness change smooth
            time.sleep(0.1)
def cli(ctx, service, persist, title, message, notification_id):
    """Send a notification with a given service."""
    import homeassistant.remote as remote

    domain = 'notify'
    data = {"title": title, "message": message}

    if service and not persist:
        if service in get_services(ctx.api, domain):
            remote.call_service(ctx.api, domain, service, data)
            ctx.vlog('Notification sent with %s at %s', service, timestamp())
            ctx.vlog('Title %s, Message: %s', title, message)
        else:
            ctx.log('Service %s is not available', service)

    if persist and not service:
        if notification_id:
            data['notification_id'] = notification_id
        if 'create' in get_services(ctx.api, 'persistent_notification'):
            remote.call_service(ctx.api, 'persistent_notification', 'create',
                                data)
            ctx.vlog('Persistent Notification created on %s at %s', ctx.host,
                     timestamp())
            ctx.vlog('Title %s, Message: %s', title, message)
        else:
            ctx.log('Service %s is not available', 'persistent_notification')
Beispiel #3
0
    def setLightColor(self, api, values):

        #Mimimum temprature
        color = ast.literal_eval(Config.get('Sectors', 'Temp_Min_Color'))
        pulsatingLightCall(api, values['temp_min'], values['temp_bright'],
                           color)

        #Maximum temprature
        color = ast.literal_eval(Config.get('Sectors', 'Temp_Max_Color'))
        pulsatingLightCall(api, values['temp_max'], values['temp_bright'],
                           color)

        #Minimum humidity
        color = ast.literal_eval(Config.get('Sectors', 'Hum_Min_Color'))
        pulsatingLightCall(api, values['hum_min'], values['hum_bright'], color)

        #Maximum humidity
        color = ast.literal_eval(Config.get('Sectors', 'Hum_Max_Color'))
        pulsatingLightCall(api, values['hum_max'], values['hum_bright'], color)

        #Maximum Co2
        color = ast.literal_eval(Config.get('Sectors', 'Co2_Max_Color'))
        pulsatingLightCall(api, values['Co2_max'], values['Co2_bright'], color)

        #When no value border is exceeded set the light to default
        if goodRoom:
            color = ast.literal_eval(Config.get('Sectors', 'Default_Color'))
            remote.call_service(
                api, 'light', 'turn_on', {
                    'entity_id': Config.get('Sensors', 'Lamp'),
                    'brightness': 1,
                    'rgb_color': color
                })
            time.sleep(10)
def arp_handle(pkt):
    global last_trigger
    if (
        ARP in pkt and pkt[ARP].op == 1 and  # who-has (request)
        abs(time.time() - last_trigger) > blackout_time
    ):
        mac = pkt[ARP].hwsrc.lower()
        logger.debug("Found ARP request")
        if mac in config.sections():
            if (
                config.has_option(mac, 'domain') and
                config.has_option(mac, 'action')
            ):
                domain = config.get(mac, 'domain')
                action = config.get(mac, 'action')
                data = json.loads(config.get(mac, 'data', fallback=''))
                logger.info(
                    "Found Button %s, will execute %s.%s with data %s",
                    mac, domain, action, data
                )
                ha.call_service(api, domain, action, data)
            else:
                logger.info(
                    "Found Button %s, will fire event for that mac", mac
                )
                ha.fire_event(api, 'dash_button_pressed', {'mac': mac})
            last_trigger = time.time()
Beispiel #5
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)})
Beispiel #6
0
 def cycle(self):
     url = "http://pegasus.cs.moravian.edu:8080/api/wemo"  # Enter url here
     api = remote.API('http://homeassistant.cs.moravian.edu:8123/states', 'raspberry')
     for i in range(3):
         remote.call_service(api, 'switch', 'turn_on')
         time.sleep(3)
         remote.call_service(api, 'switch', 'turn_off')
         time.sleep(3)
Beispiel #7
0
 async def off(self, entity: str):
     """Turn a light off"""
     try:
         domain = 'light'
         state = 'turn_off'
         remote.call_service(
             api, domain, state,
             {'entity_id': '{}'.format(domain) + '.{}'.format(entity)})
     except:
         await self.bot.say("There was an error!")
Beispiel #8
0
    def callback(self):

        if self.haevent.state == hasconst.STATE_OFF:

            status = remote.call_service(self.api, "homeassistant", 'turn_on',
                                         {'entity_id': self.haevent.entity_id})
        else:
            status = remote.call_service(self.api, "homeassistant", 'turn_off',
                                         {'entity_id': self.haevent.entity_id})

        # TODO: Fix time
        self.update_hass_event()
Beispiel #9
0
def setswitchstatus(switchstatus):
  if getswitchstatus() == switchstatus:
        return('ALREADY')
  else:
        if switchstatus == 'on':
             remote.call_service(api, domain, 'turn_on')
             print('Switch set succefully to ' + switchstatus)
             return('DONE')
        elif switchstatus == 'off': 
             remote.call_service(api, domain, 'turn_off')
             return('DONE')
        else:
             return('INVALID')
Beispiel #10
0
 def call_service(self, domain, command, entity=None):
     """
     Call a service with a given command.
     """
     if entity is not None:
         result = remote.call_service(self.api, domain, command, entity)
     else:
         result = remote.call_service(self.api, domain, command)
     if result is True:
         result = 'Ok.'
     elif result is False:
         result = 'Uh oh! Something went wrong.'
     return result
Beispiel #11
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))
    def test_call_service(self):
        """ Test Python API call_service. """
        test_value = []

        def listener(service_call):  # pylint: disable=unused-argument
            """ Helper method that will verify that our service got called. """
            test_value.append(1)

        hass.services.register("test_domain", "test_service", listener)

        remote.call_service(master_api, "test_domain", "test_service")

        hass._pool.block_till_done()

        self.assertEqual(1, len(test_value))
    def test_call_service(self):
        """ Test Python API call_service. """
        test_value = []

        def listener(service_call):   # pylint: disable=unused-argument
            """ Helper method that will verify that our service got called. """
            test_value.append(1)

        hass.services.register("test_domain", "test_service", listener)

        remote.call_service(master_api, "test_domain", "test_service")

        hass._pool.block_till_done()

        self.assertEqual(1, len(test_value))
Beispiel #14
0
def turn_on_light(sets):
    try:
        if sets['norun']:
            print(sets['norun'])
            exit(0)
    except KeyError:
        pass
    remote.call_service(
        api, 'light', 'turn_on', {
            'entity_id': 'light.hugo',
            'rgb_color': sets['rgb'],
            'brightness': sets['brightness']
        })
    print("w" + symb['state'])
    exit(0)
Beispiel #15
0
    def test_call_service(self):
        """ Test Python API call_service. """
        test_value = []

        def listener(service_call):   # pylint: disable=unused-argument
            """ Helper method that will verify that our service got called. """
            test_value.append(1)

        self.hass.services.register("test_domain", "test_service", listener)

        remote.call_service(self.api, "test_domain", "test_service")

        # Allow the event to take place
        time.sleep(1)

        self.assertEqual(len(test_value), 1)
Beispiel #16
0
    def test_call_service(self):
        """ Test Python API services.call. """
        test_value = []

        def listener(service_call):
            """ Helper method that will verify that our service got called. """
            test_value.append(1)

        hass.services.register("test_domain", "test_service", listener)

        remote.call_service(master_api, "test_domain", "test_service")

        hass.pool.block_till_done()

        self.assertEqual(1, len(test_value))

        # Should not raise an exception
        remote.call_service(broken_api, "test_domain", "test_service")
Beispiel #17
0
    def test_call_service(self):
        """ Test Python API services.call. """
        test_value = []

        def listener(service_call):
            """ Helper method that will verify that our service got called. """
            test_value.append(1)

        hass.services.register("test_domain", "test_service", listener)

        remote.call_service(master_api, "test_domain", "test_service")

        hass.pool.block_till_done()

        self.assertEqual(1, len(test_value))

        # Should not raise an exception
        remote.call_service(broken_api, "test_domain", "test_service")
Beispiel #18
0
 def turn_on_light(self, light_name, brightness=255):
     data = {
         'entity_id': 'light.{}'.format(light_name),
         'brightness': brightness
     }
     return remote.call_service(self.api,
                                'light',
                                'turn_on',
                                service_data=data)
Beispiel #19
0
    def create_reaction(self, menu, arguments, admin_access):
        if menu == MENU_MEOW:
            return COMMAND_CATS

        if SPECIAL_MONKEY in menu or SPECIAL_MONKEY in arguments:
            return SPECIAL_MONKEY
        if SPECIAL_LAUGH in menu or SPECIAL_LAUGH in arguments:
            return "🙉"

        if not admin_access:
            return ""

        if menu == MENU_DIE:
            return COMMAND_DIE

        if menu == MENU_SWITCH_SUB:
            for switch in self.sensors["switch"]:
                if switch["id"] == arguments[0]:
                    return switch["state"]

        if menu == COMMAND_STATE:
            for sensortype in self.sensors:
                for sensor in self.sensors[sensortype]:
                    if sensor["id"] == arguments[0]:
                        return sensor["state"]

        if not len(arguments) < 2:
            if menu == COMMAND_SWITCH and arguments[1] != ACTION_CANCEL:
                action = ""
                if arguments[1] == ACTION_ON:
                    action = "turn_on"
                if arguments[1] == ACTION_OFF:
                    action = "turn_off"
                remote.call_service(self.api, "switch", action,
                                    {"entity_id": arguments[0]})
                return "ok"

        if menu == MENU_STATES or menu == MENU_SWITCHES \
                or menu == MENU_STATES_SUB or menu == COMMAND_SWITCH:
            return "What do you want to do?"

        return ""
Beispiel #20
0
    def xiaomi_gateway_light(self,
                             entity_id,
                             state='turn_on',
                             rgb_color=(255, 255, 255),
                             brightness=100):
        assert state in ['turn_on', 'turn_off'
                         ], 'inputted state must be turn_on or turn_off'
        service_data = {}
        if state == 'turn_on':
            service_data = {
                'rgb_color': rgb_color,
                'brightness': brightness,
                'entity_id': entity_id
            }

        domain = 'light'  # state的前缀
        remote.call_service(self._api,
                            domain,
                            state,
                            service_data=service_data)
def cli(ctx, domain, service, data):
    """Query and call services."""
    import homeassistant.remote as remote

    # If no service is given, we want to either print all services
    # from the given domain, or everything if no domain is given
    if service is None and data is None:
        for serv in remote.get_services(ctx.api):
            if domain is not None and domain != serv['domain']:
                continue

            print_service(ctx, serv)
        return

    if data is not None:
        data = ast.literal_eval(data)

    ctx.log("Calling %s.%s with data %s", domain, service, data)
    res = remote.call_service(ctx.api, domain, service, data)
    ctx.log("Return value: %s", res)
Beispiel #22
0
def toggle_button(info):
    #toggles the button in the home assistant interface
    #used to request breaks and turn lecture on and off
    if info == "lectureOn":
        remote.call_service(
            api, 'input_boolean', 'turn_on',
            {'entity_id': '{}'.format('input_boolean.stopwatch')})
    elif info == "lectureOff":
        remote.call_service(
            api, 'input_boolean', 'turn_off',
            {'entity_id': '{}'.format('input_boolean.stopwatch')})
    elif info == "breakRequest":
        remote.call_service(
            api, 'input_boolean', 'toggle',
            {'entity_id': '{}'.format('input_boolean.breakrequest')})
Beispiel #23
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'
Beispiel #24
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]
                return build_response(output_speech) 

        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."
                return build_response(output_speech)
      
        elif request['intent']['name'] == "BedIntent":
                who = request['intent']['slots']['Who']['value']
                if who == "We are" or who == "We're":
                   script_name = "script.go_to_bed2"
                else:
                   script_name = "script.go_to_bed1"
                remote.call_service(api, 'script', 'turn_on', {'entity_id': '{}'.format(script_name)}) 
                output_speech = "Goodnight"
                return build_response(output_speech)

        elif request['intent']['name'] == "WakeIntent":
                script_name = "script.wake_up"
                remote.call_service(api, 'script', 'turn_on', {'entity_id': '{}'.format(script_name)})
                output_speech = "Good Morning"
                return build_response(output_speech)
        
        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'])
                return build_response(output_speech)

        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)
                return build_response(output_speech)
                
        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
Beispiel #25
0
	def stop_effect(self):
		remote.call_service(api,'light','turn_on',\
		{'entity_id':'light.{0}'.format(self.device_name),"effect":'{}'.format('Stop')})
Beispiel #26
0
	def effect(self,effect):
		remote.call_service(api,'light','turn_on',\
		{'entity_id':'light.{0}'.format(self.device_name),"effect":'{}'.format(effect)})	
Beispiel #27
0
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):
        try:
            if currentTemp >= 250.0:
                print('Over')
                remote.call_service(
                    api, 'input_select', 'select_option', {
                        'entity_id': 'input_select.fireplace_burn_zone',
                        'option': 'Over Temperature'
                    })
                #os.system('curl -s --data-binary \'{\"entity_id\":\"input_select.fireplace_burn_zone\",\"option\":\"Over Temperature\"}\' -H \'content-type: application/json;\' http://192.168.11.160:8123/api/services/input_select/select_option?api_password=turninTuna')
            if currentTemp >= 135.0 and currentTemp < 250.0:
                print('Optimal')
                remote.call_service(
                    api, 'input_select', 'select_option', {
                        'entity_id': 'input_select.fireplace_burn_zone',
                        'option': 'Optimal Burn Zone'
                    })
                #os.system('curl -s --data-binary \'{\"entity_id\":\"input_select.fireplace_burn_zone\",\"option\":\"Optimal Burn Zone\"}\' -H \'content-type: application/json;\' http://192.168.11.160:8123/api/services/input_select/select_option?api_password=turninTuna')
            if currentTemp >= 50.0 and currentTemp < 135.0:
                print('Under')
                remote.call_service(
                    api, 'input_select', 'select_option', {
Beispiel #28
0
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')
        pass

    previous.append(alive)
    if len(previous) > 10:
        del previous[-1]
    sleep(3)
Beispiel #29
0
def hello_world():
    message = request.form["message"]
    remote.call_service(api, 'tts', 'google_say', {'message': message})
Beispiel #30
0
	def play(self):
		remote.call_service(api,'remote','send_command',\
		{"entity_id":"remote.{}".format(self.device_name),"command":"play","device":""})
Beispiel #31
0

def get_latest_entry():
    feed = feedparser.parse(FEED_URL)
    return (feed.entries[0].enclosures[0].href, feed.entries[0].summary)


def download_file(url):
    remote_file = urllib.request.urlopen(url)
    local_name = 'daily-img.jpg'
    local_path = os.path.expanduser(os.path.join(DOWNLOAD_FOLDER, local_name))
    local_file = open(local_path, 'wb')
    local_file.write(remote_file.read())
    remote_file.close()
    local_file.close()
    return local_path


if __name__ == '__main__':
    if not os.path.exists(os.path.expanduser(DOWNLOAD_FOLDER)):
        os.makedirs(os.path.expanduser(DOWNLOAD_FOLDER))
    (url, text) = get_latest_entry()
    img_file = download_file(url)
    average = misc.imread(img_file).mean(axis=(0, 1)).tolist()
    api = remote.API('127.0.0.1', 'Waterloo!')
    remote.call_service(api, 'light', 'turn_on', {
        'entity_id': 'group.all_lights',
        'rgb_color': average
    })
    print(average)
Beispiel #32
0
	def color_name(self,color_name):
		remote.call_service(api,'light','turn_on',\
		{'entity_id':'light.{0}'.format(self.device_name),"color_name":'{}'.format(color_name)})	
Beispiel #33
0
	def color_temp(self,temp):
		remote.call_service(api,'light','turn_on',\
		{'entity_id':'light.{0}'.format(self.device_name),"color_temp":'{}'.format(temp)})	
Beispiel #34
0
	def flash(self,duration):
		remote.call_service(api,'light','turn_on',\
		{'entity_id':'light.{0}'.format(self.device_name),"flash":'{}'.format(duration)})	
Beispiel #35
0
import socket
import sys
import homeassistant.remote as remote

api = remote.API('http://homeassistant.cs.moravian.edu:8123/states', 'raspberry')

UDP_IP = socket.gethostbyname(socket.gethostname())
UDP_Port = 8123

BUFFER_SIZE = 1024

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_Port))

while True:
    data, addr = sock.recvfrom(1024)
    remote.call_service(api, 'tts', 'google_say', {'message': data.decode()})
Beispiel #36
0
def service_call (domain, service, payload):
  remote.call_service(api, domain, service, payload)
Beispiel #37
0
	def talk(self,message):
		remote.call_service(api,'tts','google_say',\
		{"entity_id":"media_player.{0}".format(self.device_name),"message":message, "language":"en"})