summaryrefslogtreecommitdiff
path: root/src/home/database/inverter.py
blob: 8ebfae262b3e2700f5bcc062cfc8f285eb4142e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import logging

from zoneinfo import ZoneInfo
from time import time
from datetime import datetime, timedelta
from typing import Optional
from collections import namedtuple

from ..config import is_development_mode
from .clickhouse import get_clickhouse


IntervalList = list[list[Optional[datetime]]]


class InverterDatabase:
    def __init__(self):
        self.db = get_clickhouse('solarmon')
        self.server_timezone = self.query('SELECT timezone()')[0][0]

        self.logger = logging.getLogger(self.__class__.__name__)

    def query(self, *args, **kwargs):
        settings = {'use_client_time_zone': True}
        kwargs['settings'] = settings

        if 'no_tz_fix' not in kwargs and len(args) > 1 and isinstance(args[1], dict):
            for k, v in args[1].items():
                if isinstance(v, datetime):
                    args[1][k] = v.astimezone(tz=ZoneInfo(self.server_timezone))

        result = self.db.execute(*args, **kwargs)

        if is_development_mode():
            self.logger.debug(args[0] if len(args) == 1 else args[0] % args[1])

        return result

    def add_generation(self, home_id: int, client_time: int, watts: int) -> None:
        self.db.execute(
            'INSERT INTO generation (ClientTime, ReceivedTime, HomeID, Watts) VALUES',
            [[client_time, round(time()), home_id, watts]]
        )

    def add_status(self, home_id: int,
                   client_time: int,
                   grid_voltage: int,
                   grid_freq: int,
                   ac_output_voltage: int,
                   ac_output_freq: int,
                   ac_output_apparent_power: int,
                   ac_output_active_power: int,
                   output_load_percent: int,
                   battery_voltage: int,
                   battery_voltage_scc: int,
                   battery_voltage_scc2: int,
                   battery_discharge_current: int,
                   battery_charge_current: int,
                   battery_capacity: int,
                   inverter_heat_sink_temp: int,
                   mppt1_charger_temp: int,
                   mppt2_charger_temp: int,
                   pv1_input_power: int,
                   pv2_input_power: int,
                   pv1_input_voltage: int,
                   pv2_input_voltage: int,
                   mppt1_charger_status: int,
                   mppt2_charger_status: int,
                   battery_power_direction: int,
                   dc_ac_power_direction: int,
                   line_power_direction: int,
                   load_connected: int) -> None:
        self.db.execute("""INSERT INTO status (
            ClientTime,
            ReceivedTime,
            HomeID,
            GridVoltage,
            GridFrequency,
            ACOutputVoltage,
            ACOutputFrequency,
            ACOutputApparentPower,
            ACOutputActivePower,
            OutputLoadPercent,
            BatteryVoltage,
            BatteryVoltageSCC,
            BatteryVoltageSCC2,
            BatteryDischargingCurrent,
            BatteryChargingCurrent,
            BatteryCapacity,
            HeatSinkTemp,
            MPPT1ChargerTemp,
            MPPT2ChargerTemp,
            PV1InputPower,
            PV2InputPower,
            PV1InputVoltage,
            PV2InputVoltage,
            MPPT1ChargerStatus,
            MPPT2ChargerStatus,
            BatteryPowerDirection,
            DCACPowerDirection,
            LinePowerDirection,
            LoadConnected) VALUES""", [[
            client_time,
            round(time()),
            home_id,
            grid_voltage,
            grid_freq,
            ac_output_voltage,
            ac_output_freq,
            ac_output_apparent_power,
            ac_output_active_power,
            output_load_percent,
            battery_voltage,
            battery_voltage_scc,
            battery_voltage_scc2,
            battery_discharge_current,
            battery_charge_current,
            battery_capacity,
            inverter_heat_sink_temp,
            mppt1_charger_temp,
            mppt2_charger_temp,
            pv1_input_power,
            pv2_input_power,
            pv1_input_voltage,
            pv2_input_voltage,
            mppt1_charger_status,
            mppt2_charger_status,
            battery_power_direction,
            dc_ac_power_direction,
            line_power_direction,
            load_connected
        ]])

    def get_consumed_energy(self, dt_from: datetime, dt_to: datetime) -> float:
        rows = self.query('SELECT ClientTime, ACOutputActivePower FROM status'
                          ' WHERE ClientTime >= %(from)s AND ClientTime <= %(to)s'
                          ' ORDER BY ClientTime', {'from': dt_from, 'to': dt_to})
        prev_time = None
        prev_wh = 0

        ws = 0  # watt-seconds
        for t, wh in rows:
            if prev_time is not None:
                n = (t - prev_time).total_seconds()
                ws += prev_wh * n

            prev_time = t
            prev_wh = wh

        return ws / 3600  # convert to watt-hours

    def get_intervals_by_condition(self,
                                   dt_from: datetime,
                                   dt_to: datetime,
                                   cond_start: str,
                                   cond_end: str) -> IntervalList:
        rows = None
        ranges = [[None, None]]

        while rows is None or len(rows) > 0:
            if ranges[len(ranges) - 1][0] is None:
                condition = cond_start
                range_idx = 0
            else:
                condition = cond_end
                range_idx = 1

            rows = self.query('SELECT ClientTime FROM status '
                              f'WHERE ClientTime > %(from)s AND ClientTime <= %(to)s AND {condition}'
                              ' ORDER BY ClientTime LIMIT 1',
                              {'from': dt_from, 'to': dt_to})
            if not rows:
                break

            row = rows[0]

            ranges[len(ranges) - 1][range_idx] = row[0]
            if range_idx == 1:
                ranges.append([None, None])

            dt_from = row[0]

        if ranges[len(ranges)-1][0] is None:
            ranges.pop()

        return ranges

    def get_grid_connected_intervals(self, dt_from: datetime, dt_to: datetime) -> IntervalList:
        return self.get_intervals_by_condition(dt_from, dt_to, 'GridFrequency > 0', 'GridFrequency = 0')

    def get_grid_used_intervals(self, dt_from: datetime, dt_to: datetime) -> IntervalList:
        return self.get_intervals_by_condition(dt_from,
                                               dt_to,
                                               "LinePowerDirection = 'Input'",
                                               "LinePowerDirection != 'Input'")

    def get_grid_consumed_energy(self, dt_from: datetime, dt_to: datetime) -> float:
        PrevData = namedtuple('PrevData', 'time, pd, bat_chg, bat_dis, wh')

        ws = 0  # watt-seconds
        amps = 0  # amper-seconds

        intervals = self.get_grid_used_intervals(dt_from, dt_to)
        for dt_start, dt_end in intervals:
            fields = ', '.join([
                'ClientTime',
                'DCACPowerDirection',
                'BatteryChargingCurrent',
                'BatteryDischargingCurrent',
                'ACOutputActivePower'
            ])
            rows = self.query(f'SELECT {fields} FROM status'
                              ' WHERE ClientTime >= %(from)s AND ClientTime < %(to)s ORDER BY ClientTime',
                              {'from': dt_start, 'to': dt_end})

            prev = PrevData(time=None, pd=None, bat_chg=None, bat_dis=None, wh=None)
            for ct, pd, bat_chg, bat_dis, wh in rows:
                if prev.time is not None:
                    n = (ct-prev.time).total_seconds()
                    ws += prev.wh * n

                    if pd == 'DC/AC':
                        amps -= prev.bat_dis * n
                    elif pd == 'AC/DC':
                        amps += prev.bat_chg * n

                prev = PrevData(time=ct, pd=pd, bat_chg=bat_chg, bat_dis=bat_dis, wh=wh)

        amps /= 3600
        wh = ws / 3600
        wh += amps*48

        return wh