コード例 #1
0
    def test_post_state_dict_none_room_none(self, mock_put, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        self.skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])

        self.skill._post_state(None, None)
        self.assertFalse(mock_put.called)
コード例 #2
0
    def test_post_state_to_ids(self, mock_post_state, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        skill._post_state_to_ids(dict(), None)

        self.assertFalse(mock_post_state.called)
コード例 #3
0
 def __init__(self):
     try:
         config = SnipsConfigParser.read_configuration_file(CONFIG_INI)
     except:
         config = None
     hostname = None
     code = None
     if config and config.get('secret') is not None:
         if config.get('secret').get('hostname') is not None:
             hostname = config.get('secret').get('hostname')
             if hostname == "":
                 hostname = None
         if config.get('secret').get(API_KEY) is not None:
             code = config.get('secret').get(API_KEY)
             if code == "":
                 code = None
     if hostname is None or code is None:
         print('No configuration')
     self.snipshue = SnipsHue(hostname, code)
     hostname = self.snipshue.hostname
     code = self.snipshue.username
     self.update_config(CONFIG_INI, config, hostname, code)
     self.queue = Queue.Queue()
     self.thread_handler = ThreadHandler()
     self.thread_handler.run(target=self.start_blocking)
     self.thread_handler.start_run_loop()
コード例 #4
0
    def test_post_state(self, mock_put, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        skill._post_state(dict(), 1)

        mock_put.assert_called_with(self.skill.lights_endpoint + "/1/state", data=json.dumps(dict()), headers=None)
コード例 #5
0
    def setUp(self, mock_rooms_lights):
        self.hostname = "192.168.1.1"
        self.username = "******"
        self.lights_id = range(1, 5)

        mock_rooms_lights.return_value = dict()

        self.skill = SnipsHue(self.hostname, self.username, self.lights_id)
コード例 #6
0
    def test_post_state_to_ids(self, mock_post_state, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        lights_id = range(1, 3)
        skill._post_state_to_ids(dict(), lights_id)

        self.assertEqual(mock_post_state.call_count, len(lights_id))
コード例 #7
0
    def __init__(self):
        config_dict = SnipsConfigParser.read_configuration_file()
        bridge_ip = config_dict.get(BRIDGE_IP_KEY, None)
        api_key = config_dict.get(API_KEY_KEY, None)
        (bridge_ip, api_key, config_changed) = HueSetup.validate_config(bridge_ip, api_key)
        if config_changed:
            SnipsConfigParser.write_configuration_file(bridge_ip, api_key)
        self.snipshue = SnipsHue(bridge_ip, api_key)

        with Hermes(MQTT_ADDR) as h:
            h.subscribe_intents(self.callback).start()
コード例 #8
0
def action_wrapper(hermes, intentMessage, conf):
    """ Write the body of the function that will be executed once the intent is recognized. 
    In your scope, you have the following objects : 
    - intentMessage : an object that represents the recognized intent
    - hermes : an object with methods to communicate with the MQTT bus following the hermes protocol. 
    - conf : a dictionary that holds the skills parameters you defined 

    Refer to the documentation for further details. 
    """ 
    #number = intentMessage.number[0] if intentMessage.number else None

    if len(intentMessage.slots.house_room):
    	for room in intentMessage.slots.house_room:
    		#snips.skill.light_on_set(None, number, room)
		    #snipshue.light_on_set("orange", 254, room)
            snipshue.light_on_set("orange", 254, "chambre")
   	else:
   		#snips.skill.light_on_set(None, number, None)
		#snipshue.light_on_set("orange", 254, None)
        snipshue.light_on_set("orange", 254, "chambre")


    current_session_id = intentMessage.session_id
    result_sentence="Lumiere allume dans la chambre"
    hermes.publish_end_session(current_session_id, result_sentence)


if __name__ == "__main__":
    snipshue= SnipsHue("192.168.1.84","YFuLloeVWUTdSO8IJKZi2OYXZJKsEFPAfatS0Fq2")
    #snipshue.light_on_set("orange",254,"chambre")
    with Hermes("localhost:1883") as h:
        h.subscribe_intent("lightsTurnOnSet", subscribe_intent_callback) \
.start()
コード例 #9
0
    def test_get_lights_ids_from_rooms(self, mock_request_get):
        mock_request_get.return_value = self.false_response({
            '1': {
                'name': 'room_name',
                'class': 'Office',
                'lights': ['1', '2', '3', '4', '5', '6']
            },
            '2': {'class': 'Bedroom', 'lights': []},
            '3': {'class': 'Kitchen', 'lights': ['1']}
        })

        skill = SnipsHue("192.168.1.1", "username", [1, 2, '3', 4, '5'])
        self.assertEqual(skill._get_light_ids_from_room("Bedroom"), []) 
        self.assertEqual(skill._get_light_ids_from_room("Office"), ['1', '2', '3', '4', '5', '6']) 
        self.assertEqual(skill._get_light_ids_from_room("Kitchen"), ['1']) 
        self.assertEqual(skill._get_light_ids_from_room("Unknown"), ['1', '2', '3', '4', '5']) 
コード例 #10
0
    def test_get_rooms_lights_simple(self, mock_request_get):
        mock_request_get.return_value = self.false_response({
            '1': {
                'name': 'room_name',
                'class': 'Office',
                'lights': ['1', '2', '3', '4', '5', '6']
            },
            '2': {'class': 'Bedroom', 'lights': []},
            '3': {'class': 'Kitchen', 'lights': ['1']}
        })

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])

        result = skill._get_rooms_lights()

        self.assertTrue(mock_request_get.called)
        self.assertEqual(result["Office"], ['1', '2', '3', '4', '5', '6'])
        self.assertEqual(result["Bedroom"], [])
        self.assertEqual(result["Kitchen"], ['1'])
コード例 #11
0
    def test_get_lights_config(self, mock_request_get, mock_get_rooms_lights):
        response_state = {
            u'on': True,
            u'hue': 9509,
            u'colormode': u'hs',
            u'effect': u'none',
            u'alert': u'none',
            u'xy': [0.0, 0.0],
            u'reachable': False,
            u'bri': 254,
            u'ct': 432,
            u'sat': 254
        }
        mock_request_get.return_value = self.false_response({u'state': response_state})

        skill = SnipsHue("192.168.1.1", "username", ['1', '2', '3'])
        self.assertEqual(skill._get_lights_config(['1']), {'1': response_state})
        self.assertEqual(skill._get_lights_config(['1', '2']), {'1': response_state, '2': response_state})
        self.assertEqual(skill._get_lights_config(['xx']), {'xx': response_state})
コード例 #12
0
class Skill_Hue:
    def __init__(self):
        config_dict = SnipsConfigParser.read_configuration_file()
        bridge_ip = config_dict.get(BRIDGE_IP_KEY, None)
        api_key = config_dict.get(API_KEY_KEY, None)
        (bridge_ip, api_key, config_changed) = HueSetup.validate_config(bridge_ip, api_key)
        if config_changed:
            SnipsConfigParser.write_configuration_file(bridge_ip, api_key)
        self.snipshue = SnipsHue(bridge_ip, api_key)

        with Hermes(MQTT_ADDR) as h:
            h.subscribe_intents(self.callback).start()

    # section -> extraction of slot value
    def _select_best_match(self, val, choices, min_match_percent):
        res = process.extractOne(val, choices)
        if res[1] > min_match_percent:
            return res[0]
        else:
            return None

    def extract_house_room(self, intent_message):
        available_house_rooms = self.snipshue.get_rooms()
        if intent_message.slots.house_room:
            best_match = self._select_best_match(intent_message.slots.house_room.first().value,
                                                 available_house_rooms.keys(), 90)
            if best_match:
                return best_match, available_house_rooms[best_match]
            else:
                return None, None

    def extract_percentage(self, intent_message, default_percentage):
        percentage = default_percentage
        if intent_message.slots.percent:
            percentage = intent_message.slots.percent.first().value
        if percentage < 0:
            percentage = 0
        if percentage > 100:
            percentage = 100
        return percentage

    def extract_scene(self, intent_message, house_room_id):
        available_scenes = self.snipshue.get_scenes_for_room(house_room_id)
        if intent_message.slots.scene:
            best_match = self._select_best_match(intent_message.slots.scene.first().value,
                                                 available_scenes.keys(), 90)
            if best_match:
                return best_match, available_scenes[best_match]
            else:
                return None, None

    # section -> handlers of intents

    def callback(self, hermes, intent_message):
        intent_name = intent_message.intent.intent_name
        if ':' in intent_name:
            intent_name = intent_name.split(":")[1]
        if intent_name not in ALL_INTENTS:
            return
        try:
            print("[HUE] Received {}".format(intent_message.intent.intent_name))
            # all the intents have to have a house_room slot, extract here
            room_name, room_id = self.extract_house_room(intent_message)
            if room_id:
                if intent_name == TURN_ON_INTENT:
                    self.turn_on(hermes, intent_message, room_id)
                if intent_name == TURN_OFF_INTENT:
                    self.turn_off(hermes, intent_message, room_id)
                if intent_name == SET_BRIGHTNESS_INTENT:
                    self.set_brightness(hermes, intent_message, room_id)
                if intent_name == SET_SCENE_INTENT:
                    self.set_scene(hermes, intent_message, room_id)
                if intent_name == SHIFT_UP_INTENT:
                    self.shift_up(hermes, intent_message, room_id)
                if intent_name == SHIFT_DOWN_INTENT:
                    self.shift_down(hermes, intent_message, room_id)
            else:
                self.terminate_feedback(hermes, intent_message, "Sorry no fitting room was detected.")
        except:
            traceback.print_exc()
            self.terminate_feedback(hermes, intent_message, "Unknown exception detected. Please consult log files.")

    def turn_on(self, hermes, intent_message, room_id):
        self.snipshue.light_on(room_id)
        self.terminate_feedback(hermes, intent_message)

    def turn_off(self, hermes, intent_message, room_id):
        self.snipshue.light_off(room_id)
        self.terminate_feedback(hermes, intent_message)

    def set_brightness(self, hermes, intent_message, room_id):
        percent = self.extract_percentage(intent_message, None)
        self.snipshue.light_brightness(percent, room_id)
        self.terminate_feedback(hermes, intent_message)

    def set_scene(self, hermes, intent_message, room_id):
        scene_name, scene_id = self.extract_scene(intent_message, room_id)
        if scene_id:
            self.snipshue.set_scene(scene_id, room_id)
            self.terminate_feedback(hermes, intent_message)
        else:
            self.terminate_feedback(hermes, intent_message, "Sorry, no matching seen found.")

    def shift_up(self, hermes, intent_message, room_id):
        percent = self.extract_percentage(intent_message, 20)
        self.snipshue.shift_brightness(room_id, percent, True)
        self.terminate_feedback(hermes, intent_message)

    def shift_down(self, hermes, intent_message, room_id):
        percent = self.extract_percentage(intent_message, 20)
        self.snipshue.shift_brightness(room_id, percent, False)
        self.terminate_feedback(hermes, intent_message)

    # section -> feedback reply // future function
    def terminate_feedback(self, hermes, intent_message, message=""):
        hermes.publish_end_session(intent_message.session_id, message)
コード例 #13
0
class Skill_Hue:
    def __init__(self):
        try:
            config = SnipsConfigParser.read_configuration_file(CONFIG_INI)
        except:
            config = None
        hostname = None
        code = None
        if config and config.get('secret', None) is not None:
            if config.get('secret').get('hostname', None) is not None:
                hostname = config.get('secret').get('hostname')
                if hostname == "":
                    hostname = None
            if config.get('secret').get(API_KEY, None) is not None:
                code = config.get('secret').get(API_KEY)
                if code == "":
                    code = None
            elif os.path.isfile(CACHE_INI):
                try:
                    cached_config = SnipsConfigParser.read_configuration_file(
                        CACHE_INI)
                except:
                    cached_config = None
                if cached_config and cached_config.get('secret',
                                                       None) is not None:
                    if cached_config.get('secret').get(API_KEY,
                                                       None) is not None:
                        code = cached_config.get('secret').get(API_KEY)
                        if code == "":
                            code = None
        if hostname is None or code is None:
            print('No configuration')
        self.snipshue = SnipsHue(hostname, code)
        hostname = self.snipshue.hostname
        code = self.snipshue.username
        self.update_config(CACHE_INI, config, hostname, code)
        self.queue = Queue.Queue()
        self.thread_handler = ThreadHandler()
        self.thread_handler.run(target=self.start_blocking)
        self.thread_handler.start_run_loop()

    def update_config(self, filename, data, hostname, code):
        if not os.path.exists(CACHE_INI_DIR):
            os.makedirs(CACHE_INI_DIR)
        if 'secret' not in data or data['secret'] is None:
            data['secret'] = {}
        data['secret']['hostname'] = hostname
        data['secret'][API_KEY] = code
        SnipsConfigParser.write_configuration_file(filename, data)

    def start_blocking(self, run_event):
        while run_event.is_set():
            try:
                self.queue.get(False)
            except Queue.Empty:
                with Hermes(MQTT_ADDR) as h:
                    h.subscribe_intents(self.callback).start()

    # section -> extraction of slot value
    def extract_house_rooms(self, intent_message):
        house_rooms = []
        if intent_message.slots.house_room:
            for room in intent_message.slots.house_room.all():
                print type(room.value)
                house_rooms.append(room.value)
        return house_rooms

    def extract_percentage(self, intent_message, default_percentage):
        percentage = default_percentage
        if intent_message.slots.percent:
            percentage = intent_message.slots.percent.first().value
        if percentage < 0:
            percentage = 0
        if percentage > 100:
            percentage = 100
        return percentage

    def extract_color(self, intent_message):
        color_code = None
        if intent_message.slots.color:
            color_code = intent_message.slots.color.first().value
        return color_code

    def extract_scene(self, intent_message):
        scene_code = None
        if intent_message.slots.scene:
            scene_code = intent_message.slots.scene.first().value
        return scene_code

    # section -> handlers of intents

    def callback(self, hermes, intent_message):
        print("[HUE] Received")
        # all the intents have a house_room slot, extract here
        rooms = self.extract_house_rooms(intent_message)
        intent_name = intent_message.intent.intent_name
        if ':' in intent_name:
            intent_name = intent_name.split(":")[1]
        if intent_name == 'turnOn':
            self.queue.put(self.turn_on(hermes, intent_message, rooms))
        if intent_name == 'turnOff':
            self.queue.put(self.turn_off(hermes, intent_message, rooms))
        if intent_name == 'setBrightness':
            self.queue.put(self.set_brightness(hermes, intent_message, rooms))
        if intent_name == 'setColor':
            self.queue.put(self.set_color(hermes, intent_message, rooms))
        if intent_name == 'setScene':
            self.queue.put(self.set_scene(hermes, intent_message, rooms))
        if intent_name == 'shiftUp':
            self.queue.put(self.shift_up(hermes, intent_message, rooms))
        if intent_name == 'shiftDown':
            self.queue.put(self.shift_down(hermes, intent_message, rooms))

    def turn_on(self, hermes, intent_message, rooms):
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_on(room.lower())
        else:
            self.snipshue.light_on_all()
        self.terminate_feedback(hermes, intent_message)

    def turn_off(self, hermes, intent_message, rooms):
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_off(room.lower())
        else:
            self.snipshue.light_off_all()
        self.terminate_feedback(hermes, intent_message)

    def set_brightness(self, hermes, intent_message, rooms):
        percent = self.extract_percentage(intent_message, None)
        if percent is None:
            self.terminate_feedback(hermes, intent_message)
            return
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_brightness(percent, room.lower())
        else:
            self.snipshue.light_brightness_all(percent)
        self.terminate_feedback(hermes, intent_message)

    def set_color(self, hermes, intent_message, rooms):
        color = self.extract_color(intent_message)
        if color is None:
            self.terminate_feedback(hermes, intent_message)
            return
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_color(color, room.lower())
        else:

            self.snipshue.light_color_all(color)
        self.terminate_feedback(hermes, intent_message)

    def set_scene(self, hermes, intent_message, rooms):
        scene = self.extract_scene(intent_message)
        if scene is None:
            self.terminate_feedback(hermes, intent_message)
            return
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_scene(scene, room.lower())
        else:
            self.snipshue.light_scene_all(scene)
        self.terminate_feedback(hermes, intent_message)

    def shift_up(self, hermes, intent_message, rooms):
        percent = self.extract_percentage(intent_message, 20)
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_up(percent, room.lower())
        else:
            self.snipshue.light_up_all(percent)
        self.terminate_feedback(hermes, intent_message)

    def shift_down(self, hermes, intent_message, rooms):
        percent = self.extract_percentage(intent_message, 20)
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_down(percent, room.lower())
        else:
            self.snipshue.light_down_all(percent)
        self.terminate_feedback(hermes, intent_message)

    # section -> feedback reply // future function
    def terminate_feedback(self, hermes, intent_message, mode='default'):
        if mode == 'default':
            hermes.publish_end_session(intent_message.session_id, "")
        else:
            # more design
            hermes.publish_end_session(intent_message.session_id, "")
コード例 #14
0
def subscribe_intent_callback(hermes, intentMessage):
    conf = read_configuration_file(CONFIG_INI)
    action_wrapper(hermes, intentMessage, conf)


def action_wrapper(hermes, intentMessage, conf):
    """ Write the body of the function that will be executed once the intent is recognized. 
    In your scope, you have the following objects : 
    - intentMessage : an object that represents the recognized intent
    - hermes : an object with methods to communicate with the MQTT bus following the hermes protocol. 
    - conf : a dictionary that holds the skills parameters you defined 

    Refer to the documentation for further details. 
    """
    if len(intentMessage.slots.house_room):
        for room in intentMessage.slots.house_room:
            snipsorange.light_off("chambre")
    else:
        snipsorange.light_off(None)

    current_session_id = intentMessage.session_id
    hermes.publish_end_session(current_session_id, result_sentence)


if __name__ == "__main__":
    snipsorange = SnipsHue("192.168.1.84",
                           "YFuLloeVWUTdSO8IJKZi2OYXZJKsEFPAfatS0Fq2")
    with Hermes("localhost:1883") as h:
        h.subscribe_intent("orangetvTurnOff", subscribe_intent_callback) \
.start()
コード例 #15
0
    def test_get_rooms_lights_empty(self, mock_request_get):
        mock_request_get.return_value = self.false_response({})

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        result = skill._get_rooms_lights()
        self.assertTrue(mock_request_get.called)
コード例 #16
0
    def test_get_hue_saturation(self, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3])
        self.assertIsNotNone(skill._get_hue_saturation(None))
