Aide pour Alexa sans cloud

Mon problème

Bonjour à tous et merci par avance pour votre aide.

Il me semblait avoir vu un sujet pour un problème similaire, mais je n’ai rien trouvé qui me vienne en aide.

J’essaie depuis ce midi d’installer alexa sur HA sans Cloud (sans nabucasa)

J’ai suivi le tuto des alexiens https://www.lesalexiens.fr/domotique/home-assistant/tutoriel-piloter-home-assistant-a-la-voix-grace-a-alexa/

Je suis a la phase « Tester la fonction lambda » est j’ai le message d’erreur suivant

pour info dans mon configuration.yaml :

configuration.yaml
############################################################
##                HOME ASSISTANT: configuration           ##
############################################################


### < Configure a default setup of Home Assistant (frontend, api, etc) >
#default_config:
#
# <Connection avec Inginx Proxy Manager >
#http:
#  use_x_forwarded_for: true
#  trusted_proxies: !secret trusted_proxies
#  trusted_proxies:
#    - xxx.xx.xx.x # Add the IP address of the proxy server

## packages
homeassistant:
# Load packages
  packages: !include_dir_named packages
#  packages: !include_dir_named integrations
#  whitelist_external_dirs:
  allowlist_external_dirs:
    - /config/

# include
#group: !include /config/entities/groups/groups.yaml
#command_line: !include /config/entities/sensors_command_line/command_line.yaml
python_script: !include_dir_merge_list python_scripts/

api: 

alexa: 
  smart_home:

pour la fonction lambda_function.py :

lambda_function
#!/usr/bin/env python3.6
# coding: utf-8

# Copyright (c) 2015 Michael Auchter <a@phire.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import os
import json
import logging
import requests

logger = logging.getLogger()


class HomeAssistant(object):
    def __init__(self, config):
        self.config = config

        self.session = requests.Session()
        self.session.headers = {
            'Authorization': f'Bearer {config.bearer_token}',
            'content-type': 'application/json',
            'User-Agent': self.get_user_agent()
        }
        self.session.verify = config.ssl_verify
        self.session.cert = config.ssl_client

    def build_url(self, endpoint):
        return f'{self.config.url}/api/{endpoint}'

    def get_user_agent(self):
        library = "Home Assistant Alexa Smart Home Skill"
        aws_region = os.environ.get("AWS_DEFAULT_REGION")
        default_user_agent = requests.utils.default_user_agent()
        return f"{library} - {aws_region} - {default_user_agent}"

    def get(self, endpoint):
        r = self.session.get(self.build_url(endpoint))
        r.raise_for_status()
        return r.json()

    def post(self, endpoint, data, wait=False):
        read_timeout = None if wait else 0.01
        try:
            logger.debug(f'calling {endpoint} with {data}')
            r = self.session.post(self.build_url(endpoint),
                                  data=json.dumps(data),
                                  timeout=(None, read_timeout))
            r.raise_for_status()
            return r.json()
        except requests.exceptions.ReadTimeout:
            # Allow response timeouts after request was sent
            logger.debug(
                f'request for {endpoint} sent without waiting for response')
            return None


class Configuration(object):
    def __init__(self, filename=None, opts_dict=None):
        self._json = {}
        if filename is not None:
            with open(filename) as f:
                self._json = json.load(f)

        if opts_dict is not None:
            self._json = opts_dict

        self.url = self.get_url(self.get(['url', 'ha_url']))
        self.ssl_verify = self.get(['ssl_verify', 'ha_cert'], default=True)
        self.bearer_token = self.get(['bearer_token'], default='')
        self.ssl_client = self.get(['ssl_client'], default='')
        self.debug = self.get(['debug'], default=False)

    def get(self, keys, default=None):
        for key in keys:
            if key in self._json:
                return self._json[key]
        return default

    def get_url(self, url):
        """Returns Home Assistant base url without '/api' or trailing slash"""
        if not url:
            raise ValueError('Property "url" is missing in config')

        return url.rstrip("/api").rstrip("/")


def event_handler(event, context):
    config = Configuration('config.json')
    if config.debug:
        logger.setLevel(logging.DEBUG)
    ha = HomeAssistant(config)

    return ha.post('alexa/smart_home', event, wait=True)

pour le config.json :

config.json
{
  "url": "https://xxxxxxxxxxxx.duckdns.org:8123/api",
  "bearer_token": "xxxxxxxxxxxxxxxxxxxxMTY5xxxxxxNjU5fxxxxxxxxxxxxxx",
  "debug": false,
  "ssl_verify": true,
  "ssl_client": []
}

Ma configuration


[center]

System Information

