first commit

This commit is contained in:
Souti
2025-03-06 11:09:58 +01:00
commit 11f7d440ff
330 changed files with 38306 additions and 0 deletions

481
lua/old/script_device_Energie.old Executable file
View File

@@ -0,0 +1,481 @@
-- demo device script
-- script names have three name components: script_trigger_name.lua
-- trigger can be 'time' or 'device', name can be any string
-- domoticz will execute all time and device triggers when the relevant trigger occurs
--
-- copy this script and change the "name" part, all scripts named "demo" are ignored.
--
-- Make sure the encoding is UTF8 of the file
--
-- ingests tables: devicechanged, otherdevices,otherdevices_svalues
--
-- device changed contains state and svalues for the device that changed.
-- devicechanged['yourdevicename']=state
-- devicechanged['svalues']=svalues string
--
-- otherdevices and otherdevices_svalues are arrays for all devices:
-- otherdevices['yourotherdevicename']="On"
-- otherdevices_svalues['yourotherthermometer'] = string of svalues
--
-- Based on your logic, fill the commandArray with device commands. Device name is case sensitive.
--
-- Always, and I repeat ALWAYS start by checking for the state of the changed device.
-- If you would only specify commandArray['AnotherDevice']='On', every device trigger will switch AnotherDevice on, which will trigger a device event, which will switch AnotherDevice on, etc.
--
-- The print command will output lua print statements to the domoticz log for debugging.
-- List all otherdevices states for debugging:
-- for i, v in pairs(otherdevices) do print(i, v) end
-- List all otherdevices svalues for debugging:
-- for i, v in pairs(otherdevices_svalues) do print(i, v) end
--
-- TBD: nice time example, for instance get temp from svalue string, if time is past 22.00 and before 00:00 and temp is bloody hot turn on fan.
require "scripts/lua/functions"
time = os.time()
annee = os.date('%Y',time)
mois = os.date('%m',time)
heures = tonumber(os.date('%H',time))
minutes = tonumber(os.date('%M',time))
secondes = tonumber(os.date('%S',time))
jour = tonumber(os.date('%w',time))
jour_s = os.date('%d',time)
heurmin = heures * 60 + minutes
PUISSANCE_DELESTAGE = 750 -- Watts
function update_meter(device, id, power, energy, index)
commandArray[index] = {['UpdateDevice'] = id .. "|0|" .. power .. ";" .. energy}
end
local function round(num, dec)
--print("Round "..tostring(num))
return ( math.floor( tonumber(num) * 10^dec ) / 10^dec )
end
local function updatenum(dev, value1)
--local cmd = string.format("%d|0|%d", otherdevices_idx[dev], math.floor(value1))
local cmd = tostring(otherdevices_idx[dev]).."|0|"..tostring(round(value1, 3))
table.insert (commandArray, { ['UpdateDevice'] = cmd } )
end
function getConsommationHC(idx)
date=annee..'-'..mois..'-'..jour_s
--date_end=annee..'-'..mois..'-'..math.floor(jour_s + 1)
-- query = 'select max(value) - min(value) from Meter mc where DeviceRowID =' ..idx
-- .. ' and date like "' .. date ..'%"'
-- .. ' and (date >= "' .. date_deb.. ' 21:29:59" or date <= "'.. date_deb ..' 05:30:00")'
query = 'select sum(hc) from (select max(value) - min(value) as hc from Meter mc where DeviceRowID =' ..idx
.. ' and date like "' .. date ..'%"'
.. ' and (date >= "' .. date.. ' 21:29:59"'
.. ' and date < "' .. date ..' 23:59:59")'
.. ' union all'
.. ' select max(value) - min(value) as hc from Meter mc where DeviceRowID =' .. idx
.. ' and date like "' .. date ..'%"'
.. ' and (date < "' .. date ..' 05:30:00")'
.. ' and (date > "' .. date ..' 00:00:00")'
.. ') as c'
--query = 'select max(value) - min(value) from Meter mc where DeviceRowID =' ..idx
-- .. ' and date like "' .. date ..'%"'
-- .. ' and not(date > "' .. date.. ' 05:29:59" and date <= "'.. date ..' 21:30:00")'
print("query="..query)
local bSuccess, aRows, iCount = executeQuery(idx, query)
if aRows[1][1] then
print("Retour executeQuery "..tostring(bSuccess)..' '..aRows[1][1])
return aRows[1][1]
end
print('retour à 0')
return 0
end
function getConsommationHP(idx)
date=annee..'-'..mois..'-'..jour_s
query = 'select max(value) - min(value) from Meter mc where DeviceRowID =' ..idx
.. ' and date like "' .. date ..'%"'
.. ' and (date > "' .. date.. ' 05:29:59" and date <= "'.. date ..' 21:30:00")'
--print("query="..query)
local bSuccess, aRows, iCount = executeQuery(idx, query)
--print("Retour executeQuery "..tostring(bSuccess)..' '..aRows[1][1])
return aRows[1][1]
end
function deleteWrongData(idx)
-- delete from MultiMeter where DeviceRowid = 1135 and date >= "2021-06-02 00:00:00"
-- and date like "2021-06-02 00:00%";
date=annee..'-'..mois..'-'..jour_s
query = 'delete from MultiMeter where DeviceRowID =' ..idx
.. ' and date like "' .. date ..' 00:00%"'
.. ' and (date >= "' .. date.. ' 00:00:00")'
print("query delete="..query)
local bSuccess, aRows, iCount = executeQuery(idx, query)
end
commandArray = {}
-- ==================================================================
-- INTENSITE_GENERALE
-- ==================================================================
if (devicechanged['Oregon_Conso']) then
local tab = getValuesInTab('Oregon_Conso')
print("Conso "..otherdevices['Oregon_Conso'])
values = split(otherdevices['Oregon_Conso'], ";")
if (tonumber(values[1]) < 0) then
if (tonumber(values[1]) == -0.1) then
watt = - tonumber(values[2])
else
watt = tonumber(values[1]) * 100 - tonumber(values[2])
end
else
watt = (tonumber(values[1]) * 100 + tonumber(values[2])) --/ 1.42
end
watt = watt - 80
print("Conso "..tostring(watt))
--print("mesure"..otherdevices['INTENSITE_GENERALE'])
amp = watt / 230 --math.max(0,round(otherdevices['INTENSITE_GENERALE'],3) - 0.54) * 7 / 8
watt_conso = watt --* 0.9459
updatenum('INTENSITE_GENERALE', amp)
print("consommation Amp="..tostring(amp).." conso="..tostring(watt_conso))
updatenum('CONSOMMATION_GENERALE', round(watt_conso,0))
local tab = getValuesInTab('SolaireProduction')
local watt_solaire = tonumber(tab[1])
local watt_solaire_jour = otherdevices_svalues['SolaireProduction']
print("Suivi "..tostring(watt_conso - watt_solaire))
if (minutes%5 == 0) then
date = annee..'-'..mois..'-'..jour_s
counter_conso = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select counter from Meter_Calendar where DeviceRowID='..
otherdevices_idx['Consommation_Apparente']..' order by Date desc limit 1;"')
counter_conso=tonumber(counter_conso) or 0
print('counter_conso='..counter_conso)
value_conso = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select Value from Meter where DeviceRowID=='..
otherdevices_idx['Consommation_Apparente']..' order by Date desc limit 1;"')
value_conso=tonumber(value_conso) or 0
print('value_conso='..value_conso)
counter_solar = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select counter from Meter_Calendar where DeviceRowID='..
otherdevices_idx['SolaireProduction']..' order by Date desc limit 1;"')
counter_solar=tonumber(counter_solar) or 0
print('counter_solar='..counter_solar)
value_solar = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select Value from Meter where DeviceRowID=='..
otherdevices_idx['SolaireProduction']..' order by Date desc limit 1;"')
value_solar=tonumber(value_solar) or 0
print('value_solar='..value_solar)
counter_injection = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select counter from Meter_Calendar where DeviceRowID='..
otherdevices_idx['INJECTION']..' order by Date desc limit 1;"')
counter_injection=tonumber(counter_injection) or 0
print('counter_injection='..counter_injection)
value_injection = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select Value from Meter where DeviceRowID=='..
otherdevices_idx['INJECTION']..' order by Date desc limit 1;"')
value_injection=tonumber(value_injection) or 0
print('value_injection='..value_injection)
counter_radiateur = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select counter from Meter_Calendar where DeviceRowID='..
otherdevices_idx['Injection_Radiateur']..' order by Date desc limit 1;"')
counter_radiateur=tonumber(counter_radiateur) or 0
print('counter_radiateur='..counter_radiateur)
value_radiateur = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select Value from Meter where DeviceRowID=='..
otherdevices_idx['Injection_Radiateur']..' order by Date desc limit 1;"')
value_radiateur=tonumber(value_radiateur) or 0
print('value_radiateur='..value_radiateur)
cumul_solar = value_solar - counter_solar
cumul_injection = value_injection - counter_injection
consommation = value_conso - counter_conso
cumul_radiateur = value_radiateur - counter_radiateur
print('conso='..consommation)
print('cumul_solar='..cumul_solar)
print('cumul_injection='..cumul_injection)
print('cumul_radiateur='..cumul_radiateur)
if (cumul_solar > 0) then
print("auto consommation="..tostring(
round((100 * (cumul_solar - cumul_injection) / cumul_solar),1))
)
commandArray['AUTO_CONSOMMATION'] = otherdevices_idx['AUTO_CONSOMMATION'] ..'|0|' .. tostring(
round((100 * (cumul_solar - cumul_injection) / cumul_solar),1)
)
updatenum('AUTO_CONSOMMATION', round((100 * (cumul_solar - cumul_injection) / cumul_solar),1)
)
end
if (consommation > 0) then
print("auto production="..tostring(100 * cumul_solar / (cumul_solar + consommation)))
updatenum('AUTO_PRODUCTION', round(100 * cumul_solar / (cumul_solar + consommation),1))
end
updatenum('COUVERTURE', round(100 * value_solar / (value_conso + value_solar),1))
if (cumul_solar > 0) then
updatenum('Consommation_Efficace', round(100 *((cumul_solar - cumul_radiateur) / cumul_solar), 1))
else
updatenum('Consommation_Efficace', 0)
end
end
end
if (devicechanged['Oregon_Solaire']) then
values2 = split(otherdevices['Mesure_Courant'], ";")
print("Solaire production 2"..otherdevices['Mesure_Courant'])
local tab = getValuesInTab('Oregon_Solaire')
print("Solaire "..otherdevices['Oregon_Solaire'])
values = split(otherdevices['Oregon_Solaire'], ";")
if (tonumber(values[1]) < 0) then
if (tonumber(values[1]) == -0.1) then
watt = - tonumber(values[2])
else
watt = tonumber(values[1]) * 100 - tonumber(values[2])
end
else
watt = math.max(0, (tonumber(values[1]) * 100 + tonumber(values[2])))
end
print("Solaire "..tostring(watt))
watt = tonumber(values2[1])
if (watt > 1000) then
watt = 0;
end
--updatenum('SolaireIntensite', round(watt / 230,3))
--updatenum('INTENSITE_GENERALE', round(watt / 230,3))
watt = math.abs(watt) --- 56
--if (watt < 0 or (heures <= 7 or heures >= 21)) then
-- watt = 0
--end
--print("Intensite solaire "..devicechanged['SolaireIntensite'])
amp = math.abs(watt / 230); --math.max(0, round(otherdevices['SolaireIntensite'],3) - 0.54) *1.18
updatenum('SolaireIntensite', amp)
print("# 2 # production amp="..tostring(amp).." watt="..tostring(watt))
updatenum('SolaireProduction', round(watt,1))
watt_solaire = math.abs(watt)
local tab = getValuesInTab('CONSOMMATION_GENERALE')
local watt_conso = tonumber(tab[1])
local tab_r = getValuesInTab('Consommation_Apparente')
local watt_reel = tonumber(tab_r[1])
if (watt_reel > 0) then
if watt_solaire > 0 then
updatenum('COUVERTURE_INSTANTANEE', round(100 * (watt_solaire / (watt_solaire + watt_reel)), 1))
else
updatenum('COUVERTURE_INSTANTANEE', 0)
end
else
updatenum('COUVERTURE_INSTANTANEE', 100)
end
end
if (devicechanged['Oregon_Conso_Reelle']) then
local tab = getValuesInTab('Oregon_Conso_Reelle')
print("Conso réelle "..otherdevices['Oregon_Conso_Reelle'])
values = split(otherdevices['Oregon_Conso_Reelle'], ";")
if (tonumber(values[1]) < 0) then
if (tonumber(values[1]) == -0.1) then
watt = - tonumber(values[2])
else
watt = tonumber(values[1]) * 100 - tonumber(values[2])
end
else
watt = math.max(0, (tonumber(values[1]) * 100 + tonumber(values[2])))
end
watt = 20 + watt * 1.10
print("Conso réelle "..tostring(watt))
updatenum('Consommation_Apparente', round(watt,0))
values = split(otherdevices['SolaireProduction'], ";")
print("Solaire production "..otherdevices['SolaireProduction'])
watt_solaire = values[1]
values2 = split(otherdevices['Mesure_Courant'], ";")
print("Solaire production 2"..otherdevices['Mesure_Courant'])
watt_solaire = values[1] --+ values2[1]
print("Watt solaire "..watt_solaire)
if (watt < 0) then
updatenum('INJECTION', - round(watt,0))
updatenum('TOTAL_INJECTION', - round(watt,0))
--updatenum('Consommation_Apparente', 0)
updatenum('TOTAL_AUTOCONSOMMATION', round(watt_solaire - math.abs(watt), 0))
else
updatenum('INJECTION', 0)
updatenum('TOTAL_INJECTION', 0)
updatenum('TOTAL_AUTOCONSOMMATION', round(watt_solaire,0))
end
-- =========================================================
--Calculate what the house is consuming
-- Get current date & time
t1 = os.time()
local currentDate = os.date("*t"); -- sets up currentDate.[table]
-- (currentDate.year [full], .month [1-12], .day [1-31], .hour [0-23], .min [0-59], .sec [0-59], .wday [0-6 {Sun-Sat}])
sCurrentTime = currentDate.year .. "-" .. currentDate.month .. "-" .. currentDate.day .. " " .. currentDate.hour .. ":" .. currentDate.min .. ":" .. currentDate.sec
counter_solar = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select counter from Meter_Calendar where DeviceRowID='..
otherdevices_idx['SolaireProduction']..' order by Date desc limit 1;"')
counter_solar=tonumber(counter_solar) or 0
print('counter_solar='..counter_solar)
value_solar = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select Value from Meter where DeviceRowID=='..
otherdevices_idx['SolaireProduction']..' order by Date desc limit 1;"')
value_solar=tonumber(value_solar) or 0
print('value_solar='..value_solar)
---------------------------------------------------------------------------------------
-- Solaire 2
date = annee..'-'..mois..'-'..jour_s
counter_solar2 = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select counter from Meter_Calendar where DeviceRowID='..
otherdevices_idx['Mesure_Courant']..
' and date like "' .. date ..'%"'..
' order by Date desc limit 1;"')
counter_solar2=tonumber(counter_solar2) or 0
print('counter_solar2='..counter_solar2)
value_solar2 = os.capture('sqlite3 '..'/opt/domoticz/domoticz.db'..' " select Value from Meter where DeviceRowID=='..
otherdevices_idx['Mesure_Courant']..
' and date like "' .. date ..'%"'..
' order by Date desc limit 1;"')
value_solar2=tonumber(value_solar2) or 0
print('value_solar2='..value_solar2)
--------------------------------------------------------------------------------------
watt_p1 = getConsommationHP(1123) or 0
watt_p2 = getConsommationHC(1123) or 0
local cmd = '1135|0|'
--USAGE1= energy usage meter tariff 1, This is an incrementing counter
--USAGE2= energy usage meter tariff 2, This is an incrementing counter
--RETURN1= energy return meter tariff 1, This is an incrementing counter
--RETURN2= energy return meter tariff 2, This is an incrementing counter
--CONS= actual usage power (Watt)
--PROD= actual return power (Watt)
.. tostring(math.floor(watt_p1)) .. ';'
.. tostring(math.floor(watt_p2)) .. ';'
-- + value_solar2 - counter_solar2
.. tostring(math.floor(value_solar - counter_solar + value_solar2 - counter_solar2)) .. ';'
.. '0;'
.. tostring(math.floor(math.max(0,watt) + watt_solaire)).. ';'
.. tostring(math.floor(watt_solaire)) --math.floor(ConsumoEnergyBalance / 1000)) --round(watt,0))
print('Consommation_Reelle_2 '..cmd)
if heures == 23 and minutes == 59 and secondes >= 45 then
-- ignored
else
table.insert (commandArray, { ['UpdateDevice'] = cmd } )
end
if heures == 00 and minutes == 05 and secondes <= 10 then
deleteWrongData(1135)
end
print('when light=' .. tostring(whenLight()))
-- =========================================================
local cmd = '1136|0|'
--USAGE1= energy usage meter tariff 1, This is an incrementing counter
--USAGE2= energy usage meter tariff 2, This is an incrementing counter
--RETURN1= energy return meter tariff 1, This is an incrementing counter
--RETURN2= energy return meter tariff 2, This is an incrementing counter
--CONS= actual usage power (Watt)
--PROD= actual return power (Watt)
.. '0;'
.. '0;'
.. '0;'
.. '0;'
.. tostring(math.floor(math.max(0,watt))).. ';'
.. '0' --math.floor(ConsumoEnergyBalance / 1000)) --round(watt,0))
table.insert (commandArray, { ['UpdateDevice'] = cmd } )
updatenum('Non_Couvert_2', math.floor(math.max(0,watt)))
-- =========================================================
local debut_injection = -20
local fin_injection = 10
if tonumber(watt_solaire) < 50 or uservariables["Dark"] == "True" then
commandArray['Dimmer'] = 'Set Level: 30'
else
if (watt < debut_injection and tonumber(watt_solaire) > 150) then
print("Allumage radiateur pour éviter l'injection " .. tostring(lastUpdateOfDevice('RadiateurBureau')))
if watt < debut_injection then
local quick_value=math.floor(math.abs(watt / (PUISSANCE_DELESTAGE / 100)))
print("quick_value plus="..tostring(quick_value))
os.execute('curl "http://192.168.125.11/plus?value=' .. tostring(quick_value).. '"');
else
commandArray['Dimmer'] = 'Set Level: 40'
end
else
print("Pas de consommation necessaire")
if (watt > 150) then
commandArray['Dimmer'] = 'Set Level: 30'
else
if (watt > fin_injection) then
local quick_value=math.floor(math.abs(watt / (PUISSANCE_DELESTAGE / 100)))
print("quick_value minus="..tostring(quick_value))
os.execute('curl "http://192.168.125.11/minus?value=' .. tostring(quick_value).. '"');
else
commandArray['Dimmer'] = 'Set Level: 50'
end
end
end
end
command = 'curl -s "http://192.168.125.11"|grep "<p>"|awk -F">" \'{print $2}\'|awk -F"<" \'{print $1}\''
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
print("result niveau d'injection= "..result)
updatenum('Injection_Radiateur', tonumber(result) * PUISSANCE_DELESTAGE / 100)
if (tonumber(result) == 1) then
commandArray['Dimmer'] = 'Set Level: 30'
end
end
return commandArray

