#!/usr/bin/env python
import OSC
import multiprocessing, time
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

pin_pairs = [[14,15], [23,24], [1,7]]


# OSC
client = OSC.OSCClient()
address = '127.0.0.1', 3000 # 57120==SC
client.connect( address ) # set the address for all following messages
oscOne = OSC.OSCMessage() # OSCresponder name: '/touch_one'
oscTwo = OSC.OSCMessage() # OSCresponder name: '/touch_two'
oscThree = OSC.OSCMessage() # OSCresponder name: '/touch_three'
oscOne.setAddress("/touch_one")
oscTwo.setAddress("/touch_two")
oscThree.setAddress("/touch_three")
print client

def osc_msg(pinpair, val):
    pinindex = pin_pairs.index(pinpair)

    if pinindex == 0:
        oscOne.append( val )
        print oscOne
        client.send(oscOne)
        oscOne.clearData()
    elif pinindex == 1:
        oscTwo.append( val )
        print oscTwo
        client.send(oscTwo)
        oscTwo.clearData()
    elif pinindex == 2:
        oscThree.append( val )
        print oscThree
        client.send(oscThree)
        oscThree.clearData()


def discharge(a_pin, b_pin):
    GPIO.setup(a_pin, GPIO.IN)
    GPIO.setup(b_pin, GPIO.OUT)
    GPIO.output(b_pin, False)
    time.sleep(0.005)

def charge_time(a_pin, b_pin):
    GPIO.setup(b_pin, GPIO.IN)
    GPIO.setup(a_pin, GPIO.OUT)
    count = 0
    GPIO.output(a_pin, True)
    while not GPIO.input(b_pin):
        count = count + 1
    return count

def analog_read(pin_pair):
    discharge(pin_pair[0],pin_pair[1])
    return charge_time(pin_pair[0],pin_pair[1])


def worker(pair):
    """thread worker function"""
    while True:
        reading = analog_read( pair ) #print(analog_read())
        osc_msg(pair, reading)
        time.sleep(0.1)

    return

if __name__ == '__main__':
    jobs = []
    for i in range(len(pin_pairs)):
        p = multiprocessing.Process(target=worker, args=(pin_pairs[i],))
        jobs.append(p)
        p.start()
