Aller au contenu
pepite

Liste Api-Lua & Api-Http Pour Hc2

Recommended Posts

Bonjour à  tous,

 

Comme évoqué dans un des topics du firmware avec @Lazer, j'initie un début de liste des différentes API-LUA et API-HTTP apparues suite aux évolutions de firmware.

 

Pour HC2 UNIQUEMENT

 

Cette liste est loin d'être exhaustive, je me suis basé sur les changelog des firmwares et le site https://developer.fibaro.com/.

 

Si vous en connaissez d'autres, n'hésitez pas (je pense à  vous les MAITRES du LUA :60::60: )

 

Les admins/modos, je vous laisse le soin de mettre le sujet où bon vous semble ;-), un sous-forum de HC2 peut-être.

 

 

  • These calls can be used to start increasing or decreasing Multilevel Switches (like Dimmer 2, RGBW or Roller Shutter 2 modules) value. 'x' and 'y' are optional parameters, used to set respectively time frame in which change should be applied and starting level. 'stopLevelChange' stops previously send action.
fibaro:call(ID, 'startLevelIncrease', x, y)
fibaro:call(ID, 'startLevelDecrease', x, y)
fibaro:call(ID, 'stopLevelChange') 
  • Call used to get table with IDs of devices that meet requirement specified by 'x'.
fibaro:getDevicesId(x)

 -- Examples:
 

print('All devices with parameter visible equal to "true" and enabled equal to "true":')
ids = fibaro:getDevicesId({visible = true, enabled = true})
print(json.encode(ids))
 
print('ALl devices with energy interface:')
ids = fibaro:getDevicesId({interfaces ={"energy"}})
print(json.encode(ids))
 
print('All devices with 'unit' property (no matter its value):')
ids = fibaro:getDevicesId({properties = {unit="nil"}})
print(json.encode(ids))

Which will set given scene respectively to Automatic, Manual and Disabled mode. Any other value will set scene triggering mode to Automatic.

fibaro:setSceneRunConfig(sceneID, runConfig)

where runConfig is string that takes one of these three values:
          - TRIGGER_AND_MANUAL
          - MANUAL_ONLY
          - DISABLED

 fibaro:getSceneRunConfig(sceneID)

          returns currently set value.

  
Old functions will keep backward compatibility and continue to work without change.

- fibaro:setSceneEnabled(sceneID, enabled)
- fibaro:isSceneEnabled(sceneID)
  • Redémarrage Home Center et Arrêt Home Center
HomeCenter.SystemService.reboot() et HomeCenter.SystemService.shutdown()

Exemples :

-- Reboot system
        HomeCenter.SystemService.reboot();
    -- Shutdown system
        HomeCenter.SystemService.shutdown();
  •   Popup service
HomeCenter.PopupService.publish({title, subtitle, contentTitle, contentBody, img, type, buttons})
Parameters

    title - string containing text to be displayed as a pop-up window title (parameter required)
    subtitle - string containing text to be displayed as a pop-up window subtitle
    contentTitle - string containing text to be displayed as a pop-up content title
    contentBody - string containing text to be displayed as a pop-up content (parameter required)
    img - string containing path of an image to be displayed in the pop-up window (supported extensions: .jpg, .bmp, .png, .gif)
    type - notification type indicated with a colour, available types:
        'Info' - blue (default)
        'Success' - green
        'Warning' - yellow
        'Critical' - red
    buttons - array containing definitions of buttons to be displayed in the pop-up, single button definition must be an array containing:
        'caption' - text displayed on the button
        'sceneId' - scene id triggered after pushing the button

Exemple 1
 

    --[[
    %% properties
    %% globals
    --]]
    -- variable containing path of Motion Sensors icon
    local imgUrl =
    'http://www.fibaro.com/sites/all/themes/fibaro/images/motion-
    sensor/en/motion_sensor_manual.png'
    -- pop-up call
    HomeCenter.PopupService.publish({
            -- title (required)
        title = 'No motion detected',
            -- subtitle(optional), e.g. time and date of the pop-up call
        subtitle = os.date("%I:%M:%S %p | %B %d, %Y"),
            -- content header (optional)
        contentTitle = 'No motion since last 15 minutes',
            -- content (required)
        contentBody = 'Should I run the scene "Night"?',
            -- notification image (assigned from the variable)
        img = imgUrl,
            -- type of the pop-up
        type = 'Success',
            -- buttons definition
        buttons = {
        { caption = 'Yes', sceneId = 0 },
        { caption = 'No', sceneId = 0 }
        }
    })

    NOTE
