--    ======================
--    Description
--    ======================
--
--    Logika umożliwiająca sterowanie rekuperatorem typu:
--
--    ALNOR HRU-ERGO
--    CHIGO AB-HRV
--
--    dokonuje konwersji jednostek temperatury i umożliwia ręczne sterowanie bypassem.
--
--    ======================
--    Parameters
--    ======================
--
--    SubLogic supports following variables:
--
--    input.room.temperature                  - z rekuperatora: temperatura wewnętrzna (zużyte powietrze wyciągane z pomieszczeń RA)
--
--    input.outdoor.temperature               - z rekuperatora: temperatura zewnętrzna (świeże powietrze zaciąganie z zewnątrz OA)
--
--    input.exhaust.temperature               - z rekuperatora: temperatura wyrzutu (zużyte powietrze wyrzucane na zewnątrz EA)
--
--    input.defrosting.temperature            - z rekuperatora: temperatura odladzania
--
--    input.errors                            - z rekuperatora: zbiorcze błędy
--
--    input.additional.signals                - z rekuperatora: dodatkowe sygnały
--
--    input.fan.operation.timer               - z rekuperatora: licznik pracy wentylacji [0.1h]
--
--    input.filter.jam.alarm.timer            - z rekuperatora: kodowa wartość przypomnienia o wymianie filtrów
--
--    input.supply.fan.speed                  - z rekuperatora: wartość wentylatora nawiewnego
--
--    output.vent.out.t.value
--    output.vent.out.t.err                   - temperatura wyrzucanego (przekonwertowana)
--
--    output.vent.in.t.value
--    output.vent.in.t.err                    - temperatura powietrza wejścia na rekuperator (przekonwertowana)
--
--    output.vent.exhaust.t.value
--    output.vent.exhaust.t.err               - temperatura powietrza wywiewanego (przekonwertowana)
--
--    output.defrosting.t.value
--    output.defrosting.t.err                 - temperatura odladzania (przekonwertowana)
--
--    output.bypass.opening.temp.x
--    output.bypass.opening.temp.y            - parametry przekazywane do rekuperatora powiązane z bypassem
--
--    output.exhaust.fan.speed                - wartość wentylatora wywiewnego
--
--    counter.eeprom.err                      - flaga: błąd eepromu
--
--    counter.fire.alert                      - flaga: alarm pożarowy
--
--    counter.bypass                          - flaga: stan bypassu
--
--    counter.defrosting                      - flaga: odladzanie
--
--    counter.filter.jam.alarm                - flaga: przypomnienie o wymianie filtrów
--
--    setting.bypass.airdamper                - by-pass wymiennika (0 - przez wymiennik; 1 - przez by-pass) [0..1]
--                                              wymiennik może być otwarty tylko jeżeli temperatura zewnętrzna będzie między 5*C a 33*C.
--                                              w innym wypadku pozostanie zamknięty niezależnie od tej nastawy
--
--    setting.exhaust.fan.mode                - tryb pracy wentylatora wyciągowego:
--                                              0 - niezależny (oryginalne sterowanie)
--                                              1 - wentylator wywiewny zawsze o 1 bieg niżej od nawiewnego.
--
--    Logic uses lua language to implement own behaviour
--
--    ======================
--    mandatory variables
--    ======================
--
--    Logic expects following mandatory variables:
--
--    reload.trigger                          - causes reloading lua script
--
--    memcnt                                  - current amount of memory used by lua in bytes
--
--    Logic expects following kv settings:
--
--    LuaScriptPath                           - path to the lua script - must be absolute
--
--    ======================
--    ChangeLog
--    ======================
--
--    2019-07-15 ver 1.0.0
--
--    # First release
--
-- user can use some functions provided by ibmanager.

-- ibmanager provides following functions to use:
--
-- function returns value of required ibmanager variable
-- @param fullName - string - variable name - name of variable of which value must be returned, for example "rs.0.id.255.input.t.0.value"
-- @return         - string or integer - variable value or "nil" if variable not exist or is not readable
--
-- getValue(fullName)


-- function set value of given ibmanager variable
-- @param fullName - string - variable name - name of variable of which value we want to set, for example "rs.0.id.255.input.t.0.value"
-- @param value    - string, int or boolean - value to set
-- @return         - nothing
--
-- setValue(fullName, value)


-- function returns value of required ibmanager variable
-- @param key      - placed in xml logic configuration file:
--                   * as attribute: Name, in Var, RemoteVar and ImportVar elements in the case of stand alone variables
--                   * as concatenation of two attributes: ListName.Postfix in VarListItem, RemoteVarListItem and ImportVarListItem elements
--                     in the case of variables that are placed in lists
-- @return         - string or integer - variable value or "nil" if variable not exist or is not readable
--
-- getLogicValue(key)