version core-2023.9.3
installation_type Home Assistant OS
dev false
hassio true
docker true
user root
virtualenv false
python_version 3.11.5
os_name Linux
os_version 6.1.45
arch x86_64
timezone Europe/Paris
config_dir /config
Home Assistant Community Store
GitHub API ok
GitHub Content ok
GitHub Web ok
GitHub API Calls Remaining 5000
Installed Version 1.33.0
Stage running
Available Repositories 1312
Downloaded Repositories 43
Home Assistant Cloud
logged_in false
can_reach_cert_server ok
can_reach_cloud_auth ok
can_reach_cloud ok
Home Assistant Supervisor
host_os Home Assistant OS 10.5
update_channel stable
supervisor_version supervisor-2023.09.2
agent_version 1.5.1
docker_version 23.0.6
disk_total 228.5 GB
disk_used 15.5 GB
healthy true
supported true
board generic-x86-64
supervisor_api ok
version_api ok
installed_addons Terminal & SSH (9.7.1), Samba share (10.0.2), File editor (5.6.0), Duck DNS (1.15.0), Mosquitto broker (6.3.1), MariaDB (2.6.1), NGINX Home Assistant SSL proxy (3.5.0), Nginx Proxy Manager (0.12.3), Node-RED (14.5.0), Plex Media Server (3.2.4), Home Assistant Google Drive Backup (0.111.1), ESPHome (2023.9.1), Network UPS Tools (0.12.1), Zigbee2MQTT (1.33.0-1), MQTT Explorer (browser-1.0.1), Samba Backup (5.2.0), Let’s Encrypt (4.12.9), Linky (1.1.0)
Dashboards
dashboards 2
resources 32
views 20
mode storage
Recorder
oldest_recorder_run 23 septembre 2023 à 18:45
current_recorder_run 30 septembre 2023 à 14:38
estimated_db_size 653.32 MiB
database_engine sqlite
database_version 3.41.2
` ___

Après quelques heure de recherche :face_with_head_bandage:
J’ai trouvé le problème !
Voici la solution :

Le fichier haaska qui contient les fichiers config.json et haaska.py doit etre modifier

  1. le fichier haaska.py doit etre renommer en lambda_function.py
  2. Ensuite, il faut éditer le fichier et remplacer def event_handler(event, context): par def lambda_handler(event, context):
  3. dans le fichier congig.json il faut remplacer "url": "https://xxxxxx.duckdns.org:8123/api", par "url": "https://xxxxxxx.duckdns.org/api",

toutes les modification peuvent être réaliser a partir de l’interface AWS

Ensuite vous devriez avoir le test lambda fonction en réussite

  • Comment faire pour n’avoir que les entités que j’ai besoin de commander avec Alexa ? Ou comment exclure les entités que je n’ai pas besoin dans Alexa. ( car ha remonte dans alexa 255 appareils :upside_down_face:)

Merci pour votre aide

Edit 1 : j’ai trouvé le code suivant sur ce lien https://www.nabucasa.com/config/amazon_alexa/ mais je n’ai pas nabucasa.
J’ai malgré tous fait les modifications suivantes

J’ai mis le code suivant dans configuration.yaml

configuration.yaml
############################################################
##                HOME ASSISTANT: configuration           ##
############################################################


### < Configure a default setup of Home Assistant (frontend, api, etc) >
#default_config:
#
# <Connection avec Inginx Proxy Manager >
#http:
#  use_x_forwarded_for: true
#  trusted_proxies: !secret trusted_proxies
#  trusted_proxies:
#    - xxx.xx.xx.x # Add the IP address of the proxy server

## packages
homeassistant:
# Load packages
  packages: !include_dir_named packages
#  packages: !include_dir_named integrations
#  whitelist_external_dirs:
  allowlist_external_dirs:
    - /config/

# include
#group: !include /config/entities/groups/groups.yaml
#command_line: !include /config/entities/sensors_command_line/command_line.yaml
python_script: !include_dir_merge_list python_scripts/

J’ai ajouté un fichier alexa.yaml dans mon dossier packages

alexa.yaml
#
api:
  alexa:
    smart_home:
      locale: fr-FR
      endpoint: https://api.eu.amazonalexa.com/v3/events
      client_id: !secret alexa_client_id 
      client_secret: !secret alexa_client_secret 
      filter:
        include_entities:
          - switch.plug_zb_001         #ZB001
          - switch.0xa4c13892cedc4ea2  #ZB002
          - switch.0xa4c1386442433559  #ZB003
          - switch.0xa4c13897b38afa8d  #ZB004
          - switch.0xa4c138d21a4ada2a  #ZB005
          - switch.0xa4c1380fee2a7965  #ZB006
          - switch.0xa4c138505168542e  #ZB007
          - switch.0xa4c138b2b8cc9c0c  #ZB008
          - switch.0xa4c1389a6388b5b5  #ZB009
          - switch.0xa4c138aefffd1e8c  #ZB010
          - switch.0xa4c138b41955b770  #ZB011      
        
      entity_config:
        switch.plug_zb_001:
          name: "bar"
          description: "prise zigbee 001 - bar"
        switch.0xa4c13892cedc4ea2:
          name: "radiateur douche"
          description: "prise zigbee 002 - radiateur douche"
        switch.0xa4c1386442433559:
          name: "radiateur bain"
          description: "prise zigbee 003 - radiateur bain"
        switch.0xa4c13897b38afa8d:
          name: "PC Pascal"
          description: "prise zigbee 004 - PC Pascal"       
        switch.0xa4c138d21a4ada2a:
          name: "congelateur"
          description: "prise zigbee 005 - congelateur"
        switch.0xa4c1380fee2a7965:
          name: "frigo indesit"
          description: "prise zigbee 006 - frigo indesit"
        switch.0xa4c138505168542e:
          name: "frigo far"
          description: "prise zigbee 007 - frigo far"
        switch.0xa4c138b2b8cc9c0c:
          name: "frigo americain"
          description: "prise zigbee 008 - frigo americain"
        switch.0xa4c1389a6388b5b5:
          name: "lave vaisselle"
          description: "prise zigbee 009 - lave vaisselle"
        switch.0xa4c138aefffd1e8c:
          name: "lave linge"
          description: "prise zigbee 010 - lave linge"
        switch.0xa4c138b41955b770:
          name: "seche linge"
          description: "prise zigbee 011 - seche linge"

Édit 2 : c’est fonctionnel, merci a @Neuvidor pour son aide :wink:

1 « J'aime »

C’est avec plaisir, quand on a la solution autant en faire profité les autres👍