Ikea Tradfri & Eedomus

Partagez ici vos guides et explications

Ikea Tradfri & Eedomus

Messagepar Cen » 09 Oct 2021 12:10

Introduction
J’ai entrepris ce projet à la suite de mes mésaventures avec Zigbee sur eedomus. J’ai acheté ma clé Zigate il y a deux ans, et j’ai fait quelques essais avec des devices Xiaomi Aqara. Ca fonctionnait. Récemment, j’ai essayé de remettre tout cela en route, mais sans succès, malgré avoir passé beaucoup beaucoup d’heures.

En résumé :
La Zigate est bien reconnue, mais « presque » impossible d’apparier. J’ai installé la dernière version sur la Zigate, soit la 3.1e puis la 3.2. J’ai upgradé depuis la box eedomus, et voyant que ça ne fonctionnait pas, je l’ai fait à nouveau séparément, depuis mon laptop. La Zigate est toujours bien reconnue, immédiatement sur la box eedomus. Tout semble OK sur la box eedomus, les deux leds sont bien allumées, elle indique bien la version 3.1e ou 3.2.
Mais l’inclusion est aléatoire : le cube, la télécommande Ikea, les ampoules Ikea, le sensor aqara Temperature and Humidity, tous causent des problèmes. J’ai fait de multiples essais, en revoyant en détails les expériences présentées dans les différents posts (rebooter la box avant, faire un erase, utiliser l’autre port USB..), mais sans succès. J’ai testé aussi sur ma deuxième box eedomus. De temps en temps, le cube est détecté (hourra !) et fonctionne pendant quelques jours. Mais ensuite, eedomus me dit « Nouveau device détecté » à chaque fois que je le touche.
Bref, ma conclusion est que Zigbee/Zigate/eedomus ne marche pas chez moi. Par contre, les produits Ikea fonctionnent parfaitement : avec mes centaines d’essais, j’ai toujours pu ré-apparier les switches, ampoules, etc, entre eux, sans aucune difficulté.

Fort de ce constat, j’ai acquis le Hub Ikea et au lieu d’accéder mes ampoules Ikea par ZigBee, je les accède à travers un actionneur http qui pilote un Raspberry Pi, qui lui pilote le Hub Ikea. C’est ce projet que je présente dans ce tuto. C’est certes un peu lourd, mais ça marche parfaitement !

Matériel et connaissances requises
Matériel
• Ampoules, interrupteurs Ikea Tradfri
• Le Hub Ikea. C’est lui qui va passer les commandes aux ampoules, etc
• Et un Raspberry Pi. Je possède un Raspberry Pi4, mais pour un tel projet, il faut le minimum du minimum

Connaissances
• Règles et actionneur http
• Installer un OS sur le Raspberry, car je ne couvre pas cela dans ce tuto
• Savoir installer les scripts et quelques manipulations sur le Raspberry

Temps nécessaire : Comptez entre 1 et 2 heures, si vous avez votre Raspberry prêt

La solution
1-Solution.jpg
Solution
1-Solution.jpg (52.17 Kio) Consulté 12776 fois


Sur eedomus : un actionneur http qui envoient les requêtes sur un Raspberry PI
Sur Raspberry :
Un server WEB qui reçoit et traite les requêtes http reçues de la box eedomus
Le protocole COAP qui envoie ces commandes au Hub Ikea
Un script qui « pool » les lampes et renvoie l’état (feedback) sur eedomus, si les lampes ont été actionnées par le switch

Les avantages de cette solution : Ca fonctionne, c’est simple à mettre en route, c’est rapide
Les inconvénients : C’est lourd, car j’ai rajouté donc le hub Ikea et le Raspberry dans l’équation. Dans mon cas, je possède déjà un Raspberry pour synchroniser les images de mes caméras sur eedomus et sur GoogleDrive. Et le Hub Ikea, je crois qu’il est de toute façon incontournable pour mettre à jour les firmeware
Un autre inconvénient est le retour d’état. Je l’ai implémenté par pooling, et le pool se fait toutes les 5 minutes. Par contre, on peut très bien augmenter la fréquence du script, et le tourner toutes les minutes.

