Page 1 sur 2

Script presence Xiaomi aide

Publié : 17 mars 2018, 04:49
par dckiller
Bonjour à tous,

Je début, j ai installé domoticz sur un Synology. J'ai réussi à installer un script de présence freebox trouver sur le forum. Cela fonctionne mais je trouve que c'est pas assez réactif. J'aimerais essayer avec un script pour mon point d acces Xiaomi R3P PRO. J'ai trouvé un script pour home assistant et j'aurais besoin d'aide pour que l'on puisse l adapter à Domoticz. Les commandes token sont OK via mon navigateur j'arrive à visualiser les adresses mac connectées via l'api suivant (le token change mais dans le script il a l'air de récupérer systématiquement comme pour le freebox)

http://monipxiaomi/cgi-bin/luci/;stok=t ... devicelist

Variable = R3P_mac_adress_smartphones

Le script home assistant que j'aimerais utilisé dans Domoticz

Code : Tout sélectionner

"""
Support for Xiaomi Mi routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.xiaomi/
"""
import logging

import requests
import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tracker import (
    DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME

_LOGGER = logging.getLogger(__name__)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Required(CONF_USERNAME, default='admin'): cv.string,
    vol.Required(CONF_PASSWORD): cv.string
})


def get_scanner(hass, config):
    """Validate the configuration and return a Xiaomi Device Scanner."""
    scanner = XiaomiDeviceScanner(config[DOMAIN])

    return scanner if scanner.success_init else None


class XiaomiDeviceScanner(DeviceScanner):
    """This class queries a Xiaomi Mi router.
    Adapted from Luci scanner.
    """

    def __init__(self, config):
        """Initialize the scanner."""
        self.host = config[CONF_HOST]
        self.username = config[CONF_USERNAME]
        self.password = config[CONF_PASSWORD]

        self.last_results = {}
        self.token = _get_token(self.host, self.username, self.password)

        self.mac2name = None
        self.success_init = self.token is not None

    def scan_devices(self):
        """Scan for new devices and return a list with found device IDs."""
        self._update_info()
        return self.last_results

    def get_device_name(self, device):
        """Return the name of the given device or None if we don't know."""
        if self.mac2name is None:
            result = self._retrieve_list_with_retry()
            if result:
                hosts = [x for x in result
                         if 'mac' in x and 'name' in x]
                mac2name_list = [
                    (x['mac'].upper(), x['name']) for x in hosts]
                self.mac2name = dict(mac2name_list)
            else:
                # Error, handled in the _retrieve_list_with_retry
                return
        return self.mac2name.get(device.upper(), None)

    def _update_info(self):
        """Ensure the information from the router are up to date.
        Returns true if scanning successful.
        """
        if not self.success_init:
            return False

        result = self._retrieve_list_with_retry()
        if result:
            self._store_result(result)
            return True
        return False

    def _retrieve_list_with_retry(self):
        """Retrieve the device list with a retry if token is invalid.
        Return the list if successful.
        """
        _LOGGER.info("Refreshing device list")
        result = _retrieve_list(self.host, self.token)
        if result:
            return result

        _LOGGER.info("Refreshing token and retrying device list refresh")
        self.token = _get_token(self.host, self.username, self.password)
        return _retrieve_list(self.host, self.token)

    def _store_result(self, result):
        """Extract and store the device list in self.last_results."""
        self.last_results = []
        for device_entry in result:
            # Check if the device is marked as connected
            if int(device_entry['online']) == 1:
                self.last_results.append(device_entry['mac'])


def _retrieve_list(host, token, **kwargs):
    """Get device list for the given host."""
    url = "http://{}/cgi-bin/luci/;stok={}/api/misystem/devicelist"
    url = url.format(host, token)
    try:
        res = requests.get(url, timeout=5, **kwargs)
    except requests.exceptions.Timeout:
        _LOGGER.exception(
            "Connection to the router timed out at URL %s", url)
        return
    if res.status_code != 200:
        _LOGGER.exception(
            "Connection failed with http code %s", res.status_code)
        return
    try:
        result = res.json()
    except ValueError:
        # If json decoder could not parse the response
        _LOGGER.exception("Failed to parse response from mi router")
        return
    try:
        xiaomi_code = result['code']
    except KeyError:
        _LOGGER.exception(
            "No field code in response from mi router. %s", result)
        return
    if xiaomi_code == 0:
        try:
            return result['list']
        except KeyError:
            _LOGGER.exception("No list in response from mi router. %s", result)
            return
    else:
        _LOGGER.info(
            "Receive wrong Xiaomi code %s, expected 0 in response %s",
            xiaomi_code, result)
        return


