-- 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 debug command will output lua debug statements to the domoticz log for debugging.
-- List all otherdevices states for debugging: 
--   for i, v in pairs(otherdevices) do debug(i, v) end
-- List all otherdevices svalues for debugging: 
--   for i, v in pairs(otherdevices_svalues) do debug(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)
jour_y   = tonumber(os.date('%j',time))

heurmin  = heures * 60 + minutes

PUISSANCE_DELESTAGE = 750 -- Watts

disable_radiateur = true 

function callExternal(command)
	local handle = io.popen(command)
	local result = handle:read("*a")
	handle:close()		
	--debug("Commande = "..command.." "..result)
	return result
end

function update_meter(device, id, power, energy, index)
	commandArray[index] = {['UpdateDevice'] = id .. "|0|" .. power .. ";" .. energy}
end 

local function round(num, dec)
	--debug("Round "..tostring(num))

	if (num and dec) then
		return ( math.floor( tonumber(num) * 10^dec ) / 10^dec )
	end
	return 0
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")'


  debug("query="..query)
  local bSuccess, aRows, iCount = executeQuery(idx, query)

  if aRows[1][1] then
  	debug("Retour executeQuery "..tostring(bSuccess)..' '..aRows[1][1])
  	return aRows[1][1]
  end
  debug('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")'

  --debug("query="..query)
  local bSuccess, aRows, iCount = executeQuery(idx, query)

  --debug("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")'

  debug("query delete="..query)
  local bSuccess, aRows, iCount = executeQuery(idx, query)

end


-- ----------------------------------
-- Gestion des batteries automatique
-- ---------------------------------

function gestionBatterie(ip_controller)

	local attente_radiateur = false
	local capacite=100 * 24 --Wh
	local charge=390 	--W
	local decharge=270 --210	--W
	local tension_charge_max_off=29.6
	local tension_charge_max_on=29.6
	local tension_injection_min_off=25.2
	local tension_injection_min_on=24.8
	local tension_force_charge=24.6
	local fact = 2 --2.43
	local regul = false

	-- Tension repos V  Conso charge W
	--   11.35		330
	--   12.35		270
	--   12.8 		233		
	--   12.67 		190		
	--   13.33 		 66		

	url = "http://"..ip_controller.."/getData"

	--result = os.execute(curl..'"'..url..'"')
	local jsonContent = getJSONContent(url)
	--print(cmd)

	local statuses = decodeJSON(jsonContent)
	--printTableAsTree(statuses)

	--updatenum("BatterieCharge", 0)
	--updatenum("BatterieInjection", 0)
	--local charge_theorique = (13.796 - tension) / 0.01213 -- -127.57 * tension + 1796.82
	if isempty(statuses) then -- or tension <= 0 then
        print("BAT ERROR getData")       
		--switchOff('Batterie')
		return 0 --commandArray
	end
	local tension = round(tonumber(statuses['V']) / 1000,2) -- tonumber(otherdevices['BatterieTension'])
	if tension <= 10 then
        	print("BAT ERROR tension fausse")       
		--switchOff('Batterie')
		return 0 --commandArray
	end

	if (otherdevices['ForceChargeBatterie'] == 'On' and 
		((tonumber(lastUpdateOfDevice('ForceChargeBatterie')) > 3 * 3600) or tension > tension_charge_max_on))
	then
		commandArray['ForceChargeBatterie'] = "Off"
        	switchOff("ForceChargeBatterie")
	end
	if (statuses['CS'] == '3' and tonumber(statuses['PPV']) > 450 or (statuses['CS'] == '4' or statuses['CS'] == '5')) then
		print("Radiateur solaire Actif CS="..statuses['CS'].." PPV="..statuses['PPV'])
		disable_radiateur = false 
	else
		print("Radiateur solaire Inactif CS="..statuses['CS'].." PPV="..statuses['PPV'])
		disable_radiateur = true	
		command = 'curl -m 3 "http://192.168.125.11/stop"'
		callExternal(command)	
		updatenum("Injection_Radiateur", 0)
	end

	local decharge_theorique = 63.29 * tension - 697.5
	--decharge=150 --decharge_theorique
	--charge=220 --charge_theorique
	--print("BAT Power theorique "..tostring(charge_theorique))
	local temperature = round(tonumber(statuses['XY_T']) / 10,1) -- tonumber(otherdevices['BatterieTension'])

	updatenum("BatterieTension", tension)
	updatenum("BatterieCharge", tonumber(statuses['PPV']))
	local decharge_tmp = tonumber(statuses['V']) * tonumber(statuses['IL']) / 1000000
	if decharge_tmp > 0 then
		decharge = decharge_tmp
	end

	updatenum("BatterieInjection", tonumber(statuses['V']) * tonumber(statuses['IL']) / 1000000)
	updatenum("TemperatureBatterie", temperature)
	--commandArray['UpdateDevice'] = "1195|0|"..tostring(tension)
	--commandArray['UpdateDevice'] = "1196|0|"..tostring(temperature)
	--commandArray['Batterie'] 	  = ternary(statuses['PIN_POWER'] == 0, 'On', 'Off') 
	--commandArray['InjectionBatterie'] = ternary(statuses['PIN_INJECTION'] == 0, 'On', 'Off') 
	--commandArray['ChargeBatterie'] 	  = ternary(statuses['PIN_CHARGE'] == 0, 'On', 'Off') 

	local  production = tonumber(split(otherdevices['SolaireProduction'], ";")[1])
	local  injection = tonumber(split(otherdevices['Injection_Radiateur'], ";")[1])
	local  injection_reseau = tonumber(split(otherdevices['INJECTION'], ";")[1])
	local  chauffe   = tonumber(split(otherdevices['Chauffe_Eau'], ";")[1])
	local  conso     = tonumber(split(otherdevices['Consommation_Apparente'], ";")[1])
	local nuages = tonumber(otherdevices['CouvertureNuageusePrevisionnelle'])
    updatenum("Surplus", injection + injection_reseau)

	  print("BAT injection="..tostring(injection)
		..' solaire='..tostring(production)
		..' chauffe='..tostring(chauffe)
		..' charge='..statuses['PPV']
		..' decharge='..tostring(tonumber(statuses['V']) * tonumber(statuses['IL']) / 1000000)
		..' conso='..tostring(conso)
		..' tension='..tostring(tension)
		..' temperature='..tostring(temperature)
		)        
	if isempty(statuses) then -- or tension <= 0 then
        	print("BAT ERROR getData")       
		--switchOff('Batterie')
		return 0 --commandArray
	end
	  print("BAT PIN_CHARGE="..statuses['PIN_CHARGE'].." PIN_INJECTION="..statuses['PIN_INJECTION'])        
	-- status 1 = ON / 0 = OFF


	if (uservariables['Dark'] == "True" and tonumber(statuses['PPV']) > 100) then
		--switchOff('LUMIERE_PLANTE')
	end

	return tonumber(statuses['PPV']) 		
end -- GestionBatterie


commandArray = {}

  if devicechanged['RadiateurGrenier'] then
    print("Dimmer Radiateur "..otherdevices_svalues['RadiateurGrenier']..tostring(otherdevices['RadiateurGrenier']))  
    local consigne = tonumber(otherdevices_svalues['RadiateurGrenier'])

    print("Dimmer Radiateur grenier="..tostring(consigne))
    if consigne <= 0 or otherdevices['RadiateurGrenier'] == "Off" then
	-- command = 'curl -m 3 "http://192.168.177.240/stop"'
	command = 'curl -m 3 "http://192.168.197.193/stop"'
    else 
    	-- command = 'curl -m 3 "http://192.168.177.240/exact?value=' .. tostring(consigne * 7).. '"'
    	command = 'curl -m 3 "http://192.168.197.193/exact?value=' .. tostring(consigne * 3.5).. '"'
    end
    callExternal(command) 
  end

-- ==================================================================
-- INTENSITE_GENERALE
-- ==================================================================
--if (devicechanged['CONSOMMATION_GENERALE']) then
function calcul()
	--local tab = getValuesInTab('Oregon_Conso')
	--debug("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
	values2 = split(otherdevices['CONSOMMATION_GENERALE'], ";")
	print("NRJ Solaire CONSOMMATION_GENERALE tabs "..otherdevices['CONSOMMATION_GENERALE'])	

	watt = tonumber(values2[1])
	for deviceName,deviceValue in pairs(devicechanged) do
		if deviceName=="CONSOMMATION_GENERALE_Utility" then
			watt = deviceValue
		end

	    debug ("Device based event fired on '"..deviceName.."', value '"..tostring(deviceValue).."'");
	end

	debug("Conso "..tostring(watt))

	--debug("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)

	debug("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'] 
	if watt_solaire == nil then
		watt_solaire = 0
	end

	debug("Suivi "..tostring(watt_conso - watt_solaire))
	if (minutes%5 == 0 and secondes < 8) 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
	    debug('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
	    debug('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
	    debug('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
	    debug('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
	    debug('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
	    debug('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
	    debug('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
	    debug('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

	    debug('conso='..consommation)
	    debug('cumul_solar='..cumul_solar)
	    debug('cumul_injection='..cumul_injection)
	    debug('cumul_radiateur='..cumul_radiateur)

	    if (cumul_solar > 0) then
	    	debug("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
			debug("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_injection) / cumul_solar), 1)) 		
		else
			updatenum('Consommation_Efficace', 0) 				
		end
	end

end

if (devicechanged['Mesure_Courant']) then
	print('NRJ Mesure_Courant '..otherdevices['Mesure_Courant'])
	values2 = split(otherdevices['Mesure_Courant'], ";")
	debug("Solaire Mesure courant tabs ") --..otherdevices['Mesure_Courant'])	


	watt = tonumber(values2[1])
	if (watt > 1600) then 
		watt = 0;
	end
	for deviceName,deviceValue in pairs(devicechanged) do
		if deviceName=="Mesure_Courant_Utility" then
			watt = deviceValue
		end

	    debug ("Device based event fired on '"..deviceName.."', value '"..tostring(deviceValue).."'");
	end
	print("NRJ Solaire Mesure courant "..tostring(watt))

	--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

	--debug("Intensite solaire "..devicechanged['SolaireIntensite'])
	amp = math.abs(watt / 230); --math.max(0, round(otherdevices['SolaireIntensite'],3)  - 0.54) *1.18
	updatenum('SolaireIntensite', amp)

	print("NRJ # 2 # production amp="..tostring(amp).." watt="..tostring(watt))
	--debug("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN")
	if (watt == nil or watt == "NAN") then
		watt = 0
	end

	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	
		updatenum('CONSOMMATION_GENERALE', watt_reel)			
		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)			
		updatenum('CONSOMMATION_GENERALE', 0)			
	end
	calcul() 
end

if (devicechanged['SolaireProduction']) then

end

if (devicechanged['Consommation_Apparente']) then
	print("NRJ Consommation_Apparente ================================================")	

	values2 = split(otherdevices['Consommation_Apparente'], ";")
	watt    = tonumber(values2[1])

	for deviceName,deviceValue in pairs(devicechanged) do
		if deviceName=="Consommation_Apparente_Utility" then
			-- watt = deviceValue
			watt = round(deviceValue, 2)
		    debug ("Device based event fired on '"..deviceName.."', value "..tostring(round(deviceValue, 2)));

		end

	    -- debug ("Device based event fired on '"..deviceName.."', value "..tostring(tonumber(deviceValue)));
	end

	debug("Solaire Consommation_Apparente "..tostring(watt))	

	values = split(otherdevices['SolaireProduction'], ";")
	--debug("Solaire production "..otherdevices['SolaireProduction'])	

	watt_solaire = values[1]

	values2 = split(otherdevices['Mesure_Courant'], ";")
	--debug("Solaire production mesure courant "..otherdevices['Mesure_Courant'])	

	watt_solaire = values[1] --+ values2[1]
	if watt_solaire == "NAN" then
		watt_solaire = "0"
	end

	injection = split(otherdevices['INJECTION'], ";")
	debug(injection[1])

	local debut_injection = - 7 
	local fin_injection   = 7

  	local currentTemp = getTemperatureFromDevice('Bureau')

	
	-- --------------------------------------------------------
	-- Gestion batterie
	-- --------------------------------------------------------
	local watt_a_enlever = gestionBatterie("batterie")
	--watt = watt - watt_a_enlever -- Charge batterie

	-- -------------------------------------------------------
	
	debug("Solaire production temperature Exterieur_Cellier "..tostring(currentTemp).." "..tostring(watt_solaire))	
	if disable_radiateur == false then
		command = 'curl -s -m 3 "http://192.168.125.11"|grep "<p>"|awk -F">" \'{print $2}\'|awk -F"<" \'{print $1}\''
		result = callExternal(command)
		local radiateur = tonumber(result) * (PUISSANCE_DELESTAGE / 100) 
		local to_inject = math.abs(watt) -- watt_a_enlever -- tonumber(result) * (PUISSANCE_DELESTAGE / 100)
		local quick_value = math.floor(0.5 * to_inject / (PUISSANCE_DELESTAGE / 100))
		print("quick_value result niveau d'injection= "..radiateur ..' to inject='..tostring(to_inject)..' quick='..tostring(quick_value)..' watt='..tostring(watt)..' a_enlever='..tostring(watt_a_enlever))
		--if (otherdevices['InjectionBatterie'] == 'On') then 
		--	command = 'curl -m 3 "http://192.168.125.11/stop"'
		--	callExternal(command)	
		--	updatenum("Injection_Radiateur", 0)
		--else
			if result == 0 or result == "" or result == nil or result == "NAN" then
				result = 0		
			end
			if (watt < debut_injection) then
				print("quick_value plus="..tostring(quick_value).." conso="..tostring(watt))
				if (quick_value > 0) then
					command = 'curl -m 3 "http://192.168.125.11/plus?value=' .. tostring(quick_value).. '"'
					callExternal(command)		
					updatenum("Injection_Radiateur", radiateur + to_inject)
				else
				 	print("quick_value reset radiateur")
					--command = 'curl -m 3 "http://192.168.125.11/stop"'
					--callExternal(command)	
					--updatenum("Injection_Radiateur", 0)
				end
			else
				if (watt > fin_injection) then 
					print("quick_value minus="..tostring(quick_value).." conso="..tostring(watt))
					command = 'curl -m 3 "http://192.168.125.11/minus?value=' .. tostring(quick_value).. '"'
					callExternal(command)		
					updatenum("Injection_Radiateur", radiateur - to_inject)
				end
			end
		--end
	
	else
		updatenum("Injection_Radiateur", 0)
	end

	if result == 0 or result == "" or result == nil or result == "NAN" then
		print("result nil value")
		updatenum('TOTAL_AUTOCONSOMMATION', 0)
	else
		if (tonumber(result) == 1) then
			commandArray['Dimmer'] = 'Set Level: 30' 
			result=0
		end
		local injection_radiateur = tonumber(result) * PUISSANCE_DELESTAGE / 100
		updatenum('Injection_Radiateur', injection_radiateur)		
		updatenum('TOTAL_AUTOCONSOMMATION', round(watt_solaire - injection[1] - math.abs(injection_radiateur), 0))
	end

	-- ========================================================================

	if (watt < 0) then	
		debug("Watt injection "..watt)

		updatenum('INJECTION', - round(watt,0))
		updatenum('TOTAL_INJECTION', - round(watt,0))
	else
		updatenum('INJECTION', 0)
		updatenum('TOTAL_INJECTION', 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
    debug('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
    debug('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
    debug('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
    debug('value_solar2='..value_solar2)

    --------------------------------------------------------------------------------------
	watt_p1 = getConsommationHP(1123) or 0
	watt_p2 = getConsommationHC(1123) or 0

	values_batterie = split(otherdevices['BatterieInjection'], ";")

	print('BatterieInjection='..otherdevices['BatterieInjection']..' '..values_batterie[1]..' '..tostring(watt_solaire))

	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 + tonumber(values_batterie[1])).. ';' 
		.. tostring(math.floor(watt_solaire + tonumber(values_batterie[1]))) --math.floor(ConsumoEnergyBalance / 1000)) --round(watt,0))
	
	debug('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
	debug('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)))

    -- =========================================================

end

-- 
return commandArray
 
