aboutsummaryrefslogtreecommitdiff
path: root/pellematic-switches
blob: 0b4ab4aba047c0bfdaf85a297d6ec569657be5ad (plain)
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
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
#
# Munin plugin to monitor the switches in the pellematic
#
# Copyright 2013 Guido Guenther <agx@sigxcpu.org>
#
# Licesnse: GPLv3
#
# depends: python-requests
#
# FIXME: This currently doesn't probe the connected systems
#
#%# capabilities=autoconf
#%# family=contrib

import requests
import os
import re
import sys
import json

username = os.getenv('username', 'oekofen')
password = os.getenv('password', username)
debug = os.getenv('debug')
url = os.getenv('url')

# The switches we want to plot (on/off 0/1 only):
items = { "CAPPL:FA[0].L_kap_sensor_raumentnahme":
          'Capacitive Sensor RA',
          "CAPPL:FA[0].L_kap_sensor_zwischenbehaelter":
          'Capacitive Sensor Hopper',
          "CAPPL:FA[0].L_br1":
          'Burner Require',
          # Brandschutzklappe
          "CAPPL:FA[0].L_bsk_status":
          'BSK Status',
          # Motor suction turbine
          "CAPPL:FA[0].ausgang_motor[0]":
          'Motor Suction Turbine',
          #"CAPPL:FA[0].ausgang_motor[1]":
          #'',
          #"CAPPL:FA[0].ausgang_motor[2]":
          #'',
          #"CAPPL:FA[0].ausgang_motor[3]":
          #'',
          #"CAPPL:FA[0].ausgang_motor[4]":
          #'',
          #"CAPPL:FA[0].ausgang_motor[5]":
          #'',
          #"CAPPL:FA[0].ausgang_motor[8]":
          #'',
          # DHW (domestic hot water) pump switch?
          #"CAPPL:FA[0].ausgang_motor[9]":
          # Pellet transport inside boiler
          "CAPPL:FA[0].ausgang_motor[11]":
          'Motor Delivery',
          "CAPPL:FA[0].ausgang_stoermelderelais":
          'Relay Malfunction',
         }

def canon(name):
    return re.sub(r"[^a-zA-Z0-9_]", "_", name)

def get_name(item):
    if item['name'] in items.keys():
        if item['shortText'] != '???':
            return item['shortText']
        else:
            return items[item['name']]
    else:
        return None

def print_config(url):
    print """graph_title Pellematic Switches 
graph_vlabel On (1) or Off (0)
graph_category Heating
graph_info This graph shows the values for different on/off switches
"""
    names = []
    draw = "AREA"
    out = fetch_raw(url)
    for item in out:
        name = get_name(item)
        if name:
            names.append(name)

    for name in sorted(names):
        print "%s.label %s" % (canon(name), name)
        print "%s.type GAUGE" % canon(name)
        print "%s.draw %s" % (canon(name), draw)
        if draw == "AREA":
            draw = "STACK"
        if 'Malfunction' in name:
            print "%s.warning 0.1" % canon(name)
            print "%s.critical 1" % canon(name)

def fetch_raw(url):
    # Perform authentication and get the cookie
    auth_formdata = {'language': 'en',
                     'username': username,
                     'password': password,
                     'submit': 'Login',
                     }
    r = requests.post(url, data=auth_formdata)

    pksession = r.cookies['pksession']
    cookies = { 'pksession': pksession,
                'language': 'en' }
    params = { 'action': 'get',
               'attr': '1',
             }

    # These are the headers used by the supplied application
    # It mostly doesn't matter what we pass but the backend
    # breaks with a lua error without a Accept-Language header:
    headers = {'Accept': 'application/json',
               'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
               'Accept-Language': 'en',
              }

    # The items to fetch are passed as simple json string
    payload = json.dumps(items.keys())
    r = requests.post(url,
                      data=payload,
                      params=params,
                      cookies=cookies,
                      headers=headers)

    if hasattr(r.json, '__call__'):
        ret = r.json()
    else: # in requests 0.12 json isn't a callable
        ret = r.json

    if debug:
        print >>sys.stderr, ret

    return ret


def fetch_values(url):
    out = fetch_raw(url)
    for item in out:
        name = get_name(item)
        if name:
            print "%s.value %s" % (canon(name), item['value'])


def main(args):
    if not url:
        print >>sys.stderr, "No url configured"
        return 1
    if len(args) > 1:
        if args[1] in [ 'autoconf', 'detect' ]:
            try:
                fetch_raw(url)
                print "yes"
                return 0
            except:
                print "no"
                return 1
        elif args[1] == 'config':
            try:
                print_config(url)
            except Exception as e:
                raise
                print >>sys.stderr, "Failed to fetch config: '%s'" % e
                return 1
            return 0
    try:
        fetch_values(url)
    except Exception as e:
        print >>sys.stderr, "Failed to fetch values: '%s'" % e
        raise
        return 1
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))