def _get_token(host, username, password):
    """Get authentication token for the given host+username+password."""
    url = 'http://{}/cgi-bin/luci/api/xqsystem/login'.format(host)
    data = {'username': username, 'password': password}
    try:
        res = requests.post(url, data=data, timeout=5)
    except requests.exceptions.Timeout:
        _LOGGER.exception("Connection to the router timed out")
        return
    if res.status_code == 200:
        try:
            result = res.json()
        except ValueError:
            # If JSON decoder could not parse the response
            _LOGGER.exception("Failed to parse response from mi router")
            return
        try:
            return result['token']
        except KeyError:
            error_message = "Xiaomi token cannot be refreshed, response from "\
                            + "url: [%s] \nwith parameter: [%s] \nwas: [%s]"
            _LOGGER.exception(error_message, url, data, result)
            return
    else:
        _LOGGER.error('Invalid response: [%s] at url: [%s] with data [%s]',
                      res, url, data)
Voilà si une personne à un peu de temps pour m'aider.

Re: Script presence Xiaomi aide

Publié : 18 mars 2018, 12:27
par papoo
tu parles de ce script?
https://github.com/home-assistant/home- ... /xiaomi.py
il est pour home assistant, il ne peut pas fonctionner en l'état pour domoticz mais ça m’intéresse aussi

Re: Script presence Xiaomi aide

Publié : 18 mars 2018, 15:52
par dckiller
Bonjour, oui c est celui-ci. Je pense qu'il doit être possible de l' adapter en script python mais j' ai peux de connaissances.

Envoyé de mon MI 4S en utilisant Tapatalk

Re: Script presence Xiaomi aide

Publié : 21 mars 2018, 22:46
par dckiller
Je reviens pour donner plus d'élément. J'arrive pas trouver ma solution.

IP = IP du router
LOGIN = par défaut admin
MDP = mot de passe de connexion au routeur

Voici comment récupérer le code token.

Code : Tout sélectionner

http://IP/cgi-bin/luci/api/xqsystem/login?username=admin&password=MDP
On obtient cette réponse.

Code : Tout sélectionner

{"url":"/cgi-bin/luci/;stok=723248b5589900828de7771961a9aa05/web/home","token":"723248b5589900828de7771961a9aa05","code":0}
Ensuite je veux appeler cette liste mais donc il faut le token du dessus qui change régulièrement.

Code : Tout sélectionner