View File

@@ -0,0 +1,210 @@
require "scripts/lua/functions"
commandArray = {}
--local switch = 'VoletCuisine'
-- ------------------------------------------------------------------------------
--recupere les minutes
-- ------------------------------------------------------------------------------
time=os.time()
minutes=tonumber(os.date('%M',time))
jour=tonumber(os.date('%w',time))
heures=tonumber(os.date('%H',time))
heurmin= heures * 60 + minutes
-- ------------------------------------------------------------------------------
-- Test temperature radiateur chambres
-- ------------------------------------------------------------------------------
function gestionRadiateur( switchTemp, switchRadiateur, consigne)
if (minutes % 10 ~= 5) then
return
end
local last = lastUpdateOfDevice(switchRadiateur)
debug("--------------"..switchRadiateur.."-----------------------------------")
debug("delai="..tostring(delai).." last="..tostring(last)..' Chauffage='..otherdevices[switchRadiateur])
debug("------------------------------------------------------------")
if (last < 600) then
debug("Aucune action. Mise à jour trop récente.".." last="..tostring(last).." temp="..tostring(currentTemp).." / Consigne="..tostring(consigne))
return
end
local delta = 0.2
local currentTemp = tonumber(otherdevices_svalues[switchTemp])
local tempAbsence = tonumber(otherdevices_svalues['ConsigneAbsence'])
local variation = variationTemp2(switchTemp, 10) -- variation des 10 dernières minutes
local variationExt = uservariables['AugmentationTempExterieure']
local augmentation = variation * 60 / 10 --time -- ° par heure
local ecart = consigne - currentTemp
local estimation = 0.0
if (augmentation > 0 and ecart > 0) then
estimation = 60 * ecart / augmentation
end
debug("Retour augmentation="..tostring(augmentation).." ecart="..tostring(ecart)..'°C Estimation='..tostring(estimation).." minutes variationExt="..tostring(variationExt).."°C / heure")
--2016-02-27 20:08:59.864 LUA: delai=180 last=37
--2016-02-27 20:08:59.918 LUA: Retour variation=0.3 switch=RadiateurManon
--2016-02-27 20:08:59.918 LUA: CHECK Temperature Variation=0.3 switch=RadiateurManon currentTemp=18.3 tempAbsence=16 consigne=18.5
debug("Retour variation="..tostring(variation).." switch="..switchRadiateur..' lastUpdate='..tostring(lastUpdateOfDevice(switchRadiateur)))
debug('CHECK Temperature Variation='..tostring(variation)..' switch='..switchRadiateur..' currentTemp='..tostring(currentTemp).. ' tempAbsence='..tostring(tempAbsence)..' consigne='..tostring(consigne))
if otherdevices['ChauffageGeneral'] == 'Off' then
if (minutes%30 == 0) then
switchOffRadiateur(switchRadiateur)
debug("ChauffageGeneral Eteint. Demande extinction.")
else
debug("Radiateur ="..switchRadiateur.." Retour sans rien faire. ChauffageGeneral Eteint.")
end
end
if lastUpdateOfDevice(switchRadiateur) < delai then
debug("Radiateur ="..switchRadiateur.." Retour sans rien faire. Delai non atteint.")
return
end
-- Periode de vacances ou absence ==> hors gel
if (otherdevices['Vacances'] == 'On' or otherdevices['AbsenceFamille'] == 'On') then
if (currentTemp > 14) then
switchOffRadiateur(switchRadiateur)
--commandArray[switchRadiateur]='Off'
else
if variation <= 0 then
--commandArray[switchRadiateur]='On'
switchOnRadiateur(switchRadiateur)
end
end
debug ('CHECK Temperature chambre : Vacances -> ' ..otherdevices_svalues[switchTemp]..' switch='..switchRadiateur)
else
debug ('CHECK Temperature: Presence -> ' ..otherdevices_svalues[switchTemp]..' '..josdGetJourSemaine(jour))
-- Température non atteinte
if (currentTemp < consigne) then
if variation <= 0.0 then
-- commandArray[switchRadiateur]='On'
switchOnRadiateur(switchRadiateur)
debug("Demande chauffe : "..tostring(currentTemp).." / "..tostring(consigne).." Variation="..tostring(variation))
else
--switchIfNeeded(switchRadiateur, 'On')
-- Dépassement prévu dans le delai on coupe
if (estimation > 0 and estimation <= delai / 60 ) then
--commandArray[switchRadiateur] = 'Off'
switchOffRadiateur(switchRadiateur)
debug("Arrêt chauffage : Température sera atteinte dans le delai "..tostring(estimation).." Minutes")
else
debug("Aucune action. Chauffage en-cours."..tostring(currentTemp).." / "..tostring(consigne).." Variation="..tostring(variation))
end
end
-- Température dépassée
else
-- Température supérieure
if (currentTemp >= consigne + delta or (estimation > 0 and estimation <= delai / 60 )) then
if (consigne == consigneAbsence) then
-- rien
switchIfNeeded(switchRadiateur,"Off")
else
if (variation > 0) then
if (variationExt <= 0) then
switchOffRadiateur(switchRadiateur)
debug("Demande arrêt. Température dépassée.")
else
switchIfNeeded(switchRadiateur,"Off")
debug("Aucune action. Augmentation due à température extérieure.")
end
end
end
else
-- Augmentation de la température non due à l'augmentation extérieure
if (variation > 0) then
-- Pas d'augmentation extérieure
if (variationExt <= 0) then
--commandArray[switchRadiateur]='Off'
switchOffRadiateur(switchRadiateur)
debug("Demande arrêt. Température atteinte et continue d'augmenter.")
else
switchIfNeeded(switchRadiateur,"Off")
debug("Aucune action. Augmentation due à température extérieure.")
end
else
-- Températue en baisse pas nécessaire d'envoyer
--switchOffRadiateur(switchRadiateur)
--commandArray[switchRadiateur]='Off'
--switchIfNeeded(switchRadiateur, 'Off')
switchIfNeeded(switchRadiateur,"Off")
debug("Aucune action. Temperature atteinte et pas d'augmentation. "..tostring(currentTemp).." / "..tostring(consigne).." Variation="..tostring(variation))
end
end
end
end
debug("------------------------------------------------------------")
end
-- ------------------------------------------------------
-- Arrêt tous les radiateurs
-- ------------------------------------------------------
if devicechanged['ChauffageGeneral'] then
if otherdevices['ChauffageGeneral'] == 'Off' then
for i = 1, 7 do
print("Arrêt radiateur="..radiateurs[i])
commandArray[radiateurs[i]]='Off'
end
end
end
-- ------------------------------------------------------
-- Chambre de Manon
-- ------------------------------------------------------
if devicechanged['ChambreManon'] or devicechanged['ConsigneConfortManon'] or devicechanged['ChauffageGeneral'] then
local consigne = tonumber(otherdevices_svalues['ConsigneConfortManon'])
gestionRadiateur('ChambreManon', 'RadiateurManon', consigne)
end
-- ------------------------------------------------------
-- Chambre de Theo
-- ------------------------------------------------------
if devicechanged['ChambreTheo'] or devicechanged['ConsigneConfortTheo'] or devicechanged['ChauffageGeneral'] then
local consigne = tonumber(otherdevices_svalues['ConsigneConfortTheo'])
gestionRadiateur('ChambreTheo', 'RadiateurTheo', consigne)
end
-- ------------------------------------------------------
-- Chambre parents
-- ------------------------------------------------------
if devicechanged['Chambre'] or devicechanged['ConsigneConfortChambre'] or devicechanged['ChauffageGeneral'] then
local consigne = tonumber(otherdevices_svalues['ConsigneConfortChambre'])
gestionRadiateur('Chambre', 'RadiateurChambre', consigne)
end
-- ------------------------------------------------------
-- Radiateur cuisine
-- ------------------------------------------------------
if devicechanged['TemperatureBarometre'] or devicechanged['ConsigneConfortSalon'] or devicechanged['ChauffageGeneral'] then
local consigne = tonumber(otherdevices_svalues['ConsigneConfortSalon'])
gestionRadiateur('TemperatureBarometre', 'RadiateurCuisine', consigne)
end
-- ------------------------------------------------------
-- Radiateur Salon
-- ------------------------------------------------------
if devicechanged['TemperatureBarometre'] or devicechanged['ConsigneConfortSalon'] or devicechanged['ChauffageGeneral'] then
local consigne = tonumber(otherdevices_svalues['ConsigneConfortSalon'])
gestionRadiateur('TemperatureBarometre', 'RadiateurSalon1', consigne)
gestionRadiateur('TemperatureBarometre', 'RadiateurSalon2', consigne)
end
-- ------------------------------------------------------
-- Radiateur Bureau
-- ------------------------------------------------------
if devicechanged['Bureau'] or devicechanged['ConsigneConfortBureau'] or devicechanged['ChauffageGeneral'] then
local consigne = tonumber(otherdevices_svalues['ConsigneConfortBureau'])
gestionRadiateur('Bureau', 'RadiateurBureau', consigne)
--gestionRadiateur('TemperatureBarometre', 'RadiateurSalon2', consigne)
end
return commandArray

39
lua/old/script_device_demo.old Executable file
View File

@@ -0,0 +1,39 @@
-- demo device script
-- script names have three name components: script_trigger_name.lua
-- trigger can be 'time' or 'device', name can be any string
-- domoticz will execute all time and device triggers when the relevant trigger occurs
--
-- copy this script and change the "name" part, all scripts named "demo" are ignored.
--
-- Make sure the encoding is UTF8 of the file
--
-- ingests tables: devicechanged, otherdevices,otherdevices_svalues
--
-- device changed contains state and svalues for the device that changed.
-- devicechanged['yourdevicename']=state
-- devicechanged['svalues']=svalues string
--
-- otherdevices and otherdevices_svalues are arrays for all devices:
-- otherdevices['yourotherdevicename']="On"
-- otherdevices_svalues['yourotherthermometer'] = string of svalues
--
-- Based on your logic, fill the commandArray with device commands. Device name is case sensitive.
--
-- Always, and I repeat ALWAYS start by checking for the state of the changed device.
-- If you would only specify commandArray['AnotherDevice']='On', every device trigger will switch AnotherDevice on, which will trigger a device event, which will switch AnotherDevice on, etc.
--
-- The print command will output lua print statements to the domoticz log for debugging.
-- List all otherdevices states for debugging:
-- for i, v in pairs(otherdevices) do print(i, v) end
-- List all otherdevices svalues for debugging:
-- for i, v in pairs(otherdevices_svalues) do print(i, v) end
--
-- TBD: nice time example, for instance get temp from svalue string, if time is past 22.00 and before 00:00 and temp is bloody hot turn on fan.
print('this will end up in the domoticz log')
commandArray = {}
if (devicechanged['MyDeviceName'] == 'On' and otherdevices['MyOtherDeviceName'] == 'Off') then
commandArray['MyOtherDeviceName']='On'
end
return commandArray

143
lua/old/script_time_DewPoint.old Executable file
View File