Please note that the example scene must be triggered manually. It just illustrates the way of creating pop-ups. Execution of this scene will not affect any device status (sceneId = 0).

NOTE
Setting an action of the button to 'sceneId = 0' means that no action will be performed.

NOTE
Created pop-up is sent to each of users and mobile devices connected with the main controller.

NOTE
There is no maximum size of image displayed in the pop-up window. However, using too large file may result in long waiting times required for downloading the image.

NOTE
Pushing one of the buttons displayed in the pop-up window may only trigger another scene.

 

Exemple 2
    --[[
    %% properties
    3814 value
    %% globals
    --]]
    local startSource = fibaro:getSourceTrigger();
    if (
        ( tonumber(fibaro:getValue(3814, "value")) > 60 )
    or
    startSource["type"] == "other"
    )
    then
    HomeCenter.PopupService.publish({
        title = 'Brightness level',
        subtitle = 'is too high',
        contentTitle = 'Dimmer',
        contentBody = 'Would you like to turn it off?',
        img = ' http://www.fibaro.com/images/eng/icon_osw.png',
        type = 'Critical',
        buttons = {
            { caption = 'Turn off', sceneId = 3228 },
            { caption = 'No', sceneId = 0 },
            { caption = 'Set to 100%', sceneId = 3229 }
        }
    })
    end

1ère MAJ venant de @Steven concernant les fonctions fibaro :

 

Telecharger le tar.gz http://updatehc2.fibaro.com/4.083/

, puis dans opt/fibaro ouvrir fibaroSceneAPI.lua

 

 

HomeCenter = {
PopupService = {
publish = function(request)
local response = api.post('/popups', request)
return response
end
},
SystemService = {
reboot = function()
local client = net.HTTPClient()
client:request("http://localhost/reboot.php")
end,
shutdown = function()
local client = net.HTTPClient()
client:request("http://localhost/shutdown.php")
end
}
}


fibaro = {}

fibaro.debug = function(self, text)
print(text)
end

fibaro.sleep = function(self, time)
__fibaroSleep(time)
end

function __convertToString(value)
if (type(value) == 'boolean') then
if (value) then
return '1'
else
return '0'
end
elseif (type(value) == 'number') then
return tostring(value)
elseif (type(value) == 'table') then
return json.encode(value)
end

return value
end

function __assert_type(value, typeOfValue)
if (type(value) ~= typeOfValue) then
error("Assertion failed: Expected " .. typeOfValue, 3)
end
end

function __fibaro_get_device(deviceID)
__assert_type(deviceID, "number")
return api.get("/devices/" .. deviceID)
end

function __fibaro_get_room(roomID)
__assert_type(roomID, "number")
return api.get("/rooms/" .. roomID)
end

function __fibaro_get_scene(sceneID)
__assert_type(sceneID, "number")
return api.get("/scenes/" .. sceneID)
end

function __fibaro_get_global_variable(varName)
__assert_type(varName, "string")
return api.get("/globalVariables/" .. varName)
end

function __fibaro_get_device_property(deviceId, propertyName)
return api.get("/devices/" .. deviceId .. "/properties/" .. propertyName)
end

--
-- getting device properties
--
fibaro.get = function(self, deviceID, propertyName)
local property = __fibaro_get_device_property(deviceID, propertyName)

if (property == nil) then
return nil
end

return __convertToString(property.value), property.modified
end

fibaro.getValue = function(self, deviceID, propertyName)
local value = fibaro:get(deviceID, propertyName)
return value
end

fibaro.getModificationTime = function(self, deviceID, propertyName)
local _, modified = fibaro:get(deviceID, propertyName)
return modified
end

--
-- global variables
--
fibaro.getGlobal = function(self, varName)
local globalVar = __fibaro_get_global_variable(varName)
if (globalVar == nil) then
return nil
end

return globalVar.value, globalVar.modified
end

