#
# gpio 25 input  in1
# gpio 24 input  in2
# gpio 23 output LED
#
import os, sys
import time
import threading
from webob import Request, Response
from threading import Thread
import RPi.GPIO as GPIO

sens_path = ""
idcodefile = "/home/pi/1wire/id.txt"

idcode = {
}
SENS_TAGS = {
}

SENS_LIST = []

SENS_VALUES = {
}

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(23, GPIO.OUT)

global runvar
global t

lock = threading.Lock()
runvar = True
count = 0
pin1count = 0
pin1state = GPIO.input(25)
pin2count = 0
pin2state = GPIO.input(24)
pin1ontime = 0
pin2ontime = 0

def myfunc(i):
    global runvar
    global count
    global pin2count
    global pin1count
    global pin1state
    global pin2state
    global pin1ontime
    global pin2ontime

#    global lock
    tick = 0
    pin1on = -1
    pin2on = -1

    print('Enter blink thread')
    ostate = 0
    while runvar == True:
        tick += 1
        if tick > 99:
            GPIO.output(23, ostate)
            ostate = not ostate
            tick = 0

        newstate = GPIO.input(25)
        if pin1state != newstate:
            pin1state = newstate
            if newstate == 0:    #on
                pin1on = count
                lock.acquire()
                try:
                    pin1count += 1

                finally:
                    lock.release()
            else:                #off
                if pin1on != -1:
                    pin1ontime = count - pin1on

        newstate = GPIO.input(24)
        if pin2state != newstate:
            pin2state = newstate
            if newstate == 0:    #on
                pin2on = count
                lock.acquire()
                try:
                    pin2count += 1

                finally:
                    lock.release()
            else:                #off
                if pin2on != -1:
                    pin2ontime = count - pin2on

        time.sleep(0.001)       # 1 ms delay ?
        count += 1

    print('Exit blink thread')



#
# Read id-file:
#
#  # comment line
#  ; comment line
#  %%part      file part
#
#  part 1:  maps the serial code
#  id  sercode  ; opt. comment
#
#  PATH:  set path to sensors
#
#   where id is a number given to the sensor
#   and sercode is the unique serial code for the 18B20
#   the ; is start of a line comment
#
#  part 2:   maps a name to the number
#  id    name
#
#
def process_idfile():
    global idcode
    global SENS_TAGS
    global SENS_LIST
    global sens_path

    try:
        file = open(idcodefile, 'r')
    except:
        return 1

    part = 1

    idcode.clear()
    SENS_TAGS.clear()
    SENS_LIST = []

    while True:
        line = file.readline()
        if line == '':     # no more lines
            break
        line = line.strip()
        if line == '' or line[0] == '#' or line[0] == ';':
            pass            # empty or comment line
        elif line[0:2] == '%%':
            part = int(line[2:])
        elif part == 1:
            list = line.split(None, 2)
            if len(list) > 1:
                if list[0] == 'PATH:' :
                    sens_path = list[1]
                else:
                    idcode[list[0]] = list[1]

        elif part == 2:
            list = line.split(None, 1)
            if len(list) > 1:
                SENS_TAGS[list[1]] = list[0]
                SENS_LIST.append(list[1])

    file.close()

    if len(sens_path) == 0 or sens_path[-1] != '/':
        sens_path += '/'

    print "idcodes"
    for id, sercode in idcode.iteritems():
        print "%2s  %s" % (id, sercode)


    print ""
    print "sensors"
    for name, id in SENS_TAGS.iteritems():
        print "%2s  %s" % (id, name)

    sens = SENS_TAGS
    print ""
    print "sens"
    for name, id in sens.iteritems():
        print "%2s  %s" % (id, name)

    print ""
    print "sens_list"
    for name in SENS_LIST:
        print "%s" % (name)


    return 0



