#!/usr/bin/python
# -*- coding: utf-8 -*-

# fetch temperature and humidity from remote sensor
# 1.0.0 - 09/2017
# Giorgio Rutigliano

import urllib
import json
import MySQLdb

# ALARM #########################################

def tbotalarm(msg):
    tgram="https://api.telegram.org/<apikey>/sendMessage?chat_id=<chat_id>"
    try:
        response = urllib.urlopen(tgram+"Serra | "+msg)
        b = md=json.loads(response.read())
        return b['ok']
    except:
        return False

# Fetch data #########################################

try:
    js=json.loads(urllib.urlopen('http://<ip_sensore>/json').read())
except Exception, e:
    tbotalarm("Errore in lettura: " + str(e))
# open db connection
db=MySQLdb.connect(host='<ip_server>',user='user',passwd='pass',db='db')
cr=db.cursor(MySQLdb.cursors.DictCursor)
# save data
cr.execute("insert into letture (let_temp, let_hum) VALUES (%s,%s)",(js['t'],js['h']))
db.commit()
js['t']=0.9
if js['t']<1:
    tbotalarm("Allarme temperatura: " + str(js['t']))
db.close()