fibaro.getGlobalValue = function(self, varName)
local globalVar = __fibaro_get_global_variable(varName)
if (globalVar == nil) then
return nil
end

return globalVar.value
end

fibaro.getGlobalModificationTime = function(self, varName)
local globalVar = __fibaro_get_global_variable(varName)
if (globalVar == nil) then
return nil
end

return globalVar.modified
end

fibaro.setGlobal = function(self, varName, value)
__assert_type(varName, "string")
local data = {["value"]=tostring(value), ["invokeScenes"]=true}
api.put("/globalVariables/" .. varName, data)
end

--
-- scenes
--
fibaro.countScenes = function(self, sceneID)
sceneID = sceneID or __fibaroSceneId

local scene = __fibaro_get_scene(sceneID)
if (scene == nil) then
return 0
end

return scene.runningInstances
end

fibaro.isSceneEnabled = function(self, sceneID)
local scene = __fibaro_get_scene(sceneID)
if (scene == nil) then
return nil
end

local enabled
if (scene.runConfig == "TRIGGER_AND_MANUAL" or scene.runConfig == "MANUAL_ONLY") then
enabled = true
else
enabled = false
end

return enabled
end

fibaro.startScene = function(self, sceneID)
api.post("/scenes/" .. sceneID .. "/action/start")
end

fibaro.killScenes = function(self, sceneID)
api.post("/scenes/" .. sceneID .. "/action/stop")
end

fibaro.setSceneEnabled = function(self, sceneID, enabled)
__assert_type(sceneID, "number")
__assert_type(enabled, "boolean")

local runConfig
if (enabled == true) then
runConfig = "TRIGGER_AND_MANUAL"
else
runConfig = "DISABLED"
end

local data = {
id = sceneID,
runConfig = runConfig
}
api.put("/scenes/" .. sceneID, data)
end

fibaro.getSceneRunConfig = function(self, sceneID)
local scene = __fibaro_get_scene(sceneID)
if (scene == nil) then
return nil
end

return scene.runConfig
end

fibaro.setSceneRunConfig = function(self, sceneID, runConfig)
__assert_type(sceneID, "number")
__assert_type(runConfig, "string")

local data = {
id = sceneID,
runConfig = runConfig
}
api.put("/scenes/" .. sceneID, data)
end

--
-- other
--
fibaro.getRoomID = function(self, deviceID)
local dev = __fibaro_get_device(deviceID)
if (dev == nil) then
return nil
end

return dev.roomID
end

fibaro.getSectionID = function(self, deviceID)
local dev = __fibaro_get_device(deviceID)
if (dev == nil) then
return nil
end

if (dev.roomID ~= 0) then
return __fibaro_get_room(dev.roomID).sectionID
end
return 0
end

fibaro.getType = function(self, deviceID)
local dev = __fibaro_get_device(deviceID)
if (dev == nil) then
return nil
end

return dev.type
end

fibaro.abort = function(self)
os.exit()
end

fibaro.getSourceTrigger = function(self)
return __fibaroSceneSourceTrigger
end

fibaro.getSourceTriggerType = function(self)
return __fibaroSceneSourceTrigger["type"]
end

fibaro.calculateDistance = function(self, position1, position2)
__assert_type(position1, "string")
__assert_type(position2, "string")
return __fibaroCalculateDistance(position1, position2)
end

fibaro.call = function(self, deviceID, actionName, ...)
deviceID = tonumber(deviceID)
__assert_type(actionName, "string")
args=""
for i, v in ipairs({...}) do
args = args .. '&arg' .. tostring(i) .. '=' .. urlencode(tostring(v))
end
api.get("/callAction?deviceID=" .. deviceID .. "&name=" .. actionName .. args)
end

function urlencode(str)
if (str) then
str = string.gsub (str, "([^%w])",
function © return string.format ("%%%02X", string.byte©) end)
end
return str
end

fibaro.getName = function(self, deviceID)
__assert_type(deviceID, 'number')
local dev = __fibaro_get_device(deviceID)
if (dev == nil) then
return nil
end

return dev.name
end

fibaro.getRoomName = function(self, roomID)
__assert_type(roomID, 'number')
local room = __fibaro_get_room(roomID)
if (room == nil) then
return nil
end

return room.name
end

