Skip to content

Commit d73197d

Browse files
authored
use filehandler for smarthome (#2817)
* use filehandler for smarthome * fix smarthome
1 parent 708114c commit d73197d

14 files changed

Lines changed: 83 additions & 141 deletions

File tree

packages/modules/smarthome/avmhomeautomation/avmcommon.py

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,8 @@ def __init__(self):
4242
if os.path.isfile(CACHEFILE):
4343
self.logMessage(LOGLEVELDEBUG, "found an AVM cache file, trying to load")
4444
try:
45-
f = open(CACHEFILE, 'r')
46-
self.cache = json.loads(f.read().strip())
47-
f.close()
45+
with open(CACHEFILE, 'r') as f:
46+
self.cache = json.loads(f.read().strip())
4847
except Exception as e:
4948
self.logMessage(LOGLEVELDEBUG, "unable to load cache file: %s" % (e))
5049

@@ -65,9 +64,8 @@ def writeCacheToRamdisk(self):
6564
else:
6665
cacheToWrite[login] = self.cache[login]
6766
try:
68-
f = open(CACHEFILE, 'w')
69-
json.dump(cacheToWrite, f)
70-
f.close()
67+
with open(CACHEFILE, 'w') as f:
68+
json.dump(cacheToWrite, f)
7169
except Exception as e:
7270
self.logMessage(LOGLEVELDEBUG, "unable to write cache file: %s" % (e))
7371

@@ -166,28 +164,7 @@ def connect(self):
166164

167165
# logMessage writes a message to the logfile for the smarthome device.
168166
def logMessage(self, level, message):
169-
if level < self.loglevel:
170-
return
171-
now = time.localtime() # getstruct_time
172-
time_string = time.strftime("%Y-%m-%d %H:%M:%S", now)
173-
logfile_string = '/var/www/html/openWB/ramdisk/smarthome.log'
174-
try:
175-
if os.path.isfile(logfile_string):
176-
f = open(logfile_string, 'a', encoding='utf8')
177-
else:
178-
f = open(logfile_string, 'w', encoding='utf8')
179-
prefix = ""
180-
if level == LOGLEVELDEBUG:
181-
prefix = "[DEBUG] "
182-
if level == LOGLEVELINFO:
183-
prefix = "[INFO] "
184-
if level == LOGLEVELERROR:
185-
prefix = "[ERROR] "
186-
log.debug('%s: (%s) AVM (actor: %s) %s%s' %
187-
(time_string, self.devicenumber, self.switchname, prefix, message), file=f)
188-
f.close()
189-
except IOError:
190-
pass
167+
log.debug(f'({self.devicenumber}) AVM (actor: {self.switchname}) {message}')
191168

192169
# getDevicesDict returns a dictionary that maps defined actor names to its
193170
# unique hardware ID (called "AIN": "Actuator Identification Number") and
@@ -362,9 +339,8 @@ def getActualPower(self):
362339
outFileString = '/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(self.devicenumber)
363340
self.logMessage(LOGLEVELDEBUG, "handing answer back to smarthomehandler via %s" % (outFileString))
364341
try:
365-
f1 = open(outFileString, 'w')
366-
json.dump(answer, f1)
367-
f1.close()
342+
with open(outFileString, 'w') as f1:
343+
json.dump(answer, f1)
368344
except IOError as e:
369345
self.logMessage(LOGLEVELERROR, "error writing power result %s" % (e))
370346
log.debug(answer) # dump answer to stdout if file cannot be written

packages/modules/smarthome/fronius/watt.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
#!/usr/bin/python3
2+
import logging
23
import sys
34
import json
45
import jq
56
import urllib.request
67

8+
log = logging.getLogger(__name__)
9+
710
devicenumber = str(sys.argv[1])
811
ipadr = str(sys.argv[2]) # IP-ADresse des Fronius Wechselrichters, mit dem der Zähler kommuniziert
912
smid = int(sys.argv[3]) # ID des Zählers im Wechselrichter (Hauptzähler 0, weitere fortlaufend)
@@ -27,7 +30,4 @@
2730
except Exception:
2831
powerc = 0
2932

30-
f1 = open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w')
31-
answer = '{"power":' + str(power) + ',"powerc":' + str(powerc) + '}'
32-
json.dump(answer, f1)
33-
f1.close()
33+
log.debug("Device" + str(devicenumber) + '{"power":' + str(power) + ',"powerc":' + str(powerc) + '}')

packages/modules/smarthome/json/watt.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
#!/usr/bin/python3
2+
import logging
23
import sys
34
import json
45
import jq
56
import urllib.request
67

8+
log = logging.getLogger(__name__)
9+
710
devicenumber = str(sys.argv[1])
811
# Abfrage-URL, die die .json Antwort liefert. Z.B.
912
# "http://192.168.0.150/solar_api/v1/GetMeterRealtimeData.cgi?Scope=Device&DeviceID=1"
@@ -26,7 +29,4 @@
2629
except Exception:
2730
powerc = 0
2831

29-
f1 = open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w')
30-
answer = '{"power":' + str(power) + ',"powerc":' + str(powerc) + '}'
31-
json.dump(answer, f1)
32-
f1.close()
32+
log.debug('Device' + str(devicenumber) + '{"power":' + str(power) + ',"powerc":' + str(powerc) + '}')

packages/modules/smarthome/mqtt/off.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,5 @@ def on_message(client, userdata, msg) -> None:
3535
client.disconnect()
3636
file_stringpv = '/var/www/html/openWB/ramdisk/smarthome_device_' + str(devicenumber) + '_pv'
3737
pvmodus = 0
38-
f = open(file_stringpv, 'w')
39-
f.write(str(pvmodus))
40-
f.close()
38+
with open(file_stringpv, 'w') as f:
39+
f.write(str(pvmodus))

packages/modules/smarthome/mqtt/on.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,5 @@ def on_message(client, userdata, msg) -> None:
3434
client.loop(timeout=2.0)
3535
client.disconnect()
3636
file_stringpv = '/var/www/html/openWB/ramdisk/smarthome_device_' + str(devicenumber) + '_pv'
37-
f = open(file_stringpv, 'w')
38-
f.write(str(1))
39-
f.close()
37+
with open(file_stringpv, 'w') as f:
38+
f.write(str(1))

packages/modules/smarthome/mqtt/watt.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,8 @@ def on_message(client, userdata, msg) -> None:
6969
# PV-Modus
7070
pvmodus = 0
7171
if os.path.isfile(file_stringpv):
72-
f = open(file_stringpv, 'r')
73-
pvmodus = int(f.read())
74-
f.close()
72+
with open(file_stringpv, 'r') as f:
73+
pvmodus = int(f.read())
7574
answer = '{"power":' + str(aktpower) + ',"powerc":' + str(powerc)
7675
answer += ',"on":' + str(pvmodus) + ',"temp0":' + str(tempa)
7776
answer += ',"temp1":' + str(tempb) + ',"temp2":' + str(tempc) + '}'

packages/modules/smarthome/mystrom/watt.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
#!/usr/bin/python3
2+
import logging
23
import sys
34
import time
45
import json
56
import urllib.request
67

8+
log = logging.getLogger(__name__)
9+
710
named_tuple = time.localtime() # getstruct_time
811
time_string = time.strftime("%m/%d/%Y, %H:%M:%S mystrom watty.py", named_tuple)
912
devicenumber = str(sys.argv[1])
@@ -21,6 +24,5 @@
2124
powerc = 0
2225
answer = '{"power":' + str(aktpower) + ',"powerc":' + str(powerc) + ',"on":' + \
2326
str(relais) + ',"temp0":' + str(temp) + '} '
24-
f1 = open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w')
25-
json.dump(answer, f1)
26-
f1.close()
27+
with open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w') as f1:
28+
log.debug('Device' + str(devicenumber) + ' ' + answer)

packages/modules/smarthome/nibe/watt.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
CurrentPower = None # Handle error case
3030

3131
answer = '{"power":' + str(CurrentPower) + '}'
32-
f1 = open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w')
33-
json.dump(answer, f1)
34-
f1.close()
32+
with open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w') as f1:
33+
json.dump(answer, f1)
3534

3635
client.close() # clean disconnect from modbus server

packages/modules/smarthome/smaem/watt.py

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
import os
3434
import datetime
3535
import time
36-
import json
3736
import signal
3837
import socket
3938
import struct
@@ -68,7 +67,7 @@ def abortprogram(signal, frame):
6867
timefile = '/var/www/html/openWB/ramdisk/smarthome_device_ret' + \
6968
str(devicenumber) + '_time' # Dummy file needed for timestamp of last metering
7069
# Logfile for additional output beside of the smarthome.log
71-
debugfile = open('/var/www/html/openWB/ramdisk/smaem.log', 'a', newline='\r\n')
70+
7271

7372
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
7473
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -108,18 +107,18 @@ def abortprogram(signal, frame):
108107
"HomeManager (2) is sending in the network.")
109108

