forked from vil1driver/lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodules.lua
More file actions
719 lines (608 loc) · 23.1 KB
/
modules.lua
File metadata and controls
719 lines (608 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
--[[
bibliothèque de fonctions pour domoticz
utiles à la réalisation de scripts d'automation en langage lua
/!\ certaines fonctions ne fonctionneront pas sous windows.
copier ce qui se trouve entre les 2 lignes ci dessous, en début de tout vos script
pour charger ce fichier et pouvoir en utiliser les fonctions
--------------------------------------------------------------------------------------------------------
-- chargement des modules (http://easydomoticz.com/forum/viewtopic.php?f=17&t=3940)
dofile('/home/pi/domoticz/scripts/lua/modules.lua')
local debug = true -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
--------------------------------------------------------------------------------------------------------
]]
--------------------------------
------ USER SETTINGS ------
--------------------------------
-- domoticz
domoticzIP = '192.168.22.100' --'127.0.0.1'
domoticzPORT = '8080'
domoticzUSER = '' -- nom d'utilisateur
domoticzPSWD = '' -- mot de pass
domoticzPASSCODE = '' -- pour interrupteur protégés
domoticzURL = 'http://'..domoticzIP..':'..domoticzPORT
-- passerelle SMS
smsGatewayIP = '192.168.22.171'
smsGatewayPORT = '41047'
smsGatewayURL = 'http://'..smsGatewayIP..':'..smsGatewayPORT
admin = 'xxxxxxxxxx@gmail.com'
--------------------------------
------ END ------
--------------------------------
-- chemin vers le dossier lua et curl
if (package.config:sub(1,1) == '/') then
-- system linux
luaDir = debug.getinfo(1).source:match("@?(.*/)")
curl = '/usr/bin/curl -m 15 ' -- ne pas oublier l'espace à la fin
else
-- system windows
luaDir = string.gsub(debug.getinfo(1).source:match("@?(.*\\)"),'\\','\\\\')
-- download curl : https://bintray.com/vszakats/generic/download_file?file_path=curl-7.54.0-win32-mingw.7z
curl = 'c:\\Programs\\Curl\\curl.exe ' -- ne pas oublier l'espace à la fin
end
-- chargement du fichier JSON.lua
json = assert(loadfile(luaDir..'JSON.lua'))()
--time.hour ou time.min ou time.sec
--ex : if (time.hour == 17 and time.min == 05) then
time = os.date("*t")
-- retourne l'heure actuelle ex: "12:45"
heure = string.sub(os.date("%X"), 1, 5)
-- retourne la date ex: "01:01"
date = os.date("%d:%m")
-- retourne l'heure du lever de soleil ex: "06:41"
leverSoleil = string.sub(os.date("!%X",60*timeofday['SunriseInMinutes']), 1, 5)
-- retourne l'heure du coucher de soleil ex: "22:15"
coucherSoleil = string.sub(os.date("!%X",60*timeofday['SunsetInMinutes']), 1, 5)
-- retourne le jour actuel en français ex: "mardi"
days = {"dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"}
jour = days[(os.date("%w")+1)]
-- est valide si la semaine est paire
-- usage :
-- if semainePaire then ..
semainePaire = os.date("%W")%2 == 0
-- il fait jour
dayTime = timeofday['Daytime']
-- il fait nuit
nightTime = timeofday['Nighttime']
-- température
function getTemp(device)
return round(tonumber(otherdevices_temperature[device]),1)
end
-- humidité
function getHum(device)
return round(tonumber(otherdevices_humidity[device]),1)
end
-- set setpoint (faster way)
function setPoint(device,value)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=udevice&idx='..otherdevices_idx[device]..'&nvalue=0&svalue='..value..'" &')
end
-- vérifie s'il y a eu changement d'état
function stateChange(device)
if (uservariables['lastState_'..device] == nil) then
creaVar('lastState_'..device,otherdevices[device])
log('stateChange : création variable manquante lastState_'..device,debug)
return false
elseif (devicechanged[device] == nil) then
return false
elseif (devicechanged[device] == uservariables['lastState_'..device]) then
return false
else
duree = lastSeen(uservariables_lastupdate['lastState_'..device])
updateVar('lastState_'..device,otherdevices[device])
return otherdevices[device]
end
end
-- convertion degrés en direction cardinale
function wind_cardinals(deg)
local cardinalDirections = {
['N'] = {348.75, 360},
['N'] = {0, 11.25},
['NNE'] = {11.25, 33.75},
['NE'] = {33.75, 56.25},
['ENE'] = {56.25, 78.75},
['E'] = {78.75, 101.25},
['ESE'] = {101.25, 123.75},
['SE'] = {123.75, 146.25},
['SSE'] = {146.25, 168.75},
['S'] = {168.75, 191.25},
['SSW'] = {191.25, 213.75},
['SW'] = {213.75, 236.25},
['WSW'] = {236.25, 258.75},
['W'] = {258.75, 281.25},
['WNW'] = {281.25, 303.75},
['NW'] = {303.75, 326.25},
['NNW'] = {326.25, 348.75}
}
local cardinal
for dir, angle in pairs(cardinalDirections) do
if (deg >= angle[1] and deg < angle[2]) then
cardinal = dir
break
end
end
return cardinal
end
-- dump all variables supplied to the script
-- usage
-- LogVariables(_G,0,'')
function LogVariables(x,depth,name)
for k,v in pairs(x) do
if (depth>0) or ((string.find(k,'device')~=nil) or (string.find(k,'variable')~=nil) or
(string.sub(k,1,4)=='time') or (string.sub(k,1,8)=='security')) then
if type(v)=="string" then print(name.."['"..k.."'] = '"..v.."'") end
if type(v)=="number" then print(name.."['"..k.."'] = "..v) end
if type(v)=="boolean" then print(name.."['"..k.."'] = "..tostring(v)) end
if type(v)=="table" then LogVariables(v,depth+1,k); end
end
end
end
-- os.execute() output or web page content return
-- usage
-- local resultat = os.capture(cmd , true)
-- print('resultat: ' .. resultat)
function os.capture(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
-- retourne le type de la variable
-- 'string' , 'number' , 'table'
function typeof(var)
local _type = type(var);
if(_type ~= "table" and _type ~= "userdata") then
return _type;
end
local _meta = getmetatable(var);
if(_meta ~= nil and _meta._NAME ~= nil) then
return _meta._NAME;
else
return _type;
end
end
-- affiche les logs en bleu sauf si debug est spécifié à false
function log(txt,debug)
if (debug ~= false) then
print("<font color='#0206a9'>"..txt.."</font>")
end
end
-- affiche les logs en rouge sauf si debug est spécifié à false
function warn(txt,debug)
if (debug ~= false) then
print("<font color='red'>"..txt.."</font>")
end
end
-- écriture dans un fichier texte dans le dossier lua
function logToFile(fileName,data)
f = assert(io.open(luaDir..fileName..'.txt',"a"))
f:write(os.date("%c")..' '..data..'\n')
f:close()
end
-- teste l'existance d'un fichier
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- encode du texte pour le passer dans une url
function url_encode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
-- supprime les accents de la chaîne
function sans_accent(str)
if (str) then
str = string.gsub (str,"Ç", "C")
str = string.gsub (str,"ç", "c")
str = string.gsub (str,"[-èéêë']+", "e")
str = string.gsub (str,"[-ÈÉÊË']+", "E")
str = string.gsub (str,"[-àáâãäå']+", "a")
str = string.gsub (str,"[-@ÀÁÂÃÄÅ']+", "A")
str = string.gsub (str,"[-ìíîï']+", "i")
str = string.gsub (str,"[-ÌÍÎÏ']+", "I")
str = string.gsub (str,"[-ðòóôõö']+", "o")
str = string.gsub (str,"[-ÒÓÔÕÖ']+", "O")
str = string.gsub (str,"[-ùúûü']+", "u")
str = string.gsub (str,"[-ÙÚÛÜ']+", "U")
str = string.gsub (str,"[-ýÿ']+", "y")
str = string.gsub (str,"Ý", "Y")
end
return str
end
-- retourne le temps en seconde depuis la dernière maj du péréphérique
function lastSeen(device)
timestamp = otherdevices_lastupdate[device] or device
y, m, d, H, M, S = timestamp:match("(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)")
difference = os.difftime(os.time(), os.time{year=y, month=m, day=d, hour=H, min=M, sec=S})
return difference
end
-- contraindre
function constrain(x, a, b)
if (x < a) then
return a
elseif (x > b) then
return b
else
return x
end
end
-- arrondire
function round(num, dec)
if num == 0 then
return 0
else
local mult = 10^(dec or 0)
return math.floor(num * mult + 0.5) / mult
end
end
-- met le script en pause (fortement déconseillé)
-- usage
-- sleep(10) -- pour mettre en pause 10 secondes
function sleep(n)
os.execute('sleep '..tonumber(n))
end
-- création de variable utilisateur
-- usage
-- creaVar('toto','10') -- pour créer une variable nommée toto comprenant la valeur 10
function creaVar(name,value)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=saveuservariable&vname='..url_encode(name)..'&vtype=2&vvalue='..url_encode(value)..'" &')
end
-- update an existing variable
function updateVar(name,value)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=updateuservariable&vname='..url_encode(name)..'&vtype=2&vvalue='..url_encode(value)..'" &')
end
-- envoie dans un capteur text une chaîne de caractères
-- le text sera intercepté et lu par la custom page grâce à sa fonction MQTT
-- usage
-- speak('tts','bonjour nous sommes dimanche')
function speak(TTSDeviceName,txt)
commandArray['OpenURL'] = domoticzIP..":"..domoticzPORT..'/json.htm?type=command¶m=udevice&idx='..otherdevices_idx[TTSDeviceName]..'&nvalue=0&svalue='..url_encode(txt)
end
-- récupère les infos json du périphérique
-- usage
-- local lampe = jsonInfos('ma lampe')
-- print(lampe.Name)
-- print(lampe.Status)
-- etc..
function jsonInfos(device)
local rid = assert(io.popen(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=devices&rid='..otherdevices_idx[device]..'"'))
local list = rid:read('*all')
rid:close()
return json:decode(list).result[1]
end
-- parcours la table dans l'ordre
function spairs(t)
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
table.sort(keys)
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
-- Renverse une table
function ReverseTable(t)
local reversedTable = {}
local itemCount = #t
for k, v in ipairs(t) do
reversedTable[itemCount + 1 - k] = v
end
return reversedTable
end
-- affiche le contenu d'une table
--[[
Author: Julio Manuel Fernandez-Diaz
Date: January 12, 2007
(For Lua 5.1)
Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount()
Formats tables with cycles recursively to any depth.
The output is returned as a string.
References to other tables are shown as values.
Self references are indicated.
The string returned is "Lua code", which can be procesed
(in the case in which indent is composed by spaces or "--").
Userdata and function keys and values are shown as strings,
which logically are exactly not equivalent to the original code.
This routine can serve for pretty formating tables with
proper indentations, apart from printing them:
print(table_show(t, "t")) -- a typical use
Heavily based on "Saving tables with cycles", PIL2, p. 113.
Arguments:
t is the table.
name is the name of the table (optional)
indent is a first indentation (optional).
]]
function table_show(t, name, indent)
local cart -- a container
local autoref -- for self references
--[[ counts the number of elements in a table
local function tablecount(t)
local n = 0
for _, _ in pairs(t) do n = n+1 end
return n
end
]]
-- (RiciLake) returns true if the table is empty
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "table"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
-- retourne la table des derniers log (première ligne = dernier log)
function lastLogEntry()
local rid = assert(io.popen(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=getlog"'))
local list = rid:read('*all')
rid:close()
local tableau = json:decode(list).result
return ReverseTable(tableau)
end
-- notification pushbullet
-- usage:
-- pushbullet('test','ceci est un message test')
function pushbullet(title,body)
local settings = assert(io.popen(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=settings"'))
local list = settings:read('*all')
settings:close()
local pushbullet_key = json:decode(list).PushbulletAPI
os.execute(curl..'-H \'Access-Token:'..pushbullet_key..'\' -H \'Content-Type:application/json\' --data-binary \'{"title":"'..title..'","body":"'..body..'","type":"note"}\' -X POST "https://api.pushbullet.com/v2/pushes"')
end
-- switch On a device and set level if dimmmable
function switchOn(device,level)
if level ~= nil then
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=switchlight&idx='..otherdevices_idx[device]..'&switchcmd=Set%20Level&level='..level..'&passcode='..domoticzPASSCODE..'" &')
else
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=switchlight&idx='..otherdevices_idx[device]..'&switchcmd=On&passcode='..domoticzPASSCODE..'" &')
end
end
-- switch On a devive for x secondes
function switchOnFor(device, secs)
switchOn(device)
commandArray[device] = "Off AFTER "..secs
end
-- switch Off a device
function switchOff(device)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=switchlight&idx='..otherdevices_idx[device]..'&switchcmd=Off&passcode='..domoticzPASSCODE..'" &')
end
-- Toggle a device
function switch(device)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=switchlight&idx='..otherdevices_idx[device]..'&switchcmd=Toggle&passcode='..domoticzPASSCODE..'" &')
end
-- switch On a group or scene
function groupOn(device)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=switchscene&idx='..otherdevices_scenesgroups_idx[device]..'&switchcmd=On&passcode='..domoticzPASSCODE..'" &')
end
-- switch Off a group
function groupOff(device)
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..'/json.htm?type=command¶m=switchscene&idx='..otherdevices_scenesgroups_idx[device]..'&switchcmd=Off&passcode='..domoticzPASSCODE..'" &')
end
-- Set switch to Stop
function switchStop(device)
local api = '/json.htm?type=command¶m=switchlight&switchcmd=Stop'
local idx = '&idx='..otherdevices_idx[device]
local passcode = '&passcode='..domoticzPASSCODE
api = api..idx..passcode
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..api..'" &')
end
-- Setup a color & brightness of an RGB(W) light
-- API : https://www.domoticz.com/wiki/Domoticz_API/JSON_URL%27s#Set_an_RGB.28W.29_light_to_a_certain_color_and_brightness
function setColorAndBrightness(device, color, brightness)
local api = '/json.htm?type=command¶m=setcolbrightnessvalue'
local idx = '&idx='..otherdevices_idx[device]
local color = '&hue='..color
local brightness = '&brightness='..brightness
local iswhite = '&iswhite=false'
api = api..idx..color..brightness..iswhite
os.execute(curl..'-u '..domoticzUSER..':'..domoticzPSWD..' "'..domoticzURL..api..'" &')
end
-- régulation chauffage (PID)
--[[
usage:
local pid={}
pid['debug'] = true -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
pid['zone'] = 'salon' -- nom de la zone pour affichage dans les logs et ditinction de variables
pid['sonde'] = 'salon' -- Nom de la sonde de température
pid['OnOff'] = 'chauffage' -- Nom de l'interrupteur virtuel de mise en route (hivers/été)
pid['thermostat'] = 'th_salon' -- consigne ou 'nom' de l'interrupteur virtuel de thermostat
-- actionneur
pid['radiateur'] = 'radiateur salon' -- Nom de l'interrupteur de chauffage
pid['invert'] = false -- si On et Off doivent être inversé ou non
-- PID --
pid['Kp'] = 70 -- Coefficient proportionnel
pid['Ki'] = 8 -- Coefficient intégrateur
pid['Kd'] = 3 -- Coefficient dérivateur
pid['cycle'] = 15 -- temps en minute d'un cycle PID
pid['secu'] = 60 -- temps mini en seconde entre 2 ordres opposés
commandArray = {}
compute(pid)
return commandArray
]]
function compute(pid)
local init = 0
-- récupération température
local temp = getTemp(pid['sonde'])
-- création variable : 4 dernières températures
if (uservariables['PID_temps_'..pid['zone']] == nil ) then
creaVar('PID_temps_'..pid['zone'],string.rep(temp..';',3)..temp)
init = 1
end
-- création variable : intégrale
if (uservariables['PID_integrale_'..pid['zone']] == nil ) then
creaVar('PID_integrale_'..pid['zone'],'0')
init = 1
end
if init == 1 then
log('PID '..pid['zone']..' initialisation..',pid['debug'])
return commandArray
end
-- définition des variables locales
local moy_erreur = 0
local n = 1
local somme_erreurs = 0
local heatTime
local marche
local arret
local tmp = {}
-- définition des commandes marche/arrêt
if pid['invert'] then
marche = 'Off' ; arret = 'On'
else
marche = 'On' ; arret = 'Off'
end
-- à chaque cycle
if ( time.min%pid['cycle'] == 0 ) then
-- maj des 4 dernières temps
local temps = string.match(uservariables['PID_temps_'..pid['zone']],";([^%s]+)")..";"..temp
commandArray['Variable:PID_temps_'..pid['zone']] = temps
-- si l'on veut chauffer
if ( otherdevices[pid['OnOff']] == 'On' ) then
-- récupération de la consigne
local consigne = tonumber(otherdevices_svalues[pid['thermostat']]) or pid['thermostat']
-- calcul de l'erreur
local erreur = consigne-temp
-- calcul intégrale auto consumée et moyenne erreur glissante
temps:gsub("([+-]?%d+%.*%d*)",function(t)
tmp[n] = tonumber(t)
err = tonumber(consigne-t)
somme_erreurs = somme_erreurs+err
moy_erreur = moy_erreur+err*n^3
n = n+1
end)
somme_erreurs = round(constrain(somme_erreurs,0,255),1)
moy_erreur = round(moy_erreur/100,2)
-- calcul de la dérivée (régression linéaire - méthode des moindres carrés)
local delta_erreurs = round((4*(4*tmp[1]+3*tmp[2]+2*tmp[3]+tmp[4])-10*(tmp[1]+tmp[2]+tmp[3]+tmp[4]))/20,2)
-- aux abords de la consigne, passage au second systême integrale
if somme_erreurs < 2 then
somme_erreurs = tonumber(uservariables['PID_integrale_'..pid['zone']])
-- re calcule intégrale si hors hysteresis
-- à moins d'un dixièmes de degré d'écart avec la consigne
-- le ratrapage est considéré OK, l'intégrale n'est pas recalculée
if math.abs(erreur) > 0.11 then
-- calcule intégrale
somme_erreurs = round(constrain(somme_erreurs+erreur/2,0,2),2)
-- maj
commandArray['Variable:PID_integrale_'..pid['zone']] = tostring(somme_erreurs)
end
end
-- calcul pid
local P = round(pid['Kp']*moy_erreur,2)
local I = round(pid['Ki']*somme_erreurs,2)
local D = round(pid['Kd']*delta_erreurs,2)
-- calcul de la commande en %
local commande = round(constrain(P+I+D,0,100))
-- calcul du temps de fonctionnement
if commande == 100 then
-- débordement de 20s pour ne pas couper avant recalcule
heatTime = (pid['cycle']*60)+20
elseif commande > 0 then
-- secu mini maxi
heatTime = round(constrain(commande*pid['cycle']*0.6,pid['secu'],(pid['cycle']*60)-pid['secu']))
elseif commande == 0 then
-- coupure retardée
heatTime = constrain(pid['secu']-lastSeen(pid['radiateur']),0,pid['secu'])
end
-- AFTER n'aime pas 1 ou 2..
if heatTime == 1 or heatTime == 2 then
heatTime = 0
end
-- action sur l'élément chauffant
if heatTime > 0 then
commandArray[1] = {[pid['radiateur']] = marche}
commandArray[2] = {[pid['radiateur']] = arret..' AFTER '..heatTime}
else
commandArray[pid['radiateur']]=arret
end
-- journalisation
if pid['debug'] then
log('PID zone: '..string.upper(pid['zone']))
log('température: '..temp..'°C pour '..consigne..'°C souhaité')
log('Kp: '..pid['Kp'])
log('Ki: '..pid['Ki'])
log('Kd: '..pid['Kd'])
log('erreur: '..moy_erreur)
log('∑ erreurs: '..somme_erreurs)
log('Δ erreurs: '..delta_erreurs)
log('P: '..P)
log('I: '..I)
log('D: '..D)
log('cycle: '..pid['cycle']..'min (sécu: '..pid['secu']..'s)')
-- avertissement si secu dépasse 1/4 du cycle
if ((100*pid['secu'])/(60*pid['cycle'])>25) then
warn('sécu trop importante, ralonger durée de cycle..')
end
log('commande: '..commande..'% ('..string.sub(os.date("!%X",heatTime),4,8):gsub("%:", "\'")..'\")')
log('')
end
end
end
-- toutes les 15 minutes, si on ne veut pas chauffer
if ( time.min%15 == 0 and otherdevices[pid['OnOff']] == 'Off' ) then
-- arrêt chauffage (renvoi commande systematique par sécurité)
commandArray[pid['radiateur']] = arret..' AFTER '..constrain(pid['secu']-lastSeen(pid['radiateur']),3,pid['secu'])
end
end