def readsensors():
    global SENS_VALUES
    sv = {}

    for name in SENS_LIST:
        try:
            id = SENS_TAGS[name]
        except:
            id = '0'

        try:
            sercode = idcode[id]
        except:
            sercode = ''

        path = sens_path + sercode + '/temperature'

        try:
            file = open(path, 'r')
            line = file.read()
            value = line.strip()
            file.close()
        except:
            value = '-'

        sv[name] = value

    if SENS_VALUES != sv:
        SENS_VALUES = sv
        for name in SENS_LIST:
            print "%8s  %s" % (name, SENS_VALUES[name])

    return

def tempreader(i):
    global runvar

    fileread = 0
    freadcount = 1
    mtime = -1

    while runvar == True:

        freadcount -= 1
        if freadcount < 1:
            freadcount = 6 # gives at least 1 minute
            m = os.stat(idcodefile).st_mtime
            if m != mtime:
                fileread = 0

        if fileread == 0:
            process_idfile()
            mtime = os.stat(idcodefile).st_mtime
            fileread = 1

        readsensors()

        time.sleep(10)       # 10 s delay ?


def readpintime(pin):
    global pin1ontime
    global pin2ontime
    cnt = 0
    if pin == 1:
        cnt = pin1ontime

    if pin == 2:
        cnt = pin2ontime

    return cnt

def readpincount(pin):
    global pin1count
    global pin2count
    cnt = 0
    if pin == 1:
        cnt = pin1count

    if pin == 2:
        cnt = pin2count

    return cnt

def readandclrpincount(pin):
    global pin1count
    global pin2count

    cnt = 0

    if pin == 1:
        lock.acquire()
        try:
            cnt = pin1count
            pin1count = 0

        finally:
            lock.release()

    if pin == 2:
        lock.acquire()
        try:
            cnt = pin2count
            pin2count = 0

        finally:
            lock.release()

    return cnt


def readcount():
    global count
    return count

def readrunvar():
    global runvar
    return runvar

def setrunvar(val):
    global runvar
    runvar = val
    return runvar


class WebApp(object):
    def __call__(self, environ, start_response):
        global runvar

        # capture the request (input)
        req = Request(environ)

        # get the name variable,
        # default value of 'World' if it is not set
#        name = req.params.get('name', 'World')

        name = req.path

        if name == "/stop":
            setrunvar(False)

        if name == "/start":
            if readrunvar() == False:
                setrunvar(True)
                t = Thread(target=myfunc, args=(1, ))
                t.start()
                t2 = Thread(target=tempreader, args=(1, ))
                t2.start()

        count = readcount()
        val1 = readpincount(1)
        val2 = readpintime(1)
        val3 = readpincount(2)
        val4 = readpintime(2)
        if name == "/r1":
            count = readpincount(1)
        if name == "/1":
            count = readpincount(1)

        if name == "/r2":
            count = readpincount(2)
        if name == "/2":
            count = readpincount(2)

        if name == "/r1c":
            val1 = readandclrpincount(1)

        if name == "/r2c":
            val3 = readandclrpincount(2)

        if name == "/rc":
            val1 = readandclrpincount(1)
            val3 = readandclrpincount(2)

        # generate the HTML for the response (output)
        html = """
<p>
count %d<br/>
pin1count %d<br/>
pin1ontime %d<br/>
pin2count %d<br/>
pin2ontime %d<br/>
"""

#"""
#<p>Hello %s! (%d)</p>
#<form method="post">
#Enter your name: <input type="text" name="name">
#<input type="submit" value="Submit Form">
#</form>
#"""

        outstr = html % (count, val1, val2, val3, val4)
        outstr += "<br/>\nTemp:<br/>\n"

        for name in SENS_LIST:
            outstr += "%s  %s<br/>\n" % (name, SENS_VALUES[name])

        outstr += "</p>"

        # create and return the response
        resp = Response(outstr)
#        resp = Response(html % (name, count))
        return resp(environ, start_response)

application = WebApp()

# main program - the web server
if __name__ == '__main__':

    from wsgiref.simple_server import make_server
    port = 8080

    t = Thread(target=myfunc, args=(1, ))
    t.start()

    t2 = Thread(target=tempreader, args=(1, ))
    t2.start()

    httpd = make_server('', port, application)
    print('Serving HTTP on port %s...'%port)
    httpd.serve_forever()


# end
