-
Notifications
You must be signed in to change notification settings - Fork 1
/
eliq2pvoutput
executable file
·182 lines (151 loc) · 5.83 KB
/
eliq2pvoutput
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
#!/usr/bin/env python3
# Copyright (c) 2016 Erik Johansson <erik@ejohansson.se>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
from eliq import EliqOnline
from pvoutput import PvOutput, DefaultStatus
from datetime import date, datetime, time, timedelta
import argparse
import configparser
import logging
import sqlite3
def initialize_database(path):
conn = sqlite3.connect(path, detect_types=sqlite3.PARSE_COLNAMES)
cur = conn.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS eliq_day_data
(date TEXT PRIMARY KEY, avgpower INTEGEAR, energy INTEGEAR)"""
)
cur.execute(
"""CREATE TABLE IF NOT EXISTS eliq_6min_data
(timestamp TEXT PRIMARY KEY, avgpower INTEGEAR, energy INTEGEAR)"""
)
conn.commit()
return conn
def save_day_data(conn, eliq, channel_id):
cur = conn.cursor()
result = cur.execute(
"""SELECT date as "date [date]" FROM eliq_day_data
ORDER BY date DESC LIMIT 1"""
)
start = result.fetchone()
if start is not None:
# Start at the next day
start = start[0] + timedelta(days=1)
else:
# Default is to start one month back
start = date.today() - timedelta(days=30)
end = date.today()
entries = []
while start < end:
data = eliq.get_day_data(start, end, channel_id)
for entry in data.data:
assert (entry.time_end - entry.time_start).days == 1
entries.append(
(entry.time_start.date(), int(entry.avgpower), int(entry.energy))
)
start = data.enddate.date()
if entries:
cur.executemany("INSERT INTO eliq_day_data VALUES (?, ?, ?)", entries)
conn.commit()
def save_6min_data(conn, eliq, channel_id):
cur = conn.cursor()
result = cur.execute(
"""SELECT timestamp as "timestamp [timestamp]"
FROM eliq_6min_data ORDER BY timestamp DESC LIMIT 1"""
)
start = result.fetchone()
if start is not None:
start = start[0]
else:
# Try to get start date from eliq_day_data instead
result = cur.execute(
"""SELECT date as "date [date]" FROM eliq_day_data
ORDER BY date ASC LIMIT 1"""
)
start = result.fetchone()
if start is not None:
start = datetime.combine(start[0], time())
if start is None:
start = datetime.now() - timedelta(days=1)
end = datetime.now().replace(second=0, microsecond=0)
end = end - timedelta(minutes=5)
while start < end:
entries = []
data = eliq.get_6min_data(start, (start + timedelta(days=1)).date(), channel_id)
for entry in data.data:
assert entry.time_start.date() == entry.time_end.date() or entry.time_end.time() == time(
0, 0, 0
)
entries.append((entry.time_end, int(entry.avgpower), int(entry.energy)))
start = data.enddate
cur.executemany("INSERT INTO eliq_6min_data VALUES (?, ?, ?)", entries)
conn.commit()
def main():
logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s")
parser = argparse.ArgumentParser(description="Connect ELIQ Online to PVoutput.org")
parser.add_argument("config", help="Configuration file to use")
parser.add_argument("database", help="Path to database")
parser.add_argument(
"-d", "--debug", help="Enable debug output", action="store_true"
)
parser.add_argument(
"-n", "--dry-run", help="Don't send any data", action="store_true"
)
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
config = configparser.ConfigParser()
config["eliq"] = {}
config["pvoutput"] = {}
config.read(args.config)
modified = False
if not config["eliq"].get("accesstoken"):
config["eliq"]["accesstoken"] = input("ELIQ Online access token: ")
modified = True
if not config["eliq"].get("channelid"):
config["eliq"]["channelid"] = input("ELIQ Online channel ID: ")
modified = True
if not config["pvoutput"].get("apikey"):
config["pvoutput"]["apikey"] = input("PVOutput API key: ")
modified = True
if not config["pvoutput"].get("systemid"):
config["pvoutput"]["systemid"] = input("PVOutput System Id: ")
modified = True
if modified:
with open(args.config, "w") as configfile:
config.write(configfile)
conn = initialize_database(args.database)
eliq = EliqOnline(config["eliq"]["accesstoken"])
# Update eliq data
save_day_data(conn, eliq, config["eliq"]["channelid"])
save_6min_data(conn, eliq, config["eliq"]["channelid"])
pvoutput = PvOutput(
config["pvoutput"]["apikey"], config["pvoutput"]["systemid"], args.dry_run
)
cur = conn.cursor()
result = cur.execute(
"""SELECT timestamp as "timstamp [timestamp]", sum(energy), avgpower
from eliq_6min_data WHERE date(timestamp) = date("now")"""
)
if result is not None:
data = result.fetchone()
status = DefaultStatus._replace(
datetime=data[0], energy_consumption=data[1], power_consumption=data[2]
)
pvoutput.add_status(status, net=True)
if __name__ == "__main__":
main()