fibaro.getRoomNameByDeviceID = function(self, deviceID)
__assert_type(deviceID, 'number')
local dev = __fibaro_get_device(deviceID)
if (dev == nil) then
return nil
end

local room = __fibaro_get_room(dev.roomID)

if (dev.roomID == 0) then
return "unassigned"
else
if (room == nil) then
return nil
end
end

return room.name
end

fibaro.wakeUpDeadDevice = function(self, deviceID)
__assert_type(deviceID, 'number')
fibaro:call(1, 'wakeUpDeadDevice', deviceID)
end

--[[
Expected input:
{
name: value, //: require name to be equal to value
properties: { //:
volume: "nil", //: require property volume to exist, any value
ip: "127.0.0.1" //: require property ip to equal 127.0.0.1
},
interface: ifname //: require device to have interface ifname

}
]]--
fibaro.getDevicesId = function(self, filter)
if type(filter) ~= 'table' or
(type(filter) == 'table' and next(filter) == nil)
then
return fibaro:getIds(fibaro:getAllDeviceIds())
end

local args = '/?'
for c, d in pairs(filter) do
if c == 'properties' and d ~= nil and type(d) == 'table' then
for a, b in pairs(d) do
if b == "nil" then
args = args .. 'property=' .. tostring(a) .. '&'
else
args = args .. 'property=[' .. tostring(a) .. ',' .. tostring(B) .. ]&'
end
end
elseif c == 'interfaces' and d ~= nil and type(d) == 'table' then
for a, b in pairs(d) do
args = args .. 'interface=' .. tostring( B) .. '&'
end
else
args = args .. tostring© .. "=" .. tostring(d) .. '&'
end
end

args = string.sub(args, 1, -2)
return fibaro:getIds(api.get('/devices' .. args))
end

fibaro.getAllDeviceIds = function(self)
return api.get('/devices/')
end

fibaro.getIds = function(self, devices)
local ids = {}
for _, a in pairs(devices) do
if a ~= nil and type(a) == 'table' and a['id'] ~= nil and a['id'] > 3 then
table.insert(ids, a['id'])
end
end
return ids
end

 

  • Backups depuis une scène (Merci à  @Nikko)
--[[
%% properties
%% events
%% globals
--]]
     
local portable = 385
local message = 'Backup du '..os.date("%d/%m/%y - %HH%M")
local url = 'http://127.0.0.1:11111/api/settings/backups'
local httpClient = net.HTTPClient()
httpClient:request(url , {
        success = function(response)
                    if tonumber(response.status) == 201 then
                        print("Backup Created at " .. os.date())
                        fibaro:call(portable,'sendPush', message .. ' effectué')
                    else
                        print("Error " .. response.status)
                        fibaro:call(portable,'sendPush', 'Erreur lors de la création du Backup')
                    end
                end,
        error = function(err)
                    print('error = ' .. err)
                end,
        options = {
                method = 'POST',
                headers = {
                    ["content-type"] = 'application/x-www-form-urlencoded;'
                            },
                data = 'action=create&description='..message
            }
});

 - Attention, si planification avec GEA, dans la nuit, ca relance le zwave ;-)

GEA.add(true, 30, "", {{"Scenario", id}})

ASTUCES DIVERSES

 

  • Affichage persistent du LOG des VDs et couleurs possibles (merci @Steven et @Berale, je ne suis que le Scrib)

 

- Code à  mettre dans le MAIN-LOOP

fibaro:log("Test")
fibaro:call(fibaro:getSelfId(), "setProperty", "logTemp", "TxtGray" )

 - Couleurs possibles :
.TxtGreen
.TxtRed
.TxtYellow
.TxtBlue
.TxtGray

Exemple de @Nico

--1er bouton VD
local deviceId = fibaro:getSelfId();
fibaro:call(deviceId, "setProperty", "ui.Label1.value", "Repos")

-- Second bouton du VD
local deviceId = fibaro:getSelfId();
fibaro:call(deviceId, "setProperty", "ui.Label1.value", "Alarme")
fibaro:call(deviceId, "setProperty", "ui.Label2.value", os.date("%m %B %Y - %H:%M:%S"))