Etape 1 : Pairing / Apps Ikea (15min)
Il faut installer le matériel Ikea, l’apps Ikea sur votre Android, faire le pairing, créer les groupes nécessaires. Dans cette étape, vous devrez avoir vos ampoules fonctionnant avec les switches Ikea, et l’application Ikea
• Pairing de l’ampoule avec un switch, … Pour cela, il faut suivre la notice d’instruction Ikea (Switch : appuyer 4x pour reset, attendre 30s, et appuyer 10s très proche de l’ampoule
• IkeaHub: Sur l’apps Ikea, créer les groups nécessaires


Etape 2 : Installation de COAP sur le Raspberry (10min)
https://github.com/glenndehaan/ikea-tradfri-coap-docs

As root

Install some tools needed
apt install autoconf automake libtool

Install git if not already installed
apt install git

Install and compile COAP
cd /home/pi
git clone --depth 1 --recursive -b dtls https://github.com/home-assistant/libcoap.git
cd libcoap
./autogen.sh
./configure --disable-documentation --disable-shared --without-debug CFLAGS="-D COAP_DEBUG_FD=stderr"
make
make install

Etape 3 : Installation de lighttpd sur le Raspberry (15min)
https://raspberrypiprojects.com/how-to- ... nd-python/

sudo apt install lighttpd
sudo vi /var/www/html/index.html "Hello World", and check that server works: http://192.168.0.10
sudo apt install php7.3 php7.3-fpm php7.3-cgi
sudo lighttpd-enable-mod fastcgi-/php
sudo service lighttpd force-reload
sudo vi /var/www/html/test.php 
<?php
print("Hello World");

Tester le server depuis un browser. Mon Raspberry est en 192.168.0.10, donc : http://192.168.0.10/test.php


sudo vi /var/www/html/switch.php

<?php
header("HTTP/1.1 200 OK");
if (isset($_REQUEST['action'], $_REQUEST['type'], $_REQUEST['device'])) {
$device = $_REQUEST['device'];
$type = $_REQUEST['type'];
$action = $_REQUEST['action'];
$cmd = "/home/pi/Ikea_Command.sh $action $type $device";
system("$cmd");
echo "Command<br>$cmd<br>executed...";
}
?>

Etape 4 : Installer les scripts sur le Raspberry (15min)
2-Scripts.jpg
2-Scripts.jpg (95.31 Kio) Consulté 12727 fois


• Connectez-vous avec votre utilisateur « pi » et installez ces 6 scripts dans /home/pi (Ikea_Command.sh, Ikea_FeedbackMain.sh, Ikea_Feedback.sh, Ikea_Info.sh, Ikea_GeneraKey.sh, Ikea_Config.conf)
• Les mettre en exécutable, grâce à la commande : chmod 755 *Ikea*
• Mettez vos informations à jour dans le fichier «Ikea_Config.conf » (sauf pour l'instant KEY)
a. IP="192.168.0.78" #IP de votre Hub Ikea tradfri
b. GATEWAYCODE="XXXXXXXXXXX" #Code spécifié sur votre hub Ikea tradfri
c. USERNAME="XXXX" #ID à utiliser pour créer une session, A vous de choisir, par exemple « EedomusIkea »
d. KEY="XXX" #Key, valable pour 6 semaines (donnée par le script « Ikea_GenerateKey.sh »
• Executez le script Ikea_GenerateKey.sh. Il va vous donner une clé « KEY», à insérer dans le script «Ikea_Config.conf »

• Tourner le script “Ikea_Info,sh”. Ce script va afficher les ID des lampes, switches, groupes. Par example
*****************************************************************************************
List of device IDs: 65548,65540,65543,65537,65544,65546,65538,65539,65542
*****************************************************************************************
65540: {"9001":"TRADFRI bulb bla bla bla}

*****************************************************************************************
List of Groups: 131077,131080,131075,131073,131078,131079
*****************************************************************************************
131077: {"5851":25,"9001":"Lampes Plafond bla bla bla}

Ayant maintenant les ID des lampes et groupes (dans l’exemple ci-dessus, l’ID de la lampe est le « 65540”, et celui du groupe appelé « Lampes Plafond » est le « 131077 »

Etape 5:Integration dans eedomus
Je montre un exemple avec un groupe de lampes. A vous ensuite de copier et créer le nombre d’actionneur désiré. Il vous faut l’adresse IP de votre Raspberry PI (192.168.0.10 dans l’exemple ci-dessous)
Paramètre « action » : on, off, ou une valeur entre 0 et 254 qui représente la luminosité voulue
Paramètre « type : Individual ou group. On spécifie ici si la commande s’adresse à une lampe en particulier ou à un groupe
Paramètre « device » : C’est le numéro de device (voir chapitre précédent, ces informations sont données par le script script “Ikea_Info,sh”.


Création de 1 actionneur HTTP
Nom personalisé Lampes Plafond
Usage Lampe
Pièce Cuisine
Note utilisateur Lance une requête HTTP sur le Raspberry Pi. Ce Raspberry pilote le hub Ikea

Example Groupe Lampe1
Eteindre http://192.168.0.10/switch.php?action=o ... ice=131077
Allumer http://192.168.0.10/switch.php?action=o ... ice=131077
On 10% http://192.168.0.10/switch.php?action=2 ... ice=131077
On 20% http://192.168.0.10/switch.php?action=5 ... ice=131077
On 30% http://192.168.0.10/switch.php?action=7 ... ice=131077
… …

On 100% http://192.168.0.10/switch.php?action=2 ... ice=131077

3a-Eedomus Integration.jpg
3a-Eedomus Integration.jpg (58.35 Kio) Consulté 12776 fois


3b-Eedomus Integration.jpg
3b-Eedomus Integration.jpg (145.18 Kio) Consulté 12776 fois



Etape 6: Feedback
Il y a encore une opération à effectuer pour installer le feedback

Modifier le script « Ikea_Feedback.sh ». Il s’agit de mettre à jour les variables eedomusA et eedomusC avec l’adresse IP de votre box eedomus, et vos codes secrets API de l’eedomus

Modifier le script « Ikea_FeedbackMain.sh ». Dans mon exemple, il y a 3 lampes qui sont questionnées par le script. Pour chacune d’elle, vous devez spécifier
« L » : l’ID zibbee de la lampe
« EEDOMUS » : l’ID de l’actionneur http. Voir dans eedomus, paramètres experts

Et faire tourner ce script automatiquement, toutes les 5min
crontab -e
#Every 5 min, check status of the Ikea bulbs
*/5 * * * * /home/pi/Ikea_FeedbackMain.sh


Et voila !

Scripts

Ikea_Command.sh
Code : Tout sélectionner
#!/bin/bash
#CEN  07/10/2021
# Parameter 1: Command :<Off|On|On10|On25|On50|On75|On100|[1..254]>
# Parameter 2: Specify if the command is for a group or an individual bulb :<Individual|Group>
# Parameter 3: Zigbee device id
# Example
#   ./Ikea_Command.sh 100 Group 131075    #Switch On, brightness 100, All bulbs in the group 131075
#   ./Ikea_Command.sh On Group 131075     #Switch On, brightness same as previous, All bulbs in the group 131075
#   ./Ikea_Command.sh On75 Group 131075   #Switch On, brightness 75% (190), All bulbs in the group 131075


##########################################
#Zigbee DeviceID
##########################################
#Group "Lampes murales cuisines, 131075
#  65537   Switch                   
#  65538   Lampe Cuisine murale 1 
#  65539   Lampe Cuisine murale 2   
#  65540   Lampe Cuisine murale 3   
#Group "Lampes Plafond",  131077
#  65542   Switch
#  65543   Lampe Cuisine plafond 1
#  65544   Lampe Cuisine plafond 2
#Group "Lampes Buanderie", 131078
#  65545        Switch
#  65546        Lampe Buanderie 1

 


############################################################################################################
#Read configuration file
############################################################################################################
source /home/pi/Ikea_Config.conf


############################################################################################################
#Register time when the script starts
############################################################################################################
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"

############################################################################################################
#Error function
############################################################################################################
Error () {
  TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
  echo "$TIMESTAMP $1"
  echo "Usage $0 <Off|On|On10|On25|On50|On75|On100|[1..254]> <Individual|Group> <Zigbee deviceid>"
}



############################################################################################################
#Retrieve parameters and check them
############################################################################################################
if [ ! $# -eq 3 ]
  then
    Error "You must provide 3 arguments to the script"
    exit 1
fi
ACTION=${1^^} #Parameter 1, in upper case
TYPE=${2^^}   #Parameter 2, in upper case
ID=$3


############################################################################################################
#Log the start of this script
############################################################################################################
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP Action=$ACTION, Type=$TYPE, ID=$ID Start"


############################################################################################################
#If $ACTION is a number in range [1..254], switch on to the brightness specified
############################################################################################################
if (($ACTION>0  && $ACTION <255))
then
  case $TYPE in
    GROUP)
      #Variables are not expanded into a single quote `. So, I to close the sq before the variable, and reopen the sq after
      #e.g, brightness of 60: coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851": 60 }' "coaps://$IP:5684/15004/$ID"
      coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851":'"$ACTION"' }' "coaps://$IP:5684/15004/$ID"
    ;;
    INDIVIDUAL)
      #Variables are not expanded into a single quote `. So, I to close the sq before the variable, and reopen the sq after
      #e.g, brightness of 60: coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": 60 }] }' "coaps://$IP:5684/15001/$ID"
      coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": '"$ACTION" ' }] }' "coaps://$IP:5684/15001/$ID"
    ;;

    *)
      Error "Unknown second parameter. Must be Individual or Group"
      exit 1
    ;;
  esac

  #Log & End of the script
  TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
  echo "$TIMESTAMP Action=$ACTION, Type=$TYPE, ID=$ID Done"
  exit
fi

############################################################################################################x
#Check the other $ACTION: INFO, ON, OFF, ON10, ON25, ON50, ON75, ON100
############################################################################################################
case $ACTION in
  INFO)
    echo "Devices id"
    coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15001"
    echo
    echo "List of available endpoints"
    coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/.well-known/core"
    echo
    echo "List of group"
    coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15004"
    echo
    echo -n "Groups details: 131073"
    coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15004/131073"
    echo
    echo -n "Groups details: 131075"
    coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15004/131075"
    echo
    echo -n "Groups details: 131077"
    coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15004/131077"
  ;;

  OFF)
    case $TYPE in
      GROUP)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5850": 0 }' "coaps://$IP:5684/15004/$ID"
      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5850": 0 }] }' "coaps://$IP:5684/15001/$ID"
      ;;
   
      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;

  ON)
    case $TYPE in
      GROUP)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5850": 1 }' "coaps://$IP:5684/15004/$ID"
      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5850": 1 }] }' "coaps://$IP:5684/15001/$ID"
      ;;

      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;

  ON10)
    case $TYPE in
      GROUP)
       coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851": 25 }' "coaps://$IP:5684/15004/$ID"
      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": 25 }] }' "coaps://$IP:5684/15001/$ID"
      ;;

      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;

  ON25)
    case $TYPE in
      GROUP)
       coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851": 60 }' "coaps://$IP:5684/15004/$ID"

      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": 60 }] }' "coaps://$IP:5684/15001/$ID"
      ;;

      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;

  ON50)
    case $TYPE in
      GROUP)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851": 127 }' "coaps://$IP:5684/15004/$ID"
      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": 127 }] }' "coaps://$IP:5684/15001/$ID"
      ;;

      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;

  ON75)
    case $TYPE in
      GROUP)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851": 190 }' "coaps://$IP:5684/15004/$ID"
      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": 190 }] }' "coaps://$IP:5684/15001/$ID"
      ;;

      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;

  ON100)
    case $TYPE in
      GROUP)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "5851": 254 }' "coaps://$IP:5684/15004/$ID"
      ;;

      INDIVIDUAL)
        coap-client -m put -u "$USERNAME" -k "$KEY" -e '{ "3311": [{ "5851": 254 }] }' "coaps://$IP:5684/15001/$ID"
      ;;

      *)
        Error "Unknown second parameter. Must be Individual or Group"
        exit 1
      ;;
    esac
  ;;
 
 
  *)
    Error "Unknown first parameter"
    exit 1
  ;;