110109
emparts = decode_speedwire(sock_data)
111-
debugfile.write(str(datetime.datetime.now()) + ': smaserial: #' + str(smaserial) + '# - Current SMA serial number:#' +
112-
str(emparts['serial']) + '# - watt:#' + str(int(emparts.get("pconsume"))) + '# - wattc:#' +
113-
str("{:.3f}".format(int(emparts.get('pconsumecounter')*1000))) + '#\n')
110+
log.debug('SMA:: smaserial: #' + str(smaserial) + '# - Current SMA serial number:#' +
111+
str(emparts['serial']) + '# - watt:#' + str(int(emparts.get("pconsume"))) + '# - wattc:#' +
112+
str("{:.3f}".format(int(emparts.get('pconsumecounter')*1000))) + '#')
114113

115114
# Remember: We assume that beside of our EnergyMeter there are more SMA devices present (like HomeManager 2.0 or other
116115
# EnergyMeter) - so must not accept any data or smaserial = None
117116
if str(emparts['serial']) == str(smaserial): # Scenario 1: Our EnergyMeter is sending, so we put the current values in
118117
# our output variables
119118
watt = str(int(emparts.get("pconsume")))
120119
wattc = str("{:.3f}".format(int(emparts.get('pconsumecounter')*1000)))
121-
debugfile.write(str(datetime.datetime.now()) + ': 1 - Our SMA EM ' + str(smaserial) +
122-
' is sending, everything fine. watt: #' + str(watt) + '# - wattc: #' + str(wattc) + '#\n')
120+
log.debug('SMA:: 1 - Our SMA EM ' + str(smaserial) +
121+
' is sending, everything fine. watt: #' + str(watt) + '# - wattc: #' + str(wattc) + '#')
123122
# Scenario 2: Our EnergyMeter is not sending but we have a returnfile which is older than n seconds (parameter
124123
# secondssincelastmetering)
125124
elif ((os.path.isfile(returnfile)) and
@@ -128,29 +127,27 @@ def abortprogram(signal, frame):
128127
# We set "0" as current Power Consume (pconsume) and (from the existing ret-file) the last value for the Power
129128
# Consume Counter (pconsumecounter)
130129
watt = '0'
131-
ret = open(returnfile, 'r')
132-
lastvalues = ret.read()
133-
ret.close()
130+
with open(returnfile, 'r') as ret:
131+
lastvalues = ret.read()
134132
timesincelastmetering = int(round(time.time(), 0)-lastmodificationtime)
135133
wattc = lastvalues[int(lastvalues.rfind('powerc')) + 9:lastvalues.find('}')]
136-
debugfile.write(str(datetime.datetime.now()) + ': 2 - Debug: time.time(): #' + str(round(time.time(), 0)) +
137-
'# - lastmodificationtime: #' + str(lastmodificationtime) +
138-
'# - timesincelastmetering: #' + str(timesincelastmetering) +
139-
'# - int(secondssincelastmetering): #' + str(int(secondssincelastmetering)) + '#\n')
140-
debugfile.write(str(datetime.datetime.now()) + ': 2 - We create a fake ret-file. watt: #' + str(watt) +
141-
'# - wattc: #' + str(
134+
log.debug('SMA:: 2 - Debug: time.time(): #' + str(round(time.time(), 0)) +
135+
'# - lastmodificationtime: #' + str(lastmodificationtime) +
136+
'# - timesincelastmetering: #' + str(timesincelastmetering) +
137+
'# - int(secondssincelastmetering): #' + str(int(secondssincelastmetering)) + '#')
138+
log.debug('SMA:: 2 - We create a fake ret-file. watt: #' + str(watt) +
139+
'# - wattc: #' + str(
142140
wattc) + '# - lastvalues: #' + lastvalues + '# - int-lastvalues.rfind-powerc: #' +
143-
str((lastvalues.rfind('powerc'))) + '#\n')
141+
str((lastvalues.rfind('powerc'))) + '#')
144142

145143
# Scenario 3: Our EnergyMeter is not sending but we have a returnfile which is younger than n seconds
146144
# (parameter secondssincelastmetering)
147145
elif ((os.path.isfile(returnfile)) and
148146
(int((round(time.time(), 0)-lastmodificationtime)) < int(secondssincelastmetering))):
149147
# We have a ret-file which is younger than n seconds. We do nothing as the existing ret-file is good enough.
150-
debugfile.write(str(datetime.datetime.now()) +
151-
': 3 - The existing ret-file is fine enough. round(time.time(),0): #' + str(round(time.time(), 0))
152-
+ '# - lastmodificationtime: #' + str(lastmodificationtime) + '# - secondssincelastmetering: #'
153-
+ str(secondssincelastmetering) + '#\n')
148+
log.debug('SMA:: 3 - The existing ret-file is fine enough. round(time.time(),0): #' + str(round(time.time(), 0))
149+
+ '# - lastmodificationtime: #' + str(lastmodificationtime) + '# - secondssincelastmetering: #'
150+
+ str(secondssincelastmetering) + '#')
154151
sys.exit("Module SMAEM: No data received but we have historical data which is younger than " +
155152
str(secondssincelastmetering) + " seconds.")
156153
else:
@@ -162,20 +159,16 @@ def abortprogram(signal, frame):
162159
# Module SMAEM: No data received and no historical data since boot time
163160
# Leistungsmessung smaem [...] Fehlermeldung: [Errno 2] No such file or directory:
164161
# '/var/www/html/openWB/ramdisk/smarthome_device_ret1'
165-
debugfile.write(str(datetime.datetime.now()) + ': 4 - No data received and no historical data since boottime\n')
162+
log.debug('SMA:: 4 - No data received and no historical data since boottime')
166163
sys.exit(str(datetime.datetime.now()) + ": Module SMAEM: No data received and no historical data since boottime")
167164

168165
# General output section
169166

170167
answer = '{"power":' + watt + ',"powerc":' + wattc + '}'
171-
f = open(returnfile, 'w')
172-
json.dump(answer, f)
173-
f.close()
174168

175-
t = open(timefile, 'w')
176-
t.write(str(datetime.datetime.now()) +
177-
': File is created by Smarthome module SMAEM for validating the timestamp of the last return-file creation.')
178-
t.close()
169+
with open(timefile, 'w') as t:
170+
t.write(str(datetime.datetime.now()) +
171+
': File is created by Smarthome module SMAEM for validating '
172+
'the timestamp of the last return-file creation.')
179173

180-
debugfile.write(str(datetime.datetime.now()) + ': 99 - Output answer: #' + answer + '#\n')
181-
debugfile.close()
174+
log.debug('SMA:: 99 - Output answer: #' + answer + '#')

packages/modules/smarthome/tasmota/watt.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,5 @@
2626
relais = 1
2727
powerc = 0
2828
answer = '{"power":' + str(aktpower) + ',"powerc":' + str(powerc) + ',"on":' + str(relais) + '} '
29-
f1 = open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w')
30-
json.dump(answer, f1)
31-
f1.close()
29+
with open('/var/www/html/openWB/ramdisk/smarthome_device_ret' + str(devicenumber), 'w') as f1:
30+
json.dump(answer, f1)

0 commit comments

Comments
 (0)