"""
'digital_out.py'
===================================
Example of turning on and off a LED
from the Adafruit IO Python Client
Author(s): Brent Rubell, Todd Treece
			with modifications by Thomas Trickel
"""
# Import standard python modules
import time
import RPi.GPIO as GPIO

# import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, RequestError

# setup GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)


# Set to your Adafruit IO key.
# Remember, your key is a secret,
# so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY'

# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME"

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

try: # if we have a 'digital' feed
    digital = aio.feeds('ledcontrol-feed')
except RequestError: # create a digital feed
    feed = Feed(name="ledcontrol-feed")
    digital = aio.create_feed(feed)

while True:
    data = aio.receive(digital.key)
    if data.value == "ON":
        print('received <- ON\n')
        GPIO.output(18, True)
    elif data.value == "OFF":
        print('received <- OFF\n')
        GPIO.output(18, False)

# timeout so we dont flood adafruit-io with requests
    time.sleep(0.5)