-- function set value of given ibmanager variable
-- @param key      - placed in xml logic configuration file:
--                   * as attribute: Name, in Var, RemoteVar and ImportVar elements in the case of stand alone variables
--                   * as concatenation of two attributes: ListName.Postfix in VarListItem, RemoteVarListItem and ImportVarListItem elements
--                     in the case of variables that are placed in lists
-- @param value    - string, int or boolean - value to set
-- @return         - nothing
--
-- setLogicValue(key, value)

-- function returns two sections of kvsettings from xml configuration file
-- returned value is two element table, each of these elements is table too.
-- indices of returned table are strings and equal "instance" and "global"
-- values of returned tables are tables and contain KVsettings for applicable section.
-- nested tables have form key = value, where key is index in nested table and value is value.
-- example: {"instance" = {"ikey1" = "ivalue1", "ikey2" = "gvalue2"}, "global" = {"gkey1" = "gvalue1", "gkey2" = "gvalue2", "gkey3" = "gvalue3"}}
-- @return          - two dimensional array - kvsettings for global and instance sections
-- getKvSettings()


-- function schedules alert to send.
-- rules are defined in separated alert configuration files and are described in ibmanager instruction manual
-- @param id - alert identifier - must be defined in current logic configuration file in section: <Alert Id="any_identifier" ...
-- scheduleAlert(id)

-- function cancels alert sending, if was previously scheduled. if not then only wakes up alerts handling thread, so if there is no need to call this function, then do not call it.
-- rules are defined in separated alert configuration files and are described in ibmanager instruction manual
-- @param id - alert identifier - must be defined in current logic configuration file in section: <Alert Id="any_identifier" ...
-- cancelAlert(name)

-- function returns table, containing Variables that belongs to required list.
-- @param listName - Name attribute of VarList, RemoteVarList or ImportVarList elemetnst in configurationfile
-- @return array of key-value pairs. Key - variable postfix, Value - Variable value
-- getVarList(listName)

-- function returns monotonic system clock value, that elapsed since specific epoch
-- returned time is expressed in milliseconds.
-- getClock()

-- function logs message to file, if defined in configuration file log level is less than passed to this function
-- @param logLevel - one of:
--        LogLevel.TraceLo
--        LogLevel.Trace
--        LogLevel.TraceHi
--        LogLevel.DebugLo
--        LogLevel.Debug
--        LogLevel.DebugHi
--        LogLevel.Info
--        LogLevel.Notice
--        LogLevel.Warning
--        LogLevel.Error
--        LogLevel.Critical
-- @param logMessage - string to log
-- log(logLevel, logMessage)


-- ibmanager provides following global variables:

-- logic type, (in this case it will always be "Lua") - the same as in logic configuration file in section: <Logic Type="Lua" ...
-- LOGIC_TYPE

-- logic version, the same as in logic configuration file in section: <Logic ... Version="x.y.z" ...
-- LOGIC_VERSION

-- logic sub-type, the same as in logic configuration file in section: <Logic ... SubType="Hysteresis" ...
-- LOGIC_SUBTYPE

-- logic sub-version, the same as in logic configuration file in section: <Logic ... SubVersion="x.y.z" ...
-- LOGIC_SUBVERSION

-- logic instance name - the same as in logic configuration file, in section: <Instance Name="0">
-- LOGIC_INSTANCE_NAME

-- add script directory to package path
package.path = package.path .. ";./logic/scripts/utils/?.lua";

-- use script - without .lua extension - delta class
require("State");
require("DownCounter");
require("Functions");

SUPPORTED_SUBLOGIC_TYPE = "Recu03";
SUPPORTED_SUBLOGIC_VERSION = "1.0.0";
g_versionChecked = false;