-- Mainloop pour affichage persistent du log
local deviceId = fibaro:getSelfId();
local value = fibaro:getValue(deviceId, "ui.Label2.value")
fibaro:log(value)
fibaro:call(fibaro:getSelfId(), "setProperty", "logTemp", "TxtGray" )

Affichage persistent HORS MAIN-LOOP

fibaro:call(fibaro:getSelfId(), "setProperty", "log", "blablabla" )

MISE à  jour suite à  la version stable 4.10 :

 

Merci à  @Steven

fibaro:callGroupAction(action, filters)
 
    {
      "filter": "hasProperty",
      "value": ["configured", "dead", "model"]
    }
    {
      "filter": "interface",
      "value": ["Z-Wave", "levelChange"]
    }
    {
      "filter": "parentId",
      "value": [664]
    }
    {
      "filter": "type",
      "value": ["com.fibaro.multilevelSwitch"]
    }
    {
      "filter": "roomID",
      "value": [2, 3]
    }
    {
      "filter": "baseType",
      "value": ["com.fibaro.binarySwitch"]
    }
    {
      "filter": "isTypeOf",
      "value": ["com.fibaro.binarySwitch"]
    }
    {
      "filter": "isPlugin",
      "value": [true]
    }
    {
      "filter": "propertyEquals",
      "value":
      [
        {
          "propertyName": "configured",
          "propertyValue": [true]
        },
        {
          "propertyName": "dead",
          "propertyValue": [false]
        },
        {
          "propertyName": "deviceIcon",
          "propertyValue": [15]
        },
        {
          "propertyName": "deviceControlType",
          "propertyValue": [15,20,25]
        }
      ]
    }
    {
      "filter": "deviceID",
      "value": [55,120,902]
    }
    Parameters
 
action: action name
 
filters: filters object
Returned values
 
devices: array of device id's filtered by given rule.
Code example
 
    --[[
    %% properties
    %% events
    %% globals
    --]]
    local data =
    {
      args = { 1 },
      filters =
      {
        {
          filter = "roomID",
          value = { 2 }
        },
        {
          filter = "type",
          value = { "com.fibaro.motionSensor" }
        }
      }
    }
    local devices = fibaro:callGroupAction("setArmed", data)
    for k,v in ipairs(devices) do
      print (v)
    end
 
 
HomeCenter.NotificationService.publish(payload)
Name
 
Function name must be always the same: HomeCenter.NotificationService.publish
Application
 
Publishes notification.
Parameters
 
request: request object
Code example
 
    HomeCenter.NotificationService.publish({
        type = "GenericDeviceNotification",
        priority = "warning",
        data =
        {
            deviceId = 2643,
            title = "foo",
            text =  "bar"
        }
    })
 
HomeCenter.NotificationService.update(id, payload)
Name
 
Function name must be always the same: HomeCenter.NotificationService.update
Application
 
Updates notification.
Parameters
 
id: notification id
 
request: request object
Code example
 
    HomeCenter.NotificationService.update(7, {
        canBeDeleted = true,
        data =
        {
            title = "udapted foo",
            text =  "udapted bar"
        }
    })
 
HomeCenter.NotificationService.remove(id)
Name
 
Function name must be always the same: HomeCenter.NotificationService.remove
Application
 
Removes notification.
Parameters
 
id: notification id
Code example
    HomeCenter.NotificationService.remove(7)

Info du jour concernant le centre de notification de la HC2, merci @tinman,

c'est ici :

 

 - Pour utiliser le centre de notification avec des infos "perso" :

Tester et aprouvé en 4.10


 

function doNotify(text, devid)
  api.post('/notificationCenter', {
        type = 'GenericDeviceNotification',
        canBeDeleted = true,
        -- priority can be
        -- alert -- red alert sign
        -- warning -- yellow warning sign
        -- info -- same as warning
        priority = 'alert',
        data = {
               deviceId = devid,
               text = text,
               title = text
        }
  })
end

doNotify('Test notif HC2', 12 )

 

Modifié par pepite
  • Like 1
  • Upvote 13

Partager ce message


Lien à poster
Partager sur d’autres sites

bien ça :)

 

je pense que j'aurais plutôt séparé les API LUA et HTTP en 2 topics distincts, non ?

En plus l'API HTTP est dispo aussi bien pour HC2 que HCL, tandis que l'API LUA c'est uniquement sur HC2.