esac

#Log & End of the script
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP Action=$ACTION, Type=$TYPE, ID=$ID Done"
exit






Ikea_FeedbackMain.sh
Code : Tout sélectionner
#!/bin/bash
#CEN 07/10/2021
#Call Ikea_Feedback.sh with the first lamp of each group and the eedomus device ID


############################################################################################################
#Log file and redirection
############################################################################################################
LOG=/home/pi/Ikea_FeedbackMain.log
exec 1>>$LOG 2>&1

#Pool first lamp of group "Ampoules Mur"
L="65538"
EEDOMUS="YOUR ACTIONNEUR HTTP EEDOMUS ID"
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo
echo "$TIMESTAMP Bulb $L Start"
/home/pi/Ikea_Feedback.sh $L $EEDOMUS
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP Bulb $L Done"

#Pool first lamp of group "Ampoules Plafond"
L="65543"
EEDOMUS="YOUR ACTIONNEUR HTTP EEDOMUS ID"
echo
echo "$TIMESTAMP Bulb $L Start"
/home/pi/Ikea_Feedback.sh $L $EEDOMUS
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP Bulb $L Done"

#Pool first lamp of group "Buanderie"
L="65546"
EEDOMUS="YOUR ACTIONNEUR HTTP EEDOMUS ID"
echo
echo "$TIMESTAMP Bulb $L Start"
/home/pi/Ikea_Feedback.sh $L $EEDOMUS
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP Bulb $L Done"


