#!/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',
  '2': 'Humidity',
  '3': 'Dew_point'
}

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
        ])
      else:
        # temperature and humidity sensor
        ret[id2name[id]] = [
          float(sns.getAttribute('val')),
          float(sns.getAttribute('w-min') or 0.0),
          float(sns.getAttribute('w-max') or 999)
        ]
    return ret

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

d = getdata(sys.argv[2])

for name, (val, min, max) in d.items():
  if min<=val<=max:
    pass
  else:
    status('CRITICAL', d)
    sys.exit(2)

status('OK', d)
sys.exit(0)
