#!/usr/bin/python

import mraa
import time
import firebase

class List:
        list

mylist = List()

sendData = firebase.FirebaseApplication('https://resplendent-torch-1749.firebaseio.com')

def firebase():
        if (mylist.list[0] == "1"):
                print "flat 1"
                sendData.put('/FlatNo1', 'FlowRate', {'value': mylist.list[1]});
                sendData.put('/FlatNo1', 'WaterConsumed', {'value': mylist.list[2]});
        if (mylist.list[0] == "2"):
                sendData.put('/FlatNo2', 'FlowRate', {'value': mylist.list[1]});
                sendData.put('/FlatNo2', 'WaterConsumed', {'value': mylist.list[2]});
        if (mylist.list[0] == "3"):
                sendData.put('/FlatNo3', 'FlowRate', {'value': mylist.list[1]});
                sendData.put('/FlatNo3', 'WaterConsumed', {'value': mylist.list[2]});


def fileRead(args):
        fd = open("/arduino_notification_out.txt", "r");
        str = fd.read();
        fd.close();
        mylist.list = str.split(",");
        print str;
        firebase();

x = mraa.Gpio(7)
x.dir(mraa.DIR_IN)
x.isr(mraa.EDGE_RISING, fileRead, 0)

relayPin = mraa.Gpio(8)
relayPin.dir(mraa.DIR_OUT)

flag = List();
flag.list = 0;

while True:
        relay = sendData.get('/Led', None);
        if (relay == 1):
                if (flag.list == 0):
                        relayPin.write(1) #RELAY ON
                        flag.list = 1;
        else:
                if (flag.list == 1):
                        relayPin.write(0) #RELAY OFF
                        flag.list = 0;

