Compare commits

...

14 Commits

Author SHA1 Message Date
Thomas Kolb 26cda2c4ae Improved handling of unavailable devices 2020-01-20 12:09:11 +01:00
Thomas Kolb 9d51def740 First version of collectd plugin 2020-01-19 20:10:07 +01:00
Thomas Kolb ff904d0cd7 Merge branches 'power_factor' and 'gitignore' into collectd 2020-01-19 18:46:43 +01:00
Thomas Kolb 64673d3ff3 Ignore some files in Git
Specifically compiled Python code and Vim swap files.
2020-01-19 17:57:34 +01:00
Thomas Kolb 7b82461f03 example: restart on BrokenPipeError 2020-01-19 17:48:02 +01:00
Thomas Kolb 2f13d6f6a5 example: print power factor 2020-01-19 17:46:55 +01:00
Thomas Kolb 01cc1ed9b7 example: removed invalid constructor argument 2020-01-19 17:34:57 +01:00
Thomas Kolb 8f06b28f31 Added power factor calculation 2020-01-19 17:34:18 +01:00
sqozz d824a93c5b Merge branch 'remove_reconnect' of sqozz/sem6000 into master 2020-01-17 11:43:45 +01:00
sqozz e38d6abb12 Remove automatic reconnect 2020-01-17 11:43:45 +01:00
sqozz d0a57f483e Merge branch 'shebang' of cfr34k/sem6000 into master 2020-01-16 19:08:41 +01:00
Thomas Kolb 50cb935f80 Add shebang to example script 2020-01-16 18:50:34 +01:00
sqozz 60199338bf Merge branch 'improved_reconnect' of cfr34k/sem6000 into master 2020-01-16 18:43:20 +01:00
Thomas Kolb 2378f52a7e Reliable reconnect in user script 2020-01-16 14:50:48 +01:00
5 changed files with 245 additions and 30 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
__pycache__/
*.pyc
.*.sw?

View File