http://IP/cgi-bin/luci/;stok=723248b5589900828de7771961a9aa05/api/misystem/devicelist
On obtient cette réponse (j'ai remplacé volontairement les adresses mac par 00:00:00:00:00:00 et ip 192.168.1.0)

Code : Tout sélectionner

{"mac":"00:00:00:00:00:00","list":[{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"00:00:00:00:00:00","times":0,"ip":[{"downspeed":"0","online":"4432","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"4432","upspeed":"0"},"icon":"","type":2},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"Microsoft Corporation ","times":0,"ip":[{"downspeed":"0","online":"64614","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"64614","upspeed":"0"},"icon":"device_list_windows.png","type":0},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"Philips Lighting BV ","times":0,"ip":[{"downspeed":"0","online":"165970","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"165970","upspeed":"0"},"icon":"device_list_philips.png","type":0},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"Microsoft Corporation ","times":0,"ip":[{"downspeed":"0","online":"48552","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"48552","upspeed":"0"},"icon":"device_list_windows.png","type":2},{"mac":"00:00:00:00:00:00","oname":"Unknown","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":1},"push":0,"online":1,"name":"Unknown","times":0,"ip":[{"downspeed":"0","online":"10147","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"10147","upspeed":"0"},"icon":"device_list_mi.png","type":2},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"00:00:00:00:00:00","times":0,"ip":[{"downspeed":"0","online":"165970","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"165970","upspeed":"0"},"icon":"","type":1},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"00:00:00:00:00:00","times":0,"ip":[{"downspeed":"0","online":"165970","active":1,"upspeed":"0","ip":"192.168.1.0"}],"statistics":{"downspeed":"0","online":"165970","upspeed":"0"},"icon":"","type":0},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"00:00:00:00:00:00","times":0,"ip":[{"downspeed":"0","online":"165970","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"165970","upspeed":"0"},"icon":"","type":0},{"mac":"00:00:00:00:00:00","oname":"","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"00:00:00:00:00:00","times":0,"ip":[{"downspeed":"0","online":"165970","active":1,"upspeed":"0","ip":"192.168.1.00"}],"statistics":{"downspeed":"0","online":"165970","upspeed":"0"},"icon":"","type":0}],"code":0}

Re: Script presence Xiaomi aide

Publié : 24 mars 2018, 14:45
par papoo
malheureusement mon switch ne me fournie pas d'info en mode répéteur du coup difficile de mettre au point un truc
essaie quand meme ça

Code : Tout sélectionner





--------------------------------------------
------------ Variables à éditer ------------
--------------------------------------------
local debugging = true  			                -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local script_actif = true                           -- active (true) ou désactive (false) ce script simplement
local IP = "192.168.155.155"                           -- adresse IP du routeur XIAOMI sans le http
local password = "ton_mot_de_passe_routeur"                  -- mot de passe du routeur XIAOMI          




-- Test la présence d'un smartphone par son adress MAC

--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------
--------------------------------------------
------------- Autres Variables -------------
--------------------------------------------
local nom_script = 'Xiaomi Network Status'
local version = '0.01'
local URL_login = "http://" .. IP .. "/cgi-bin/luci/api/xqsystem/login?username=admin&password="
local URL_token1 = "http://" .. IP .. "/cgi-bin/luci/;stok="
local URL_token2 = "/api/misystem/devicelist"
local url
local token
curl = '/usr/bin/curl -m 5 '		 	    -- pour linux, ne pas oublier l'espace à la fin
-- curl = 'c:\\Programs\\Curl\\curl -m 5 '  -- pour windows, ne pas oublier l'espace à la fin
-- chemin vers le dossier lua
	if (package.config:sub(1,1) == '/') then
		 luaDir = debug.getinfo(1).source:match("@?(.*/)")
	else
		 luaDir = string.gsub(debug.getinfo(1).source:match("@?(.*\\)"),'\\','\\\\')
	end
	json = assert(loadfile(luaDir..'JSON.lua'))()						-- chargement du fichier JSON.lua
--json = assert(loadfile('/home/pi/domoticz/scripts/lua/JSON.lua'))() --Linux 
--------------------------------------------
----------- Fin Autres Variables -----------
--------------------------------------------
--------------------------------------------
---------------- Fonctions -----------------
-------------------------------------------- 
function voir_les_logs (s, debugging)
    if (debugging) then 
		if s ~= nil then
        print ("<font color='#f3031d'>".. s .."</font>");
		else
		print ("<font color='#f3031d'>aucune valeur affichable</font>");
		end
    end
end	
--------------------------------------------
-------------- Fin Fonctions ---------------
-------------------------------------------- 

commandArray = {}
-- Boucle principale
if script_actif == true then
    voir_les_logs("========= ".. nom_script .." (v".. version ..") =========",debugging) 

        --=========== Lecture json ===============--
local config = assert(io.popen(curl..' "'.. URL_login .. password..'"')) 
voir_les_logs(curl..' "'.. URL_login .. password..'"',debugging)
        local blocjson = config:read('*all')
        config:close()
        local jsonValeur = json:decode(blocjson)
        if jsonValeur then
       
        url     = jsonValeur.url
        token   = jsonValeur.token
         voir_les_logs("========= URL du routeur XIAOMI =========",debugging)
        voir_les_logs(url,debugging)
        voir_les_logs("========= token du routeur XIAOMI =========",debugging)
        voir_les_logs(token,debugging)
        else
        voir_les_logs("========= aucune donnée json à décoder =========",debugging)
        end
        --local URL_token = "http://" .. IP .. "cgi-bin/luci/;stok=" ..token .. "/api/misystem/devicelist"
        local URL_token = URL_token1 .. token .. URL_token2
        local config = assert(io.popen(curl..' "'.. URL_token ..'"'))
        voir_les_logs(curl..' "'.. URL_token ..'"',debugging)
        local blocjson = config:read('*all')
        config:close()
        local jsonValeur = json:decode(blocjson)
        if jsonValeur then
        for I, Value in pairs( jsonValeur.list ) do
              voir_les_logs(Value.mac,debugging)  
              voir_les_logs(Value.online,debugging)

                for I, Value in pairs( Value.ip ) do
                voir_les_logs(Value.ip,debugging)
                end 
       end
        else
        voir_les_logs("========= aucune donnée json à décoder =========",debugging)
        end    
    
    


    voir_les_logs("======= Fin ".. nom_script .." (v".. version ..") =======",debugging)    
end
return commandArray

Re: Script presence Xiaomi aide

Publié : 25 mars 2018, 03:45
par dckiller
Bonjour Papoo,

Merci beaucoup du temps passer pour la réalisation du script. Ça fonctionne très bien du 1er coup. Les adresses mac remontent bien. Plus qu'à remonter l’info au switch correspondant.

Pour ma part je suis en mode point d’accès (par câble sur la freebox). J'utilise par contre le firmware dev 2.13.65 avec l'activation SSH.

Sinon je testais Life360 c'est pas mal aussi. (Pour ceux qui veullent tester, dans life360 du téléphone créer votre domicile en Home les personnes de votre cercle remontent automatiquement en interupteur)

https://www.domoticz.com/forum/viewtopic.php?t=20392

Re: Script presence Xiaomi aide

Publié : 27 janv. 2019, 14:26
par calouis
Bonjour papoo
je suis tombé par hazard sur ton script qui m'intéresse compte tenu que j'ai un xiaomi miwifi3 comme ici https://domotique-home.fr/installer-rou ... aedd0e4327.
Voilà comment j'ai tenté de l'adapter:

Code : Tout sélectionner

-- script_device_Xiaomi Network Status.lua
--------------------------------------------
------------ Variables à éditer ------------
--------------------------------------------
local debugging = true  			                -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local script_actif = true                           -- active (true) ou désactive (false) ce script simplement
local IP = "192.168.31.1"                           -- adresse IP du routeur XIAOMI sans le http
local password = "XXXXXXXXX"                  -- mot de passe du routeur XIAOMI          

-- Test la présence d'un smartphone par son adress MAC

--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------
--------------------------------------------
------------- Autres Variables -------------
--------------------------------------------
local nom_script = 'Xiaomi Network Status'
local version = '0.01'

--local URL_login = "http://192.168.31.1/cgi-bin/luci/api/xqsystem/login?username=admin&password=XXXXXXXXX"
local URL_login = "http://" .. IP .. "/cgi-bin/luci/api/xqsystem/login?username=admin&password="

local URL_token1 = "http://" .. IP .. "/cgi-bin/luci/;stok="
local URL_token2 = "/api/misystem/devicelist"
-- http://192.168.31.1/cgi-bin/luci/;stok=5b0a87eea2be461c9efa798e0cf1e69f/api/misystem/devicelist

local url
local token
curl = '/usr/bin/curl -m 5 '		 	    -- pour linux, ne pas oublier l'espace à la fin
-- curl = 'c:\\Programs\\Curl\\curl -m 5 '  -- pour windows, ne pas oublier l'espace à la fin
-- chemin vers le dossier lua
	if (package.config:sub(1,1) == '/') then
		 luaDir = debug.getinfo(1).source:match("@?(.*/)")
	else
		 luaDir = string.gsub(debug.getinfo(1).source:match("@?(.*\\)"),'\\','\\\\')
	end
--	json = assert(loadfile(luaDir..'JSON.lua'))()						-- chargement du fichier JSON.lua
json = assert(loadfile('/home/pi/domoticz/scripts/lua/JSON.lua'))() --Linux 
--------------------------------------------
----------- Fin Autres Variables -----------
--------------------------------------------
--------------------------------------------
---------------- Fonctions -----------------
-------------------------------------------- 
function voir_les_logs (s, debugging)
    if (debugging) then 
		if s ~= nil then
        print (s);
		else
		print ("aucune valeur affichable");
		end
    end
end	
--------------------------------------------
-------------- Fin Fonctions ---------------
-------------------------------------------- 

commandArray = {}
-- Boucle principale
if script_actif == true then
    voir_les_logs("========= ".. nom_script .." (v".. version ..") =========",debugging) 

        --=========== Lecture json ===============--
local config = assert(io.popen(curl..' "'.. URL_login .. password..'"')) 
voir_les_logs(curl..' "'.. URL_login .. password..'"',debugging)
local blocjson = config:read('*all')
config:close()
local jsonValeur = json:decode(blocjson)
if jsonValeur then
    url     = jsonValeur.url
    token   = jsonValeur.token
    voir_les_logs("========= URL du routeur XIAOMI MiWifi3=========",debugging)
    voir_les_logs(url,debugging)
    voir_les_logs("========= token du routeur XIAOMI MiWifi3 =========",debugging)
    voir_les_logs(token,debugging)
else
    voir_les_logs("========= aucune donnée json à décoder =========",debugging)
end
    
--local URL_token = "http://192.168.31.1/cgi-bin/luci/;stok=5b0a87eea2be461c9efa798e0cf1e69f/api/misystem/devicelist"
     local URL_token = "http://" .. IP .. "cgi-bin/luci/;stok=" ..token .. "/api/misystem/devicelist"
 --       local URL_token = URL_token1 .. token .. URL_token2
local config = assert(io.popen(curl..' "'.. URL_token ..'"'))
voir_les_logs(curl..' "'.. URL_token ..'"',debugging)
local blocjson = config:read('*all')
config:close()
local jsonValeur = json:decode(blocjson)
    if jsonValeur then
        for I, Value in pairs( jsonValeur.list ) do
                voir_les_logs(Value.mac,debugging)  
                voir_les_logs(Value.online,debugging)
                for I, Value in pairs( Value.ip ) do  voir_les_logs(Value.ip,debugging) end 
       end
    else
        voir_les_logs("========= aucune donnée json à décoder =========",debugging)
    end    
  
voir_les_logs("======= Fin ".. nom_script .." (v".. version ..") =======",debugging)    
end
return commandArray
en retour :

Code : Tout sélectionner

2019-01-27 14:15:12.016 Status: LUA: /usr/bin/curl -m 5 "http://192.168.31.1/cgi-bin/luci/api/xqsystem/login?username=admin&password=XXXXXX"
2019-01-27 14:15:15.195 Status: LUA: ========= aucune donnée json à décoder =========
2019-01-27 14:15:15.195 Error: EventSystem: in script_device_Xiaomi Network Status: [string "-- script_device_Xiaomi Network Status.lua..."]:82: attempt to concatenate local 'token' (a nil value)
Pour info, quand je saisis l'url suivante :
http://192.168.31.1/cgi-bin/luci/;stok= ... devicelist
j'ai en retour :

Code : Tout sélectionner

{"mac":"00:1C:B3:FF:7A:E1","list":[{"mac":"xx:xx:xx:xx:xx:xx","oname":"Unknown","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"Unknown","times":0,"ip":[{"downspeed":"0","online":"7988","active":1,"upspeed":"0","ip":"192.168.31.181"}],"statistics":{"downspeed":"0","online":"7988","upspeed":"0"},"icon":"","type":2},{"mac":"xx:xx:xx:xx:xx:xx","oname":"Unknown","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"Unknown","times":0,"ip":[{"downspeed":"0","online":"831313","active":1,"upspeed":"0","ip":"192.168.31.148"}],"statistics":{"downspeed":"0","online":"831313","upspeed":"0"},"icon":"device_list_oneplus.png","type":2},{"mac":"xx:xx:xx:xx:xx:xx","oname":"RedmiS2-axelle","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":0},"push":0,"online":1,"name":"RedmiS2-axelle","times":0,"ip":[{"downspeed":"0","online":"15151","active":1,"upspeed":"0","ip":"192.168.31.137"}],"statistics":{"downspeed":"0","online":"15151","upspeed":"0"},"icon":"","type":1},{"mac":"xx:xx:xx:xx:xx:xx","oname":"XiaoMiRepeater","isap":1,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":1},"push":0,"online":1,"name":"小米Wi-Fi放大器","times":0,"ip":[{"downspeed":"0","online":"263370","active":1,"upspeed":"0","ip":"192.168.31.58"}],"statistics":{"downspeed":"0","online":"263370","upspeed":"0"},"icon":"device_list_miwifi_repeater.png","type":1},{"mac":"xx:xx:xx:xx:xx:xx","oname":"Prodexxxxx","isap":0,"parent":"","authority":{"wan":1,"pridisk":0,"admin":1,"lan":1},"push":0,"online":1,"name":"Prodexxxxxx","times":0,"ip":[{"downspeed":"0","online":"8554","active":1,"upspeed":"0","ip":"192.168.31.82"}],"statistics":{"downspeed":"0","online":"8554","upspeed":"0"},"icon":"device_list_apple.png","type":2}],"code":0}
Voilà, si tu pouvais me venir en aide....
Merci d'avance

Re: Script presence Xiaomi aide

Publié : 27 janv. 2019, 14:31
par calouis
et si je remplace la ligne :

Code : Tout sélectionner

local URL_token = "http://" .. IP .. "cgi-bin/luci/;stok=" ..token .. "/api/misystem/devicelist"[/codepar
[code]local URL_token = "http://192.168.31.1/cgi-bin/luci/;stok=5b0a87eea2be461c9efa798e0cf1e69f/api/misystem/devicelist"
j'ai ceci comme réponse :

Code : Tout sélectionner

2019-01-27 14:30:58.176 Status: LUA: /usr/bin/curl -m 5 "http://192.168.31.1/cgi-bin/luci/api/xqsystem/login?username=admin&password=aavqxdmq"
2019-01-27 14:31:01.355 Status: LUA: ========= aucune donnée json à décoder =========
2019-01-27 14:31:01.361 Status: LUA: /usr/bin/curl -m 5 "http://192.168.31.1/cgi-bin/luci/;stok=5b0a87eea2be461c9efa798e0cf1e69f/api/misystem/devicelist"
2019-01-27 14:31:04.555 Status: LUA: ========= aucune donnée json à décoder =========
2019-01-27 14:31:04.555 Status: LUA: ======= Fin Xiaomi Network Status (v0.01) =======

Re: Script presence Xiaomi aide

Publié : 27 janv. 2019, 16:49
par calouis
J'essaie en vain de modifier comme ceci :

Code : Tout sélectionner

-- script_device_Xiaomi Network Status.lua
--------------------------------------------
dofile('/home/pi/domoticz/scripts/lua/fonctions/fonctions_perso.lua')
------------ Variables à éditer ------------
--------------------------------------------
local debugging = true  			                -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local script_actif = true                           -- active (true) ou désactive (false) ce script simplement
local IP = "192.168.31.1"                           -- adresse IP du routeur XIAOMI sans le http
local password = "XXXXX"                  -- mot de passe du routeur XIAOMI          

-- Test la présence d'un smartphone par son adress MAC

--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------
--------------------------------------------
------------- Autres Variables -------------
--------------------------------------------
local nom_script = 'Xiaomi Network Status'
local version = '0.04'

local URL_login = "http://" .. IP .. "/cgi-bin/luci/api/xqsystem/login?username=admin&password="

local URL_token1 = "http://" .. IP .. "/cgi-bin/luci/;stok="
local URL_token2 = "/api/misystem/devicelist"
local url
local token
curl = '/usr/bin/curl -m 5 '		 	    -- pour linux, ne pas oublier l'espace à la fin
-- chemin vers le dossier lua
	if (package.config:sub(1,1) == '/') then
		 luaDir = debug.getinfo(1).source:match("@?(.*/)")
	else
		 luaDir = string.gsub(debug.getinfo(1).source:match("@?(.*\\)"),'\\','\\\\')
	end
json = assert(loadfile('/home/pi/domoticz/scripts/lua/JSON.lua'))() --Linux 
--json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")()  -- For Linux
--------------------------------------------
----------- Fin Autres Variables -----------
--------------------------------------------
--------------------------------------------
---------------- Fonctions -----------------

package.path = package.path..";/home/pi/domoticz/scripts/lua/fonctions/?.lua"   -- ligne à commenter en cas d'utilisation des fonctions directement dans ce script
require('fonctions_perso')                                                      -- ligne à commenter en cas d'utilisation des fonctions directement dans ce script

commandArray = {}
-- Boucle principale
if script_actif == true then
    voir_les_logs("========= ".. nom_script .." (v".. version ..") =========",debugging) 

        --=========== Lecture json ===============--

local config = assert(io.popen(curl..' "'.. URL_login .. password..'"')) 

voir_les_logs(curl..' "'.. URL_login .. password..'"',debugging)
local blocjson = config:read('*all')
config:close()
print (blocjson)
local jsonValeur = json:decode(blocjson)
if jsonValeur then
    url     = jsonValeur.url
    token   = jsonValeur.token
    voir_les_logs("========= URL du routeur XIAOMI MiWifi3=========",debugging)
    voir_les_logs(url,debugging)
    voir_les_logs("========= token du routeur XIAOMI MiWifi3 =========",debugging)
    voir_les_logs(token,debugging)
else
    voir_les_logs("========= aucune donnée json à décoder =========",debugging)
end
    
local URL_token = "http://192.168.31.1/cgi-bin/luci/;stok=5b0a87eea2be461c9efa798e0cf1e69f/api/misystem/devicelist"
--     local URL_token = "http://" .. IP .. "cgi-bin/luci/;stok=" ..token .. "/api/misystem/devicelist"
 --       local URL_token = URL_token1 .. token .. URL_token2
 
local config = assert(io.popen(curl..' "'.. URL_token ..'"'))


voir_les_logs(curl..' "'.. URL_token ..'"',debugging)
local blocjson = config:read('*all')
config:close()
local jsonValeur = json:decode(blocjson)
    if jsonValeur then
        for I, Value in pairs( jsonValeur.list ) do
                voir_les_logs(Value.mac,debugging)  
                voir_les_logs(Value.online,debugging)
                for I, Value in pairs( Value.ip ) do  voir_les_logs(Value.ip,debugging) end 
       end
    else
        voir_les_logs("========= aucune donnée json à décoder =========",debugging)
    end    
  
voir_les_logs("======= Fin ".. nom_script .." (v".. version ..") =======",debugging)    
end
return commandArray
Résultat :

Code : Tout sélectionner

2019-01-27 16:45:50.462 Status: LUA: ========= Xiaomi Network Status (v0.04) =========
2019-01-27 16:45:50.466 Status: LUA: /usr/bin/curl -m 8 -u domoticzUSER:domoticzPSWD "http://192.168.31.1/cgi-bin/luci/api/xqsystem/login?username=admin&password=xxxxxxx"
2019-01-27 16:45:50.504 Status: LUA:
2019-01-27 16:45:50.504 Status: LUA: ========= aucune donnée json à décoder =========
2019-01-27 16:45:50.508 Status: LUA: /usr/bin/curl -m 8 -u domoticzUSER:domoticzPSWD "http://192.168.31.1/cgi-bin/luci/;stok=5b0a87eea2be461c9efa798e0cf1e69f/api/misystem/devicelist"
2019-01-27 16:45:50.547 Status: LUA: ========= aucune donnée json à décoder =========
2019-01-27 16:45:50.547 Status: LUA: ======= Fin Xiaomi Network Status (v0.04) =======
Je tourne en rond!

Re: Script presence Xiaomi aide

Publié : 27 janv. 2019, 21:18
par papoo
je suis en mode répéteur, je n'ai pas accès aux peripherique connecté sur mon MIWIFI
fais moi passer le fichier complet generé par cette requete que j'essaie de bosser dessus