############################################################################################################
#Log file management
############################################################################################################
maximumsize=5000  #5MB
actualsize=$(du -k "$LOG" | cut -f 1)
if [ $actualsize -ge $maximumsize ]; then
  TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
  echo "$TIMESTAMP $0 $LOG size is $actualsize. This is over $maximumsize kb, move as .old"
  mv $LOG $LOG.old
fi



Ikea_Feedback.sh
Code : Tout sélectionner
#!/bin/bash
#CEN 07/10/2021
# Query the first lamp of the group "Lampes murales Cuisine
# if the Lamp is On
#   Check if a file exist (./Ikea-65538-Off-100.status)
#   if this file exists, all OK
#   if this file does not exist, inform eedomus and create it
# if the Lamp is Off
#   Check if a file exist (./Ikea-65538-Off-100.status)
#   if this file exists, inform eedomus and delete the file
#   if this file does not exist, all OK

# Parameter 1: Zigbee device id
# Parameter 2: eedomus periph id
# Example ./Ikea_Feedback 65538 xxxxxxxx


##########################################
#Zigbee DeviceID
##########################################
#Group "Lampes murales cuisines, 131075
#  65537        Switch
#  65538        Lampe Cuisine murale 1
#  65539        Lampe Cuisine murale 2
#  65540        Lampe Cuisine murale 3
#Group "Lampes Plafond",  131077
#  65542        Switch
#  65543        Lampe Cuisine plafond 1
#  65544        Lampe Cuisine plafond 2
#Group "Lampes Buanderie", 131078
#  65545        Switch
#  65546        Lampe Buanderie 1