Partager ce message


Lien à poster
Partager sur d’autres sites

Beau boulôt !

Sent from my Note4

Partager ce message


Lien à poster
Partager sur d’autres sites

Yes, GG Pepite !

Partager ce message


Lien à poster
Partager sur d’autres sites

@Lazer, oui très bonne idée, tu peux diviser en 2 parties sans souci pour moi ;-) et le déplacer.

Partager ce message


Lien à poster
Partager sur d’autres sites

je ne peux pas diviser un post en 2.

Tu peux juste le modifier pour couper la partie API HTTP, et créer un nouveau topic.

Enfin ça je peux le faire, mais autant que tu le fasses, c'est ton post ;)

Partager ce message


Lien à poster
Partager sur d’autres sites

et tu veux que je le poste où ?

 

Quelqu'un a deja essaye le POP UP ?

Partager ce message


Lien à poster
Partager sur d’autres sites

Pas dans "Firmware" déjà  (je vais déplacer ce topic-ci) car c'est réservé aux firmwares.

 

Met le dans le dossier parent "Home Center 2 & Lite", je pense que c'est le mieux.

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

Même pas vrai, je ne me permettrais pas :) (bon OK si parfois ça arrive, mais pas là)

Partager ce message


Lien à poster
Partager sur d’autres sites

C'est pas bête ça !

Mais je crois que seul Yohan peut modifier ces pages, et il n'est pas très dispo.

Sans compter que ce topic va évoluer, avec les découvertes de nouvelles Api

Partager ce message


Lien à poster
Partager sur d’autres sites

Yes, on conserve le fofo pour en discuter, mais si Yohan pouvait donner les droits, on pourrait mettre àjour, car c'est très pratique.

Partager ce message


Lien à poster
Partager sur d’autres sites

dites, chez moi, je met ça derrière un bouton, mais ça ne fonctionne pas...

HomeCenter.SystemService.shutdown();

J'ai cette rerreur dans le debug:

[ERROR] 20:50:24: line 14: attempt to index global 'net' (a nil value)
suis en 4.090 une idée ?

Partager ce message


Lien à poster
Partager sur d’autres sites

Ce n'est que dans une scène, on en a parlé dans le topic du firmware qui a apporté cette nouvelle API, et Steven a proposé une méthode pour les VD

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

Mise à  jour ASTUCES DIVERSES  (log persistent) et backups depuis l'APi

 

Merci @steven, @berale24 et @Nikko

Partager ce message


Lien à poster
Partager sur d’autres sites

hello ! Est ce que code fonctionne pour l'affichage persistant ?

fibaro:log("Test")
fibaro:call(fibaro:getSelfId(), "setProperty", "logTemp", "TxtGray" )

parce que chez moi non.

Lorsque je clique sur les bouton du VD "Test" apparait bien en gris, mais finit quand même par disparaitre...

Partager ce message


Lien à poster
Partager sur d’autres sites

fibaro:log ne s"affiche que pendant 9s.

Il faut utiliser fibaro:call(fibaro:getSelfId(), "setProperty", "log", "text àafficher" );

Partager ce message


Lien à poster
Partager sur d’autres sites

na !!!

 

désolé il est dans le mainloop de mon VD et j'ai bien mis ce que tu me dis @Berale24 mais il disparait quand même...

  • Upvote 3

Partager ce message


Lien à poster
Partager sur d’autres sites

voilàexactement mon mainloop :

if response.OUT3 == 1 then
	fibaro:call(fibaro:getSelfId(), "setProperty", "currentIcon", 145)
  	fibaro:call(fibaro:getSelfId(), "setProperty", "log", "42.00W")
else
	fibaro:call(fibaro:getSelfId(), "setProperty", "currentIcon", 146)
  	fibaro:call(fibaro:getSelfId(), "setProperty", "log", "0.00W")
end
  • Upvote 2

Partager ce message


Lien à poster
Partager sur d’autres sites

alors en faite :

 

tant que je quitte pas la page d'accueil de la HC2, il reste affiché,

mais si je quitte la page et que je reviens dessus ou que je fais un refresh, il disparait !

Partager ce message


Lien à poster
Partager sur d’autres sites

Mise àjour firmware 4.10 ;-)

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

×