-- entry point to the logic
-- @param firstCall - tells if logic is called first time
-- @return        - nothing
function onLogicCall(firstCall)

  if not g_versionChecked then
    -- checking sublogic type and sublogic version
    if LOGIC_SUBTYPE ~= SUPPORTED_SUBLOGIC_TYPE then
      error("Wrong logic sub-type. expected " .. SUPPORTED_SUBLOGIC_TYPE .. " but used " .. LOGIC_SUBTYPE);
    end
    local versionWithoutBuild = string.match(LOGIC_SUBVERSION, "[0-9]+%.[0-9]+%.[0-9]+");
    if versionWithoutBuild ~= SUPPORTED_SUBLOGIC_VERSION then
      error("Wrong logic sub-version. expected " .. SUPPORTED_SUBLOGIC_VERSION .. " but used " .. LOGIC_SUBVERSION);
    end
    g_versionChecked = true;
  end

  local inputRoomTemperature = getLogicValue("input.room.temperature");
  local inputOutdoorTemperature = getLogicValue("input.outdoor.temperature");
  local inputExhaustTemperature = getLogicValue("input.exhaust.temperature");
  local inputDefrostingTemperature = getLogicValue("input.defrosting.temperature");
  local inputErrors = getLogicValue("input.errors");
  local inputAdditionalSignals = getLogicValue("input.additional.signals");
  local inputFanOperationTimer = getLogicValue("input.fan.operation.timer");
  local inputFilterJamAlarmTimer = getLogicValue("input.filter.jam.alarm.timer");
  local inputSupplyFanSpeed = getLogicValue("input.supply.fan.speed");
  local settingBypassAirdamper = getLogicValue("setting.bypass.airdamper");
  local settingExhaustFanMode = getLogicValue("setting.exhaust.fan.mode");

  local outputExhaustFanSpeed = 0;

  local counterEepromErr = ((inputErrors & 6) ~= 0);
  local outputVentOutTErr = ((inputErrors & 4) ~= 0);
  local outputVentInTErr = ((inputErrors & 3) ~= 0);
  local outputVentExhaustTErr = ((inputErrors & 5) ~= 0);
  local outputDefrostingTErr = 0;

  local counterFireAlert = ((inputAdditionalSignals & 1) ~= 0);
  local counterBypass = ((inputAdditionalSignals & 2) ~= 0);
  local counterDefrosting = ((inputAdditionalSignals & 4) ~= 0);

  local outputVentOutTValue = (inputRoomTemperature-40)*10;
  local outputVentInTValue = (inputOutdoorTemperature-40)*10;
  local outputVentExhaustTValue = (inputExhaustTemperature-40)*10;
  local outputDefrostingTValue = (inputDefrostingTemperature-40)*10;
    
  local outputBypassOpeningTempX = (inputOutdoorTemperature-40);
  local outputBypassOpeningTempY = 2;

  local counterFilterJamAlarm = 0;
  
  if (settingBypassAirdamper == 0) then
    if outputBypassOpeningTempX > 29 then
      outputBypassOpeningTempX = 5;
      outputBypassOpeningTempY = 2;
    else
      outputBypassOpeningTempX = 30;
      outputBypassOpeningTempY = 2;
    end
  else
    outputBypassOpeningTempX = outputBypassOpeningTempX - 1;
    outputBypassOpeningTempY = 15;
  end

  if outputBypassOpeningTempX < 5 then
    outputBypassOpeningTempX = 5;
  end
    
  if outputBypassOpeningTempX > 30 then
    outputBypassOpeningTempX = 5;
  end

  local filterJamAlarmTime = 180;
  if (inputFilterJamAlarmTimer == 0) then
    filterJamAlarmTime = 45;
  elseif (inputFilterJamAlarmTimer == 1) then
    filterJamAlarmTime = 60;
  elseif (inputFilterJamAlarmTimer == 2) then
    filterJamAlarmTime = 90;
  end

  if (inputFanOperationTimer > filterJamAlarmTime) then
    counterFilterJamAlarm = 0;
  end

  if (settingExhaustFanMode == 1) then
    if (inputSupplyFanSpeed == 2) then
      outputExhaustFanSpeed = 0;
    elseif (inputSupplyFanSpeed == 3) then
      outputExhaustFanSpeed = 2;
    elseif (inputSupplyFanSpeed == 5) then
      outputExhaustFanSpeed = 3;
    elseif (inputSupplyFanSpeed == 8) then
      outputExhaustFanSpeed = 5;
    elseif (inputSupplyFanSpeed == 9) then
      outputExhaustFanSpeed = 8;
    elseif (inputSupplyFanSpeed == 10) then
      outputExhaustFanSpeed = 9;
    elseif (inputSupplyFanSpeed == 11) then
      outputExhaustFanSpeed = 10;
    elseif (inputSupplyFanSpeed == 12) then
      outputExhaustFanSpeed = 11;
    elseif (inputSupplyFanSpeed == 13) then
      outputExhaustFanSpeed = 12;
    elseif (inputSupplyFanSpeed == 14) then
      outputExhaustFanSpeed = 13;
    end

    setLogicValue("output.exhaust.fan.speed", outputExhaustFanSpeed);

  end

  -- send logic variables to ibmanager
  setLogicValue("output.vent.out.t.value", outputVentOutTValue);
  setLogicValue("output.vent.out.t.err", outputVentOutTErr);
  setLogicValue("output.vent.in.t.value", outputVentInTValue);
  setLogicValue("output.vent.in.t.err", outputVentInTErr);
  setLogicValue("output.vent.exhaust.t.value", outputVentExhaustTValue);
  setLogicValue("output.vent.exhaust.t.err", outputVentExhaustTErr);
  setLogicValue("output.defrosting.t.value", outputDefrostingTValue);
  setLogicValue("output.defrosting.t.err", outputDefrostingTErr);
  setLogicValue("output.bypass.opening.temp.x", outputBypassOpeningTempX);
  setLogicValue("output.bypass.opening.temp.y", outputBypassOpeningTempY);
  setLogicValue("counter.eeprom.err", counterEepromErr);
  setLogicValue("counter.fire.alert", counterFireAlert);
  setLogicValue("counter.bypass", counterBypass);
  setLogicValue("counter.defrosting", counterDefrosting);
  setLogicValue("counter.filter.jam.alarm", counterFilterJamAlarm);

end