############################################################################################################
#Command eedomus, Header and Footer
############################################################################################################
eedomusA="http://IPEEDOMUS/api/set?action=periph.value&periph_id="     
eedomusB="&value="
eedomusC="&api_user=XXXX&api_secret=XXXX"


############################################################################################################
#Read configuration file
############################################################################################################
source /home/pi/Ikea_Config.conf


############################################################################################################
#Register time when the script starts
############################################################################################################
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`

############################################################################################################
#Retrieve parameters and check them
############################################################################################################
if [ ! $# -eq 2 ]
  then
    echo "You must provide 2 parameters"
    echo "Usage $0 <device id> <eedomus periph id>"
    exit 1
fi
DEVICEID=${1}    #Parameter 1
EEDOMUSID=${2}   #Parameter 2



############################################################################################################
#Function Query
############################################################################################################
query () {
  LDEVICEID=$1

  #Run the command coap command and pass the result to awk, given as parameter the device id
  /usr/local/bin/coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15001/$LDEVICEID"  | awk  -F "," '

    BEGIN {}

    #On/Off
    /"5850":1/   {res="ON "}
    /"5850":0/   {res="OFF "}

    #Brightness
    {
      i=index($0,"5851")  #i is the index in the string, where we have the parameter 5851
      a=substr($0,i,9)    #Extract 9 chars from there, so we are sure to have 3 digits parameters ==> a=5851":10}
      split(a,b,":");     #b[2] contains 10}
      a=b[2]+0;           #Converts the string to numeric. awk takes only the values that fit the numeric description. ==> 10} ==10; 60,"==60
      res=res a
    }
    END {
      print res
    }' >./Ikea_$1_State
    result=$(cat ./Ikea_$1_State)
} #function query



############################################################################################################
#Function eedomus
############################################################################################################
Updateeedomus() {
#if http OK, curl returns:{ "success": 1, "body": { "result": "[OK]" } }
#if not OK:               { "success": "0", "body": { "error_code": "1", "error_msg": "Authentification error." } }
#                         { "success": "0", "body": { "error_code": "6", "error_msg": "Unknown peripheral value [NodeKMCUEMOOK]." } }
#                         { "success": "0", "body": { "error_code": "3", "error_msg": "Peripheral does not exist." } }

case $STATUS in
  OFF)
    EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"0"$eedomusC  #0==> Off
  ;;

  ON)
    #2 ways of comparing
    if   [[ $BRIGHTNESS -gt 242 ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"100"$eedomusC  #100%
    elif [[ $BRIGHTNESS -gt 216 ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"90"$eedomusC   # 90%
    elif [[ $BRIGHTNESS -gt 191 ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"80"$eedomusC   # 80%
    elif [[ $BRIGHTNESS -gt 165 ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"70"$eedomusC   # 70%
    elif [[ $BRIGHTNESS -gt 140 ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"60"$eedomusC   # 60%
    elif [[ $BRIGHTNESS -gt 115 ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"50"$eedomusC   # 50%
    elif [[ $BRIGHTNESS -gt 89  ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"40"$eedomusC   # 40%
    elif [[ $BRIGHTNESS -gt 64  ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"30"$eedomusC   # 30%
    elif [[ $BRIGHTNESS -gt 38  ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"20"$eedomusC   # 20%
    elif [[ $BRIGHTNESS -gt 0   ]]; then EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"10"$eedomusC   # 10%
    else EedomusHTTP=$eedomusA$EEDOMUSID$eedomusB"0"$eedomusC                                    #0==> Off
    fi
  ;;
esac

#echo $EedomusHTTP
curl "$EedomusHTTP" 2>/dev/null  #To avoid to have some stats in the logfile
} #Updateeedomus



############################################################################################################
#MAIN
############################################################################################################

#1-Keep a backup of the current State file
if [ -f "./Ikea_$1_State" ]
then
  cp ./Ikea_$1_State ./Ikea_$1_State.previous
fi


#2-Query device. This will create a new State file
query $DEVICEID  # return result=  "Result= Ikea-65538-Off-100"
STATUS=$(echo $result| awk  '{print $1}')
BRIGHTNESS=$(echo $result| awk '{print $2}')
echo "State= " $result
#echo Status=$STATUS
#echo Brightness=$BRIGHTNESS

#3-Compare previous state with Current state
if cmp -s ""./Ikea_$1_State ""./Ikea_$1_State.previous; then
  #printf 'The file "%s" is the same as "%s"\n' "./Ikea_$1_State" "./Ikea_$1_State.previous"
  echo "No update needed"
else
  #printf 'The file "%s" is different from "%s"\n' "./Ikea_$1_State" "./Ikea_$1_State.previous"
  echo "Eedomus updade needed"
  Updateeedomus
fi


exit



Ikea_Info.sh
Code : Tout sélectionner
#!/bin/bash
#CEN  07/10/2021
#Query the Ikea hub.
# Get the list of devices, and query the details for each device
# Get the list of groups, and query the details for each group

exec 2>>/dev/null

############################################################################################################
#Read configuration file
############################################################################################################
source /home/pi/Ikea_Config.conf


############################################################################################################
#Register time when the script starts
############################################################################################################
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`


