#!/usr/bin/python

'''
Check for temperature sensors from papouch.com devices.

Usage: check_papouch -H hostname
'''

import sys, os, urllib2
from xml.dom.minidom import parse, parseString

id2name = {
  '1': ['Temperature', 'C'],
  '2': ['Humidity', '%'],
  '3': ['Dew_point', 'C']
}

def getdata(host):
    f = urllib2.urlopen('http://%s/fresh.xml' % host)
    dom = parse(f)
    ret = {}
    for sns in dom.getElementsByTagName('sns'):
      id = sns.getAttribute('id')
      if not id:
        # temperature sensor only
        return dict(temp=[
          float(sns.getAttribute('val'))/10.0,
          float(sns.getAttribute('min'))/10.0,
          float(sns.getAttribute('max'))/10.0,
          'C'
        ])
      else:
        # temperature and humidity sensor
        name, cp = id2name[id]
        ret[name] = [
          float(sns.getAttribute('val')),
          float(sns.getAttribute('w-min') or 0.0),
          float(sns.getAttribute('w-max') or 999),
          cp
        ]
    return ret

def status(s, d):
    ret = []
    for name, (val, min, max, cp) in d.items():
      ret.append("%s=%3.2f;;%3.2f" % (name, val, max))
    print s+"|"+' '.join(ret)

d = getdata(sys.argv[2])

sum = []
for name, (val, min, max, cp) in d.items():
  if min<=val<=max:
    sum.append("%s=%s%s" % (name.lower(), val, cp))
  else:
    status('CRITICAL %s=%s%s' % (name.lower(), val, cp), d)
    sys.exit(2)

status('OK %s' % ', '.join(sum), d)
sys.exit(0)
