-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshelly.py
215 lines (176 loc) · 8.05 KB
/
shelly.py
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
# HTTP interface between Shelly device & EmonCMS
#
# coded by: Emmanuel Havet
# --------------------------------------------------------------------------- #
# Dependencies
# --------------------------------------------------------------------------- #
import os
import requests
import json
from pathlib import Path
from configparser import ConfigParser
from datetime import datetime
from time import sleep
import time
# --------------------------------------------------------------------------- #
# Globals
# --------------------------------------------------------------------------- #
version = "v1.0.0"
ConfFile = str(Path(__file__).parent.absolute() / 'shelly.conf')
Config = None
Shellycfg = None
Emoncfg = None
data = None
Shellydata = None
debug = False
senddata = False
# --------------------------------------------------------------------------- #
# Functions - configuration
# --------------------------------------------------------------------------- #
def getConfig(file):
global Shellycfg, Emoncfg, debug, Config, senddata
if os.path.isfile(file):
Config = ConfigParser()
Config.read(file)
if (debug): print(Config.sections())
Emoncfg = dict(Config['emoncms'])
Emoncfg['enabled'] = str2bool(Emoncfg['enabled'])
Shellycfg = dict(Config['shellypro3em'])
Shellycfg['enabled'] = str2bool(Shellycfg['enabled'])
debug = Config['general'].getboolean('debug')
senddata = Config['general'].getboolean('senddata')
if (debug):
print(f'Emoncfg: {Emoncfg}')
print(f'Shellycfg: {Shellycfg}')
return True
else:
print(f'No config file found {file}')
return False
def setConfig():
global Config, ConfFile
with open(ConfFile, 'w') as configfile:
Config.write(configfile)
return
# --------------------------------------------------------------------------- #
# Functions - Shelly pro 3 EM
# --------------------------------------------------------------------------- #
def getShellydata():
global Shellydata, Shellycfg, debug
if(Shellycfg['enabled']):
params = dict(id=0)
url = f"{Shellycfg['url']}{Shellycfg['r_data_uri']}?id=0"
if (debug): printDebug('Shelly data url', url)
#Shellydata = requests.get(url, headers={'Content-Type': 'application/json'})
Shellydata = dict(requests.get(url, headers={'Content-Type': 'application/json'}).json())
if (debug): printDebug('Shelly data', Shellydata)
return
else:
# test data
s = '{"id":0,"a_current":4.029,"a_voltage":236.1,"a_act_power":951.2,"a_aprt_power":951.9,"a_pf":1,"a_freq":50,"b_current":4.027,"b_voltage":236.201,"b_act_power":-951.1,"b_aprt_power":951.8,"b_pf":1,"b_freq":50,"c_current":3.03,"c_voltage":236.402,"c_active_power":715.4,"c_aprt_power":716.2,"c_pf":1,"c_freq":50,"n_current":11.029,"total_current":11.083,"total_act_power":2484.782,"total_aprt_power":2486.7,"user_calibrated_phase":[],"errors":["phase_sequence"]}'
Shellydata = dict(s)
return
def toggleShellyswitch(command = 'off'):
global Shellycfg, senddata, debug
if(Shellycfg['enabled'] and command in ("on", "off", "toggle")):
url = f"{Shellycfg['url']}relay/{Shellycfg['relay_id']}?turn={command}"
if (debug): printDebug('Shelly Switch', url)
if (senddata):
resp = requests.get(url, headers={'Content-Type': 'application/json'})
if (debug): printDebugHttp('Shelly Switch', resp)
return
else:
if (debug):
printDebug('Shelly enabled', Shellycfg['enabled'])
printDebug('Shelly Switch command', command)
return
# --------------------------------------------------------------------------- #
# Functions - energy routing limitation
#
# 2 options to manage the routing energy quantity.
# a- using solcast to get power generation forecast.
# b- using ECS temperature
# c- using routed energy
#
# The ideal is using a combination of the 3 data
#
# --------------------------------------------------------------------------- #
def getDailyProd():
#from feed
#returns value in Wh https://identity-dev.mobifactory.net
global Emoncfg, debug
url = Emoncfg['url']+Emoncfg['r_uri_dailyenergy']+str(todayMidnight())+'&apikey='+Emoncfg['apikey']
if (debug): printDebug('EmonURL energy', url)
resp = requests.get(url)
if (debug): printDebugHttp('Daily Energy', resp)
return float(resp.text) * 1000
def getDailyProd2():
#from input {'time': 1717015802, 'value': 14.68, 'processList': ''}
#returns value in Wh
global Emoncfg, debug
url = Emoncfg['url']+Emoncfg['r_uri_daily2']+'?apikey='+Emoncfg['apikey']
if (debug): printDebug('EmonURL energy', url)
resp = requests.get(url)
if (debug): printDebugHttp('Daily Energy', resp)
return float(resp.json()['value']) * 1000
def limitFromProduction():
# --------------------------------------------------------------------------- #
# Functions - utils funtions
# --------------------------------------------------------------------------- #
def str2bool(v):
return v.lower() in ("true", "t")
def remapKeys(data, remap, allkeys = False):
if(allkeys):
# return all keys from data and remap selected keys
return dict((remap[key], data[key]) if key in remap else (key, value) for key, value in data.items())
else:
# return only selected keys in remapping
return dict((remap[key], data[key]) for key, value in data.items() if key in remap)
def printDebugHttp (sentto, requestObject):
print(f'{sentto} data sent: {requestObject}')
print(f'response: {requestObject.json()}\n')
return
def printDebug(message, data):
print(f'{message}: {data}\n')
return
# --------------------------------------------------------------------------- #
# Functions - send data to outside world
# --------------------------------------------------------------------------- #
def sendEmonCMS(data):
global Emoncfg, debug, senddata
if(Emoncfg['enabled']):
if ('user_calibrated_phase' in data): data.pop('user_calibrated_phase') #not managed by EmonCMS
if ('errors' in data): data.pop('errors') #not managed by EmonCMS
if (debug): printDebug('Emondata', data)
params = dict(node=Emoncfg['nodename_shelly'], fulljson=json.dumps(data), apikey=Emoncfg['apikey'])
if (senddata):
res = requests.get(Emoncfg['url']+Emoncfg['uri_senddata'], params=params)
if (debug):
printDebugHttp('Emon data sent', res)
else:
return
# --------------------------------------------------------------------------- #
# Functions - rate export to platforms limit management
# --------------------------------------------------------------------------- #
def setNextResetAllowedTime():
global Config
#Tomorrow timestamp 00:00
next = datetime.strptime(str(datetime.today().strftime('%Y-%m-%d')) + ' 00:00:00', '%Y-%m-%d %H:%M:%S').timestamp() + 86400
#Set tomorrow at the conf hour
Config['shellypro3em']['next_relay_reset'] = str(next)
setConfig()
def todayMidnight():
return int(datetime.strptime(str(datetime.today().strftime('%Y-%m-%d')) + ' 00:00:00', '%Y-%m-%d %H:%M:%S').timestamp())
def todayNow():
return int(datetime.today().timestamp())
# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
if(getConfig(ConfFile)):
#getShellydata()
#toggleShellyswitch('toto')
#sendEmonCMS(Shellydata) #send data to EmonCMS
print( getDailyProd())
print(getDailyProd2())
else:
print('Can do nothing, no config found')