###################################################################################################################
#List of available endpoints
###################################################################################################################
echo "List of available endpoints"
coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/.well-known/core"
echo


###################################################################################################################
#Device ID
###################################################################################################################
#The command "coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15001"" provides the following output
#[65543,65540,65539,65542,65537,65544,65538,65546,65548]
coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15001" |  awk -v KEY="$KEY" -v USER="$USERNAME" -v IP="$IP"  '
BEGIN { }
// {
  gsub(/\[/,"")        #replace [ by nothing
  gsub(/\]/,"")        #replace ] by nothing
  n=split($0,Arr,",")  #Split with ","
 
  print "*****************************************************************************************"
  print "List of device IDs: " $0
  print "*****************************************************************************************"
  for (i = 1; i <=n; i++) {
    printf Arr[i] ": "
    cmd="coap-client -m get -u "USER " -k "KEY " \"coaps://"IP":5684/15001/"Arr[i]"\""
    #print "cmd command:" cmd

    while (( cmd  | getline res ) > 0) {               #Read all the lines provided by cmd
     print res                     
    }
    close(cmd)
  }
}
'  #end awk

echo

###################################################################################################################
#Groups
###################################################################################################################
#The command "coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15004" provides the following output
#[131077,131075,131073,131078,131079,131080]
coap-client -m get -u "$USERNAME" -k "$KEY" "coaps://$IP:5684/15004" |  awk -v KEY="$KEY" -v USER="$USERNAME" -v IP="$IP"  '
BEGIN { }
// {
  gsub(/\[/,"")        #replace [ by nothing
  gsub(/\]/,"")        #replace ] by nothing
  n=split($0,Arr,",")  #Split with ","

  print "*****************************************************************************************"
  print "List of Groups: " $0
  print "*****************************************************************************************"
  for (i = 1; i <=n; i++) {
    printf Arr[i] ": "
    cmd="coap-client -m get -u "USER " -k "KEY " \"coaps://"IP":5684/15004/"Arr[i]"\""
    #print "cmd command:" cmd

    while (( cmd  | getline res ) > 0) {               #Read all the lines provided by cmd
     print res
    }
    close(cmd)
  }
}
'  #end awk