コード例 #17
0
class SnipsHueGetRequests(TestCase):
    @patch.object(SnipsHue, '_get_rooms_lights')
    def setUp(self, mock_rooms_lights):
        self.hostname = "192.168.1.1"
        self.username = "******"
        self.lights_id = range(1, 5)

        mock_rooms_lights.return_value = dict()

        self.skill = SnipsHue(self.hostname, self.username, self.lights_id)

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch('requests.put')
    def test_post_state(self, mock_put, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        skill._post_state(dict(), 1)

        mock_put.assert_called_with(self.skill.lights_endpoint + "/1/state", data=json.dumps(dict()), headers=None)

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch('requests.put')
    def test_post_state_room_none(self, mock_put, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        self.skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])

        self.skill._post_state(dict(), None)
        self.assertFalse(mock_put.called)

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch('requests.put')
    def test_post_state_dict_none(self, mock_put, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        self.skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])

        self.skill._post_state(None, 1)
        self.assertFalse(mock_put.called)

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch('requests.put')
    def test_post_state_dict_none_room_none(self, mock_put, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        self.skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])

        self.skill._post_state(None, None)
        self.assertFalse(mock_put.called)

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch.object(SnipsHue, '_post_state')
    def test_post_state_to_ids(self, mock_post_state, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        lights_id = range(1, 3)
        skill._post_state_to_ids(dict(), lights_id)

        self.assertEqual(mock_post_state.call_count, len(lights_id))

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch.object(SnipsHue, '_post_state')
    def test_post_state_to_ids(self, mock_post_state, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        skill._post_state_to_ids(dict(), None)

        self.assertFalse(mock_post_state.called)

    @patch.object(SnipsHue, '_get_rooms_lights')
    def test_get_hue_saturation(self, mock_get_rooms_lights):
        mock_get_rooms_lights.return_value = dict()

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3])
        self.assertIsNotNone(skill._get_hue_saturation(None))

    class false_response():
        def __init__(self, content):
            self.content = content
        def json(self):
            return self.content


    @patch('requests.get')
    def test_get_rooms_lights_simple(self, mock_request_get):
        mock_request_get.return_value = self.false_response({
            '1': {
                'name': 'room_name',
                'class': 'Office',
                'lights': ['1', '2', '3', '4', '5', '6']
            },
            '2': {'class': 'Bedroom', 'lights': []},
            '3': {'class': 'Kitchen', 'lights': ['1']}
        })

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])

        result = skill._get_rooms_lights()

        self.assertTrue(mock_request_get.called)
        self.assertEqual(result["Office"], ['1', '2', '3', '4', '5', '6'])
        self.assertEqual(result["Bedroom"], [])
        self.assertEqual(result["Kitchen"], ['1'])

    @patch('requests.get')
    def test_get_rooms_lights_empty(self, mock_request_get):
        mock_request_get.return_value = self.false_response({})

        skill = SnipsHue("192.168.1.1", "username", [1, 2, 3, 4, 5])
        result = skill._get_rooms_lights()
        self.assertTrue(mock_request_get.called)

    @patch('requests.get')
    def test_get_lights_ids_from_rooms(self, mock_request_get):
        mock_request_get.return_value = self.false_response({
            '1': {
                'name': 'room_name',
                'class': 'Office',
                'lights': ['1', '2', '3', '4', '5', '6']
            },
            '2': {'class': 'Bedroom', 'lights': []},
            '3': {'class': 'Kitchen', 'lights': ['1']}
        })

        skill = SnipsHue("192.168.1.1", "username", [1, 2, '3', 4, '5'])
        self.assertEqual(skill._get_light_ids_from_room("Bedroom"), []) 
        self.assertEqual(skill._get_light_ids_from_room("Office"), ['1', '2', '3', '4', '5', '6']) 
        self.assertEqual(skill._get_light_ids_from_room("Kitchen"), ['1']) 
        self.assertEqual(skill._get_light_ids_from_room("Unknown"), ['1', '2', '3', '4', '5']) 

    @patch.object(SnipsHue, '_get_rooms_lights')
    @patch('requests.get')
    def test_get_lights_config(self, mock_request_get, mock_get_rooms_lights):
        response_state = {
            u'on': True,
            u'hue': 9509,
            u'colormode': u'hs',
            u'effect': u'none',
            u'alert': u'none',
            u'xy': [0.0, 0.0],
            u'reachable': False,
            u'bri': 254,
            u'ct': 432,
            u'sat': 254
        }
        mock_request_get.return_value = self.false_response({u'state': response_state})

        skill = SnipsHue("192.168.1.1", "username", ['1', '2', '3'])
        self.assertEqual(skill._get_lights_config(['1']), {'1': response_state})
        self.assertEqual(skill._get_lights_config(['1', '2']), {'1': response_state, '2': response_state})
        self.assertEqual(skill._get_lights_config(['xx']), {'xx': response_state})

    @patch.object(SnipsHue, '_get_rooms_lights')
    def test_color_map(self, mock_get_rooms_lights):
        skill = SnipsHue("192.168.1.1", "username", ['1', '2', '3'])

        self.assertEqual(skill._get_hue_saturation('red'), {'hue': 2869, 'sat': 255})
        self.assertEqual(skill._get_hue_saturation('blue'), {'hue': 44161, 'sat': 255})
        self.assertEqual(skill._get_hue_saturation('green'), {'hue': 21845, 'sat': 255})

    def tearDown(self):
        pass