@@ -0,0 +1,143 @@
--[[
~/domoticz/scripts/lua/script_device_givre.lua
auteur : papoo
MAJ : 28/02/2018
création : 06/05/2016
Principe :
Calculer via les informations température et hygrométrie d'une sonde extérieure
le point de rosée ainsi que le point de givre
puis en comparant ensuite le point de givre et l'a température extérieure, création d'une alerte givre.
http://pon.fr/script-calcul-et-alerte-givre/
http://easydomoticz.com/forum/viewtopic.php?f=21&t=1085&start=10#p17545
https://github.com/papo-o/domoticz_scripts/blob/master/Lua/script_device_givre.lua
--]]
--------------------------------------------
------------ Variables à éditer ------------
--------------------------------------------
require "scripts/lua/functions"
local debugging = true -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local temp_ext = 'BarometreLaGacilly' -- nom de la sonde de température/humidité extérieure
local dev_dew_point = 'Point de rosee' -- nom de l'éventuel dummy température point de rosée si vous souhaitez le suivre sinon nil
local dev_freeze_point = 'Point de givre' -- nom de l'éventuel dummy température point de givre si vous souhaitez le suivre sinon nil
local dev_hum_abs_point = nil -- nom de l'éventuel dummy humidité absolue si vous souhaitez le suivre sinon nil
local dev_freeze_alert = 'Alerte givre' -- nom de l'éventuel dummy alert point de givre si vous souhaitez le suivre sinon nil
--------------------------------------------
----------- Fin variables à éditer ---------
--------------------------------------------
local nom_script = 'Point de rosée et point de givrage'
local version = 1.2 -- version du script
commandArray = {}
--------------------------------------------
---------------- Fonctions -----------------
--------------------------------------------
function voir_les_logs (s, debugging)
if (debugging) then
if s ~= nil then
debug ("<font color='#f3031d'>".. tostring(s) .."</font>");
else
debug ("<font color='#f3031d'>aucune valeur affichable</font>");
end
end
end
function round(value, digits)
if not value or not digits then
return nil
end
local precision = 10^digits
return (value >= 0) and
(math.floor(value * precision + 0.5) / precision) or
(math.ceil(value * precision - 0.5) / precision)
end
function dewPoint (T, RH)
local b,c = 17.67, 243.5
--voir_les_logs("--- 1",debugging)
RH = math.max (tonumber(RH), 1e-3)
--voir_les_logs("--- 1",debugging)
local gamma = math.log (tonumber(RH)/100) + b * T / (c + T)
--voir_les_logs("--- 1",debugging)
return c * gamma / (b - gamma)
end
function freezing_point(dp, t)
if not dp or not t or dp > t then
return nil, " La température du point de rosée est supérieure à la température. Puisque la température du point de rosée ne peut être supérieure à la température de l'air , l\'humidité relative a été fixée à nil."
end
T = t + 273.15
Td = dp + 273.15
return (Td + (2671.02 /((2954.61/T) + 2.193665 * math.log(T) - 13.3448))-T)-273.15
end
function hum_abs(t,hr)
-- https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
-- Formule pour calculer l'humidité absolue
-- Dans la formule ci-dessous, la température (T) est exprimée en degrés Celsius, l'humidité relative (hr) est exprimée en%, et e est la base des logarithmes naturels 2.71828 [élevée à la puissance du contenu des crochets]:
-- Humidité absolue (grammes / m3 ) = (6,122 * e^[(17,67 * T) / (T + 243,5)] * rh * 2,1674))/(273,15 + T)
-- Cette formule est précise à 0,1% près, dans la gamme de température de -30 ° C à + 35 ° C
ha = round((6.112 * math.exp((17.67 * t)/(t+243.5)) * hr * 2.1674)/ (273.15 + t),1)
return ha
end
--------------------------------------------
-------------- Fin Fonctions ---------------
--------------------------------------------
time=os.date("*t")
if (time.min%15 == 0) then -- si script_time
--if devicechanged[temp_ext] then -- si script_device
--print("script_device_givre.lua")
print('valeurs '..otherdevices_svalues[temp_ext]);
voir_les_logs("=========== ".. nom_script .." (v".. version ..") ===========",debugging)
Temp, Humidity = otherdevices_svalues[temp_ext]:match("([^;]+);([^;]+)")
voir_les_logs("--- --- --- Température Ext : ".. Temp,debugging)
voir_les_logs("--- --- --- Humidité : ".. Humidity,debugging)
if dev_dew_point ~= nil then
local dew = dewPoint(Temp,Humidity)
voir_les_logs("--- --- --- Dew point calculated : ".. tostring(dew),debugging)
DewPoint = round(dew,2)
voir_les_logs("--- --- --- Point de Rosée : ".. DewPoint,debugging)
commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[dev_dew_point] .. "|0|" .. DewPoint} -- Mise à jour point de rosée
end
--voir_les_logs("--- 1",debugging)
if dev_freeze_point ~= nil then
FreezingPoint = round(freezing_point(DewPoint, tonumber(Temp)),2)
voir_les_logs("--- --- --- Point de Givrage : ".. FreezingPoint,debugging)
commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[dev_freeze_point] .. "|0|" .. FreezingPoint} -- Mise à jour point de givrage
end
--voir_les_logs("--- 2",debugging)
if dev_hum_abs_point ~= nil then
hum_abs_point = hum_abs(Temp, Humidity)
voir_les_logs("--- --- --- Humidité absolue : ".. hum_abs_point,debugging)
commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[dev_hum_abs_point] .. "|0|" .. hum_abs_point} -- Mise à jour humidité absolue
end
--voir_les_logs("--- 3",debugging)
if dev_freeze_alert ~= nil and time.hour == 7 and time.min >= 30 then
if(tonumber(Temp)<=1 and tonumber(FreezingPoint)<=0) then
voir_les_logs("--- --- --- Givre --- --- ---",debugging)
commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[dev_freeze_alert]..'|4|'..FreezingPoint}
commandArray['SendNotification'] = 'Alert#Présence de givre!'
elseif(tonumber(Temp)<=3 and tonumber(FreezingPoint)<=0)then
voir_les_logs("--- --- --- Risque de Givre --- --- ---",debugging)
commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[dev_freeze_alert]..'|2|'..FreezingPoint}
commandArray['SendNotification'] = 'Alert#Risque de givre!'
else
voir_les_logs("--- --- --- Aucun risque de Givre --- --- ---",debugging)
commandArray[#commandArray+1] = {['UpdateDevice'] = otherdevices_idx[dev_freeze_alert]..'|1|'..'Pas de givre'}
end
end
voir_les_logs("========= Fin ".. nom_script .." (v".. version ..") =========",debugging)
end
return commandArray

View File

@@ -0,0 +1,262 @@
--------------------------------------------------------------------------------
-- Probabilite pluie neige
--------------------------------------------------------------------------------
--[[
name : script_time_probabilite_pluie.lua
auteur : papoo
version : 1.11
date de création : 08/08/2016
Date de mise à jour : 10/08/16
Principe : Ce script a pour but d'interroger l'API du site https://www.wunderground.com/ toutes les heures afin de
récuperer les calculs de probabilités de pluie et de neige sur 36 heures pour une ville donnée. Cette API utilise une clé gratuite pour 500 requetes par heure
Il faut donc sinscrire sur weatherunderground pour avoir accès à cette API
URL post : http://easydomoticz.com/forum/viewtopic.php?f=17&t=2301
Ce script utilise Lua-Simple-XML-Parser https://github.com/Cluain/Lua-Simple-XML-Parser
]]--
-- ========================================================================
-- Variables à éditer
-- ========================================================================
local debugging = true -- true pour voir les logs dans la console log Dz ou false pour ne pas les voir
local countryCode="FRANCE" -- Votre countryCode, nécessaire pour l'API
local APIKEY="48a08328a93a18a1" -- Votre Key API Weather Underground de 16 caractères
local ville="Redon" -- Votre ville ou commune nécessaire pour l'API
-- L'api fournie 36 probabilités de pluie, 1 par heure.
local proba_pluie_h = {} -- Ajoutez, modifiez ou supprimez les variables proba_pluie_h[]
-- en changeant le N° entre [] correspondant à l'heure souhaitée pour l'associer au device concerné dans dz
proba_pluie_h[1]=328 -- renseigner l'id du device % probabilité pluie à 1 heure associé, nil si non utilisé
proba_pluie_h[2]=329 -- renseigner l'id du device % probabilité pluie à 2 heures associé, nil si non utilisé
proba_pluie_h[4]=nil -- renseigner l'id du device % probabilité pluie à 4 heures associé, nil si non utilisé
proba_pluie_h[6]=nil -- renseigner l'id du device % probabilité pluie à 6 heures associé, nil si non utilisé
proba_pluie_h[12]=nil -- renseigner l'id du device % probabilité pluie à 12 heures associé, nil si non utilisé
proba_pluie_h[24]=nil -- renseigner l'id du device % probabilité pluie à 24 heures associé, nil si non utilisé
-- L'api fournie 36 probabilités de neige, 1 par heure.
local proba_neige_h={} -- comme pour la pluie Ajoutez, modifiez ou supprimez les variables proba_neige_h[]
-- en changeant le N° entre [] correspondant à l'heure souhaitée pour l'associer au device concerné dans dz
proba_neige_h[1]=nil -- renseigner l'id du device % probabilité neige à 1 heure associé, nil si non utilisé
proba_neige_h[3]=nil -- renseigner l'id du device % probabilité neige à 2 heures associé, nil si non utilisé
proba_neige_h[6]=nil -- renseigner l'id du device % probabilité neige à 4 heures associé, nil si non utilisé
proba_neige_h[12]=nil -- renseigner l'id du device % probabilité neige à 6 heures associé, nil si non utilisé
proba_neige_h[24]=nil -- renseigner l'id du device % probabilité neige à 12 heures associé, nil si non utilisé
proba_neige_h[36]=nil -- renseigner l'id du device % probabilité neige à 24 heures associé, nil si non utilisé
local seuil_notification=80 -- pourcentage au delà duquel vous souhaitez être notifié, nil si non utilisé
-- ========================================================================
-- Fin Variables à éditer
-- ========================================================================
local pluie = nil
local neige = nil
local indexArray=0
---------------------------------------------------------------------------
--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
---------------------------------------------------------------------------------
-- Lua-Simple-XML-Parser
---------------------------------------------------------------------------------
XmlParser = {};
self = {};
function XmlParser:ToXmlString(value)
value = string.gsub(value, "&", "&amp;"); -- '&' -> "&amp;"
value = string.gsub(value, "<", "&lt;"); -- '<' -> "&lt;"
value = string.gsub(value, ">", "&gt;"); -- '>' -> "&gt;"
value = string.gsub(value, "\"", "&quot;"); -- '"' -> "&quot;"
value = string.gsub(value, "([^%w%&%;%p%\t% ])",
function(c)
return string.format("&#x%X;", string.byte(c))
end);
return value;
end
function XmlParser:FromXmlString(value)
value = string.gsub(value, "&#x([%x]+)%;",
function(h)
return string.char(tonumber(h, 16))
end);
value = string.gsub(value, "&#([0-9]+)%;",
function(h)
return string.char(tonumber(h, 10))
end);
value = string.gsub(value, "&quot;", "\"");
value = string.gsub(value, "&apos;", "'");
value = string.gsub(value, "&gt;", ">");
value = string.gsub(value, "&lt;", "<");
value = string.gsub(value, "&amp;", "&");
return value;
end
function XmlParser:ParseArgs(node, s)
string.gsub(s, "(%w+)=([\"'])(.-)%2", function(w, _, a)
node:addProperty(w, self:FromXmlString(a))
end)
end
function XmlParser:ParseXmlText(xmlText)
local stack = {}
local top = newNode()
table.insert(stack, top)
local ni, c, label, xarg, empty
local i, j = 1, 1
while true do
ni, j, c, label, xarg, empty = string.find(xmlText, "<(%/?)([%w_:]+)(.-)(%/?)>", i)
if not ni then break end
local text = string.sub(xmlText, i, ni - 1);
if not string.find(text, "^%s*$") then
local lVal = (top:value() or "") .. self:FromXmlString(text)
stack[#stack]:setValue(lVal)
end
if empty == "/" then -- empty element tag
local lNode = newNode(label)
self:ParseArgs(lNode, xarg)
top:addChild(lNode)
elseif c == "" then -- start tag
local lNode = newNode(label)
self:ParseArgs(lNode, xarg)
table.insert(stack, lNode)
top = lNode
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
if #stack < 1 then
error("XmlParser: nothing to close with " .. label)
end
if toclose:name() ~= label then
error("XmlParser: trying to close " .. toclose.name .. " with " .. label)
end
top:addChild(toclose)
end
i = j + 1
end
local text = string.sub(xmlText, i);
if #stack > 1 then
error("XmlParser: unclosed " .. stack[#stack]:name())
end
return top
end
function XmlParser:loadFile(xmlFilename, base)
if not base then
base = system.ResourceDirectory
end
local path = system.pathForFile(xmlFilename, base)
local hFile, err = io.open(path, "r");
if hFile and not err then
local xmlText = hFile:read("*a"); -- read file content
io.close(hFile);
return self:ParseXmlText(xmlText), nil;
else
print(err)
return nil
end
end
function newNode(name)
local node = {}
node.___value = nil
node.___name = name
node.___children = {}
node.___props = {}
function node:value() return self.___value end
function node:setValue(val) self.___value = val end
function node:name() return self.___name end
function node:setName(name) self.___name = name end
function node:children() return self.___children end
function node:numChildren() return #self.___children end
function node:addChild(child)
if self[child:name()] ~= nil then
if type(self[child:name()].name) == "function" then
local tempTable = {}
table.insert(tempTable, self[child:name()])
self[child:name()] = tempTable
end
table.insert(self[child:name()], child)
else
self[child:name()] = child
end
table.insert(self.___children, child)
end
function node:properties() return self.___props end
function node:numProperties() return #self.___props end
function node:addProperty(name, value)
local lName = "@" .. name
if self[lName] ~= nil then
if type(self[lName]) == "string" then
local tempTable = {}
table.insert(tempTable, self[lName])
self[lName] = tempTable
end
table.insert(self[lName], value)
else
self[lName] = value
end
table.insert(self.___props, { name = name, value = self[name] })
end
return node
end
---------------------------------------------------------------------------
-- Fin Fonctions
---------------------------------------------------------------------------
commandArray = {}
now=os.date("*t")
if now.min == 15
and ((now.hour >= 11 and now.hour <= 13) or (now.hour >= 17 and now.hour <= 20))
then -- éxécution du script toutes les heures
voir_les_logs("script_time_probabilite_pluie.lua",debugging)
local fname ="/tmp/weather"..ville.."1.out"
os.execute("wget -q -O " .. fname .. " http://api.wunderground.com/api/"..APIKEY.."/hourly/lang:FR/q/"..countryCode.."/"..ville..".xml")
--voir_les_logs("Fichier local : " ..fname,debugging)
local f = io.open(fname, "r")
if f == nil then
voir_les_logs("Error opening file '" .. fname .. "'.",debugging)
os.exit(1)
end
local testXml = f:read("*all")
f:close()
local parsedXml = XmlParser:ParseXmlText(testXml)
if (parsedXml) then local abr = parsedXml.response.hourly_forecast
for i in pairs(abr:children()) do
if proba_pluie_h[i] ~= nil then
pluie = tonumber(abr:children()[i]:children()[19]:value())
voir_les_logs("Probabilite de pluie a ".. i .."h => " .. pluie,debugging)
commandArray[indexArray] = {['UpdateDevice'] = proba_pluie_h[i]..'|0|'.. pluie}
indexArray=indexArray+1
if seuil_notification ~= nil and pluie > seuil_notification then
commandArray[indexArray] = {['SendNotification'] = 'Alerte : '.. pluie ..' % de probabilité de pluie dans '.. i ..'heure(s)'}
indexArray=indexArray+1
end
end
if proba_neige_h[i] ~=nil then
neige = tonumber(abr:children()[i]:children()[18]:children()[2]:value())
voir_les_logs("probabilite de neige a ".. i .."h => " .. neige,debugging)
commandArray[indexArray] = {['UpdateDevice'] = proba_neige_h[i]..'|0|'.. neige}
indexArray=indexArray+1
if seuil_notification ~= nil and neige > seuil_notification then
commandArray[indexArray] = {['SendNotification'] = 'Alerte : '.. neige ..' % de probabilité de neige dans '.. i ..'heure(s)'}
indexArray=indexArray+1
end
end
end
end
end -- if now
return commandArray

View File

@@ -0,0 +1,237 @@
--[[ Virtual Lux sensor and other real-time solar data
~/domoticz/scripts/lua/script_time_SolarSensor.lua
-- http://www.domoticz.com/wiki/Real-time_solar_data_without_any_hardware_sensor_:_azimuth,_Altitude,_Lux_sensor...#Installation_instructions
-- Autors ----------------------------------------------------------------
V1.0 - Sébastien Joly - Great original work
V1.1 - Neutrino - Adaptation to Domoticz
V1.2 - Jmleglise - An acceptable approximation of the lux below 1° altitude for Dawn and dusk + translation + several changes to be more userfriendly.
V1.3 - Jmleglise - No update of the Lux data when <=0 to get the sunset and sunrise with lastUpdate
V1.4 - use the API instead of updateDevice to update the data of the virtual sensor to be able of using devicechanged['Lux'] in our scripts. (Due to a bug in Domoticz that doesn't catch the devicechanged event of the virtual sensor)
]]--
-- Variables to customize ------------------------------------------------
local localhost = '127.0.0.1:81' -- Set your port. (Not the universal IP).
local city = "Redon" -- Your city for Wunderground API
local countryCode = "FR" -- Your country code for Wunderground API
local idxLux ='653' -- Your virtual Lux Device ID
local idxSolarAzimuth ='321' -- Your virtual Azimuth Device ID
local idxSolarAltitude ='322' -- Your virtual Solar Altitude Device ID
local idxUserVarOcta='31' -- Your user variable ID , named octa
local wuAPIkey = "48a08328a93a18a1" -- Your Weather Underground API Key
local latitude = 47.726872 -- your home
local longitude = -2.131937 -- your home
local altitude = 19 -- Your home altitude : run once in debug = 1 to found your altitude in Log and write it here
local WMOID = '07130' --Rennes -- Your nearest SYNOP Station for ogimet. Very important ! http://www.ogimet.com/
local DEBUG = 0
if (otherdevices['Debug'] == 'On') then
DEBUG = 1 -- 0 , 1 for domoticz log , 2 for file log
end
-- and customize the URL of api.wunderground around line 104 according to your country.
-- Below , edit at your own risk ------------------------------------------
function leapYear(year)
return year%4==0 and (year%100~=0 or year%400==0)
end
function split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
function pow(num, dec)
return num^dec
end
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
commandArray = {}
time = os.date("*t")
if ((time.min % 10)==0) then -- Run every n minutes. Check the wundergroud API limitation before changing this
json = (loadfile "/opt/domoticz/scripts/lua/JSON.lua")() -- For Linux
--json = (loadfile "D:\\Domoticz\\scripts\\lua\\json.lua")() -- For Windows
local arbitraryTwilightLux=6.32 -- W/m² egal 800 Lux (the theoritical value is 4.74 but I have more accurate result with 6.32...)
local constantSolarRadiation = 1361 -- Solar Constant W/m²
if (uservariables['octa'] == nil) then print("Error : Did you create the Uservariable octa ?") end
-- API Wunderground
local url_json = 'curl http://api.wunderground.com/api/'..wuAPIkey..'/conditions/q/'..countryCode..'/'..city..'.json'
print('url_json='..url_json)
--local config=assert(io.popen('curl http://api.wunderground.com/api/'..wuAPIkey..'/conditions/q/'..countryCode..'/'..city..'.json'))
--local location = config:read('*all')
--config:close()
--local jsonLocation = json:decode(location)
--if( DEBUG == 1) then
-- local latitude = jsonLocation.current_observation.display_location.latitude
-- local longitude = jsonLocation.current_observation.display_location.longitude
-- local altitude = jsonLocation.current_observation.display_location.elevation
-- print('Lat: '..latitude..'Long: '..longitude..'Alt: '..altitude)
-- end
--relativePressure = jsonLocation.current_observation.pressure_mb -- if you have an another way to get the Pressure, (local barometer ...) then you may optimize the script and avoid the call to api.wunderground)
----------------------------------
print("valeurs"..otherdevices_svalues['BarometreLaGacilly'])
local tab = split(otherdevices_svalues['BarometreLaGacilly'], ";")
print("Pressure="..tostring(tab[4]))
relativePressure = tonumber(tab[4])
local year = os.date("%Y")
local numOfDay = os.date("%j")
if leapYear(year) == true then
nbDaysInYear = 366 -- How many days in the year ?
else
nbDaysInYear = 365
end
angularSpeed = 360/365.25
local Declinaison = math.deg(math.asin(0.3978 * math.sin(math.rad(angularSpeed) *(numOfDay - (81 - 2 * math.sin((math.rad(angularSpeed) * (numOfDay - 2))))))))
timeDecimal = (os.date("!%H") + os.date("!%M") / 60) -- Coordinated Universal Time (UTC)
solarHour = timeDecimal + (4 * longitude / 60 ) -- The solar Hour
hourlyAngle = 15 * ( 12 - solarHour ) -- hourly Angle of the sun
sunAltitude = math.deg(math.asin(math.sin(math.rad(latitude))* math.sin(math.rad(Declinaison)) + math.cos(math.rad(latitude)) * math.cos(math.rad(Declinaison)) * math.cos(math.rad(hourlyAngle))))-- the height of the sun in degree, compared with the horizon
local azimuth = math.acos((math.sin(math.rad(Declinaison)) - math.sin(math.rad(latitude)) * math.sin(math.rad(sunAltitude))) / (math.cos(math.rad(latitude)) * math.cos(math.rad(sunAltitude) ))) * 180 / math.pi -- deviation of the sun from the North, in degree
local sinAzimuth = (math.cos(math.rad(Declinaison)) * math.sin(math.rad(hourlyAngle))) / math.cos(math.rad(sunAltitude))
if(sinAzimuth<0) then azimuth=360-azimuth end
sunstrokeDuration = math.deg(2/15 * math.acos(- math.tan(math.rad(latitude)) * math.tan(math.rad(Declinaison)))) -- duration of sunstroke in the day . Not used in this calculation.
RadiationAtm = constantSolarRadiation * (1 +0.034 * math.cos( math.rad( 360 * numOfDay / nbDaysInYear ))) -- Sun radiation (in W/m²) in the entrance of atmosphere.
-- Coefficient of mitigation M
absolutePressure = relativePressure - round((altitude/ 8.3),1) -- hPa
sinusSunAltitude = math.sin(math.rad(sunAltitude))
if (DEBUG == 1) then
print('<b style="color:Blue"============== SUN LOG ==================</b>')
print(os.date("%Y-%m-%d %H:%M:%S", os.time()))
print(city .. ", latitude:" .. latitude .. ", longitude:" .. longitude)
print("Home altitude = " .. tostring(altitude) .. " m")
print("number Of Day = " .. numOfDay)
if nbDaysInYear==366 then
print(year .." is a leap year !")
else
print(year.." is not a leap year")
end
print("Angular Speed = " .. angularSpeed .. " per day")
print("Declinaison = " .. Declinaison .. "°")
print("Universel Coordinated Time (UTC)".. timeDecimal .." H.dd")
print("Solar Hour ".. solarHour .." H.dd")
print("Altitude of the sun = " .. sunAltitude .. "°")
print("Angular hourly = ".. hourlyAngle .. "°")
print("Azimuth of the sun = " .. azimuth .. "°")
print("Duration of the sunstroke of the day = " .. round(sunstrokeDuration,2) .." H.dd") -- not used
print("Radiation max in atmosphere = " .. round(RadiationAtm,2) .. " W/m²")
print("Local relative pressure = " .. relativePressure .. " hPa")
print("Absolute pressure in atmosphere = " .. absolutePressure .. " hPa")
end
local sun = 614 * sinusSunAltitude * 614 * sinusSunAltitude
M0 = math.sqrt(1229 + sun) - 614 * sinusSunAltitude
M = M0 * relativePressure/absolutePressure
print("Coefficient of mitigation M = " .. M .." M0:"..M0)
-- Get SYNOP message from Ogimet web site
hourUTCminus1 = math.floor(os.date("!%H")-1)
print("hourUTCminus1 = " .. tostring(hourUTCminus1))
if string.len(hourUTCminus1) == 1 then
hourUTCminus1 = "0" .. hourUTCminus1
print("hourUTCminus1 = " .. tostring(hourUTCminus1))
end
UTC = os.date("%Y%m%d").. hourUTCminus1.."00" -- os.date("!%M")
-- if (DEBUG == 1) then
-- local WMOID = jsonLocation.current_observation.display_location.wmo
-- end
cmd='curl "http://www.ogimet.com/cgi-bin/getsynop?block='..WMOID..'&begin='..UTC..'"'
print(cmd)
local ogimet=assert(io.popen(cmd))
local synop = ogimet:read('*all')
ogimet:close()
if( DEBUG == 1) then print('ogimet:'..synop) end
if string.find(synop,"Status: 500") == nil
then
rslt = split(synop,",")
CodeStation = rslt[1]
rslt = split(synop, " "..CodeStation.. " ")
Trame = string.gsub(rslt[2], "=", "")
Trame = CodeStation .." ".. Trame
rslt = split(Trame, " ")
Octa = string.sub(rslt[3], 1, 1) -- 3rd char is the cloud layer. 0=no cloud , 1-8= cloudy from 1 to 8 max , 9 =Fog , / = no data
if Octa == "/" then -- not defined ? take the previous value
Octa = uservariables['octa']
elseif Octa == "9" then
Octa = 8
end
else
Octa = uservariables['octa']
end
--os.execute('curl "http://127.0.0.1:8081/json.htm?type=command&param=updateuservariable&idx='..idxUserVarOcta..'&vname=octa&vtype=0&vvalue='..tostring(Octa)..'"')
commandArray[#commandArray + 1] = {['Variable:octa'] = tostring(Octa)}
Kc=1-0.75*pow(Octa/8,3.4) -- Factor of mitigation for the cloud layer
if sunAltitude > 1 then -- Below 1° of Altitude , the formulae reach their limit of precision.
directRadiation = RadiationAtm * pow(0.6,M) * sinusSunAltitude
scatteredRadiation = RadiationAtm * (0.271 - 0.294 * pow(0.6,M)) * sinusSunAltitude
totalRadiation = scatteredRadiation + directRadiation
Lux = totalRadiation / 0.0079 -- Radiation in Lux. 1 Lux = 0,0079 W/m²
weightedLux = Lux * Kc -- radiation of the Sun with the cloud layer
elseif sunAltitude <= 1 and sunAltitude >= -7 then -- apply theoretical Lux of twilight
directRadiation = 0
scatteredRadiation = 0
arbitraryTwilightLux=arbitraryTwilightLux-(1-sunAltitude)/8*arbitraryTwilightLux
totalRadiation = scatteredRadiation + directRadiation + arbitraryTwilightLux
Lux = totalRadiation / 0.0079 -- Radiation in Lux. 1 Lux = 0,0079 W/m²
weightedLux = Lux * Kc -- radiation of the Sun with the cloud layer
elseif sunAltitude < -7 then -- no management of nautical and astronomical twilight...
directRadiation = 0
scatteredRadiation = 0
totalRadiation = 0
Lux = 0
weightedLux = 0 -- should be around 3,2 Lux for the nautic twilight. Nevertheless.
end
if (DEBUG == 1) then
print("Station SYNOP = " .. WMOID)
print( Octa .. " Octa")
print("Kc = " .. Kc)
print("Direct Radiation = ".. round(directRadiation,2) .." W/m²")
print("Scattered Radiation = ".. round(scatteredRadiation,2) .." W/m²")
print("Total radiation = " .. round(totalRadiation,2) .." W/m²")
print("Total Radiation in lux = ".. round(Lux,2).." Lux")
print("and at last, Total weighted lux = ".. round(weightedLux,2).." Lux")
end
if tonumber(otherdevices_svalues['Lux'])+round(weightedLux,0)>0 -- No update if Lux is already 0. So lastUpdate of the Lux sensor will keep the time when Lux has reached 0. (Kind of timeofday['SunsetInMinutes'])
then
-- commandArray[#commandArray + 1] = {['UpdateDevice'] = idxLux..'|0|'..tostring(round(weightedLux,0))} -- THis form is not recommended. due to limitation of the eventsystem of Domoticz
commandArray[#commandArray + 1]={['OpenURL']="http://"..localhost.."/json.htm?type=command&param=udevice&idx="..idxLux.."&nvalue=0&svalue="..tostring(round(weightedLux,0)) }
end
-- commandArray[#commandArray + 1] = {['UpdateDevice'] = idxSolarAzimuth..'|0|'..tostring(round(azimuth,0))}
commandArray[#commandArray + 1]={['OpenURL']="http://"..localhost.."/json.htm?type=command&param=udevice&idx="..idxSolarAzimuth.."&nvalue=0&svalue="..tostring(round(azimuth,0)) }
-- commandArray[#commandArray + 1] = {['UpdateDevice'] = idxSolarAltitude..'|0|'..tostring(round(sunAltitude,0))}
commandArray[#commandArray + 1]={['OpenURL']="http://"..localhost.."/json.htm?type=command&param=udevice&idx="..idxSolarAltitude.."&nvalue=0&svalue="..tostring(round(sunAltitude,0)) }
if (DEBUG == 2) then
logDebug=os.date("%Y-%m-%d %H:%M:%S",os.time())
logDebug=logDebug.." Azimuth:" .. azimuth .. " Height:" .. sunAltitude
logDebug=logDebug.." Octa:" .. Octa.." KC:".. Kc
logDebug=logDebug.." Direct:"..directRadiation.." inDirect:"..scatteredRadiation.." TotalRadiation:"..totalRadiation.." LuxCloud:".. round(weightedLux,2)
os.execute('echo '..logDebug..' >>logSun.txt') -- compatible Linux & Windows
end
end
return commandArray

View File

@@ -0,0 +1,51 @@
--curl http://domogeek.entropialux.com/vigilance/56/
require "scripts/lua/functions"
--recupere les minutes
time=os.time()
minutes=tonumber(os.date('%M',time))
heures=tonumber(os.date('%H',time))
commandArray = {}
-- Function to update a switch
function updateVigilance(zone, idx)
local cmd = "curl -y 1 http://domogeek.entropialux.com/vigilance/"..zone.."/color"
local vac = os.capture(cmd, true)
local level = 0
if (vac == "rouge") then level = 4 end
if (vac == "orange") then level = 3 end
if (vac == "jaune") then level = 2 end
if (vac == "vert") then level = 1 end
if (level >= 3 or (level == 2 and heures == 18)) then
--local html = os.capture("curl \"http://vigilance.meteofrance.com/Bulletin_sans.html?a=dept44&b=2&c=\"", true)
commandArray['SendNotification']='Alerte Vigilance '..vac..'#Attention alerte vigilance '..vac..' sur le '..zone..' \nhttp://vigilance.meteofrance.com/\n#0'
end
debug("Sunset" .. cmd .. ": "..vac..' Level '..level)
commandArray['UpdateDevice']=idx..'|'..level..'|Niveau de vigilance '..vac..' Departement '..zone
end
time = os.date("*t")
-- local cmd = "curl http://domogeek.entropialux.com/vigilance/56/all"
-- local vac = os.capture(cmd, true)
-- print(vac)
-- Trigger at 0:03 every day
if (time.hour == 0 or time.hour == 6 or time.hour == 12 or time.hour == 18) then
if time.min == 1 then
updateVigilance("56", "185")
end
if time.min == 2 then
updateVigilance("44", "315")
end
if time.min == 3 then
updateVigilance("35", "314")
end
end
return commandArray

View File

@@ -0,0 +1,146 @@
require "scripts/lua/functions"
-- URL du fichier JSON
local url = "http://api.openweathermap.org/data/2.5/weather?q=La%20gacilly,fr&APPID=feba3f4d926db3b358a25ec782bd1c8b&lang=FR&units=metric"
time=os.time()
seconds=tonumber(os.date('%S',time))
minutes=tonumber(os.date('%M',time))
heures=tonumber(os.date('%H',time))
jour=tonumber(os.date('%w',time))
mois=tonumber(os.date('%M',time))
function updateBarometerDevice(deviceId, temperature, humidity, pressure, cloud)
local svalue = string.format("%.1f;%d;%d;%d;%d;", temperature, humidity, humidity, pressure, cloud)
--local svalue = "TEMP;HUM;HUM_STAT;BAR;BAR_FOR"
url = domoticzURL..'/json.htm?type=command&param=udevice&idx='..deviceId..'&svalue='..svalue
print(url)
result = os.execute(curl..'"'..url..'" &')
print(result)
end
commandArray = {}
if minutes == 00 and heures == 08 then
if mois == 2 and jour == 01 then
commandArray['SendNotification']='Changement d\'anglet#Passer l\'angle des pannneaux à 60°!'
end
if mois == 3 and jour == 01 then
commandArray['SendNotification']='Changement d\'anglet#Passer l\'angle des pannneaux à 45!'
end
if mois == 4 and jour == 24 then
commandArray['SendNotification']='Changement d\'anglet#Passer l\'angle des pannneaux à 30°!'
end
if mois == 8 and jour == 19 then
commandArray['SendNotification']='Changement d\'anglet#Passer l\'angle des pannneaux à 45!'
end
if mois == 10 and jour == 13 then
commandArray['SendNotification']='Changement d\'anglet#Passer l\'angle des pannneaux à 60°!'
end
end
if minutes%15 == 0 then
local cmd = 'curl "'..url..'"'
local jsonContent = os.capture(cmd, true)
-- jsonContent = '{"coord":{"lon":-2.1322,"lat":47.7656},"weather":[{"id":803,"main":"Clouds","description":"nuageux","icon":"04d"}],"base":"stations","main":{"temp":22.33,"feels_like":22.21,"temp_min":21.14,"temp_max":23.77,"pressure":1012,"humidity":61,"sea_level":1012,"grnd_level":1010},"visibility":10000,"wind":{"speed":4.87,"deg":265,"gust":5.72},"clouds":{"all":58},"dt":1686396178,"sys":{"type":2,"id":2007485,"country":"FR","sunrise":1686370227,"sunset":1686427534},"timezone":7200,"id":3009239,"name":"La Gacilly","cod":200}'
print(cmd)
-- Appel de la fonction pour récupérer le contenu JSON de l'URL
-- local jsonContent = getJSON(url)
json = (loadfile "/opt/domoticz/scripts/lua/JSON.lua")()
local devices = json:decode(jsonContent)
printTableAsTree(devices)
-- local jsonTable = domoticz.utils.fromJSON(jsonContent)
-- Vérification si la récupération du JSON a réussi
if jsonContent then
print("Contenu JSON récupéré avec succès:")
--print(jsonContent)
else
print("Erreur lors de la récupération du JSON")
end
-- Conversion du contenu JSON en une table Lua
-- local devices = json.decode(jsonContent)
--local devices = domoticz.utils.fromJSON(jsonContent)
--for k, v in pairs(devices) do
--print(k .. ' '.. v)
--end
pluie_1h = 0
local main = searchKeyInTable("main", devices['weather'])
print('main='..main)
forecast = 0
if main == "Clouds" then
nuage = searchKeyInTable("all", devices)
if (tonumber(nuage) > 50) then
forecast = 3
else
forecast = 2
end
print("Nuage " .. nuage)
elseif main == "Rain" then
forecast = 4
pluie_1h = searchKeyInTable("1h", devices)
elseif main == "Clear" then
nuage = searchKeyInTable("all", devices)
forecast = 1
end
print("pluie " .. pluie_1h)
deviceId = 1159
-- /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=RAINRATE;RAINCOUNTER
local svalue = string.format(";%d", pluie_1h)
url = domoticzURL..'/json.htm?type=command&param=udevice&idx='..deviceId..'&svalue='..svalue
print(url)
result = os.execute(curl..'"'..url..'" &')
print(result)
deviceId = 1160
-- /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=RAINRATE;RAINCOUNTER
local svalue = string.format("%d", nuage)
url = domoticzURL..'/json.htm?type=command&param=udevice&idx='..deviceId..'&svalue='..svalue
print(url)
result = os.execute(curl..'"'..url..'" &')
print(result)
local temp_min = searchKeyInTable("temp", devices)
local humidity = searchKeyInTable("humidity", devices)
local grnd_level = searchKeyInTable("pressure", devices)
local cloud = searchKeyInTable("all", devices)
updateBarometerDevice(1157, temp_min, humidity, grnd_level, forecast)
local temp = searchKeyInTable("temp", devices)
local feels_like = searchKeyInTable("feels_like", devices)
local deg = searchKeyInTable("pressure", devices)
local speed = searchKeyInTable("speed", devices) * 10
local gust = searchKeyInTable("gust", devices) * 10
deviceId = 1158
local svalue = string.format("%d;;%.1f;%.1f;%.1f;%.1f", deg, speed, gust, temp, feels_like)
--local svalue = "TEMP;HUM;HUM_STAT;BAR;BAR_FOR"
url = domoticzURL..'/json.htm?type=command&param=udevice&idx='..deviceId..'&svalue='..svalue
print(url)
result = os.execute(curl..'"'..url..'" &')
print(result)
end
return commandArray

245
lua/old/script_time_general.old Executable file
View File

@@ -0,0 +1,245 @@
require "scripts/lua/functions"
--recupere les minutes
time=os.time()
seconds=tonumber(os.date('%S',time))
minutes=tonumber(os.date('%M',time))
heures=tonumber(os.date('%H',time))
jour=tonumber(os.date('%w',time))
mois=tonumber(os.date('%M',time))
--Initialise la commande de retour finale
commandArray={}
-- -----------------------------------------------------------------------
-- Test la dernière réception d'un switch et déclenche une alerte
-- Il faut une variable de la forme PILE_nowswitch pour mettre à jour le
-- témoin de notification envoyée
-- -----------------------------------------------------------------------
function levelBattery( switch )
if (lastUpdateOfDevice(switch) > 3600 ) then
if (uservariables['Variable:PILE_'..switch] == 'Normal') then
commandArray['SendNotification']='Alerte niveau pile#Attention plus de réception de température depuis '..switch..'#0'
commandArray['Variable:PILE_'..switch]='Plus de réception'
end
else
commandArray['Variable:PILE_'..switch]='Normal'
end
end
-- -----------------------------------------------------------------------
-- Test le nombre d'erreur dans le log toutes les heures
-- -----------------------------------------------------------------------
if (minutes == 0) then
local var = os.capture("grep Error /var/log/syslog |wc -l")
--print(var)
if (tonumber(var) > 0 and tonumber(uservariables['Variable:Erreurs']) == 0) then
commandArray['SendNotification']='Alerte Erreur '..var..'#Attention Il y a des erreurs dans domoticz #0'
end
commandArray['Variable:Erreurs']=var
end
-- -----------------------------------------------------------------------
-- Vérifie le nombre de sequences capturées par motion
-- -----------------------------------------------------------------------
if (minutes % 10 == 0) then
local f = io.popen("ls /home/pi/motion/ |grep avi| cut -c 1-2 |uniq| wc -l") -- runs command
local l = f:read("*a") -- read output of command
debug("Nombre de detection "..l)
f:close()
commandArray['PhotoMotion']=tostring(l)
commandArray['UpdateDevice']="136|0|"..l
end
-- -----------------------------------------------------------------------
--recupere les minutes
-- -----------------------------------------------------------------------
if (minutes % 10 == 0) then
debug('####### Lancement du check Presence ' ..heures..'h'..minutes)
if (otherdevices['Vacances'] == 'On') then
switchIfNeeded('Presence','Off')
else
--commandArray['Presence']='Off'
------------------------------------------------------------------------
if (josdJourChome() or otherdevices['PresenceForcee'] == 'On') then
debug(' Jour Chômé / Presence normale à la maison')
switchIfNeeded('Presence','On')
else
local jourS=josdGetJourSemaine()
debug("jour "..jourS)
if otherdevices['AbsenceFamille'] == 'Off' then
if ((jourS == "mercredi" and (heures >= 13 or (heures == 12 and minutes >= 30)))
or heures >= 17 or heures < 8
or (heures == 8 and minutes <= 30)
or otherdevices["Zone B"] == 'On' ) then
debug(' Jour non Chômé pas de vacances '..tostring(heures))
switchIfNeeded('Presence','On')
else
switchIfNeeded('Presence','Off')
end
else
if (((heures == 8 and minutes <= 15) or heures < 8) or heures >= 20 or otherdevices['moi'] == 'On' or otherdevices['Akhenaton'] == 'On') then
switchIfNeeded('Presence','On')
else
switchIfNeeded('Presence','Off')
end
end
end
end
end
-- --------------------------------------------------------------------------------
-- Vérification des dernières mises à jour des températures
-- --------------------------------------------------------------------------------
if (minutes%10== 0) then
levelBattery('Bureau')
levelBattery('ChambreManon')
levelBattery('ChambreTheo')
levelBattery('Chambre')
--levelBattery('ATMEGA_TEMP_1')
levelBattery('TemperatureBarometre')
end
-- --------------------------------------------------------------------------------
-- Function to update a switch
-- --------------------------------------------------------------------------------
function updateSunset(zone)
local cmd = "curl http://domogeek.entropialux.com/sun/" .. zone .. "/sunset/now"
local vac = os.capture(cmd, true)
debug("Sunset" .. cmd .. ": " .. vac)
commandArray['Variable:Couche']=vac
local cmd = "curl http://domogeek.entropialux.com/sun/" .. zone .. "/sunrise/now"
local vac = os.capture(cmd, true)
debug("Sunrise" .. cmd .. ": " .. vac)
commandArray['Variable:Lever']=vac
end
-- --------------------------------------------------------------------------------
-- Trigger at 0:03 every day
-- --------------------------------------------------------------------------------
if (minutes == 3 and (heures == 0 or heures == 8)) then
updateSunset("redon")
end
-- -------------------------------------------------------------------
-- Performance ping
-- -------------------------------------------------------------------
if (minutes % 10 == 0 ) then
local f = io.popen("ping -c 5 192.168.0.1 2>/dev/null |grep rtt |awk -F = '{print $2}'|awk -F / '{print $2}'") -- runs command
local l = f:read("*a") -- read output of command
debug("##### Perf ping : temps de ping "..l)
f:close()
-- Perf Reseau
commandArray['UpdateDevice']="145|0|"..l
end
-- ------------------------------------------------------------------------------
-- Lampes eteinte après 22 heures 30 / 23 heures si pas d'activite depuis 10 minutes
-- ------------------------------------------------------------------------------
-- Pas de traitement en cas d'alerte fumée
if otherdevices['DétecteurFuméeCuisine'] == "Normal"
-- Pas de traitement si lampe allumée il y a moins d'une heure
and (lastUpdateOfDevice('Lampe_Buffet') > 3600 and otherdevices['Lampe_Buffet'] == 'On')
then
if ((heures >= 23 or (heures == 22 and minutes >= 30)) and (minutes%5==0)) then
t1 = os.time()
s = uservariables_lastupdate['DerniereDetection'] --otherdevices_lastupdate['Detecteur Salon']
-- returns a date time like 2013-07-11 17:23:12
year = string.sub(s, 1, 4)
month = string.sub(s, 6, 7)
day = string.sub(s, 9, 10)
hour = string.sub(s, 12, 13)
minu = string.sub(s, 15, 16)
seconds = string.sub(s, 18, 19)
t2 = os.time{year=year, month=month, day=day, hour=hour, min=minu, sec=seconds}
difference = (os.difftime (t1, t2))
debug("Eteindre les lumieres, DerniereDetection="..tostring(difference))
if (difference > 300 or heures >= 23) then
switchIfNeeded('Salon_Halogene', 'Off')
switchIfNeeded('Lampe_Buffet', 'Off')
switchIfNeeded('LumiereTele', 'Off')
switchIfNeeded('SonoJasper', 'Off')
end
end
end
-- Variation de pression
if minutes%10 == 0 then
local pressure = otherdevices_svalues['Pression']
local variationPressure = variationPressure('Barometre',60)
print("variationPressure="..tostring(variationPressure)..' Pression='..tostring(pressure))
end
-- ---------------------------------
-- Réglage des consigne temperature
-- ---------------------------------
if minutes%10 == 0 then
debug('####### Lancement du calcul consigne ' ..heures..'h'..minutes)
--commandArray['UpdateDevice'] = '214|0|25.00'
if (otherdevices['Vacances'] == 'On') then
commandArray['UpdateDevice'] = "213|0|16.5" -- Chambre
commandArray['UpdateDevice'] = "211|0|16.5" -- ChambreTheo
commandArray['UpdateDevice'] = "212|0|16.5" -- ChambreManon
commandArray['UpdateDevice'] = "214|0|16.5" -- Bureau
else
--commandArray['Presence']='Off'
------------------------------------------------------------------------
if (josdJourChome() or otherdevices['PresenceForcee'] == 'On') then
debug(' Jour Chômé / consigne temperature présence')
commandArray['UpdateDevice'] = "213|0|18" -- Chambre
commandArray['UpdateDevice'] = "211|0|18.5" -- ChambreTheo
commandArray['UpdateDevice'] = "212|0|18.5" -- ChambreManon
commandArray['UpdateDevice'] = "214|0|18" -- Bureau
else
local jourS=josdGetJourSemaine()
debug("jour "..jourS)
if otherdevices['AbsenceFamille'] == 'Off' then
if ((jourS == "mercredi" and (heures >= 13 or (heures == 12 and minutes >= 30)))
or heures >= 17 or heures < 8
or (heures == 8 and minutes <= 30)
or otherdevices["Zone B"] == 'On' ) then
debug(' Jour non Chômé pas de vacances '..tostring(heures))
commandArray['UpdateDevice'] = "213|0|18" -- Chambre
commandArray['UpdateDevice'] = "211|0|18.5" -- ChambreTheo
commandArray['UpdateDevice'] = "212|0|18.5" -- ChambreManon
commandArray['UpdateDevice'] = "214|0|18" -- Bureau
else
commandArray['UpdateDevice'] = "213|0|16.5" -- Chambre
commandArray['UpdateDevice'] = "211|0|16.5" -- ChambreTheo
commandArray['UpdateDevice'] = "212|0|16.5" -- ChambreManon
commandArray['UpdateDevice'] = "214|0|16.5" -- Bureau
end
else
if (((heures == 8 and minutes <= 15) or heures < 8) or heures >= 20 or otherdevices['moi'] == 'On'
or otherdevices['Akhenaton'] == 'On') then
commandArray['UpdateDevice'] = "213|0|18" -- Chambre
commandArray['UpdateDevice'] = "211|0|18.5" -- ChambreTheo
commandArray['UpdateDevice'] = "212|0|18.5" -- ChambreManon
commandArray['UpdateDevice'] = "214|0|18" -- Bureau
else
commandArray['UpdateDevice'] = "213|0|16.5" -- Chambre
commandArray['UpdateDevice'] = "211|0|16.5" -- ChambreTheo
commandArray['UpdateDevice'] = "212|0|16.5" -- ChambreManon
commandArray['UpdateDevice'] = "214|0|16.5" -- Bureau
end
end
end
end
end
-- return commandArray

5
lua/old/script_time_list.old Executable file
View File

@@ -0,0 +1,5 @@
print('Liste des capteurs : ')
commandArray = {}
for i, v in pairs(otherdevices) do print(i, v) end
return commandArray

95
lua/old/script_time_livebox.old Executable file
View File

@@ -0,0 +1,95 @@
---------------------------------
-- Script de détection de présence via livebox
-- Auteur : Sopalin
-- Date : 22 Juillet 2016
-- Nécessite un switch classique
-- source :
---------------------------------
require "scripts/lua/functions"
--recupere les minutes
time=os.time()
seconds=tonumber(os.date('%S',time))
minutes=tonumber(os.date('%M',time))
commandArray={}
function testActive(name, active)
if active then
--commandArray[name]='On'
switchIfNeeded(name, 'On')
else
switchIfNeeded(name, 'Off')
--commandArray[name]='Off'
end
debug("### Test active Name : "..name.." active "..tostring(active))
end
--time = os.date("*t")
if (minutes % 10 == 7) then
--import des fontions pour lire le JSON
json = (loadfile "/opt/domoticz/scripts/lua/JSON.lua")()
--Récupération des informations sur la livebox
--Utilisation d'un script VBS sous windows
--Utilisation d'un script bash pour extraire les données
----------------------------------------------------------------
--Lecture des données
local f = assert(io.open("/tmp/getHosts.txt","r"))
local livebox = f:read('*all')
f:close()
--Décodage ud fichier
local jsonLivebox = json:decode(livebox)
--debug("DEBUG")
--debug(timedifference(otherdevices_lastupdate['Presence Thomas']))
--commandArray['Theo']='Off'
--commandArray['Moi']='Off'
--commandArray['Manon']='Off'
devices = jsonLivebox['result']['status']
--Parcours du fichier pour vérifier la présence d'un téléphone
for result,status in pairs(devices) do
local name = status['hostName']
debug("Name : "..name.." IP : "..status['ipAddress'].." "..tostring(status['active']))
if (name == "Windows-Phone" or name == "Akhesa" or name == "Playstation3") then
--commandArray['Theo']='On'
testActive('Theo', status['active'])
end
if (name == "iPhone-de-Jerome") then
--commandArray['moi']='On'
testActive("Moi", status['active'])
end
if (name == "Akhenaton-1" or name == "Akhenaton") then
testActive("Akhenaton", status['active'])
end
if (name == "Manon" or name == "AcerManon") then
--commandArray['Manon']='On'
testActive("Manon", status['active'])
end
if (name == "TeleChambre" or name == "AcerManon"
or name == "Volumio" or name == "LibreELEC" or name == "Akhesa"
or name == "SoutiHP" or name == "Hackintosh"
or name == "Akhenaton"
or name == "Domi" or name == "DomiPro" or name == "Octoprint"
or name == "Recovery" or name == "orangepizero" or name == "orangepizero-1") then
testActive(name, status['active'])
end
if (name == "RadiateurManon" or name == "RadiateurTheo" or name == "RadiateurBureau"
or name == "RadiateurChambre") then
if status['active'] then
-- nothing
else
-- commandArray['SendNotification']='Alerte radiateur '..name..'#Alerte radiateur ne repond pas au ping '..name
end
end
end
end
return commandArray

View File

@@ -0,0 +1,36 @@
require "scripts/lua/functions"
commandArray = {}
--recupere les minutes
time=os.time()
minutes=tonumber(os.date('%M',time))
if (minutes % 10 == 0 ) then
local f = io.popen("ping -c 5 192.168.0.1 2>/dev/null |grep rtt |awk -F = '{print $2}'|awk -F / '{print $2}'") -- runs command
local l = f:read("*a") -- read output of command
debug("##### Perf ping : temps de ping "..l)
f:close()
-- Perf Reseau
commandArray['UpdateDevice']="145|0|"..l
end
if (minutes % 30 == 0 ) then
local f = io.popen("ping -c 4 -n www.free.fr|grep packet|awk -F ' ' '{print $1}'") -- runs command
local l = f:read("*a") -- read output of command
debug("##### Nombre de ping: "..l)
f:close()
if (l == "4") then
debug("##### Internet fonctionne correctement")
switchIfNeeded('Internet','On')
else
debug("##### Internet ne répond pas")
switchIfNeeded('Internet','Off')
end
end
return commandArray

30
lua/old/script_time_soleil.lua Executable file
View File

@@ -0,0 +1,30 @@
---------------------------------
-- Script de collecte de quelques indicateurs solaire
-- Auteur : Sébastien Joly
-- Adapté pour Domoticz par Neutrino
-- Date : 29 août 2015
-- Eléments de calculs :
-- http://www.plevenon-meteo.info/technique/theorie/enso/ensoleillement.html
-- http://herve.silve.pagesperso-orange.fr/solaire.htm
-- http://www.domotique-info.fr/2015/09/ou-est-le-soleil-pour-votre-homecenter-2/
---------------------------------
require "scripts/lua/functions"
commandArray = {}
time = os.date("*t")
local idxLux="320"
if ((time.min % 5)==0) then
if (timeofday['Nighttime']) then
--il fait nuit
LuxPondere = 0
--mise a jour du dispositif
commandArray[1] = {['UpdateDevice'] = idxLux..'|0|' .. tostring(LuxPondere)}
else
os.execute("lua /opt/domoticz/scripts/lua/soleil.lua "..uservariables['octa'].." &")
end
end
return commandArray

89
lua/old/script_time_tele.old Executable file
View File

@@ -0,0 +1,89 @@
require "scripts/lua/functions"
--Initialise la commande de retour finale
commandArray={}
--Prefixe pour les sorties de log
prefixe="(PING) "
--recupere les minutes
time=os.time()
minutes=tonumber(os.date('%M',time))
heures=tonumber(os.date('%H',time))
if (heures >= 22 and (minutes % 10 == 0)) then
-- ------------------------------
--Tableau des périphérique"pinguer"
-- Key = adresse ip pinguer
-- Value = périphérique virtueswitcher
-- ------------------------------
local ping={}
ping['192.168.0.17']='TeleChambre'
ping['akhenaton']='Akhenaton'
AuMoinsUnPing=false
-- ------------------------------
--pour chaque entree du tableau
-- ------------------------------
for ip, switch in pairs(ping) do
--Le Ping ! : -c1 = Un seul ping , -w1 délai d'une seconde d'attente de réponse
ping_success=os.execute('ping -c1 -w1 '..ip)
-- ------------------------------
--Si le ping a répondu
-- ------------------------------
if ping_success then
AuMoinsUnPing=true
debug(prefixe.."ping success "..switch)
-- ------------------------------
--si le switch etait sur off on l'allume
-- ------------------------------
switchIfNeeded(switch, 'On')
--if(otherdevices[switch]=='Off') then
-- commandArray[switch]='On'
--end
else
-- ------------------------------
--Si pas de réponse
-- ------------------------------
debug(prefixe.."ping sans reponse "..switch)
-- ------------------------------
--si le switch etait sur oN on l'eteint
-- ------------------------------
switchIfNeeded(switch, 'Off')
--if(otherdevices[switch]=='On') then
-- commandArray[switch]='Off'
--end
end
end
if AuMoinsUnPing then
else
-- ------------------------------
-- Extinction halogene
-- ------------------------------
debug("Tout le monde est couché")
-- if(otherdevices["Salon_Halogene"]=='On')
switchIfNeeded("Salon_Halogene",'Off')
switchIfNeeded("LumiereTele",'Off')
switchIfNeeded("Lampe_Buffet",'Off')
-- end
if(otherdevices["Volet droit"]=='On') then
debug("Attention le volet droit est ouvert")
end
if(otherdevices["Volet gauche"]=='On') then
debug("Attention le volet gauche est ouvert")
end
end
end
return commandArray

601
lua/old/script_time_vmc.old Executable file
View File

@@ -0,0 +1,601 @@
-- http://easydomoticz.com/forum/viewtopic.php?f=17&t=2869&hilit=vmc
require "scripts/lua/fonctions2"
commandArray = {}
--recupere les minutes
time=os.time()
minutes=tonumber(os.date('%M',time))
--jour=tonumber(os.date('%w',time))
heures=tonumber(os.date('%H',time))
if minutes%10 == 6 then
INTERVAL_MESURE = 2 -- Nombre d'intervals de mesure entre deux cycles d'analyse de l'humidité (en nombre de cycles = nombre de minutes)
SEUIL_DECLENCHEMENT_VMC = 2 -- Augmentation en % au-delà de laquelle on déclenche la GV de la VMC
NbCycles_Max_GV_VMC = 5 -- Nombre de cycles maximum durant lequel la GV de la VMC peut rester ON
-- à partir du moment où il n'y a plus d'augmentation de l'humidité entre deux mesures
Anticipation_Arret= 1 -- l'arrêt de la grande vitesse se fera à l'humidité avant déclenchement de la GV plus cette valeur
-- ce qui permet d'anticiper l'arrêt de la grande vitesse avant d'atteindre la valeur initiale
NOM_INTERRUPTEUR_PILOTAGE_VMC = 'VMC'
NOM_INTERRUPTEUR_OnOff_VMC = 'VMC-OnOff'
NOM_INTERRUPTEUR_GV_VMC = 'VMC-GV'
NOM_CAPTEUR_HUMIDITE1 = 'TemperatureSDB'
NOM_CAPTEUR_HUMIDITE2 = 'TemperatureCuisine'
NOM_INTERRUPTEUR_DEBUG = 'Debug'
NOM_INTERRUPTEUR_TEST = 'Test-GV-SDB'
--NOM_CAPTEUR_VIRTUEL_HYGRO_MOYENNE= 'Hygro_Maison_Moyenne'
VALEUR_TEST_HUMIDITE1 = 'VMC_TST_HUM_SDB1' -- valeur de test pour l'umidité positionné dans les variables domoticz
VALEUR_TEST_HUMIDITE2 = 'VMC_TST_HUM_SDB2' -- valeur de test pour l'umidité positionné dans les variables domoticz
-- ---------------------------------------------------------------------
-- Récupération de paramètres de Domoticz passés par les interrupteurs
-- ---------------------------------------------------------------------
if(otherdevices[NOM_INTERRUPTEUR_DEBUG]=='On') then -- Si le mode debug est activé dans Domoticz (inter debug sur on)
MODE_DEBUGG= true
else
MODE_DEBUGG= false
end
if(otherdevices[NOM_INTERRUPTEUR_TEST]=='On') then -- Si le mode test est activé dans Domoticz (inter Test sur on)
MODE_TEST=true
else
MODE_TEST=false
end
-- MODE_TEST=true
if MODE_DEBUGG== true then
print(' ')
print('>>>>>>>>>>>>>> Script de controle de la VMC v1.0 <<<<<<<<<<<<<<<<<<<<<')
end
-- ----------------------------------------------------------------------------------
-- --Récupération de toutes les variables Domoticz servant au script et remise à 0 --
-- ----------------------------------------------------------------------------------
VMC_VAR_Compteur_Cycles = tonumber(uservariables['VMC_VAR_Compteur_Cycles']) -- compteur de cycles
VMC_VAR_Histo_Hum1_SDB1 = tonumber(uservariables['VMC_VAR_Histo_Hum1_SDB1']) -- mesure la plus récente SDB1
VMC_VAR_Histo_Hum1_SDB2 = tonumber(uservariables['VMC_VAR_Histo_Hum1_SDB2']) -- mesure la plus récente SDB2
VMC_VAR_Histo_Hum2_SDB1 = tonumber(uservariables['VMC_VAR_Histo_Hum2_SDB1']) -- mesure la plus ancienne SDB1
VMC_VAR_Histo_Hum2_SDB2 = tonumber(uservariables['VMC_VAR_Histo_Hum2_SDB2']) -- mesure la plus ancienne SDB2
VMC_VAR_Cible_Hum_GV_Off_SDB1 = tonumber(uservariables['VMC_VAR_Cible_Hum_GV_Off_SDB1']) -- Cible à atteindre pour arrêter la deshumidification SDB1 lorsqu'elle est active
VMC_VAR_Cible_Hum_GV_Off_SDB2 = tonumber(uservariables['VMC_VAR_Cible_Hum_GV_Off_SDB2']) -- Cible à atteindre pour arrêter la deshumidification SDB2 lorsqu'elle est active
VMC_VAR_TimerSecuriteArret_SDB1 = tonumber(uservariables['VMC_VAR_TimerSecuriteArret_SDB1']) -- Nb de cycles restants avant l'arrête automatique de sécurité de la SDB1
VMC_VAR_TimerSecuriteArret_SDB2 = tonumber(uservariables['VMC_VAR_TimerSecuriteArret_SDB2']) -- Nb de cycles restants avant l'arrête automatique de sécurité de la SDB2
VMC_VAR_Deshumidification_On_SDB1 = tonumber(uservariables['VMC_VAR_Deshumidification_On_SDB1']) -- Vaut 1 si la deshumidification est en cours dans la SDB1, 0 sinon
VMC_VAR_Deshumidification_On_SDB2 = tonumber(uservariables['VMC_VAR_Deshumidification_On_SDB2']) -- Vaut 1 si la deshumidification est en cours dans la SDB2, 0 sinon
Cible_Humidite_SDB1 = 0 -- Variable servant à calculer la cible d'humidité lorsuqe la déshumidification s'active pour la SDB1
Cible_Humidite_SDB2 = 0 -- Variable servant à calculer la cible d'humidité lorsuqe la déshumidification s'active pour la SDB2
Humidite_Actuelle_EXT = tonumber(otherdevices_humidity["BarometreLaGacilly"])
Temperature_Actuelle_EXt = tonumber(otherdevices_temperature["BarometreLaGacilly"])
-- ********************************************************************
-- SI L'UTILISATEUR A ACTIVé LA VMC DE MANIERE MANUELLE ON N'EXECUTE --
-- PAS LE SCRIPT ET ON POSITIONNE LA VMC A LA BONNNE VALEUR
-- ********************************************************************
Etat_Pilotage_VMC = tonumber(otherdevices_svalues[NOM_INTERRUPTEUR_PILOTAGE_VMC]) -- récupération de l'état de l'inter 4 positions de pilotage de la VMC
print('Etat_Pilotage_VMC='..tostring(Etat_Pilotage_VMC))
if Etat_Pilotage_VMC < 30 then -- Si inter sur mode différent d'automatique (qui vaut 30)
if Etat_Pilotage_VMC == 0 then -- Si inter sur VMC Off
print('VMC arretee manuellement via l interrupteur. Sortie du script')
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'Off'
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'Off'
end
if Etat_Pilotage_VMC == 10 then -- Si inter sur VMC petite vitesse
print('VMC positionnee en marche / petite vitesse via l interrupteur. Sortie du script')
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On'
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'Off'
end
if Etat_Pilotage_VMC == 20 then -- si inter sur VMC grande vitesse
print('VMC positionnee en marche / grande vitesse via l interrupteur. Sortie du script')
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On'
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'On'
end
print('NOM_CAPTEUR_HUMIDITE1 '..tostring(tonumber(otherdevices_humidity[NOM_CAPTEUR_HUMIDITE1])))
-- On n'est plus en mode automatique donc on sort du script après l'avoir remis à 0 (réinitialisation de toutes les variables)
commandArray['Variable:VMC_VAR_Compteur_Cycles'] = '0'
commandArray['Variable:VMC_VAR_Histo_Hum2_SDB1'] = tostring(math.floor(tonumber(otherdevices_humidity[NOM_CAPTEUR_HUMIDITE1])))
commandArray['Variable:VMC_VAR_Histo_Hum1_SDB1'] = tostring(math.floor(tonumber(otherdevices_humidity[NOM_CAPTEUR_HUMIDITE1])))
commandArray['Variable:VMC_VAR_Cible_Hum_GV_Off_SDB1'] = '0'
commandArray['Variable:VMC_VAR_TimerSecuriteArret_SDB1'] = '0'
commandArray['Variable:VMC_VAR_Deshumidification_On_SDB1'] = '0'
commandArray['Variable:VMC_VAR_Histo_Hum2_SDB2'] = tostring(math.floor(tonumber(otherdevices_humidity[NOM_CAPTEUR_HUMIDITE2])))
commandArray['Variable:VMC_VAR_Histo_Hum1_SDB2'] = tostring(math.floor(tonumber(otherdevices_humidity[NOM_CAPTEUR_HUMIDITE2])))
commandArray['Variable:VMC_VAR_Cible_Hum_GV_Off_SDB2'] = '0'
commandArray['Variable:VMC_VAR_TimerSecuriteArret_SDB2'] = '0'
commandArray['Variable:VMC_VAR_Deshumidification_On_SDB2'] = '0'
return commandArray
end
print('mode automatique')
-- **************************************
-- Recuperation des valeurs d'humidite
-- **************************************
if (MODE_TEST) then
-- Si on est en mode test, on prends les valeurs fixées dans les variables DOMOTICZ
Humidite_Actuelle_SDB1 = tonumber(uservariables['VMC_TST_HUM_SDB1'])
Humidite_Actuelle_SDB2 = tonumber(uservariables['VMC_TST_HUM_SDB2'])
Hygro_Moyenne_Maison = tonumber(uservariables['VMC_TST_HUM_MOYENNE_MAISON'])
else
-- Si on est en mode normal, on prends les valeurs remontées par les capteurs
Humidite_Actuelle_SDB1 = otherdevices_humidity[NOM_CAPTEUR_HUMIDITE1]
Humidite_Actuelle_SDB2 = otherdevices_humidity[NOM_CAPTEUR_HUMIDITE2]
Humidite_Actuelle_CELLIER = otherdevices_humidity["TemperatureCellier"]
Hygro_Moyenne_Maison = math.max(Humidite_Actuelle_SDB1, Humidite_Actuelle_CELLIER) -- otherdevices_humidity[NOM_CAPTEUR_VIRTUEL_HYGRO_MOYENNE]
end
print('Hygro_Moyenne_Maison='..tostring(Hygro_Moyenne_Maison))
-- L'humidité maximum acceptable dans la salle de bain est le maximum de la valeur moyenne humidité
-- en cours dans la maison et de la valeur fixées
-- Cette humidité max permet de maintenir la VMC en petite vitesse même si l'humidité de la salle de
-- bain est redescendue après un pic
Maximum_Humidite_Acceptable_SDB = math.max(tonumber(uservariables['Hygro_Max_SDB']), Hygro_Moyenne_Maison)
-- ******************************************************************************
-- Sortie du script si les valeurs d'humidité récupérées ne sont pas exploitables
-- *******************************************************************************
if (Humidite_Actuelle_SDB1 == 0 or Humidite_Actuelle_SDB1 == nil) then
print('Pas de signal du capteur ' .. NOM_CAPTEUR_HUMIDITE1 .. '. Sortie du script')
return commandArray
end
if (Humidite_Actuelle_SDB2 == 0 or Humidite_Actuelle_SDB2 == nil) then
print('Pas de signal du capteur ' .. NOM_CAPTEUR_HUMIDITE2 .. '. Sortie du script')
return commandArray
end
if (Hygro_Moyenne_Maison== 0 or Hygro_Moyenne_Maison== nil) then
print('Pas de signal du capteur virtuel d humidite moyenne de la maison, Sortie du script')
return commandArray
end
print('Les capteurs sont ok ')
-- ************************************************************************************
-- Le script est executé toutes les minutes, on augmente la valeur du compteur de cycle
-- ************************************************************************************
VMC_VAR_Compteur_Cycles = VMC_VAR_Compteur_Cycles + 1
-- ***************************************************************************************************
-- On commence par traiter l'humidité globale de la maison pour savoir si la VMC doit être activée ou non
-- ***************************************************************************************************
local humidite_ext = humiditeAbsolue(Temperature_Actuelle_EXt, Humidite_Actuelle_EXT)
local humidite_sdb = humiditeAbsolue(tonumber(otherdevices_temperature["TemperatureSDB"]),
tonumber(otherdevices_humidity["TemperatureSDB"]))
if humidite_ext > humidite_sdb then
print("L'humidité extérieure est trop élevée. Arret VMC")
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'Off'
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'Off'
return commandArray
else
if Hygro_Moyenne_Maison > uservariables['Hygro_Max_Maison'] then
Hygro_Max_Depassee = 1 -- L'humidité de la maison est trop importante on active la VMC
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On'
else -- L'humidité de la maison est correcte
Hygro_Max_Depassee = 0
if VMC_VAR_Deshumidification_On_SDB1 == 0 and VMC_VAR_Deshumidification_On_SDB2 == 0 then
if Humidite_Actuelle_SDB1 <= Maximum_Humidite_Acceptable_SDB and
Humidite_Actuelle_SDB2 <= Maximum_Humidite_Acceptable_SDB
then
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'Off' -- on arrête la VMC si aucune des salles de bains n'est utilisée et que l'humidité des salles de bain est acceptable
else
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On' -- on allume la VMC si aucune des salles de bains n'est utilisée mais que l'humidité des salles de bain n'est pas acceptable
end
end
end
end
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('***************')
print('ETAT ACTUEL : ')
print('***************')
if Hygro_Moyenne_Maison <= uservariables['Hygro_Max_Maison']
and VMC_VAR_Deshumidification_On_SDB1 ==0
and VMC_VAR_Deshumidification_On_SDB2 == 0
then
if Humidite_Actuelle_SDB1 <= Maximum_Humidite_Acceptable_SDB and Humidite_Actuelle_SDB2 <= Maximum_Humidite_Acceptable_SDB then
print('[Hygro Maison] - Hygrometrie correcte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max) et aucune salle de bain en cours d utilisation, desactivation de la vmc')
else
print('[Hygro Maison] - Hygrometrie correcte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max), aucune salle de bain en cours d utilisation mais humidite SDB toujours trop elevee, VMC laissee active en petite vitesse')
end
else
if VMC_VAR_Deshumidification_On_SDB1 ==0 and VMC_VAR_Deshumidification_On_SDB2 == 0 then
print('[Hygro Maison] - Hygrometrie incorrect (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max), maintien de la VMC meme si aucune salle de bain en cours d utilisation')
end
end
if VMC_VAR_Deshumidification_On_SDB1 == 0 then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Deshumidification OFF - actuelle : ' .. Humidite_Actuelle_SDB1 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB1 .. '% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB1 .. '%')
else
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Deshumidification ON - actuelle : ' .. Humidite_Actuelle_SDB1 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB1 ..'% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB1 .. '% / Cible arret : ' .. VMC_VAR_Cible_Hum_GV_Off_SDB1 .. '% / arret de securite dans ' .. VMC_VAR_TimerSecuriteArret_SDB1 .. ' cycle(s)')
end
if VMC_VAR_Deshumidification_On_SDB2 == 0 then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Deshumidification OFF - actuelle : ' .. Humidite_Actuelle_SDB2 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB2 .. '% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB2 .. '%')
else
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Deshumidification ON - actuelle : ' .. Humidite_Actuelle_SDB2 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB2 ..'% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB2 .. '% / Cible arret : ' .. VMC_VAR_Cible_Hum_GV_Off_SDB2 .. '% / arret de securite dans ' .. VMC_VAR_TimerSecuriteArret_SDB2 .. ' cycle(s)')
end
end
if (VMC_VAR_Compteur_Cycles >= INTERVAL_MESURE) then
-- *************************************************************************************
-- Si le nombre de cycles a atteint l'interval de mesure fixé on commence l'analyse pour
-- identifier les besoins d'activation ou désactivation de la grande vitesse de la VMC
-- *************************************************************************************
VMC_VAR_Compteur_Cycles = 0 -- remise à 0 du compteur de cycle
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print(' ')
print('***************')
print('ANALYSE : ')
print('***************')
print('Nombre de cycles atteint (' .. VMC_VAR_Compteur_Cycles .. '/' .. INTERVAL_MESURE .. '), realisation des tests pour adapter la vitesse VMC')
end
-- ***************************************************************************
-- Initialisation des historiques s'ils ne contiennent aucune information. On
-- positionne alors dans les deux historiques les valeurs d'hulidité actuelles
-- ***************************************************************************
if (VMC_VAR_Histo_Hum1_SDB1 == 0) then
-- Initialisation des valeurs historiques
VMC_VAR_Histo_Hum1_SDB1 = Humidite_Actuelle_SDB1
VMC_VAR_Histo_Hum2_SDB1 = Humidite_Actuelle_SDB1
end
if (VMC_VAR_Histo_Hum1_SDB2 == 0) then
-- Initialisation des valeurs historiques
VMC_VAR_Histo_Hum1_SDB2 = Humidite_Actuelle_SDB2
VMC_VAR_Histo_Hum2_SDB2 = Humidite_Actuelle_SDB2
end
-- ********************************************************************
-- Calcul des écarts maximum d'humidité constatés dans chacune des SDB
-- ********************************************************************
Ecart_Max_Humidite_SDB1 = Humidite_Actuelle_SDB1 - math.min(VMC_VAR_Histo_Hum2_SDB1, VMC_VAR_Histo_Hum1_SDB1)
Ecart_Max_Humidite_SDB2 = Humidite_Actuelle_SDB2 - math.min(VMC_VAR_Histo_Hum2_SDB2, VMC_VAR_Histo_Hum1_SDB2)
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Ecart max d humidite constate sur les dernieres periodes : ' .. Ecart_Max_Humidite_SDB1)
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Ecart max d humidite constate sur les dernieres periodes : ' .. Ecart_Max_Humidite_SDB2)
end
-- ********************************************************************************************************
-- Identification de la cible humidité à atteindre si la grande vitesse de la VMC est activée. Il s'agira
-- de redescendre à la plus basse des valeurs d'humidité de l'historique + un % défini dans "Anticipation_Arret"
-- ********************************************************************************************************
Cible_Humidite_SDB1 = math.min(VMC_VAR_Histo_Hum2_SDB1, VMC_VAR_Histo_Hum1_SDB1) + Anticipation_Arret
Cible_Humidite_SDB2 = math.min(VMC_VAR_Histo_Hum2_SDB2, VMC_VAR_Histo_Hum1_SDB2) + Anticipation_Arret
-- *****************************************************************************
-- Sauvegarde dans l'historique des mesures précédentes et de la mesure actuelle
-- *****************************************************************************
VMC_VAR_Histo_Hum2_SDB1 = VMC_VAR_Histo_Hum1_SDB1 -- L'historique le plus ancien reçoit l'historique plus récent de l'humidité
VMC_VAR_Histo_Hum2_SDB2 = VMC_VAR_Histo_Hum1_SDB2
VMC_VAR_Histo_Hum1_SDB1 = Humidite_Actuelle_SDB1 -- L'historique plus récent reçoit la valeur actuelle d'humidité
VMC_VAR_Histo_Hum1_SDB2 = Humidite_Actuelle_SDB2
-- ********************************************************************************************************
-- Remise à 0 des indicateurs précisant s'il y a eu un déclenchement de la GV pour une des SDB lors
-- de l'execution du script en cours. Pour l'instant aucune mise en route n'a été décidée/effectuée
-- ********************************************************************************************************
Declenchement_SDB1 = 0
Declenchement_SDB2 = 0
-- *****************************************************************************
-- Si le ventilateur est off alors qu'un des deux programmes est en route, on
-- force l'arrêt des programmes de déshumidification (arrêt manuel extérieur)
-- *****************************************************************************
if (otherdevices[NOM_INTERRUPTEUR_GV_VMC]=='Off')
and (VMC_VAR_Deshumidification_On_SDB1 == 1 or VMC_VAR_Deshumidification_On_SDB2 ==1)
then
VMC_VAR_Deshumidification_On_SDB1 = 0
VMC_VAR_Deshumidification_On_SDB2 = 0
end
-- *****************************************************************************************
-- Si la VMC n'est pas en grande vitesse ou si une des deux SDB n'est pas en grande vitesse
-- on identifie s'il est nécessaire de mettre en route la marche forcée pour une des SDBs
-- *****************************************************************************************
if otherdevices[NOM_INTERRUPTEUR_GV_VMC]=='Off'
or VMC_VAR_Deshumidification_On_SDB1 == 0
or VMC_VAR_Deshumidification_On_SDB2 == 0
then
-- **************************************************************************
-- Identification du besoin éventuel de déclenchement de la VMC pour la SDB1
-- Besoin identifié si humidité > au seuil de déclenchement et que le programme
-- de déshumidification n'est pas déjà activé pour cette SDB
-- **************************************************************************
if Ecart_Max_Humidite_SDB1 >= SEUIL_DECLENCHEMENT_VMC and VMC_VAR_Deshumidification_On_SDB1 == 0 then
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'On'
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On'
VMC_VAR_Deshumidification_On_SDB1 = 1
VMC_VAR_Cible_Hum_GV_Off_SDB1 = Cible_Humidite_SDB1
VMC_VAR_TimerSecuriteArret_SDB1 = NbCycles_Max_GV_VMC
Declenchement_SDB1 = 1
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Augmentation soudaine de l humidite. Activation de la VMC en grande vitesse. Ecart d humidite observe: ' .. Ecart_Max_Humidite_SDB1)
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Cible a atteindre pour l extinction du ventilateur : ' ..VMC_VAR_Cible_Hum_GV_Off_SDB1)
end
else
if MODE_DEBUGG== true and Ecart_Max_Humidite_SDB2 >= SEUIL_DECLENCHEMENT_VMC and VMC_VAR_Deshumidification_On_SDB1 == 0 then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Ecart non significatif, pas de mise en route du programme de deshumidification')
end
end
-- **************************************************************************
-- Identification du besoin éventuel de déclenchement de la VMC pour la SDB2
-- Besoin identifié si humidité > au seuil de déclenchement et que le programme
-- de déshumidification n'est pas déjà activé pour cette SDB
-- **************************************************************************
if Ecart_Max_Humidite_SDB2 >= SEUIL_DECLENCHEMENT_VMC and VMC_VAR_Deshumidification_On_SDB2 == 0 then
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'On'
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On'
VMC_VAR_Deshumidification_On_SDB2 = 1
VMC_VAR_Cible_Hum_GV_Off_SDB2 = Cible_Humidite_SDB2
VMC_VAR_TimerSecuriteArret_SDB2 = NbCycles_Max_GV_VMC
Declenchement_SDB2 = 1
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Augmentation soudaine de l humidite. Activation de la VMC en grande vitesse. Ecart d humidite observe: ' .. Ecart_Max_Humidite_SDB2)
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Cible a atteindre pour l extinction du ventilateur : ' ..VMC_VAR_Cible_Hum_GV_Off_SDB2)
end
else
if MODE_DEBUGG== true and Ecart_Max_Humidite_SDB1 >= SEUIL_DECLENCHEMENT_VMC and VMC_VAR_Deshumidification_On_SDB2 == 0 then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Ecart non significatif, pas de mise en route du programme de deshumidification')
end
end
end
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if Ecart_Max_Humidite_SDB1 < SEUIL_DECLENCHEMENT_VMC
and Ecart_Max_Humidite_SDB2 < SEUIL_DECLENCHEMENT_VMC
then
if MODE_DEBUGG== true then
print('Ecarts non significatif sur les deux SDB, pas de mise en route du programme de deshumidification')
end
end
-- *****************************************************************************************
-- Si la VMC est en grande vitesse après l'analyse du besoin effectuée ci-dessus
-- *****************************************************************************************
if (otherdevices[NOM_INTERRUPTEUR_GV_VMC]=='On') or VMC_VAR_Deshumidification_On_SDB1 == 1 or VMC_VAR_Deshumidification_On_SDB2 == 1 then
if (VMC_VAR_TimerSecuriteArret_SDB1 > 0) then -- Si le déshumidification est en courspour la SDB1 on diminue
VMC_VAR_TimerSecuriteArret_SDB1 = VMC_VAR_TimerSecuriteArret_SDB1 - 1 -- la valeur du timer de sécurité pour l'arrêt automatique
end
if (VMC_VAR_TimerSecuriteArret_SDB2 > 0) then -- Si le déshumidification est en courspour la SDB2 on diminue
VMC_VAR_TimerSecuriteArret_SDB2 = VMC_VAR_TimerSecuriteArret_SDB2 - 1 -- la valeur du timer de sécurité pour l'arrêt automatique
end
end
-- *****************************************************************************************
-- Si la VMC est en grande vitesse pour la SDB1 et que l'humidité continue d'augmenter
-- *****************************************************************************************
if (VMC_VAR_Deshumidification_On_SDB1 == 1) then
if (Ecart_Max_Humidite_SDB1 >= SEUIL_DECLENCHEMENT_VMC and Declenchement_SDB1 == 0) then
-- S'il y a encore un écart d'humidité constaté sur la dernière période (augmentation humidité toujours en cours) et qu'il n'y a pas
-- eu de déclenchement dans ce cycle, on considère qu'on n'a pas encore atteint l'humidité max et on remet à 0 la VMC_VAR_TimerSecuriteArret_SDB1
VMC_VAR_TimerSecuriteArret_SDB1 = NbCycles_Max_GV_VMC
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - L humidite est toujours en augmentation, remise a 0 de la Securite Arret. Ecart constate sur la derniere periode : ' .. Ecart_Max_Humidite_SDB1)
end
end
end
-- *****************************************************************************************
-- Si la VMC est en grande vitesse pour la SDB2 et que l'humidité continue d'augmenter
-- *****************************************************************************************
if (VMC_VAR_Deshumidification_On_SDB2 == 1) then
if (Ecart_Max_Humidite_SDB2 >= SEUIL_DECLENCHEMENT_VMC and Declenchement_SDB2 == 0) then
-- S'il y a encore un écart d'humidité constaté sur la dernière période (augmentation humidité toujours en cours) et qu'il n'y a pas
-- eu de déclenchement dans ce cycle, on considère qu'on n'a pas encore atteint l'humidité max et on remet à 0 la VMC_VAR_TimerSecuriteArret_SDB2
VMC_VAR_TimerSecuriteArret_SDB2 = NbCycles_Max_GV_VMC
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - L humidite est toujours en augmentation, remise a 0 de la Securite Arret. Ecart constate sur la derniere periode : ' .. Ecart_Max_Humidite_SDB2)
end
end
end
-- *************************************************************************************************************
-- Analyse pour identifier si la grande vitesse peut être arrêtée si elle a été activée auparavant.
-- Si les Timers de sécurité sont atteints ou que l'humidité est redescendu pour les deux SDB on
-- arrête la grande vitesse et on regarde si on peut arrêter complètement la VMC (si l'humidité globale est Ok)
-- *************************************************************************************************************
if (VMC_VAR_TimerSecuriteArret_SDB1 == 0 or Humidite_Actuelle_SDB1 <= VMC_VAR_Cible_Hum_GV_Off_SDB1) and (VMC_VAR_TimerSecuriteArret_SDB2 == 0 or Humidite_Actuelle_SDB2 <= VMC_VAR_Cible_Hum_GV_Off_SDB2) then
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'Off'
if Hygro_Max_Depassee == 0 then -- Si l'humidité maximum globale de la maison n'est pas atteinte
if Humidite_Actuelle_SDB1<= uservariables['Hygro_Max_SDB'] and Humidite_Actuelle_SDB2<= uservariables['Hygro_Max_SDB'] then -- Si l'humidité des deux SDB est inférieure à l'humidité maximum acceptable dans une SDB
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'Off' -- on arrête complètement la VMC
if MODE_DEBUGG== true then
print('[Hygro Maison] - Hygrometrie correcte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max) et aucune salle de bain en cours d utilisation, desactivation de la vmc')
end
else
-- sinon (hygro maison Ok, mais humidité d'une des deux SDB dépasse la valeur maximum acceptable), on active la VMC en petite vitesse
commandArray[NOM_INTERRUPTEUR_OnOff_VMC] = 'On'
if MODE_DEBUGG== true then
print('[Hygro Maison] - Hygrometrie correcte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max), aucune salle de bain en cours d utilisation mais humidite SDB toujours trop elevee, VMC laissee active en petite vitesse')
end
end
end
end
-- *************************************************************************************************************
-- Analyse pour identifier s'il faut arrêter la grande vitesse suite à atteinte du timer de sécurité sur la SDB1
-- *************************************************************************************************************
if (VMC_VAR_TimerSecuriteArret_SDB1 == 0 and Humidite_Actuelle_SDB1 > VMC_VAR_Cible_Hum_GV_Off_SDB1 and VMC_VAR_Deshumidification_On_SDB1 == 1) then
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - L humidite n est pas redescendue a sa valeur initiale (avant activation de la grande vitesse) mais le TimeOut de securite pour l arret est atteint. Arret de la grande vitesse de la VMC pour ' .. NOM_CAPTEUR_HUMIDITE1)
end
-- Si on a atteint le timer de sécurité on réinitialise l'historique avec la valeur d'hulidité actuelle ainsi que les variables de la SDB1
VMC_VAR_Histo_Hum2_SDB1 = VMC_VAR_Histo_Hum1_SDB1
VMC_VAR_Deshumidification_On_SDB1 = 0
VMC_VAR_Cible_Hum_GV_Off_SDB1 = 0
VMC_VAR_TimerSecuriteArret_SDB1 = 0
VMC_VAR_Deshumidification_On_SDB1 = 0
end
-- *************************************************************************************************************
-- Analyse pour identifier s'il faut arrêter la grande vitesse suite à retour à au taux d'humidité initial sur la SDB1
-- *************************************************************************************************************
if (VMC_VAR_TimerSecuriteArret_SDB1 > 0 and Humidite_Actuelle_SDB1 <= VMC_VAR_Cible_Hum_GV_Off_SDB1 and VMC_VAR_Deshumidification_On_SDB1 == 1) then
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - L humidite est redescendue a une valeur proche de sa valeur initiale ('.. VMC_VAR_Cible_Hum_GV_Off_SDB1 ..'%). Arret de la grande vitesse de la VMC pour ' .. NOM_CAPTEUR_HUMIDITE1)
end
-- On réinitialise l'historique avec la valeur d'hulidité actuelle ainsi que les variables de la SDB1
VMC_VAR_Histo_Hum2_SDB1 = VMC_VAR_Histo_Hum1_SDB1
VMC_VAR_Deshumidification_On_SDB1 = 0
VMC_VAR_Cible_Hum_GV_Off_SDB1 = 0
VMC_VAR_TimerSecuriteArret_SDB1 = 0
VMC_VAR_Deshumidification_On_SDB1 = 0
end
-- *************************************************************************************************************
-- Analyse pour identifier s'il faut arrêter la grande vitesse suite à atteinte du timer de sécurité sur la SDB2
-- *************************************************************************************************************
if (VMC_VAR_TimerSecuriteArret_SDB2 == 0 and Humidite_Actuelle_SDB2 > VMC_VAR_Cible_Hum_GV_Off_SDB2 and VMC_VAR_Deshumidification_On_SDB2 == 1) then
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - L humidite n est pas redescendue a sa valeur initiale (avant activation de la grande vitesse) mais le TimeOut de securite pour l arret est atteint. Arret de la grande vitesse de la VMC pour ' .. NOM_CAPTEUR_HUMIDITE2)
end
-- Si on a atteint le timer de sécurité on réinitialise l'historique avec la valeur d'hulidité actuelle ainsi que les variables de la SDB2
VMC_VAR_Deshumidification_On_SDB2 = 0
VMC_VAR_Cible_Hum_GV_Off_SDB2 = 0
VMC_VAR_TimerSecuriteArret_SDB2 = 0
VMC_VAR_Deshumidification_On_SDB2 = 0
VMC_VAR_Histo_Hum2_SDB2 = VMC_VAR_Histo_Hum1_SDB2
end
-- *************************************************************************************************************
-- Analyse pour identifier s'il faut arrêter la grande vitesse suite à retour à au taux d'humidité initial sur la SDB2
-- *************************************************************************************************************
if (VMC_VAR_TimerSecuriteArret_SDB2 > 0 and Humidite_Actuelle_SDB2 <= VMC_VAR_Cible_Hum_GV_Off_SDB2 and VMC_VAR_Deshumidification_On_SDB2 == 1) then
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - L humidite est redescendue a une valeur proche de sa valeur initiale ('.. VMC_VAR_Cible_Hum_GV_Off_SDB2 ..'%). Arret de la grande vitesse de la VMC pour ' .. NOM_CAPTEUR_HUMIDITE2)
end
-- On réinitialise l'historique avec la valeur d'hulidité actuelle ainsi que les variables de la SDB2
VMC_VAR_Deshumidification_On_SDB2 = 0
VMC_VAR_Cible_Hum_GV_Off_SDB2 = 0
VMC_VAR_TimerSecuriteArret_SDB2 = 0
VMC_VAR_Deshumidification_On_SDB2 = 0
VMC_VAR_Histo_Hum2_SDB2 = VMC_VAR_Histo_Hum1_SDB2
end
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
if (Humidite_Actuelle_SDB1 > VMC_VAR_Cible_Hum_GV_Off_SDB1 and VMC_VAR_TimerSecuriteArret_SDB1 > 0 and Declenchement_SDB1 == 0) then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Deshumidification toujours en cours, humidite actuelle = ' .. Humidite_Actuelle_SDB1.. '% ,cible = ' .. VMC_VAR_Cible_Hum_GV_Off_SDB1 .. '% ,TimerSecurite= ' .. VMC_VAR_TimerSecuriteArret_SDB1)
end
if (Humidite_Actuelle_SDB2 > VMC_VAR_Cible_Hum_GV_Off_SDB2 and VMC_VAR_TimerSecuriteArret_SDB2 > 0 and Declenchement_SDB2 == 0) then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Deshumidification toujours en cours, humidite actuelle = ' .. Humidite_Actuelle_SDB2.. '% ,cible = ' .. VMC_VAR_Cible_Hum_GV_Off_SDB2 .. '% ,TimerSecurite= ' .. VMC_VAR_TimerSecuriteArret_SDB2)
end
end
else
-- -----------------------------------
-- Affichage des infos en mode debug
-- -----------------------------------
if MODE_DEBUGG== true then
print('Nombre de cycles avant la realisation des tests d adaptation de la vitesse VMC non atteint (' .. VMC_VAR_Compteur_Cycles .. '/' .. INTERVAL_MESURE .. ')')
end
end
-- *******************************************************
-- Si la VMC est arrêtée on arrête aussi la grande vitesse
-- *******************************************************
if commandArray[NOM_INTERRUPTEUR_OnOff_VMC] == 'Off' then
commandArray[NOM_INTERRUPTEUR_GV_VMC] = 'Off'
end
if MODE_DEBUGG== true then
print(' ')
print('***************')
print('ETAT EN SORTIE : ')
print('***************')
if VMC_VAR_Deshumidification_On_SDB1 == 0 then
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Deshumidification OFF - actuelle : ' .. Humidite_Actuelle_SDB1 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB1 .. '% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB1 .. '%')
else
print('[' .. NOM_CAPTEUR_HUMIDITE1 .. '] - Deshumidification ON - actuelle : ' .. Humidite_Actuelle_SDB1 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB1 ..'% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB1 .. '% / Cible arret : ' .. VMC_VAR_Cible_Hum_GV_Off_SDB1 .. '% / arret de securite dans ' .. VMC_VAR_TimerSecuriteArret_SDB1 .. ' cycle(s)')
end
if VMC_VAR_Deshumidification_On_SDB2 == 0 then
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Deshumidification OFF - actuelle : ' .. Humidite_Actuelle_SDB2 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB2 .. '% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB2 .. '%')
else
print('[' .. NOM_CAPTEUR_HUMIDITE2 .. '] - Deshumidification ON - actuelle : ' .. Humidite_Actuelle_SDB2 .. '% / Precedente : ' .. VMC_VAR_Histo_Hum1_SDB2 ..'% / Cycle -2 : ' .. VMC_VAR_Histo_Hum2_SDB2 .. '% / Cible arret : ' .. VMC_VAR_Cible_Hum_GV_Off_SDB2 .. '% / arret de securite dans ' .. VMC_VAR_TimerSecuriteArret_SDB2 .. ' cycle(s)')
end
if Hygro_Moyenne_Maison <= uservariables['Hygro_Max_Maison'] and VMC_VAR_Deshumidification_On_SDB1 ==0 and VMC_VAR_Deshumidification_On_SDB2 == 0 then
if Humidite_Actuelle_SDB1 <= Maximum_Humidite_Acceptable_SDB and Humidite_Actuelle_SDB2 <= Maximum_Humidite_Acceptable_SDB then
print('[Hygro Maison] - Hygrometrie correcte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max) et aucune salle de bain en cours d utilisation, VMC desactivee')
else
print('[Hygro Maison] - Hygrometrie correcte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max), aucune salle de bain en cours d utilisation mais humidite SDB toujours trop elevee, VMC laissee active en petite vitesse')
end
else
if Hygro_Moyenne_Maison > uservariables['Hygro_Max_Maison'] then
print('[Hygro Maison] - Hygrometrie incorrecte (' .. Hygro_Moyenne_Maison .. '% vs ' .. uservariables['Hygro_Max_Maison'] ..'% max), VMC activee')
end
end
end
-- Sauvegarde des variables
commandArray['Variable:VMC_VAR_Compteur_Cycles'] = tostring(VMC_VAR_Compteur_Cycles)
commandArray['Variable:VMC_VAR_Histo_Hum2_SDB1'] = tostring(math.floor(tonumber(VMC_VAR_Histo_Hum2_SDB1)))
commandArray['Variable:VMC_VAR_Histo_Hum1_SDB1'] = tostring(math.floor(tonumber(VMC_VAR_Histo_Hum1_SDB1)))
commandArray['Variable:VMC_VAR_Cible_Hum_GV_Off_SDB1'] = tostring(VMC_VAR_Cible_Hum_GV_Off_SDB1)
commandArray['Variable:VMC_VAR_TimerSecuriteArret_SDB1'] = tostring(VMC_VAR_TimerSecuriteArret_SDB1)
commandArray['Variable:VMC_VAR_Deshumidification_On_SDB1'] = tostring(VMC_VAR_Deshumidification_On_SDB1)
commandArray['Variable:VMC_VAR_Histo_Hum2_SDB2'] = tostring(math.floor(tonumber(VMC_VAR_Histo_Hum2_SDB2)))
commandArray['Variable:VMC_VAR_Histo_Hum1_SDB2'] = tostring(math.floor(tonumber(VMC_VAR_Histo_Hum1_SDB2)))
commandArray['Variable:VMC_VAR_Cible_Hum_GV_Off_SDB2'] = tostring(VMC_VAR_Cible_Hum_GV_Off_SDB2)
commandArray['Variable:VMC_VAR_TimerSecuriteArret_SDB2'] = tostring(VMC_VAR_TimerSecuriteArret_SDB2)
commandArray['Variable:VMC_VAR_Deshumidification_On_SDB2'] = tostring(VMC_VAR_Deshumidification_On_SDB2)
end
return commandArray

205
lua/old/script_time_volets.old Executable file
View File

@@ -0,0 +1,205 @@
require "scripts/lua/functions"
commandArray = {}
local HEURE_DEB = 9
local HEURE_FIN = 17
local TEMP_MAX = 24
local TEMP_MAX_2 = 28
--recupere les minutes
time=os.time()
minutes=tonumber(os.date('%M',time))
--jour=tonumber(os.date('%w',time))
heures=tonumber(os.date('%H',time))
local saison = uservariables["Saison"]
local jourS = josdGetJourSemaine()
-- -------------------------------------------------------------------
-- Verification des volets ouverts si température trop basse
-- -------------------------------------------------------------------
if (minutes == 0 or minutes == 30 ) then
debug('########## Lancement du check fermeture velux du grenier ' ..heures..'h'..minutes)
tab = getValuesInTab('BarometreLaGacilly')
local tmp = tonumber(tab[1])
debug('########## Lancement du check fermeture velux du grenier ' ..heures..'h'..minutes..' tmp='..tostring(tmp))
if (tmp < 14.0 and (otherdevices['Velux droit'] == 'Open' or otherdevices['Velux gauche'] == 'Open')) then
commandArray['notification']="Volet ouvert#Un des volets du grenier est reste ouvert #0"
end
end
-- -----------------------
-- Fermeture volet central
-- -----------------------
if minutes%30 == 0
and (saison ~= "Ete")
and (heures >= 22) -- or uservariables['Dark'] == "True")
then
debug('------------------------------------------------------')
debug(' Test fermeture volet Central '..otherdevices['VoletPorteSalon'])
debug('------------------------------------------------------')
if (otherdevices['VoletPorteSalon'] ~= 'Closed') then
commandArray['VoletPorteSalon']='On'
end
end
-- ---------------------------------------------------------------------------------------
-- Fermeture des volets en fonction de la temperature exterieure Pas l'ETE
-- ---------------------------------------------------------------------------------------
--print("DARK=="..tostring(uservariables['Dark'] == "True"))
if minutes%9 == 0 and
(saison ~= "Ete")
and (otherdevices['VoletCuisine'] == 'Open' or otherdevices['VoletSalonTele'] == 'Open')
and (heures >= 18 or
(
heures >= 17 and (
uservariables['Dark'] == "True")
or (tonumber(otherdevices['Lux']) < tonumber(uservariables["LuxMini"]))
)
)
then
debug('------------------------------------------------------')
debug(' Test fermeture volet ')
debug('------------------------------------------------------')
debug('####### Comparaison heure vs Couche du soleil ========>'..uservariables["Heure"].." "..uservariables["Couche"])
debug('####### Lancement du check test ' ..heures..'h'..minutes..' volet cuisine '..otherdevices['BarometreLaGacilly']..' svalues='..otherdevices_svalues['BarometreLaGacilly']..' VoletCuisine='..otherdevices['VoletCuisine'])
tmp = otherdevices_svalues['BarometreLaGacilly']
tab = split(tmp, ";")
debug("######### Check fermeture : temperature lue par BarometreLaGacilly "..tab[1])
temp = tonumber(tab[1])
if (
(
(
(temp < 6.0 and whenDark() <= 30)
or (temp < 8 and whenDark() <= 15)
or (temp < 10 and whenDark() <= 0)
)
)
or (
uservariables['Dark'] == "True"
)
)
then
debug("######### Dans temperature")
if (otherdevices['VoletCuisine'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20) ) then
commandArray['VoletCuisine']='On'
end
if (otherdevices['VoletSalonTele'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20)) then
commandArray['VoletSalonTele']='On'
end
else
debug("############ PAS DANS LE IF")
end
end
-- ------------------------------------------------------------------------------
-- Ouverture des volets en fonction de la temperature exterieure Hiver et Automne
-- ------------------------------------------------------------------------------
if minutes%5 == 0
and heures <= HEURE_DEB
and ((heures >= 9 and josdJourChome()) or (heures > 6 and not josdJourChome()))
and (saison == "Hiver" or saison == "Automne")
and (greater2(uservariables["Heure"],uservariables["Lever"], - 30)) -- heures >= 20
and (otherdevices['VoletCuisine'] == 'Closed'
or otherdevices['VoletSalonTele'] == 'Closed'
or otherdevices['VoletPorteSalon'] == 'Closed'
)
then
debug('------------------------------------------------------')
debug(' Test ouverture volet ')
debug('------------------------------------------------------')
debug('####### Comparaison heure vs Lever du soleil ========>'..uservariables["Heure"]..
" "..uservariables["Lever"])
debug('####### Lancement du check test ' ..heures..'h'..minutes..' volet cuisine '
..otherdevices['BarometreLaGacilly']..' svalues='..otherdevices_svalues['BarometreLaGacilly']..' VoletCuisine='..otherdevices['VoletCuisine'])
tmp = otherdevices_svalues['BarometreLaGacilly']
tab = split(tmp, ";")
debug("######### Check Ouverture : temperature lue par BarometreLaGacilly "..tab[1])
temp = tonumber(tab[1])
if (temp > 12.0 or (heures >=9 and minutes >= 30)) then
if (otherdevices['VoletCuisine'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
commandArray['VoletCuisine']='Off'
end
if (otherdevices['VoletSalonTele'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
commandArray['VoletSalonTele']='Off'
end
if (otherdevices['VoletPorteSalon'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
commandArray['VoletPorteSalon']='Off'
end
end
end
-- ------------------------------------------------------------------------------
-- fermeture des volets en fonction de la temperature interieure en ete
-- ------------------------------------------------------------------------------
if minutes%5 == 0 --and uservariables['Dark'] == "False"
and (heures > HEURE_DEB and heures <= HEURE_FIN)
--and (saison == "ete")
--and (greater(uservariables["Heure"] , uservariables["Lever"])) -- heures >= 20
--and (otherdevices['VoletCuisine'] == 'Open' or otherdevices['VoletSalonTele'] == 'Open' or otherdevices['VoletPorteSalon'] == 'Open')
then
debug('------------------------------------------------------')
debug(' Test fermeture volet Ete')
debug('------------------------------------------------------')
debug('####### Lancement du check test ' ..heures..'h'..minutes..' volet cuisine '..otherdevices['BarometreLaGacilly']..' svalues='..otherdevices_svalues['BarometreLaGacilly']..' VoletCuisine='..otherdevices['VoletCuisine'])
local val
local val2
val, val2 = otherdevices_svalues['BarometreLaGacilly']:match("([^;]+);([^;]+)")
debug("BarometreLaGacilly"..otherdevices["BarometreLaGacilly"]..val.." "..val2..otherdevices['VoletCuisine'].." "..otherdevices['VoletSalonTele'].." "..otherdevices['VoletPorteSalon'])
local temp = tonumber(val)
if temp >= TEMP_MAX and (otherdevices['VoletCuisine'] == 'Open' and otherdevices['VoletSalonTele'] == 'Open'
and otherdevices['VoletPorteSalon'] == 'Open') then
debug("fermeture volets : temp élevée")
if temp >= TEMP_MAX_2 then
os.execute("/opt/domoticz/scripts/volets2.sh On &")
else
os.execute("/opt/domoticz/scripts/volets.sh On &")
end
end
end
-- ------------------------------------------------------------------------------
-- Réouverture après la vague de chaleur ETE
-- ------------------------------------------------------------------------------
if minutes%5 == 0
and (heures > HEURE_FIN and heures <= 19)
and (saison == "ete" )
then
local val
local val2
val, val2 = otherdevices_svalues['BarometreLaGacilly']:match("([^;]+);([^;]+)")
print("BarometreLaGacilly"..otherdevices["BarometreLaGacilly"].." "..val.." "..val2..otherdevices['VoletCuisine'].." "..otherdevices['VoletSalonTele'].." "..otherdevices['VoletPorteSalon'])
local temp = tonumber(val)
if ((temp <= 24 or (temp <= TEMP_MAX and heures >= 18))
and (otherdevices['VoletCuisine'] == 'Closed' and
otherdevices['VoletSalonTele'] == 'Closed' and
otherdevices['VoletPorteSalon'] == 'Closed'))
then
debug("Ouverture volets : temp en baisse")
os.execute("/opt/domoticz/scripts/volets.sh Off &")
end
end
return commandArray

238
lua/old/soleil.lua Executable file
View File

@@ -0,0 +1,238 @@
--Variables à éditer--------------
local Ville = "pws:ILAGACIL2" --Ville de référence
local idxLux = '320' --Capteur virtuel de Luminosité
local idxOcta = '5' -- idx de la variable Utilisateur
local wuAPIkey = "48a08328a93a18a1"
local DEBUG = 'OUI'
--import des fontions pour lire le JSON
json = (loadfile "/opt/domoticz/scripts/lua/JSON.lua")()
-- Fonction déterminant si année bissextile
function AnneeBissextile(annee)
return annee%4==0 and (annee%100~=0 or annee%400==0)
end
---------------------------------
-- Fonction spliter
function split(s, delimiter)
result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match);
end
return result;
end
---------------------------------
-- Fonction Arrondir
function arrondir(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
---------------------------------
-- Procedure principale
---------------------------------
---------------------------------
-- Meteo API Wunderground
local config=assert(io.popen('curl http://api.wunderground.com/api/'..wuAPIkey..'/conditions/q/FR/'..Ville..'.json'))
local location = config:read('*all')
config:close()
local jsonLocation = json:decode(location)
local Latitude = jsonLocation.current_observation.display_location.latitude
local Longitude = jsonLocation.current_observation.display_location.longitude
local Altitude = jsonLocation.current_observation.display_location.elevation
PressionRelative = jsonLocation.current_observation.pressure_mb
----------------------------------
local An = os.date("%Y")
local NiemeJourDeLAnnee = os.date("%j")
---------------------------------
DateHeure = os.date("%Y-%m-%d %H:%M:%S", os.time())
-- Début debug
if( DEBUG == 'OUI') then
print("=====================================")
print(os.date("%Y-%m-%d %H:%M:%S", os.time()))
print(Ville .. ", " .. Latitude .. ", " .. Longitude)
print("Altitude = " .. tostring(Altitude) .. " m")
print("NiemeJourDeLAnnee = " .. NiemeJourDeLAnnee)
end
---------------------------------
--calcul de l'année bissextile
if AnneeBissextile(An) == true then
if( DEBUG == 'OUI') then
print( An .. " est bissextile.")
end
JourDansLAnnee = 366
else
if( DEBUG == 'OUI') then
print( An .. " n'est pas bissextile.")
end
JourDansLAnnee = 365
end
---------------------------------
-- Vitesse angulaire = Combien de degrés par jour
VitesseAngulaire = 360/365.25 ----JourDansLAnnee -- ou approximativement 365.25
if( DEBUG == 'OUI') then
print("Vitesse angulaire = " .. VitesseAngulaire .. " par jour")
end
---------------------------------
-- Formule Declinaison = ArcSin(0,3978 x Sin(Va x (j - (81 - 2 x Sin(Va� x (j - 2))))))
local Declinaison = math.deg(math.asin(0.3978 * math.sin(math.rad(VitesseAngulaire) *(NiemeJourDeLAnnee - (81 - 2 * math.sin((math.rad(VitesseAngulaire) * (NiemeJourDeLAnnee - 2))))))))
if( DEBUG == 'OUI') then
print("La déclinaison = " .. Declinaison .. "°")
end
---------------------------------
-- Temps universel décimal (UTC)
TempsDecimal = (os.date("!%H") + os.date("!%M") / 60)
if( DEBUG == 'OUI') then
print("Temps universel decimal (UTC)".. TempsDecimal .." H.dd")
end
---------------------------------
-- Temps solaire
HeureSolaire = TempsDecimal + (4 * Longitude / 60 )
if( DEBUG == 'OUI') then
print("Temps solaire ".. HeureSolaire .." H.dd")
end
---------------------------------
-- Angle horaire du soleil
AngleHoraire = 15 * ( 12 - HeureSolaire )
if( DEBUG == 'OUI') then
print("Angle Horaire = ".. AngleHoraire .. "°")
end
---------------------------------
-- La hauteur du soleil (Elévation ou altitude)
HauteurSoleil = math.deg(math.asin(math.sin(math.rad(Latitude))* math.sin(math.rad(Declinaison)) + math.cos(math.rad(Latitude)) * math.cos(math.rad(Declinaison)) * math.cos(math.rad(AngleHoraire))))
if( DEBUG == 'OUI') then
print("Hauteur du soleil = " .. HauteurSoleil .. "°")
end
local Azimut = math.acos((math.sin(math.rad(Declinaison)) - math.sin(math.rad(Latitude)) * math.sin(math.rad(HauteurSoleil))) / (math.cos(math.rad(Latitude)) * math.cos(math.rad(HauteurSoleil) ))) * 180 / math.pi
local SinAzimut = (math.cos(math.rad(Declinaison)) * math.sin(math.rad(AngleHoraire))) / math.cos(math.rad(HauteurSoleil))
if(SinAzimut<0) then
Azimut=360-Azimut
end
if( DEBUG == 'OUI') then
print("Azimut du soleil = " .. Azimut .. "°")
end
---------------------------------
-- La durée d'insolation journalière - non stockée en VG
DureeInsolation = math.deg(2/15 * math.acos(- math.tan(math.rad(Latitude)) * math.tan(math.rad(Declinaison))))
DureeInsolation = arrondir(DureeInsolation,2)
if( DEBUG == 'OUI') then
print("La durée d'insolation journalière = " .. DureeInsolation .." H.dd")
end
---------------------------------
-- Constantes Solaire
ConstanteRatiationSolaire = 1361 -- W/m²
ConstanteRadiationLux = 200000 -- Lux
---------------------------------
-- Rayonnement solaire (en W/m²) présent à l'entrée de l'atmosphère.
RadiationAtm = ConstanteRatiationSolaire * (1 +0.034 * math.cos( math.rad( 360 * NiemeJourDeLAnnee / JourDansLAnnee )))
if( DEBUG == 'OUI') then
print("Radiation max en atmosphère = " .. arrondir(RadiationAtm,2) .. " W/m²")
end
---------------------------------
-- Coefficient d'attenuation M
PressionAbsolue = PressionRelative - arrondir((Altitude/ 8.3),1) -- hPa
SinusHauteurSoleil = math.sin(math.rad(HauteurSoleil))
M0 = math.sqrt(1229 + math.pow(614 * SinusHauteurSoleil,2)) - 614 * SinusHauteurSoleil
M = M0 * PressionRelative/PressionAbsolue
if( DEBUG == 'OUI') then
print("Pression relative locale = " .. PressionRelative .. " hPa")
print("Pression absolue atmosphère = " .. PressionAbsolue .. " hPa")
print("Coefficient d'attenuation = " .. M )
end
---------------------------------
-- Récupérer message SYNOP sur le site Ogimet
heureUTCmoins1 = os.date("!%H")-1
if string.len(heureUTCmoins1) == 1 then
heureUTCmoins1 = "0" .. heureUTCmoins1
end
UTC = os.date("%Y%m%d").. heureUTCmoins1.."00" -- os.date("!%M")
local WMOID = jsonLocation.current_observation.display_location.wmo
print("WMOID="..WMOID)
local ogimet=assert(io.popen('curl "http://www.ogimet.com/cgi-bin/getsynop?block='..WMOID..'&begin='..UTC..'"'))
local synop = ogimet:read('*all')
ogimet:close()
rslt = split(synop,",")
CodeStation = rslt[1]
rslt = split(synop, " "..CodeStation.. " ")
Trame = string.gsub(rslt[2], "=", "")
Trame = CodeStation .." ".. Trame
rslt = split(Trame, " ")
if( DEBUG == 'OUI') then
print("Horodatage UTC = " .. UTC)
print("Station SYNOP = " .. WMOID)
end
---------------------------------
-- Récupérer le premier caractere du 3eme mot = Nebulosité en Octa
Octa = string.sub(rslt[3], 1, 1)
--print(rslt[3])
-- 0 Pas de couverture nuageuse
-- 1-8 Huitième
-- 9 Brouillard
-- / Couverture indiscernable
-- cas particulier si valeur indéterminé un slash est renvoyé.
if Octa == "/" then
-- si la couverture est indiscernable, on reprend l'ancienne valeur
-- cela evite les violentes cassures dans la courbe
--Octa = uservariables['octa']
Octa = arg[1]
elseif Octa == "9" then
Octa = 8
end
if( DEBUG == 'OUI') then
print( Octa .. " Octa")
end
-- stockage de la variable octa
--commandArray['Variable:octa']=tostring(Octa)
os.execute('/usr/bin/curl "http://127.0.0.1:8080/json.htm?type=command&param=updateuservariable&idx='..idxOcta..'&vname=octa&vtype=0&vvalue='..tostring(Octa)..'"')
---------------------------------
-- Facteur d'atténuation des couches nuageuses Kc
-- Kc=1-(0.75*((OCTA)**(3.4))
Kc=1-0.75*(math.pow(Octa/8,3.4))
if( DEBUG == 'OUI') then
print("Kc = " .. Kc)
end
---------------------------------
-- Au lever/coucher du soleil, on atteind les limites de précisions de ces calculs.
-- J'interrompts donc le calcul de radiation dès 1°.
if HauteurSoleil > 1 then
-- Radiation directe
RadiationDirecte = RadiationAtm * math.pow(0.6,M) * SinusHauteurSoleil
-- Radiation Diffuse
RadiationDiffuse = RadiationAtm * (0.271 - 0.294 * math.pow(0.6,M)) * SinusHauteurSoleil
-- Radiation totale
RadiationTotale = RadiationDiffuse + RadiationDirecte
-- Radiation en Lux : -- 1 Lux = 0,0079 W/m²
Lux = RadiationTotale / 0.0079
--Lux = ConstanteRadiationLux / ConstanteRatiationSolaire * RadiationTotale
-- Le rayonnement solaire avec ciel nuageux
RTOTC = RadiationTotale * Kc
-- Radiation en Lux pondéré
-- LuxPondere = ConstanteRadiationLux / ConstanteRatiationSolaire * RTOTC
LuxPondere = RTOTC / 0.0079
print("Radiation totale en lux pondéré = ".. arrondir(LuxPondere,2).." Lux")
if( DEBUG == 'OUI') then
print("RadiationDirecte = ".. arrondir(RadiationDirecte,2) .." W/m²")
print("Radiation Diffuse = ".. arrondir(RadiationDiffuse,2) .." W/m²")
print("Radiation totale = " .. arrondir(RadiationTotale,2) .." W/m²")
print("Radiation totale en lux = ".. arrondir(Lux,2).." Lux")
print("Le rayonnement solaire avec pondération = " .. arrondir(RTOTC,2))
end
else
--le soleil est trop bas
RTOTC = 0
LuxPondere = 0
end
--mise à jour du dispositif
os.execute('/usr/bin/curl "http://127.0.0.1:8080/json.htm?type=command&param=udevice&idx='..idxLux..'&svalue="'..tostring(LuxPondere)..' -s -o /dev/null')