Ikea_GeneraKey.sh
Code : Tout sélectionner
#!/bin/bash
# CEN 07/10/2021
# Reniew the Ikea Key
IP="IP OF YOUR IKEA HUB"                    #IP of the Ikea tradfri hub
GATEWAYCODE="YOUR CODE"      #Code written on the Ikea tradfree hub
USERNAME="YOUR SESSION ID"   #Name used to open the session, and at each session. Valid for 6 weeks



############################################################################################################
#To get the key, valid for 6 weeks
############################################################################################################
coap-client -m post -u "Client_identity" -k "$GATEWAYCODE" -e "{\"9090\":\"$USERNAME\"}" "coaps://$IP:5684/15011/9063"
echo "Include the information into the variable \"KEY\" in all scripts"



Ikea_Config.conf
Code : Tout sélectionner
############################################################################################################
#Contain all the configuration required by the Ikea scripts
#CEN / 07/10/2021
############################################################################################################
IP="192.168.0.78"                    #IP of the Ikea tradfri hub
GATEWAYCODE="XXXXXXX"       #Code written on the Ikea tradfri hub
USERNAME="XXXX"                   #Name used to open the session, and at each session. Valid for 6 weeks
KEY="XXXX"               #Key given, valid for 6 weeks. 6 weeks extended at each call. Used with username USERNAME
Dernière édition par Cen le 10 Oct 2021 10:54, édité 1 fois.
Cen
 
