DROP FUNCTION IF EXISTS ems.fn_telemetry_inverter_sample;

CREATE OR REPLACE FUNCTION ems.fn_telemetry_inverter_sample(
  p_site_id int,
  p_inverter_id int,
  p_measured_at timestamptz,
  p_pv_power_w int,
  p_pv1_power_w int,
  p_pv2_power_w int,
  p_gen_port_power_w int,
  p_battery_soc_percent double precision,
  p_battery_power_w int,
  p_batt_charge_today_wh int,
  p_batt_discharge_today_wh int,
  p_grid_power_w int,
  p_load_power_w int,
  p_grid_import_total_wh bigint,
  p_grid_export_total_wh bigint,
  p_run_state int,
  p_is_export_limited boolean DEFAULT NULL,
  p_pv_derating_flags int DEFAULT NULL,
  p_inverter_grid_port_w int DEFAULT NULL,
  p_ups_load_w int DEFAULT NULL
)
RETURNS void
LANGUAGE sql
AS $fn$
  INSERT INTO ems.telemetry_inverter (
    site_id,
    inverter_id,
    measured_at,
    pv_power_w,
    pv1_power_w,
    pv2_power_w,
    gen_port_power_w,
    battery_soc_percent,
    battery_power_w,
    batt_charge_today_wh,
    batt_discharge_today_wh,
    grid_power_w,
    load_power_w,
    grid_import_total_wh,
    grid_export_total_wh,
    run_state,
    is_export_limited,
    pv_derating_flags,
    inverter_grid_port_w,
    ups_load_w
  )
  VALUES (
    p_site_id,
    p_inverter_id,
    p_measured_at,
    p_pv_power_w,
    p_pv1_power_w,
    p_pv2_power_w,
    p_gen_port_power_w,
    p_battery_soc_percent,
    p_battery_power_w,
    p_batt_charge_today_wh,
    p_batt_discharge_today_wh,
    p_grid_power_w,
    p_load_power_w,
    p_grid_import_total_wh,
    p_grid_export_total_wh,
    p_run_state,
    p_is_export_limited,
    p_pv_derating_flags,
    p_inverter_grid_port_w,
    p_ups_load_w
  )
  ON CONFLICT (inverter_id, measured_at) DO NOTHING;
$fn$;

COMMENT ON FUNCTION ems.fn_telemetry_inverter_sample IS
  'Insert jednoho vzorku telemetrie střídače (telemetry_collector). grid_power_w = ulice (CT reg 619 u instalací s CT, jinak reg 625); load_power_w = celková spotřeba domu (dopočet); inverter_grid_port_w = reg 625; ups_load_w = reg 653.';
