Skip to content

Commit

Permalink
Added room recognition feature do AWS version (disabled by default). …
Browse files Browse the repository at this point in the history
…Issue #3
  • Loading branch information
fabianosan committed Dec 28, 2024
1 parent a1d0333 commit 62f2ea4
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 9 deletions.
32 changes: 30 additions & 2 deletions doc/en/INSTALLATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
6. [Test the Lambda Function](#test-the-lambda-function)
7. [Configure the Skill Service Endpoint](#configure-the-skill-service-endpoint)
8. [Account Linking](#account-linking)
9. [Enabling skill on Alexa App](#enabling-skill-on-alexa-app)
10. [Alexa Locale](#alexa-locale)
9. [Enabling room recognition](#enabling-room-recognition)
10. [Enabling skill on Alexa App](#enabling-skill-on-alexa-app)
11. [Alexa Locale](#alexa-locale)

---

Expand Down Expand Up @@ -86,6 +87,7 @@ Next, you need to create a Lambda function.
- (required) Key = **home_assistant_url**, Value = your Home Assistant instance’s Internet accessible URL _(on 443 port)_. _Do not include the trailing `/` at the end._
- (optional) Key = **home_assistant_agent_id**, Value = Your Assist Agent ID. [Instructions here](#getting-the-home_assistant_agent_id)
- (optional) Key = **home_assistant_language**, Value = Your Assist Language. _(The default is the Assist configured language)_
- (optional) Key = **home_assistant_room_recognition**: Enable the device area recognition mode with `True`. **Attention**, it only works with AI. If using the default Assist, disable this option, as no commands will work (this includes the new `Assist fallback` feature introduced in HA 2024.12 that will no longger work too).
- (optional) Key = **home_assistant_dashboard**, Value = Your dashboard path name. Example: `mushroom`. _(The default is `lovelace`)_
- (optional) Key = **home_assistant_kioskmode**, Value = `True`. Set this variable to enable KIOSKMODE. _(Make sure you have this component installed, up, and running in your Home Assistant instance)._
- (optional) Key = **debug**, Value = `True`. Set this variable to log the debug messages and allow the `home_assistant_token` environment variable.
Expand Down Expand Up @@ -198,6 +200,32 @@ Despite the Alexa documentation’s disclaimer, however, `Let’s Encrypt` certi

![](images/skill_accountlinking.png)

### Enabling room recognition
- **(ONLY WORKS WITH AI)** In this mode, the skill sends the device ID (of the `echo` device running the skill) in the Home Assistant conversation API call. With a command instruction for the AI and a label associated with the device, the AI can identify the devices in the same area as your `Alexa`. To activate, follow the steps below:

***Attention!***
## This mode slows down commands and requires more complex configurations. Additionally, it does not work with the "Assist fallback" mode enabled, which was introduced in version 2024.12 of HA:
1. Change the `home_assistant_room_recognition` configuration to `True` and perform a new `deploy`;
2. Enable conversation API debug logging by adding the following configuration to the Home Assistant `configuration.yaml` file:
```yaml
logger:
logs:
homeassistant.components.conversation: debug
```
3. Restart Home Assistant and start the skill from the desired echo device. After activation, the log will display the instruction received by the skill as shown in the example below:
```txt
2024-10-10 11:04:56.798 DEBUG (MainThread) [homeassistant.components.conversation.agent_manager] Processing in pt-BR: ligue a luz da sala. device_id: amzn1.ask.device.AMAXXXXXX
```
You can also obtain the device_id from the "device: " log using the `AWS Developer Console` > `Monitor` > `Cloud Watch logs` if you know how to do it.
4. Take the entire identifier following the device_id, e.g., `amzn1.ask.device.AMAXXXXXX`, and add a new label to the **echo device** via the `Alexa Media Player` Integration:

![Label on the echo device with the device ID received from the skill](images/echo_device_label.png)

5. Update the **AI command prompt** of your choice with the instruction below or try one that your AI understands:
```txt
If an action is requested on a device and its area is not provided, capture the identifier found after "device_id:" in the command, retrieve the label with the same identifier, and associate the area of that label with the device to determine which area the device belongs to.
```

## Enabling skill on Alexa App
- You need to use the `Alexa Mobile App` to link your account.
- In the `Alexa app`, navigate to `More` > `Skills & Games` > `Your Skills` -> `Dev`.
Expand Down
Binary file added doc/en/images/echo_device_label.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 31 additions & 2 deletions doc/pt/INSTALLATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
6. [Testar a Função Lambda](#testar-a-função-lambda)
7. [Configurar o Endpoint do Serviço da Skill](#configurar-o-endpoint-do-serviço-da-skill)
8. [Vinculação de Conta](#vinculação-de-conta)
9. [Habilitar a Skill no App Alexa](#habilitar-a-skill-no-app-alexa)
10. [Localização da Alexa](#localização-da-alexa)
9. [Ativando o reconhecimento de área](#ativando-o-reconhecimento-de-área)
10. [Habilitar a Skill no App Alexa](#habilitar-a-skill-no-app-alexa)
11. [Localização da Alexa](#localização-da-alexa)

---

Expand Down Expand Up @@ -86,6 +87,7 @@ Agora você precisa criar uma função Lambda.
- (obrigatório) Chave = **home_assistant_url**, Valor = A URL raiz do seu Home Assistant acessível pela Internet _(na porta 443)_. _Não inclua a barra `/` no final._
- (opcional) Chave = **home_assistant_agent_id**, Valor = O Agent ID do seu Assist. [instruções aqui](#obtendo-o-home_assistant_agent_id)
- (opcional) Chave = **home_assistant_language**, Valor = O idioma configurado no seu Assist. _(O padrão é o idioma configurado no Assist)_
- (opcional) Chave = **home_assistant_room_recognition**: Ative o modo de identificação de área do dispositivo com `True`. **Atenção**, só funciona com IA, se utilizar o Assist padrão, desative essa opção, pois nenhum comando não irá funcionar (isso inclui a nova funcionalidade `Assist fallback` do HA 2024.12 que também não irá funcionar).
- (opcional) Chave = **home_assistant_dashboard**, Valor = O ID do seu painel. Exemplo: `mushroom`. _(O padrão é 'lovelace') _
- (opcional) Chave = **home_assistant_kioskmode**, Valor = `True`. Defina esta variável para habilitar o KIOSKMODE. _(Certifique-se de que você tenha este componente instalado, configurado e funcionando em sua instância do Home Assistant)._
- (opcional) Chave = **debug**, Valor = `True`. Defina esta variável para registrar as mensagens de depuração e permitir a variável de ambiente `home_assistant_token`.
Expand Down Expand Up @@ -197,6 +199,33 @@ Apesar do aviso de isenção de responsabilidade da documentação da Alexa, os

![](../en/images/skill_accountlinking.png)

### Ativando o reconhecimento de área
- **(SÓ FUNCIONA COM IA)** Nesse modo, a skill envia o device id (do dispositivo `echo` que está executando a skill) na chamada da API de conversação do Home Assistant, então com uma instrução de comando para a IA e um rótulo associado no dispositivo, a IA consegue identificador os dispositivo da mesma área onde está localizado sua `Alexa`, para ativar, siga os passos abaixo:

***Atenção !***
## Esse modo deixa os comandos mais lentos e e exige configurações mais complexas, além de não funcionar com o modo "Assist fallback" ativado que foi incluido na versão 2024.12 do HA:
1. Altere a configuração `home_assistant_room_recognition` para `True` e faça um novo `deploy`;
2. Ative o log de debug da API de conversação adicionando a seguinte configuração no `configuration.yaml` do Home Assistant:
- Insira a seguinte informação:
```txt
logger:
logs:
homeassistant.components.conversation: debug
```
3. Reinicie o Home Assistant e inicie a skill pelo dispositivo echo desejado, depois de ativado, o log mostrará a instrução recebida pela skill conforme o exemplo abaixo:
```txt
2024-10-10 11:04:56.798 DEBUG (MainThread) [homeassistant.components.conversation.agent_manager] Processing in pt-BR: ligue a luz da sala. device_id: amzn1.ask.device.AMAXXXXXX
```
Você também pode obter o device_id no log "device: " pela ``AWS Developer Console`` > ```Monitor`` ``Cloud Watch logs`` se souber como fazê-lo.
4. Pegue todo o identificador que estiver após o device_id, ex.: `amzn1.ask.device.AMAXXXXXX` e adicione um novo rótulo no **dispositivo echo** pela Integração `Alexa Media Player`:
![Rótulo no dispositivo echo com o device ID recebido da skill](images/echo_device_label.png)
5. Atualize o **prompt de comando da IA** de sua preferência com a instrução abaixo ou tente uma instrução que a sua IA entenda:
```txt
Se solicitado uma ação em um dispositivo e sua área não for fornecida, capture o identificador contido após o "device_id:" no comando, obtenha o rótulo com mesmo identificador e associe a área desse rótulo ao dispositivo para saber área o dispositivo pertence.
```
## Habilitar a Skill no App Alexa
- Você precisa usar o `Alexa Mobile App` para vincular sua conta.
- No `app Alexa`, vá para `More` > `Skills & Games` > `Your Skills` -> `Dev`.
Expand Down
Binary file added doc/pt/images/echo_device_label.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 7 additions & 1 deletion lambda_functions/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,20 @@ def handle(self, handler_input):
if response:
return response

device_id = ""
home_assistant_room_recognition = bool(os.environ.get("home_assistant_room_recognition", False))
if home_assistant_room_recognition:
# Obter o deviceId do dispositivo que executou a skill
device_id = ". device_id: " + handler_input.request_envelope.context.system.device.device_id

# Resposta inicial informando que a solicitação está sendo processada
initial_response = globals().get("alexa_speak_processing")
handler_input.response_builder.speak(initial_response).set_should_end_session(False)

# Executa a parte assíncrona com asyncio
loop = asyncio.new_event_loop() # Cria um novo event loop
asyncio.set_event_loop(loop) # Define o loop de eventos para a thread atual
future = loop.run_in_executor(executor, process_conversation, query)
future = loop.run_in_executor(executor, process_conversation, query + device_id)
response = loop.run_until_complete(future)

return handler_input.response_builder.speak(response).ask(globals().get("alexa_speak_question")).response
Expand Down
10 changes: 6 additions & 4 deletions release_notes.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# New release

## What's changed
- Added English Canada language
- Fixed issue with special characters in some languages.
- Added English Canada language;
- Fixed issue with special characters in some languages;
- Added room recognition feature (disabled by default).

---

# Nova versão

## O que mudou
- Inclusão do idioma inglês canadense
- Corrigido o problema com caracteres especiais em algums idiomas.
- Inclusão do idioma inglês canadense;
- Corrigido o problema com caracteres especiais em algums idiomas;
- Adicionado a funcionalidade de reconhecimento de área/cômodo, desativado por padrão.

0 comments on commit 62f2ea4

Please sign in to comment.