#!/usr/bin/env python

###################################
# HME LED DAEMON FOR RASPBERRY PI #
###################################
import multiprocessing
import sys, os, time
import RPi.GPIO as GPIO

__LED_DIR__ = '/var/run/hme/led'
__LED1__ = __LED_DIR__ + '/led1'
__LED2__ = __LED_DIR__ + '/led2'
__PIDFILE__ = __LED_DIR__ + '/pid'

if not os.path.isdir(__LED_DIR__):
    os.makedirs(__LED_DIR__)

__LED1_PIN__ = 7
__LED2_PIN__ = 8
__LED3_PIN__ = 25

def init():
    GPIO.setwarnings(False) 
    GPIO.setmode(GPIO.BCM)

    GPIO.setup(__LED1_PIN__, GPIO.OUT)
    GPIO.setup(__LED2_PIN__, GPIO.OUT)

    led_status(__LED1__, 'off')
    led_status(__LED2__, 'off')

def led_status(led, status = None):
    if status == None:
        f = open(led, 'r')
        s = f.read().strip()
        f.close()
        return s
    else:
        f = open(led, 'w+')
        f.write(status)
        f.close()

def lastpid(pid = None):
    if pid == None:
        if not os.path.isfile(__PIDFILE__):
            return None
        f = open(__PIDFILE__, 'r')
        p = f.read().strip()
        f.close()
        if p:
            return int(p)
        else:
            return None
    else:
        f = open(__PIDFILE__, 'w+')
        f.write(str(pid))
        f.close()

def pid_exists(pid):
    if not pid:
        return False
    else: 
        return os.path.exists('/proc/' + str(pid))

def blink(pin):  
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(pin, GPIO.LOW)
    # time.sleep(0.2)

def on(pin):
    GPIO.output(pin, GPIO.HIGH)

def off(pin):
    GPIO.output(pin, GPIO.LOW)

def cleanup():
    GPIO.cleanup()

if __name__ == '__main__':

    pid = lastpid()

    if pid_exists(pid):
        if len(sys.argv) == 3:
            p1 = sys.argv[1]
            p2 = sys.argv[2]

            if p1 in ['led1', 'led2'] and p2 in ['on', 'off', 'blink']:
                led = __LED1__ if p1 == 'led1' else __LED2__
                led_status(led, p2)
                 
        sys.exit(0)

    try: 
        pid = os.fork()
        if pid > 0:
            # in parent
            sys.exit(0)
        else:
            lastpid(os.getpid())

            init()

            # in child
            while (1):
                if led_status(__LED1__) == 'on':
                    on(__LED1_PIN__)
                elif led_status(__LED1__) == 'off':
                    off(__LED1_PIN__)
                elif led_status(__LED1__) == 'blink':
                    blink(__LED1_PIN__)
                
                if led_status(__LED2__) == 'on':
                    on(__LED2_PIN__)
                elif led_status(__LED2__) == 'off':
                    off(__LED2_PIN__)
                elif led_status(__LED2__) == 'blink':
                    blink(__LED2_PIN__)
                                        
                time.sleep(0.2)

    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