Messages : 53
Inscription : 14 Oct 2015

Re: Ikea Tradfri & Eedomus

Messagepar ARTNOW » 09 Oct 2021 13:03

Beau boulot CEN ;)
EEDOMUS + -RFP1000-IPX 800 V4-IPX 800 V5 - FIBARO -GOOGLE(Home-Nest & mini)
ARDUINO-RASPBERRY PRUSA MK3S
Domotisation de :1xPiscine/9xClimatisations réversibles/2xVolets somfy/1xAlarme/1xChauffe-Eau thermodynamique/3xPortes Garage et 1xportail
ARTNOW
 
Messages : 1280
Inscription : 22 Avr 2018
Localisation : LOIRE ATLANTIQUE

Re: Ikea Tradfri & Eedomus

Messagepar Cen » 10 Oct 2021 07:52

Merci!!! N’hésite pas à me solliciter si nécessaire
Cen
 
Messages : 53
Inscription : 14 Oct 2015

Re: Ikea Tradfri & Eedomus

Messagepar galaksy2001 » 12 Oct 2021 07:51

Merci pour le partage ;)
galaksy2001
 
Messages : 727
Inscription : 06 Jan 2014

Re: Ikea Tradfri & Eedomus

Messagepar eedomusbox » 18 Oct 2021 11:07

Super boulot.
eedomusbox
 
Messages : 887
Inscription : 12 Sep 2014
Localisation : 69

Re: Ikea Tradfri & Eedomus

Messagepar KikiFUNstyle » 19 Oct 2021 09:46

Superbe tuto :)

Il y a aussi la possibilité de contrôler ça avec Node-RED (je n'ai pas de module Ikea Tradfri ...)
https://flows.nodered.org/node/node-red ... ea-tradfri
ZWave / RFXCom / broadlink RM /Google Mini / Yeelight / Xiaomi Vacuum V1 / Shelly <3 / Node-RED <3 <3
[Store] Shelly
KikiFUNstyle
 
Messages : 908
Inscription : 24 Avr 2014
Localisation : Toulouse

Re: Ikea Tradfri & Eedomus

Messagepar Cen » 19 Oct 2021 09:52

KikiFUNstyle a écrit:Superbe tuto :)

Il y a aussi la possibilité de contrôler ça avec Node-RED (je n'ai pas de module Ikea Tradfri ...)
https://flows.nodered.org/node/node-red ... ea-tradfri



Merci!!
En effet. L'avantage, c'est qu'on n'a pas besoin d'un raspberry. Mais un inconvénivent, c'est qu'avec Node-RED, on passe par Internet
Cen
 
Messages : 53
Inscription : 14 Oct 2015

Re: Ikea Tradfri & Eedomus

Messagepar KikiFUNstyle » 19 Oct 2021 16:59

Tout se passe en local, il utilise aussi l'API de la gateway (CoAP), par contre le pré requis est d'avoir un Node-RED d'installé quelque part (rpi, HA, docker ...) :?
ZWave / RFXCom / broadlink RM /Google Mini / Yeelight / Xiaomi Vacuum V1 / Shelly <3 / Node-RED <3 <3
[Store] Shelly
KikiFUNstyle
 
Messages : 908
Inscription : 24 Avr 2014
Localisation : Toulouse

Re: Ikea Tradfri & Eedomus

Messagepar VelmaHanson » 01 Déc 2021 13:29

Merci beaucoup pour le partage, c'est bien détaillé!
VelmaHanson
 
Messages : 3
Inscription : 22 Nov 2021


Retour vers Tutoriels

Qui est en ligne ?

Utilisateurs parcourant ce forum : Aucun utilisateur inscrit et 2 invité(s)