#!/usr/bin/env python2
"""
Copyright (c) 2013-2015 Ben Croston

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

"""This test suite assumes the following circuit is connected:
GND_PIN = 6
LED_PIN = 12 (with resistor to 0v)
SWITCH_PIN = 18 (with 0.1 uF capacitor around switch) to 0v
LOOP_IN = 16 connected with 1K resistor to LOOP_OUT
LOOP_OUT = 22
"""

import sys
import warnings
import time
from threading import Timer
import RPi.GPIO as GPIO
if sys.version[:3] == '2.6':
    import unittest2 as unittest
else:
    import unittest

GND_PIN = 6
LED_PIN = 12
LED_PIN_BCM = 18
SWITCH_PIN = 18
LOOP_IN = 16
LOOP_OUT = 22

non_interactive = False
for i,val in enumerate(sys.argv):
    if val == '--non_interactive':
        non_interactive = True
        sys.argv.pop(i)

# Test starts with 'AAA' so that it is run first
class TestAAASetup(unittest.TestCase):
    def runTest(self):
        # Test mode not set (BOARD or BCM) exception
        with self.assertRaises(RuntimeError) as e:
            GPIO.setup(LED_PIN, GPIO.OUT)
        self.assertEqual(str(e.exception), 'Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)')

        # Test trying to change mode after it has been set
        GPIO.setmode(GPIO.BCM)
        with self.assertRaises(ValueError) as e:
            GPIO.setmode(GPIO.BOARD)
        GPIO.setup(LED_PIN_BCM, GPIO.IN)
        GPIO.cleanup()

        # Test getmode()
        self.assertEqual(GPIO.getmode(), GPIO.UNKNOWN)
        GPIO.setmode(GPIO.BCM)
        self.assertEqual(GPIO.getmode(), GPIO.BCM)
        GPIO.setup(LED_PIN_BCM, GPIO.IN)
        GPIO.cleanup()
        GPIO.setmode(GPIO.BOARD)
        self.assertEqual(GPIO.getmode(), GPIO.BOARD)

        # Test not set as OUTPUT message
        GPIO.setmode(GPIO.BOARD)
        with self.assertRaises(RuntimeError) as e:
            GPIO.output(LED_PIN, GPIO.HIGH)
        self.assertEqual(str(e.exception), 'The GPIO channel has not been set up as an OUTPUT')

        # Test setup(..., pull_up_down=GPIO.HIGH) raises exception
        GPIO.setmode(GPIO.BOARD)
        with self.assertRaises(ValueError):
            GPIO.setup(LED_PIN, GPIO.IN, pull_up_down=GPIO.HIGH)

        # Test not valid on a raspi exception
        GPIO.setmode(GPIO.BOARD)
        with self.assertRaises(ValueError) as e:
            GPIO.setup(GND_PIN, GPIO.OUT)
        self.assertEqual(str(e.exception), 'The channel sent is invalid on a Raspberry Pi')

        # Test 'already in use' warning
        GPIO.setmode(GPIO.BOARD)
        with open('/sys/class/gpio/export','wb') as f:
            f.write(str(LED_PIN_BCM).encode())
        with open('/sys/class/gpio/gpio%s/direction'%LED_PIN_BCM,'wb') as f:
            f.write(b'out')
        with open('/sys/class/gpio/gpio%s/value'%LED_PIN_BCM,'wb') as f:
            f.write(b'1')
        time.sleep(0.2)
        with warnings.catch_warnings(record=True) as w:
            GPIO.setup(LED_PIN, GPIO.OUT)    # generate 'already in use' warning
            self.assertEqual(w[0].category, RuntimeWarning)
        with open('/sys/class/gpio/unexport','wb') as f:
            f.write(str(LED_PIN_BCM).encode())
        GPIO.cleanup()

        # test initial value of high reads back as high
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.HIGH)
        self.assertEqual(GPIO.input(LED_PIN), GPIO.HIGH)
        GPIO.cleanup()

        # test initial value of low reads back as low
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.LOW)
        self.assertEqual(GPIO.input(LED_PIN), GPIO.LOW)
        GPIO.cleanup()

        # test setup of a list of channels
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup( [LED_PIN, LOOP_OUT], GPIO.OUT)
        self.assertEqual(GPIO.gpio_function(LED_PIN), GPIO.OUT)
        self.assertEqual(GPIO.gpio_function(LOOP_OUT), GPIO.OUT)
        GPIO.cleanup()
        GPIO.setmode(GPIO.BOARD)
        with self.assertRaises(ValueError) as e:
            GPIO.setup( [LED_PIN, GND_PIN], GPIO.OUT)
        self.assertEqual(GPIO.gpio_function(LED_PIN), GPIO.OUT)
        self.assertEqual(str(e.exception), 'The channel sent is invalid on a Raspberry Pi')
        GPIO.cleanup()

        # test setup of a tuple of channels
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup( (LED_PIN, LOOP_OUT), GPIO.OUT)
        self.assertEqual(GPIO.gpio_function(LED_PIN), GPIO.OUT)
        self.assertEqual(GPIO.gpio_function(LOOP_OUT), GPIO.OUT)
        GPIO.cleanup()

        # test warning when using pull up/down on i2c channels
        GPIO.setmode(GPIO.BOARD)
        if GPIO.RPI_INFO['P1_REVISION'] == 0: # compute module