コード例 #18
0
class Skill:
    def __init__(self):
        try:
            config = SnipsConfigParser.read_configuration_file(CONFIG_INI)
        except:
            config = None
        hostname = None
        code = None
        if config and config.get('secret') is not None:
            if config.get('secret').get('hostname') is not None:
                hostname = config.get('secret').get('hostname')
                if hostname == "":
                    hostname = None
            if config.get('secret').get(API_KEY) is not None:
                code = config.get('secret').get(API_KEY)
                if code == "":
                    code = None
        if hostname is None or code is None:
            print('No configuration')
        self.snipshue = SnipsHue(hostname, code)
        hostname = self.snipshue.hostname
        code = self.snipshue.username
        self.update_config(CONFIG_INI, config, hostname, code)
        self.queue = Queue.Queue()
        self.thread_handler = ThreadHandler()
        self.thread_handler.run(target=self.start_blocking)
        self.thread_handler.start_run_loop()

    def update_config(self, filename, data, hostname, code):
        if not os.path.exists(CONFIG_INI_DIR):
            os.makedirs(CONFIG_INI_DIR)
        if 'secret' not in data or data['secret'] is None:
            data['secret'] = {}
        data['secret']['hostname'] = hostname
        data['secret'][API_KEY] = code
        SnipsConfigParser.write_configuration_file(filename, data)

    def start_blocking(self, run_event):
        while run_event.is_set():
            try:
                self.queue.get(False)
            except Queue.Empty:
                with Hermes(MQTT_ADDR) as h:
                    h.subscribe_intents(self.callback).start()

    def extract_house_rooms(self, intent_message):
        house_rooms = []
        if intent_message.slots.house_room is not None:
            for room in intent_message.slots.house_room:
                house_rooms.append(room.slot_value.value.value)
        return house_rooms

    def extract_number(self, intent_message, default_number):
        number = default_number
        if intent_message.slots.intensity_number:
            number = intent_message.slots.intensity_number.first().value
        if intent_message.slots.intensity_percent:
            number = intent_message.slots.intensity_percent.first().value
        return number

    def extract_up_down(self, intent_message):
        res = "down"
        if intent_message.slots.up_down:
            res = intent_message.slots.up_down.first().value
        return res

    def extract_color(self, intent_message):
        res = None
        if intent_message.slots.color:
            res = intent_message.slots.color.first().value
        return res
        pass

    def callback(self, hermes, intent_message):
        rooms = self.extract_house_rooms(intent_message)
        if intent_message.intent.intent_name == 'lightsTurnOff':
            self.queue.put(self.lights_turn_off(hermes, intent_message, rooms))
        if intent_message.intent.intent_name == 'lightsTurnOnSet':
            self.queue.put(
                self.lights_turn_on_set(hermes, intent_message, rooms))
        if intent_message.intent.intent_name == 'lightsShift':
            self.queue.put(self.lights_shift(hermes, intent_message, rooms))
        if intent_message.intent.intent_name == 'lightsSet':
            self.queue.put(
                self.lights_turn_on_set(hermes, intent_message, rooms))
        if intent_message.intent.intent_name == 'snips-labs:lightsColor_FR_':
            self.queue.put(
                self.lights_turn_on_set(hermes, intent_message, rooms))
        if intent_message.intent.intent_name == 'snips-labs:lightsColor_EN':
            self.queue.put(
                self.lights_turn_on_set(hermes, intent_message, rooms))

    def lights_turn_off(self, hermes, intent_message, rooms):
        hermes.publish_end_session(intent_message.session_id, None)
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_off(room)
        else:
            self.snipshue.light_off(None)

    def lights_turn_on_set(self, hermes, intent_message, rooms):
        hermes.publish_end_session(intent_message.session_id, None)
        number = self.extract_number(intent_message, 100)
        color = self.extract_color(intent_message)
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_on_set(color, number, room)
        else:
            self.snipshue.light_on_set(color, number, None)

    def lights_shift(self, hermes, intent_message, rooms):
        hermes.publish_end_session(intent_message.session_id, None)
        number = self.extract_number(intent_message, 20)
        if "down" == self.extract_up_down(intent_message):
            self.lights_turn_down(number, rooms)
        else:
            self.lights_turn_up(number, rooms)

    def lights_turn_down(self, number, rooms):
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_down(number, room)
        else:
            self.snipshue.light_down(number, None)

    def lights_turn_up(self, number, rooms):
        if len(rooms) > 0:
            for room in rooms:
                self.snipshue.light_up(number, room)
        else:
            self.snipshue.light_up(number, None)
コード例 #19
0
    def test_color_map(self, mock_get_rooms_lights):
        skill = SnipsHue("192.168.1.1", "username", ['1', '2', '3'])

        self.assertEqual(skill._get_hue_saturation('red'), {'hue': 2869, 'sat': 255})
        self.assertEqual(skill._get_hue_saturation('blue'), {'hue': 44161, 'sat': 255})
        self.assertEqual(skill._get_hue_saturation('green'), {'hue': 21845, 'sat': 255})