@ -1,3 +1,11 @@
# SEM6000 Python Library
SEM6000 is a energy meter and power switch with Bluetooth 4.0.
This library provides a Python module for these devices
## Run the example code
```
$ git clone … sem6000
$ cd sem6000
@ -5,4 +13,52 @@ $ virtualenv -p python3 python3_venv
$ . ./python3_venv/bin/activate
$ pip3 install -r requirements.txt
$ python3 example.py
```
```
## Collectd Plugin
You can find a Plugin for [collectd](https://collectd.org) in the `collectd`
subdirectory.
Installation procedure (the target directory may be changed of course):
```shell
# mkdir -p /usr/local/lib/collectd/python
# cp collectd/collectd_sem6000.py /usr/local/lib/collectd/python
# cp sem6000.py /usr/local/lib/collectd/python
```
Add or adjust the configuration for your collectds Python plugin as follows:
```
<Plugin python>
ModulePath "/usr/local/share/collectd/python"
LogTraces true
Interactive false
Import "collectd_sem6000"
<Module collectd_sem6000>
Address "12:34:56:78:90:ab"
SocketName "FirstSocket"
ReadTimeout 30
SuspendTime 300
</Module>
<Module collectd_sem6000>
Address "ab:cd:ef:13:37:42"
SocketName "ASecondSocket"
</Module>
# ...
</Plugin>
```
`ReadTimeout` and `SuspendTime` control whats happening when a device is
unavailable. If no value could be retrieved for `ReadTimeout` seconds, the
plugin does not retry for `SuspendTime` seconds. After that, normal operation
is resumed. This procedure ensures that an unreachable device does not block
other devices (too often) in the current single-threaded architecture.
If not specified, `ReadTimeout` is 30 seconds and `SuspendTime` is 5 minutes.
Make sure that everything listed in `requirements.txt` is available to the user
running collectd.

144
collectd/collectd_sem6000.py Executable file
View File

@ -0,0 +1,144 @@
#!/usr/bin/env python3
# coding: utf-8
# vim: noet ts=2 sw=2 sts=2
import os
import time
import collectd
from sem6000 import SEMSocket
import bluepy
instances = []
def init_func():
pass
def config_func(cfg):
global instances
config = {}
for node in cfg.children:
key = node.key.lower()
value = node.values[0]
if key in ['address', 'socketname']:
config[key] = value
if key == 'readtimeout':
config['readtimeout'] = int(value)
if key == 'suspendtime':
config['suspendtime'] = int(value)
if 'address' not in config.keys():
collectd.error('sem6000: address must be set')
return
if 'socketname' not in config.keys():
config['socketname'] = config['address'].replace(':', '')
if 'readtimeout' not in config.keys():
config['readtimeout'] = 30
if 'suspendtime' not in config.keys():
config['suspendtime'] = 300
instances.append( {
'config': config,
'socket': None,
'suspended': False,
'lastsuccess': 0,
'resumetime': 0
} )
def read_func():
global instances
for inst in instances:
config = inst['config']
if inst['suspended']:
if time.time() < inst['resumetime']:
continue
else:
collectd.info("sem6000: Device {} waking up.".format(config['address']))
inst['suspended'] = False
inst['lastsuccess'] = time.time()
try:
if inst['socket'] == None:
collectd.info("sem6000: Connecting to {}...".format(config['address']))
inst['socket'] = SEMSocket(config['address'])
collectd.info("sem6000: Connected.")
inst['socket'].getStatus()
except (SEMSocket.NotConnectedException, bluepy.btle.BTLEDisconnectError, BrokenPipeError) as e:
collectd.warning("sem6000: Exception caught: {}".format(e))
collectd.warning("sem6000: Restarting on next cycle...")
if inst['lastsuccess'] < time.time() - config['readtimeout']:
collectd.error("sem6000: no successful communication with {} for {:.1f} seconds. Suspending device for {:.1f} seconds.".format(
config['address'], config['readtimeout'], config['suspendtime']))
inst['suspended'] = True
inst['resumetime'] = time.time() + config['suspendtime']
if inst['socket'] != None:
inst['socket'].disconnect()
inst['socket'] = None
socket = inst['socket']
if socket != None and socket.voltage != 0:
collectd.debug("Uploading values for {}".format(socket.mac_address))
inst['lastsuccess'] = time.time()
val = collectd.Values(plugin = 'sem6000-{}'.format(config['socketname']))
val.type = 'voltage'
val.type_instance = 'grid'
val.values = [ socket.voltage ]
val.dispatch()
val.type = 'current'
val.type_instance = 'load'
val.values = [ socket.current ]
val.dispatch()
val.type = 'power'
val.type_instance = 'real_power'
val.values = [ socket.power ]
val.dispatch()
val.type = 'gauge'
val.type_instance = 'power_factor'
val.values = [ socket.power_factor ]
val.dispatch()
val.type = 'gauge'
val.type_instance = 'load_on'
val.values = [ socket.powered ]
val.dispatch()
val.type = 'frequency'
val.type_instance = 'grid'
val.values = [ socket.frequency ]
val.dispatch()
def shutdown_func():
global instances
for inst in instances:
if inst['socket'] != None:
inst['socket'].disconnect()
instances = []
collectd.register_config(config_func)
collectd.register_init(init_func)
collectd.register_read(read_func)
collectd.register_shutdown(shutdown_func)

View File

@ -1,23 +1,37 @@
#!/usr/bin/env python3
import time
from sem6000 import SEMSocket
# auto_reconnect_timeout enabled auto reconnect if sending a command fails. Valid values:
# None (default): everything that fails throws NotConnectedException's
# -1: infinite retries
# integer: seconds before exception is thrown
import bluepy
socket = SEMSocket('f0:c7:7f:0d:e7:17', auto_reconnect_timeout=None)
#socket.login("1337")
#socket.changePassword("1234")
#socket.login("1234")
socket = None
while True:
time.sleep(1)
try:
if socket == None:
print("Connecting...")
# auto_reconnect_timeout enabled auto reconnect if sending a command fails. Valid values:
# None (default): everything that fails throws NotConnectedException's
# -1: infinite retries
# integer: seconds before exception is thrown
socket = SEMSocket('f0:c7:7f:0d:e7:17')
print("Connected.")
#socket.login("1337")
#socket.changePassword("1234")
#socket.login("1234")
socket.getStatus()
socket.setStatus(True)
print("=== {} ({}) ===".format(socket.mac_address, "on" if socket.powered else "off"))
print("\t{}V {}A → {}W@{}Hz".format(socket.voltage, socket.current, socket.power, socket.frequency))
except SEMSocket.NotConnectedException:
socket.reconnect(-1) #infinite reconnect attempts
print("\t{}V {}A → {}W@{}Hz (PF: {})".format(socket.voltage, socket.current, socket.power, socket.frequency, socket.power_factor))
except (SEMSocket.NotConnectedException, bluepy.btle.BTLEDisconnectError, BrokenPipeError):
print("Restarting...")
if socket != None:
socket.disconnect()
socket = None

View File

@ -4,11 +4,11 @@ import uuid
class SEMSocket():
password = "0000"
auto_reconnect_timeout = None
powered = False
voltage = 0
current = 0
power = 0
power_factor = 0
frequency = 0
mac_address = ""
custom_service = None
@ -17,9 +17,8 @@ class SEMSocket():
_notify_char = None
_btle_device = None
def __init__(self, mac, auto_reconnect_timeout = None):
def __init__(self, mac):
self.mac_address = mac
self.auto_reconnect_timeout = auto_reconnect_timeout
self._btle_device = btle.Peripheral(None ,addrType=btle.ADDR_TYPE_PUBLIC,iface=0)
try:
self.reconnect()
@ -80,18 +79,9 @@ class SEMSocket():
except:
return False
def __reconnect(self):
def reconnect(self):
self.disconnect()
self.connect()
def reconnect(self, timeout = None):
if timeout == None:
self.__reconnect()
else:
reconnect_start = time.time()
while abs(reconnect_start - time.time()) < timeout or timeout == -1:
self.__reconnect()
if not self.connected:
raise self.NotConnectedException
@ -182,7 +172,7 @@ class SEMSocket():
def send(self):
if not self.__btle_device.connected:
self.__btle_device.reconnect(self.__btle_device.auto_reconnect_timeout)
self.__btle_device.reconnect()
self.__btle_device._write_char.write(self.__data, True)
self.__btle_device._btle_device.waitForNotifications(5)
@ -204,11 +194,18 @@ class SEMSocket():
print("Switch toggled")
self.__btle_device.getStatus()
elif message_type == 0x04: #status related data
self.__btle_device.voltage = data[8]
self.__btle_device.current = (data[9] << 8 | data[10]) / 1000
self.__btle_device.power = (data[5] << 16 | data[6] << 8 | data[7]) / 1000
voltage = data[8]
current = (data[9] << 8 | data[10]) / 1000
power = (data[5] << 16 | data[6] << 8 | data[7]) / 1000
self.__btle_device.voltage = voltage
self.__btle_device.current = current
self.__btle_device.power = power
self.__btle_device.frequency = data[11]
self.__btle_device.powered = bool(data[4])
# calculated values
self.__btle_device.power_factor = power / (voltage * current)
elif message_type == 0x17:
if data[5] == 0x00 or data[5] == 0x01:
if data[4]: