substitutions:
  ec_k: '0.97090'
  # ec_ref & ec_res2: https://github.com/DFRobot/DFRobot_EC/blob/master/DFRobot_EC.cpp#L28 // https://www.dfrobot.com/forum/topic/28708
  ec_ref: '200.0'
  ec_res2: '820.0'

globals:
  - id: ec_k  # raw V value from probe using EC 1.1413 calibration solution.
    type: float
    restore_value: yes
    initial_value: ${ec_k}
  
sensor:
  - platform: ads1115
    id: analog_ec
    name: "EC: Analog Voltage"
    multiplexer: 'A1_GND'
    gain: 4.096 # max: 3.4V
    update_interval: 5s
    accuracy_decimals: 5
    <<: !include filter.yaml
  # - platform: template
  #   name: "EC: K Value"
  #   unit_of_measurement: "K"
  #   accuracy_decimals: 5
  #   update_interval: 5s
  #   lambda: !lambda return id(ec_k);
  - platform: template
    name: "EC"
    id: ec
    unit_of_measurement: "mS"
    accuracy_decimals: 3
    update_interval: 5s
    lambda: |-
      float ec_raw = id(analog_ec).state / ${ec_res2} / ${ec_ref} * 1000.0 * 1000.0;
      float ec = ec_raw * id(ec_k);
      return ec / (1 + (0.0185 * (id(water_temperature).state - 25)));   // return with temperature correction

button:
  - platform: template
    name: "EC: Calibrate"
    on_press:
      - then:
        - lambda: |-
            float buffer_solution = -1;
            if (id(ec).state > 0.9 && id(ec).state < 1.9) {         //  recognize 1.413us/cm buffer solution
              ESP_LOGI("ec", "Calibrating EC with 1.413 mS/cm solution");
              buffer_solution = 1.413 * (1.0 + 0.0185 * (id(water_temperature).state - 25.0));
            } else if (id(ec).state > 9 && id(ec).state < 16.8) {  // recognize 12.88ms/cm buffer solution
              buffer_solution = 12.88 * (1.0 + 0.0185 * (id(water_temperature).state - 25.0));
              ESP_LOGI("ec", "Calibrating EC with 12.88 mS/cm solution");
            } else {
              ESP_LOGI("ec", "Not calibrating EC, probe not in 1.413 or 12.88 mS/cm solution");
            }
            if(buffer_solution != -1 ) {
              float k = ${ec_res2} * ${ec_ref} * buffer_solution / 1000.0 / 1000.0 / id(analog_ec).state;
              ESP_LOGI("ec", "New K value: %f", k);
              id(ec_k) = k;
            }
