You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tplink_hs110.py 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """
  2. Collect power usage data from TP-Link HS110 SmartPlugs.
  3. Copyright (C) 2017 Bernd Zeimetz <bernd@bzed.de
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. """
  15. import collectd
  16. import re
  17. from pyHS100 import SmartPlug
  18. from pprint import pformat as pf
  19. PLUGIN_NAME = 'tplink_hs110'
  20. INTERVAL = 10 # seconds
  21. config = {}
  22. plugs = {}
  23. def configure(configobj):
  24. global config
  25. global plugs
  26. #collectd.info('tplink_hs110: Configure with: key=%s, children=%r' % (
  27. # configobj.key, configobj.children))
  28. config = {c.key: c.values[0] for c in configobj.children}
  29. collectd.info('tplink_hs110: Configured hs110 name/ip: %r' % (config))
  30. for name, ip in config.items():
  31. try:
  32. plug = SmartPlug(ip)
  33. collectd.info('tplink_hs110: %s' % pf(plug.hw_info))
  34. except Exception, e:
  35. collectd.error('tplink_hs110: Failed to connect to %s - %s' %(name, ip))
  36. else:
  37. collectd.info('tplink_hs110: Connected to %s - %s' %(name, ip))
  38. plugs[name] = plug
  39. def read(data=None):
  40. # {u'current': 0.685227,#012 u'power': 87.350224,#012 u'total': 1.423,#012 u'voltage': 234.660149}
  41. # {u'total_wh': 4474, u'current_ma': 9099, u'power_mw': 2245448, u'voltage_mv': 249459}
  42. global plugs
  43. for name, plug in plugs.items():
  44. plugin_instance = name
  45. measurements = plug.get_emeter_realtime()
  46. data = measurements.keys()
  47. for i in data:
  48. type_instance = re.sub('_.*', '', i)
  49. if 'total' == type_instance:
  50. _type = 'power'
  51. else:
  52. _type = type_instance
  53. p = collectd.Values(type=_type, type_instance=type_instance, plugin_instance=plugin_instance)
  54. p.plugin = PLUGIN_NAME
  55. measurement = measurements[i]
  56. if '_m' in i:
  57. # measurement is in milli volt/watt/ampere
  58. measurement = measurement / 1000.0
  59. p.values = [ measurement ]
  60. p.dispatch()
  61. collectd.register_config(configure)
  62. collectd.register_read(read, INTERVAL)