def main():
    if (len(sys.argv) != 5):
        sys.stderr.write(
            'Usage: "{0}" $AIOUsername $AIOKey $tankMeasureFeedKey $tankStatusFeedKey\n'
            .format(sys.argv[0]))
        os._exit(1)

    AIOUsername = sys.argv[1]
    AIOKey = sys.argv[2]  # Beware, your Key is Secret!
    tankMeasureFeedKey = sys.argv[
        3]  # Feed key where tank measure data is received
    tankStatusFeedKey = sys.argv[
        4]  # Feed key where tank status data is received

    # Connect to Adafruit IO Server
    aio = Client(username=AIOUsername, key=AIOKey)

    # Link to feeds
    tankMeasureFeedInstance = aio.feeds(tankMeasureFeedKey)
    tankStatusFeedInstance = aio.feeds(tankStatusFeedKey)

    # Create messageSendControl instance
    messageInstance = MessageSendControl("")

    # Setup GPIO mode
    GPIO.setmode(GPIO.BCM)

    # List with all GPIO pin numbers
    pinList = {"bajo": 10, "normal": 11, "alto": 12}

    # write on log file
    logFile = open("log fuel.txt", "a", encoding="utf8")
    logFile.write("{}~{}~{}~{}\n".format(datetime.datetime.now(), "Nulo",
                                         "Nulo", "Aplicación iniciada"))
    logFile.close()

    # Setup Threading, to publish message every 10 seconds
    hilo0 = threading.Thread(target=send_message,
                             args=[
                                 aio,
                                 tankMeasureFeedInstance,
                                 tankStatusFeedInstance,
                                 messageInstance,
                                 pinList,
                             ])
    hilo0.start()

    # Mod publish value
    while True:
        messageInstance.message = input("Ingrese nuevo valor para el tanque\n")
        # Sincronization threads
        lock.acquire()
        # write on log file
        logFile = open("log fuel.txt", "a", encoding="utf8")
        logFile.write("{}~{}~{}~{}\n".format(
            datetime.datetime.now(), "Nulo", "Nulo",
            "Valor de temperatura modificado a {}".format(
                messageInstance.message)))
        logFile.close()
        lock.release()
Example #2
0
def adafruit_auth(n):
    x = os.getenv("ADAFRUIT_IO_USERNAME")  #ADAFRUIT_IO_USERNAME
    y = os.getenv("ADAFRUIT_IO_KEY")    #ADAFRUIT_IO_KEY
    aio = Client(x,y)
    if n==1:            #light on condtion 
      test = aio.feeds('lightstatus')
      aio.send_data(test.key, 10)
    else:               #light off condition
      test = aio.feeds('lightstatus')
      aio.send_data(test.key, 0)
Example #3
0
def main():

    logging.basicConfig(format="%(asctime)-15s %(message)s",
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    parser = argparse.ArgumentParser(description='Climate')
    parser.add_argument('-i',
                        '--interval',
                        help='reporting interval in seconds')
    parser.add_argument('-d',
                        '--display_only',
                        help='only display, no reporting',
                        action="store_true")
    args = parser.parse_args()

    if args.interval:
        Registry.reporting_interval = int(args.interval)
    display_only = args.display_only

    # REST client.
    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Adafruit IO Feeds.
    temperature_feed = aio.feeds('rafi-temperature')
    humidity_feed = aio.feeds('rafi-humidity')

    while True:

        try:
            temperature, humidity = HTU21D.get_temperature_humidity()

            temperature = f'{temperature:.1f}'
            humidity = f'{humidity:.1f}'

            if humidity is not None and temperature is not None:
                if not display_only:
                    send_readings(aio, temperature, humidity, temperature_feed,
                                  humidity_feed)
                logging.info(
                    f'Temp={temperature}*C Humidity={humidity}% Send={not display_only}'
                    f' (next in {Registry.reporting_interval} secs)')
            else:
                logging.info(
                    f'Failed to get readings, trying again in {Registry.reporting_interval} seconds'
                )

        except Exception as ex:
            logging.exception('Cannot send data')

        # Avoid flooding Adafruit IO
        time.sleep(Registry.reporting_interval)
def adafruitIOaccess(quotes):

    # load adafruit IO key and username as environment variables
    load_dotenv()
    ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY')
    ADAFRUIT_IO_USERNAME = os.getenv('ADAFRUIT_IO_USERNAME')

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

    # assign feeds
    text_feed = aio.feeds(TEXT_FEED)
    color_feed = aio.feeds(COLOR_FEED)

    # retrieve all current quotes on Adafruit IO
    published = aio.data(text_feed.key)

    # get just the text values from published quotes
    for i, p in enumerate(published):
        published[i] = p.value

    # for every quote, check if it's already published
    for q in quotes:
        # if already there, don't publish
        if q['text'] in published:
            continue
        # send new text value
        print(f"\tAdded data to text feed: {q['text']}.")
        aio.send_data(text_feed.key, q['text'])
        # send corresponding color value
        print(f"\tAdded data to color feed: {q['color']}.")
        aio.send_data(color_feed.key, q['color'])

    # retrieve all current quotes on Adafruit IO
    published = aio.data(text_feed.key)

    # keep only the most recent MAX_QUOTES, remove all others
    for i, p in enumerate(published):
        if i > MAX_QUOTES - 1:
            # delete a data value from text feed
            print(f"\tRemoved data from text feed: {p.value}.")
            data = aio.delete(text_feed.key, p.id)

    # retrieve all current colors on Adafruit IO
    published = aio.data(color_feed.key)

    # keep the most recent MAX_QUOTES, remove all others
    for i, p in enumerate(published):
        if i > MAX_QUOTES - 1:
            # delete a data value from color feed
            print(f"\tRemoved data from color feed: {p.value}.")
            data = aio.delete(color_feed.key, p.id)
Example #5
0
def send_speedtest_report(download_mbps, upload_mbps):
    """ Report internet speed to Adafruit IO """

    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    feed_internet_download_name = "internet-download"
    feed_internet_upload_name = "internet-upload"

    feed_internet_download = aio.feeds(feed_internet_download_name)
    feed_internet_upload = aio.feeds(feed_internet_upload_name)

    aio.send(feed_internet_download.key, f'{download_mbps:.2f}')
    aio.send(feed_internet_upload.key, f'{upload_mbps:.2f}')
Example #6
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("secret", help="Secret")
    args = parser.parse_args()

    aio = Client(ADAFRUIT_IO_USERNAME, args.secret)

    temperature_feed = aio.feeds('temperature')
    humidity_feed = aio.feeds('humidity')
    pressure_feed = aio.feeds('pressure')

    aio.send(temperature_feed.key, str(25.0))
    aio.send(humidity_feed.key, str(10.0))
    aio.send(pressure_feed.key, str(50.0))
Example #7
0
class Outbound():
    def __init__(self):
        aio = self.start()

    def start(self):
        self.aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    def send(self, sensor):
        temperature = self.aio.feeds("temperature")
        humidity = self.aio.feeds("humidity")
        pressure = self.aio.feeds("pressure")

        self.aio.send_data(temperature.key, sensor.temperature)
        self.aio.send_data(humidity.key, sensor.humidity)
        self.aio.send_data(pressure.key, sensor.pressure)
class adaFruitTalker():
    def __init__(self, username, api_key, feed_names: list):
        self.aio = Client(username, api_key)
        self.feed_names = feed_names
        self.feeds_dict = self.inialize_feeds()

    def inialize_feeds(self):

        feeds_dict = dict()

        for feed_name in self.feed_names:
            feeds_dict[feed_name] = self.aio.feeds(feed_name)

        return feeds_dict

    def write_feeds(self, thing_speak_to_ada_dict: dict,
                    thing_speak_values: dict):

        for key, value in thing_speak_values.items():

            if value is None:
                continue

            ada_feed_name = thing_speak_to_ada_dict[key]
            ada_feed = self.feeds_dict[ada_feed_name]

            self.aio.send(ada_feed.key, value)
Example #9
0
class AdafruitIoClient(threading.Thread):
    def __init__(self, my_key, my_username):
        threading.Thread.__init__(self)
        self.my_key = my_key
        self.my_username = my_username
        self.mqttdevice = MQTTClient(self.my_username, self.my_key)
        self.device = Client(self.my_username, self.my_key)

    def subscribe(self, feed_id):
        self.mqttdevice.subscribe(feed_id)

    def set_on_connect(self, callback):
        self.mqttdevice.on_connect = callback

    def set_on_disconnect(self, callback):
        self.mqttdevice.on_disconnect = callback

    def set_on_message(self, callback):
        self.mqttdevice.on_message = callback

    def get_feeds(self):
        return self.device.feeds()

    def create_feed(self, feed):
        return self.device.create_feed(feed)

    def run(self):
        self.mqttdevice.connect()
        self.mqttdevice.loop_blocking()

    def send_data(self, name, value):
        self.device.send_data(str(name).lower(), value)
Example #10
0
def main():
	if(len(sys.argv)!=7):
		sys.stderr.write('Usage: "{0}" $AIOUsername $AIOKey $AIOFeedKeySoilMoisture $AIOFeedKeyAmbientTemperature $AIOFeedKeyAmbientHumidity $AIOFeedKeyIrrigation\n'.format(sys.argv[0]))
		os._exit(1)

	AIOUsername=sys.argv[1]
	AIOKey=sys.argv[2]# Beware, your Key is Secret!
	AIOFeedKeySoilMoisture=sys.argv[3] # Feed key where data is received
	AIOFeedKeyAmbientTemperature=sys.argv[4] # Feed key where data is received
	AIOFeedKeyAmbientHumidity=sys.argv[5] # Feed key where data is received
	AIOFeedKeyIrrigation=sys.argv[6] # Feed key where data is received

	# Connect to Adafruit IO Server
	aio=Client(username=AIOUsername, key=AIOKey)

	# Link to feeds
	soilMoistureFeed=aio.feeds(AIOFeedKeySoilMoisture)
	ambientTemperatureFeed=aio.feeds(AIOFeedKeyAmbientTemperature)
	ambientHumidityFeed=aio.feeds(AIOFeedKeyAmbientHumidity)
	irrigationFeed=aio.feeds(AIOFeedKeyIrrigation)

	# Dict with some GPIO pin numbers
	pinSoilMoisture={"humedad suelo baja":14, "humedad suelo normal":15, "humedad suelo alta":16}

	# Dict with GPIO pin numbers for temperature alert
	pinTemperature={"temperatura ambiente baja":8, "temperatura ambiente normal":9, "temperatura ambiente alta":10}

	# Dict with GPIO pin numbers for humidty alert
	pinHumidity={"humedad ambiente baja":21, "humedad ambiente normal":22, "humedad ambiente alta":23}

	# Setup GPIO setmode
	GPIO.setmode(GPIO.BCM)

	# Set GPIO pin signal OUT and initial value "shutdown"
	GPIO.setup(list(pinTemperature.values())+list(pinSoilMoisture.values())+list(pinHumidity.values()), GPIO.OUT, initial=GPIO.LOW)

	# set control state var
	humidityLastState=""
	temperatureLastState=""
	soilMoistureLastState=""

	humidityLastUpdate=""
	temperatureLastUpdate=""
	soilMoistureLastUpdate=""
Example #11
0
def refresh_connection():
  # Create an instance of the REST client.
  global aio
  aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

  try:
      global door
      door = aio.feeds('door')
  except RequestError:
      log.critical('No feed called Door.')
      quit()
Example #12
0
def manual():
    if request.method == 'POST':
        espcode = request.json.get('espcode')
        state = request.json.get('data')
        Mode.query.filter_by(espcode=espcode).delete()

        mo = Mode(espcode=espcode, mode='MANU')
        db.session.add(mo)
        db.session.commit()

        ADAFRUIT_IO_KEY = 'PUT_YOUR_OWN_KEY'
        ADAFRUIT_IO_USERNAME = '******'
        aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
        espcodeAdafruit1 = "motor"

        if state == 'ON':
            aio.send_data(aio.feeds(espcodeAdafruit1).key, 'ON')
        else:
            aio.send_data(aio.feeds(espcodeAdafruit1).key, 'OFF')

        return Response(status=200)
Example #13
0
class AdafruitIO(drivers.Exporter):

    THROTTLE_SLEEP_TIME = 60

    blacklist = [constants.IMAGE, constants.NOTES]

    username = '******'
    key = 'IO_KEY'

    def setup(self):
        self.client = Client(self.username, self.key)
        self.feed_cache = {}

    def get_feed(self, metric_name):

        # make request for feed if it hasn't been retrieved yet
        if metric_name not in self.feed_cache:
            try:
                feed = self.client.feeds(metric_name)
            except RequestError:  # Doesn't exist, create a new feed
                feed = self.client.create_feed(Feed(name=metric_name))

            self.feed_cache[metric_name] = feed

        return self.feed_cache[metric_name]

    def export(self, logs):

        # TODO: user send_batch_data instead
        # https://github.com/adafruit/Adafruit_IO_Python/blob/869cf3547cbda48a3e51029419cf82cef4c5b8ad/Adafruit_IO/client.py#L158

        for log in logs:
            feed = self.get_feed(log.metric.name)

            try:
                self.client.send_data(
                    feed.key, log.value, {
                        'created_at': log.timestamp.isoformat(),
                        'lat': '0',
                        'lon': '0',
                        'ele': '0'
                    })
            except ThrottlingError:
                logger.warning('Adafruit max requests reached, sleeping...')
                time.sleep(self.THROTTLE_SLEEP_TIME)
                logger.warning('Sleep done, attempting request again')
                self.client.send_data(
                    feed.key, log.value, {
                        'created_at': log.timestamp.isoformat(),
                        'lat': '0',
                        'lon': '0',
                        'ele': '0'
                    })
def create_feed_connection(aio: Client, feed_name: str) -> None:
    """
    Connects to a feed and creates it if it does not exists.

    Arguments:
        - aio: Adafruit IO Client object
        - feed_name: A feed name to connect to

    Returns: None
    """
    try:
        return aio.feeds(feed_name)
        logging.info("[{0}] Connected to {1} feed".format(datetime.now(), feed_name))
    except RequestError: # Doesn't exist, create a new feed
        feed = Feed(name=feed_name)
        logging.info("[{0}] Created {1} feed".format(datetime.now(), feed_name))
        return aio.create_feed(feed)
Example #15
0
    def test_adafruit_io_feed(self):
        load_dotenv(verbose=True)

        KEY = os.getenv("ADAFRUIT_IO_KEY")
        USERNAME = os.getenv("ADAFRUIT_IO_USERNAME")
        aio = Client(USERNAME, KEY)

        try:
            test = aio.feeds("test")
        except RequestError:  # Doesn't exist, create a new feed
            feed = Feed(name="test")
            test = aio.create_feed(feed)

        for i in range(5):
            value = randint(0, 50)
            aio.send_data(test.key, value)

        data = aio.receive(test.key)
        self.assertIsNotNone(data.value)
Example #16
0
def publish(order):
        aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Connect to the client
        try:
                temp_feed = aio.feeds('order') # Set up the feed
        # If the feed doesn't exist, we create a new one
        except RequestError:
                temp_feed=Feed(name='order')
                temp_feed=aio.create_feed(temp_feed)

        aio.send('order',order) # Send the order value to Adafruit


        # We are going to create a new database (CSV) containing the order and its time
        # Collect the time
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S") # Convert into a string

        c = csv.writer(open('order.csv', 'a'))
        c.writerow([order,dt_string]) # Writing in a line the order and its time
def main():
    args = ArgumentParser(
        description=
        "An MQTT client that gets messages from an Adafruit IO feed and sends its payload to a NEXA server"
    )
    args.add_argument(
        "--feed-name",
        "-f",
        default="NEXA Switches",
        help="The name of the feed on Adafruit.io that you want to subscribe to"
    )
    args.add_argument(
        "--server-url",
        "-u",
        default="http://localhost:5000",
        help="The URL of the server that controls the NEXA switches")
    ns = args.parse_args()
    FEED_NAME = ns.feed_name
    SERVER_URL = ns.server_url

    # List feeds
    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    feeds = aio.feeds()
    feed_names = [f.name for f in feeds]
    if FEED_NAME not in feed_names:
        print(f"The feed \"{FEED_NAME}\" does not exist")
        print(f"Please choose between the available feeds: {feed_names}")
        sys.exit(-1)

    # Connect to Adafruit IO MQTT server
    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    lamp_endpoint = SERVER_URL + "/lamp"
    client.on_message = get_on_message(lamp_endpoint)

    # For modifying TLS settings (since it did not work, due to self-signed certificate)
    import ssl
    client._client._ssl_context = None
    client._client.tls_set_context(ssl._create_unverified_context())

    client.connect()
    client.subscribe(FEED_NAME)
    client.loop_blocking()
Example #18
0
def main():

    logging.basicConfig(format="%(asctime)-15s %(message)s",
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    parser = argparse.ArgumentParser(description='Climate')
    parser.add_argument('-i', '--interval', help='reporting interval in seconds')
    parser.add_argument('-d', '--display_only', help='only display, no reporting', action="store_true")
    args = parser.parse_args()

    if args.interval:
        Registry.reporting_interval = int(args.interval)
    display_only = args.display_only

    # REST client.
    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Adafruit IO Feeds.
    temperature_feed = aio.feeds('room-temperature')

    while True:

        try:
            temperature = DS18B20.get_temperature()

            if temperature is not None:
                logging.info('Temp={0:0.1f}*C Send readings={1}'.format(temperature, not display_only))
            else:
                logging.info('Failed to get readings, trying again in {} seconds'.format(Registry.reporting_interval))

            if not display_only:
                send_readings(aio, temperature, temperature_feed)

        #except Adafruit_IO.errors.ThrottlingError as ex:
        #    logging.info('Throttling occured - Caught exception: %s', ex.__class__.__name__)
        except Exception as ex:
            logging.info('Caught exception: %s', ex.__class__.__name__)
            traceback.print_exc()

        # Avoid flooding Adafruit IO
        time.sleep(Registry.reporting_interval)
def hello_pubsub(event, context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    print("Execution Starting")
    pubsub_message = json.loads(base64.b64decode(event['data']).decode('utf-8'))
    time_elapsed = 240
    limit = float(120)
    print("Checking Time limit")
    print(time_elapsed)
    if time_elapsed > limit:
        print("Limit exceeded, connecting to twillio client")
        prob_list = pubsub_message['probs']
        appliances = ["treadmill", "washing machine", "dishwasher", "microwave", "microwave", "kettle", " ", " "]
        active_appliances = []
        print("Checking probabilities of appliances")
        for prob in prob_list:
            if prob > 0.2:
                index = prob_list.index(prob)
                device_name = appliances[index]
                active_appliances.append(device_name)
                print("Appliance {} detected".format(device_name))
    if active_appliances:
        # Create an instance of the REST client.
        aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
        devices = aio.feeds('devices')
        # aio.send_data(devices.key, active_appliances.index(appliance))
        # for appliance in active_appliances:
        #     aio.send_data(devices.key, appliance)
        #     print("Sending data to adafruit feed")
        #     print("Data Sent")
        str = " "
        data = str.join(active_appliances)
        aio.send_data(devices.key, data)
        print("Sent")
Example #20
0
import urllib.request
import json
import time
from pprint import pprint

# import Adafruit IO REST client
from Adafruit_IO import Client

ADAFRUIT_IO_USERNAME = '******'
ADAFRUIT_IO_KEY = '2ab0daef666e49c5b98c0fce4901e647'

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

# set up Adafruit IO feeds
temperature = aio.feeds('temperature')
humidity = aio.feeds('humidity')

while True:
  TS = urllib.request.urlopen("https://api.thingspeak.com/channels/859453/feeds.json?results=2")

  response = TS.read()
  data=json.loads(response)
  pprint(data)
  #b = data['channel']['field1']
  temperature_data = data['feeds'][1]['field1']
  #e = data['feeds'][1]['field1']
  print ("Temperature: " + temperature_data)
  aio.send(temperature.key, temperature_data)

  humidity_data = data['feeds'][0]['field2']
Example #21
0
pip install adafruit-io

import pandas as pd

from Adafruit_IO import RequestError, Client, Feed
import time
import heapq
import queue


Adafruit_IO_USER = '******'
Adafruit_IO_KEY = 'aio_vPev73gZSpASX8arSEyZ0bik3Hc4'

aio = Client(Adafruit_IO_USER,Adafruit_IO_KEY)

feeds = aio.feeds()

firename = []
smokename = []
ledname = []


firekey = []
smokekey = []
ledkey = []

class Map (object):
    def __init__(self):
        self.fire_place_num = []
        self.exit = [1, 3]  # 탈출구인 노드 num 들
        self.all_node_num = 12
Example #22
0
from adafruit_mcp3xxx.mcp3008 import MCP3008
from adafruit_mcp3xxx.analog_in import AnalogIn

# 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 = '******'
# Create an instance of the REST client
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

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

# Create an instance of the `busio.spi` class
spi = busio.SPI(board.SCLK, board.MOSI, board.MISO)

# create the cs (chip select)
cs = digitalio.DigitalInOut(board.D12)

# create a mcp3008 object
mcp = MCP3008(spi, cs)

# create an an adc (single-ended) on pin 0
chan = AnalogIn(mcp, MCP3008.pin_0)
Example #23
0
# Main program logic follows:
# Process arguments
parser = argparse.ArgumentParser()
parser.add_argument('-c',
                    '--clear',
                    action='store_true',
                    help='clear the display on exit')
parser.add_argument('config_file')
parser.add_argument('color')
args = parser.parse_args()

print('Press Ctrl-C to quit.')
if not args.clear:
    print('Use "-c" argument to clear LEDs on exit')

if args.config_file:
    with open(args.config_file, 'r') as f:
        print("reading config file")
        config_data = json.load(f)
else:
    print("no configuration file given, please provide one")

if not args.color:
    exit(1)

ADAFRUIT_IO_USERNAME = config_data["connection"]["aio_username"]
ADAFRUIT_IO_KEY = config_data["connection"]["aio_key"]
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
colorButtonFeed = aio.feeds('long-distance-lamps.colorbutton')
aio.send(colorButtonFeed.key, int(args.color))
Example #24
0
DHT_DATA_PIN = 6

# 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 = '******'

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

# Set up Adafruit IO Feeds.
temperature_feed = aio.feeds('temperature')
humidity_feed = aio.feeds('humidity')

# Set up DHT22 Sensor.
dht22_sensor = Adafruit_DHT.DHT22

while True:
    humidity, temperature = Adafruit_DHT.read_retry(dht22_sensor, DHT_DATA_PIN)
    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
        # Send humidity and temperature feeds to Adafruit IO
        temperature = '%.2f'%(temperature)
        humidity = '%.2f'%(humidity)
        aio.send(temperature_feed.key, str(temperature))
        aio.send(humidity_feed.key, str(humidity))
    else:
Example #25
0
class Lamp:

    logger = ""

    # 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 = ''

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

    # LED strip configuration:
    LED_COUNT = 12  # Number of LED pixels.
    LED_PIN = 18  # GPIO pin connected to the pixels (18 uses PWM!).
    #LED_PIN        = 10     # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
    LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
    LED_DMA = 5  # DMA channel to use for generating signal (try 10)
    LED_BRIGHTNESS = 150  # Set to 0 for darkest and 255 for brightest
    LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
    LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53
    # Use GRB instead of RGB!
    LED_STRIP = ws.SK6812_STRIP_RGBW

    LED_COLORS = 7  # Number of possible led colors
    BUTTON_COLOR_PIN = 27  # GPIO connected to the touch button used to change leds color
    BUTTON_POWER_PIN = 17  # GPIO connected to the switch button used turn off the leds
    BUTTON_SEND_PIN = 22  # GPIO connected to the touch button used to 'answer' to the sister lamp

    currentColor = -1
    # UTC Timezone in ISO-8601 format "YYYY-MM-DDTHH:MM:SSZ"
    colorUpdateTimestamp = ''

    powerButtonPressTimestamp = ''

    strip = None
    hostname = None

    aio = None
    colorButtonFeed = None
    # Wait 'timeoutSend' seconds after choosing the color before sending to aio
    timeoutSend = 5
    # 'True' if the user is in the middle of changing the leds color
    changingColor = False
    # 'True' to indicate that a thread must exit
    exit = False

    lastSavedState = None

    bootstrap = True

    BOUNCE_TIME = 200

    pulseThread = None
    stopPulse = True

    def __init__(self, aio_username, aio_key, logger, debug=False):

        self.logger = logger

        # Setup buttons GPIO
        self.logger.debug("Lamp: setting up gpio")
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.BUTTON_POWER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.BUTTON_COLOR_PIN, GPIO.IN)
        GPIO.setup(self.BUTTON_SEND_PIN, GPIO.IN)
        GPIO.add_event_detect(self.BUTTON_COLOR_PIN,
                              GPIO.FALLING,
                              callback=self.buttonLedCallback,
                              bouncetime=self.BOUNCE_TIME)
        GPIO.add_event_detect(self.BUTTON_POWER_PIN,
                              GPIO.FALLING,
                              callback=self.buttonPowerCallback,
                              bouncetime=self.BOUNCE_TIME)
        GPIO.add_event_detect(self.BUTTON_SEND_PIN,
                              GPIO.FALLING,
                              callback=self.buttonSendCallback,
                              bouncetime=self.BOUNCE_TIME)
        #TODO : gpio per il pulsante di spegnimento del raspberry

        # Initialize Adafruit IO
        # Create an instance of the REST client
        self.logger.debug("Lamp: initiating adafruit connection")
        self.ADAFRUIT_IO_USERNAME = aio_username
        self.ADAFRUIT_IO_KEY = aio_key
        self.aio = Client(self.ADAFRUIT_IO_USERNAME, self.ADAFRUIT_IO_KEY)

        # Initialize feeds
        # Read from existing feeds
        self.colorButtonFeed = self.aio.feeds(
            'long-distance-lamps.colorbutton')

        # Set to true when the send button is pressed
        #sendAnimation = 0

        signal.signal(signal.SIGALRM, self.sendColorTimeoutHandler)

        self.colorUpdateTimestamp = datetime.datetime.utcnow().replace(
            microsecond=0).isoformat()
        self.colorUpdateTimestamp += 'Z'

        # Retrieve Pi hostname to distinguish lamps
        self.hostname = check_output(["hostname"]).decode().strip("\ \n \t")
        self.logger.debug("Lamp: hostname = %s", self.hostname)
        # Create NeoPixel object with appropriate configuration
        if self.hostname == "flash":
            self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN,
                                           self.LED_FREQ_HZ, self.LED_DMA,
                                           self.LED_INVERT,
                                           self.LED_BRIGHTNESS,
                                           self.LED_CHANNEL, self.LED_STRIP)
        elif self.hostname == "priscilla":
            self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN,
                                           self.LED_FREQ_HZ, self.LED_DMA,
                                           self.LED_INVERT,
                                           self.LED_BRIGHTNESS,
                                           self.LED_CHANNEL)
        else:
            self.logger.debug("Invalid hostname!")
            exit(1)

        # Intialize the NeoPixel library (must be called once before other functions)
        self.strip.begin()
        self.strip.setBrightness(self.LED_BRIGHTNESS)
        # Leds are turned off at the beginning

        self.clear()

        threading.Thread(target=self.syncColors).start()
        self.pulseThread = threading.Thread(target=self.newColorReceived)

        self.logger.debug('Lamp: Ready\n \
            d         b\n \
           d           b\n \
          d             b\n \
         d               b\n \
        d     BradiPi     b\n \
         """:::.....:::"""\n \
                fff\n \
              ."   ".\n \
             ^       ^."--.\n \
             b       d     ,\n \
              zzzzzzz       ..oOo\n \
        ')

    def newColorReceived(self):
        self.logger.debug("pulsing...")
        # 10 minutes
        timeout = 600
        while (not self.stopPulse) and timeout >= 0:
            pulse(self.strip, int(self.currentColor), self.LED_BRIGHTNESS)
            timeout -= 1
        self.stopPulse = True
        self.logger.debug("stop pulsing")

    def rollback(self):
        self.logger.debug("Rolling back to last known state....")
        if self.lastSavedState is not None:
            showColor(self.strip, int(self.lastSavedState.value))
            self.colorUpdateTimestamp = self.lastSavedState.updated_at
        self.stopPulse = True
        self.changingColor = False

    @atomicConnection
    def sendColorTimeoutHandler(self, signum, frame):
        self.logger.debug("Lamp: Timeout reached. Sending Color....")
        self.aio.send(self.colorButtonFeed.key, self.currentColor)
        time.sleep(2)
        self.colorUpdateTimestamp = self.aio.receive(
            self.colorButtonFeed.key).updated_at
        self.logger.debug("Lamp: Color sent. Timestamp: %s",
                          self.colorUpdateTimestamp)
        self.changingColor = False

    def buttonLedCallback(self, channel):
        self.logger.debug("Lamp: Led button Pressed")
        if self.stopPulse == False:
            #if it was pulsing wait to stop pulsing
            self.stopPulse = True
            self.pulseThread.join()

        self.changingColor = True
        # Colors range from 0 to COLORS-1
        self.currentColor = (self.currentColor + 1) % self.LED_COLORS
        self.logger.debug("current color %s", self.currentColor)
        showColor(self.strip, self.currentColor)
        # Send signal timer
        signal.alarm(self.timeoutSend)

    @atomicConnection
    def buttonPowerCallback(self, channel):
        self.logger.debug("Lamp: Power button Pressed")
        colorWipe(self.strip, Color(0, 0, 0))
        self.currentColor = -1
        colorButtonData = self.aio.receive(self.colorButtonFeed.key)
        self.powerButtonPressTimestamp = colorButtonData.updated_at

    def buttonSendCallback(self, channel):
        self.logger.debug("Lamp: Send button Pressed")
        #self.strip.setBrightness(50)
        # TODO send animation to adafruit io
        #sendAnimation = 1

    @atomicConnection
    def doSyncColor(self):
        self.logger.debug("syncing color")
        colorButtonData = self.aio.receive(self.colorButtonFeed.key)
        self.lastSavedState = colorButtonData
        #self.logger.debug("%s",colorButtonData.updated_at)
        # If the online value is more recent than local
        if colorButtonData.updated_at > self.colorUpdateTimestamp and not self.bootstrap:
            self.logger.debug("updating colors")
            self.logger.debug("%s", colorButtonData)
            self.currentColor = int(colorButtonData.value)
            self.colorUpdateTimestamp = colorButtonData.updated_at
            showColor(self.strip, self.currentColor)
            self.logger.debug("Lamp: color updated. Timestamp: %s",
                              self.colorUpdateTimestamp)
            #received new color, start to pulse
            if self.pulseThread.is_alive():
                #wait for termination of any running thread
                self.stopPulse = True
                self.pulseThread.join()
            self.stopPulse = False
            self.pulseThread = threading.Thread(target=self.newColorReceived)
            self.pulseThread.start()
            # Update global timestamp
            #self.aio.send(self.colorButtonFeed.key, self.currentColor)
        if self.bootstrap:
            #just started the lamp, set to the last color
            self.logger.debug("updating colors")
            self.logger.debug("%s", colorButtonData)
            self.bootstrap = False
            self.currentColor = int(colorButtonData.value)
            self.colorUpdateTimestamp = colorButtonData.updated_at
            showColor(self.strip, self.currentColor)
            self.logger.debug("Lamp: color updated. Timestamp: %s",
                              self.colorUpdateTimestamp)
            #received new color, start to pulse
            # Update global timestamp
            #self.aio.send(self.colorButtonFeed.key, self.currentColor)

        #self.colorUpdateTimestamp = self.aio.receive(self.colorButtonFeed.key).updated_at
        #self.logger.debug("curent update time %s", self.colorUpdateTimestamp )

    def syncColors(self):
        """ Function used to synchronize the color of the two lamps, after one has been modified """
        while not self.exit:
            if (not self.changingColor):
                self.doSyncColor()
            # 10 seconds timer
            time.sleep(10)

    def clear(self):
        self.stopPulse = True
        colorWipe(self.strip, Color(0, 0, 0))
# import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, RequestError

# 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 = '******'

aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

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

# Values to send to Adafruit IO
char_val = 'a'
string_val = 'adafruit'
bool_val = True
int_val = 3
long_val = 0x80000000
double_val = 3.1415926535897932
float_val = +1E6


"""
Example #27
0
import re
import time
from Adafruit_IO import Client, Feed
import serial
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # GPIO Numbers instead of board numbers
RELAIS_1_GPIO = 21
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT) # GPIO Assign mode
GPIO.output(RELAIS_1_GPIO, GPIO.LOW) # on

DHT_READ_TIMEOUT = 1
DHT_DATA_PIN = 26
ADAFRUIT_IO_KEY = 'aio_Suyn56lYQOeL8qSBXjKhZ7beh7hM'
ADAFRUIT_IO_USERNAME = '******'
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
temperature_feed = aio.feeds('temperature')
Humadity_feed = aio.feeds('humadit')
indicator_feed = aio.feeds('checkindicator')
soil_feed = aio.feeds('soil')

port = serial.Serial("/dev/rfcomm0", baudrate=115200)

def ternOnPumb():
    StartTime = time.time()
    GPIO.output(RELAIS_1_GPIO, GPIO.HIGH) # out
    while True:
        data=sensor()
        if(float(data[1])<1800):
            StopTime = time.time()
            GPIO.output(RELAIS_1_GPIO, GPIO.LOW) # on
            print(StartTime-StopTime)
Example #28
0
from Adafruit_IO import Client, Feed, RequestError

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

# 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'

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

try: # if we have a 'servo' feed
    servo_feed = aio.feeds('servo')
except RequestError: # create a servo feed
    feed = Feed(name='servo')
    servo_feed = aio.create_feed(feed)

# Create the I2C bus interface.
i2c_bus = I2C(SCL, SDA)

# Create a simple PCA9685 class instance.
pca = PCA9685(i2c_bus)

# Set the PWM frequency to 50hz.
pca.frequency = 50
SERVO_CHANNEL = 0

# counter variable for the last servo angle
Example #29
0
# 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 = 'e69155097ffa4624ae09d57213e200ed'


# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_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('MasterBath')
except RequestError: # create a digital feed
    feed = Feed(name="MasterBath")
    digital = aio.create_feed(feed)

# led set up
#led = digitalio.DigitalInOut(board.D5)
#led.direction = digitalio.Direction.OUTPUT


while True:
#    data = aio.receive(digital.key)
    data = aio.receive(digital.Default)
    if int(data.value) == 1:
        print('received <- ON\n')
    elif int(data.value) == 0:
Example #30
0
BLUE_PIN = 4

# 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 = '******'

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

try: # if we have a 'color' feed
    color = aio.feeds('color')
except RequestError: # create an `color` feed
    feed = Feed(name='color')
    color = aio.create_feed(feed)

# Create the I2C bus interface.
i2c_bus = I2C(SCL, SDA)

# Create a simple PCA9685 class instance.
pca = PCA9685(i2c_bus)
pca.frequency = 60
prev_color = '#000000'

def map_range(x, in_min, in_max, out_min, out_max):
    """re-maps a number from one range to another."""
    mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
Example #31
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Jämföra två filer
#
import time
from Adafruit_IO import Client, Data
aio = Client('1326749aacca46de9b9b34c6a105cb92')


# Print out the feed names:
feeds = aio.feeds()
for f in feeds:
    print('Feed: {0}'.format(f.name))


# Print out the feed metadata.
feed = aio.feeds('StatusColor')
print(feed)

print '/n/n'
    

sc = aio.receive('StatusColor')
print sc
print sc.value

aio.send('StatusColor', '#ff0000')
time.sleep(2)
aio.send('StatusColor', '#ff8800')
time.sleep(2)
Example #32
0
#Import library and create new REST client
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Get a list of feeds
feeds = aio.feeds()

# Print out feed names
for f in feeds:
    print('Feed: {0}'.format(f.name))
Example #33
0
# 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 = '******'

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

# Assign a location feed, if one exists already
try:
    location = aio.feeds('location')
except RequestError: # Doesn't exist, create a new feed
    feed = Feed(name="location")
    location = aio.create_feed(feed)

# limit feed updates to every 3 seconds, avoid IO throttle
loop_delay = 5

# We dont' have a GPS hooked up, but let's fake it for the example/test:
# (replace this data with values from a GPS hardware module)
value = 0
lat = 40.726190
lon = -74.005334
ele = 6 # elevation above sea level (meters)

Example #34
0
import json

# 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 = '******'

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

# List all of your feeds
feeds = aio.feeds()
print(feeds)

# Create a new feed
feed = Feed(name="PythonFeed")
response = aio.create_feed(feed)
print(response)

# List a specific feed
feed = aio.feeds(response.key)
print(feed)


# Delete a feed
aio.delete_feed(response.key)
from discord.ext import commands
from Adafruit_IO import Client, Feed, Data, RequestError
from enum import Enum

ADAFRUIT_IO_KEY = "ADAFRUIT_IO_KEY"
ADAFRUIT_IO_USERNAME = "******"
ADAFRUIT_IO_VIDISCORDMONITOR_FEED_KEY = 'ADAFRUIT_IO_VIDISCORDMONITOR_FEED_KEY'

DISCORDBOT_PRIVATE_KEY = 'DiscordBotPrivateKeyHere'

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

#Try and open feed, if nonexistent, create:
try:
    viDiscordMonitorFeed = aio.feeds(ADAFRUIT_IO_VIDISCORDMONITOR_FEED_KEY)
except RequestError:
    print('Error accessing Adafruit io')
'''
LightByte: a special variable containing all data needed for which colors an RGB light should be flashing in a single 
byte (integer) by combining Binary with "Red Orange Yellow Green Blue Indigo Violet Off" (ROYGBIV+White). This variable is 
initialized to 0 representing "No Lights." This is done so that only a single variable needs to be stored, and only
a single variable needs to be read to determine which status lights need to flash.

LightByte key:
255 = All Statuses + White
128 = All (Flash Red, Orange, Yellow, Green, Blue, Indigo, and Violet.)
64 =  Flash Orange, Yellow, Green, Blue, Indigo, and Violet
and so on.

This will likely need to be interpreted via modulo on the other end by whatever devices are using the LightByte
Example #36
0
# 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 = '******'

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

# Adafruit IO Pi Camera Feed
# note: this feed requires its history to be
# turned off from the adafruit io feed page
picam_feed = aio.feeds('picam')

# set up picamera
camera = picamera.PiCamera()

# set the resolution of the camera's captures
# note: Adafruit IO feeds with history turned
# OFF only support images < 1kb
camera.resolution = (200, 200)

print('Adafruit IO: Raspberry Pi Camera Example')

while True:
  camera.capture('image.jpg')
  print('Camera: SNAP!')
  with open("image.jpg", "rb") as imageFile:
from Adafruit_IO import Client, Feed, RequestError

# 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 = '******'

# 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('digital')
except RequestError: # create a digital feed
    feed = Feed(name="digital")
    digital = aio.create_feed(feed)

# led set up
led = digitalio.DigitalInOut(board.D5)
led.direction = digitalio.Direction.OUTPUT


while True:
    data = aio.receive(digital.key)
    if int(data.value) == 1:
        print('received <- ON\n')
    elif int(data.value) == 0:
        print('received <- OFF\n')
Example #38
0
class AirMonitor:
    def __init__(self):
        self.temperature_celsius = None
        self.temperature_fahrenheit = None
        self.humidity = None

        GPIO.setwarnings(True)
        GPIO.setmode(GPIO.BCM)

        self.config = configparser.ConfigParser()
        self.config.read('AirMonitor.cfg')
        self.SetupSesnors()

        if self.config['DISPLAY']['ENABLED'].upper() == 'Y':
            self.display = lcddriver.lcd()

        if self.config['ADAFRUIT_IO']['ENABLED'].upper() == 'Y':
            self.adafruit_last_upload = None
            self.aio = Client(self.config['ADAFRUIT_IO']['USER'],
                              self.config['ADAFRUIT_IO']['KEY'])

    def Run(self):
        """Main run sequence
        """
        while True:
            self.GetEnvironmentMetrics()
            self.LogResults()

            if self.config['DISPLAY']['ENABLED'].upper() == 'Y':
                self.UpdateLCDDisplay()

            self.AdafruitUpload()

            time.sleep(int(self.config['DEFAULT']['UPDATE_INTERVAL']))

    def _FormatResult(self, unformatted_value):
        """Formats a value to a single precision floating point

        :param unformatted_value: Value to format
        :type unformatted_value: float
        :return: Formatted value
        :rtype: float
        """
        value = '{0:.3g}'.format(unformatted_value)
        if '.' in value:
            value = value.rstrip('0')
        return value

    def _ctof(self, celsius_temperature):
        """Helper to convert celsius to fahrenheit

        :param celsius_temperature: celsius value to convert
        :type celsius_temperature: float
        :return: Fahrenheit temperature
        :rtype: float
        """
        return (celsius_temperature * (9 / 5)) + 32

    def AdafruitUpload(self):
        """Upload observed values to Adafruit IO
        """
        if self.config['ADAFRUIT_IO']['ENABLED'].upper() == 'Y':

            if not self.adafruit_last_upload or \
            datetime.datetime.now() >= self.adafruit_last_upload + \
                datetime.timedelta(
                    minutes=int(self.config['ADAFRUIT_IO']['UPLOAD_INTERVAL'])):

                values = self.GetValueDict()

                for key in values:
                    if values[key]:
                        try:
                            feed = self.aio.feeds(feed=key)
                        except RequestError:
                            feed = Feed(name=key)
                            feed = self.aio.create_feed(feed)

                        self.aio.send_data(feed.key, values[key])
                self.adafruit_last_upload = datetime.datetime.now()

    def Cleanup(self):
        """Run cleanup and shutdown tasks
        """
        self.Log("Shutting Down")
        GPIO.cleanup()

    def DHT11Read(self):
        """Read data from a DHT11 sensor
        """
        result = self.dht_sensor.read()

        if result.is_valid():
            corrected_temperature = result.temperature + \
                float(self.config['DHT11']['TEMPERATURE_CALIBRATION'])
            corrected_humidity = result.humidity + \
                float(self.config['DHT11']['HUMIDITY_CALIBRATION'])
            self.temperature_celsius = self._FormatResult(
                corrected_temperature)
            self.temperature_fahrenheit = self._FormatResult(
                self._ctof(corrected_temperature))
            self.humidity = self._FormatResult(corrected_humidity)
        else:
            self.Log("DHT11 Error: %d" % result.error_code)

    def GetEnvironmentMetrics(self):
        """Collect data from the available sensors
        """
        if self.dht_sensor:
            self.DHT11Read()

    def GetValueDict(self):
        """Get data values in dict format

        :return: Observed data values
        :rtype: dict
        """
        return {
            'fahrenheit': self.temperature_fahrenheit,
            'celsius': self.temperature_celsius,
            'humidity': self.humidity
        }

    def Log(self, message):
        """Logging wrapper

        :param message: Message to log
        :type message: string
        """
        if self.config['LOGGING']['CONSOLE_ENABLED'].upper() == 'Y':
            print(message)

    def LogResults(self):
        """Log data results
        """
        self.Log(f"{datetime.datetime.now()}")
        self.Log(f"celsius: {self.temperature_celsius}C")
        self.Log(f"Fahrenheit: {self.temperature_fahrenheit}F")
        self.Log(f"Humidity: {self.humidity}%")

    def SetupSesnors(self):
        """Initializes sensors

        :raises Exception: If invalid sensor configuration provided
        """
        if self.config['ENV_SENSOR']['TYPE'] == 'DHT11':
            self.dht_sensor = dht11.DHT11(pin=int(self.config['DHT11']['PIN']))
        else:
            raise Exception('Invalid sensor defined')

    def UpdateLCDDisplay(self):
        """Update the LCD display
        """
        self.display.lcd_clear()
        self.display.lcd_display_string(f'{datetime.datetime.now()}', 1)
        self.display.lcd_display_string(
            f'T|{self.temperature_fahrenheit}F H|{self.humidity}%', 2)
Example #39
0
from Adafruit_IO import RequestError, Client, Feed

ADAFRUIT_IO_USERNAME = "******"
ADAFRUIT_IO_KEY = "aio_VZpp31HB6hfilyplS2rj1zre0wST"

aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

hum = aio.feeds('hum')

aio.send_data(hum.key, 78)
Example #40
0
    # Starting Program    #
    #######################
    print('*****************************************************')
    print('*****************************************************')
    print('***     Raspberry Pi: LEM-KIT v2                  ***')
    print('***       GPS: ok                                 ***')
    print('***       BME: ok                                 ***')
    print('***       CO2: ok                                 ***')
    print('*****************************************************')
    print('*****************************************************')
    print('=' * 40)  # Print a separator line.

    #Assigning Feeds from Adafruit.IO, only if useAIO=true
    try:
        tempFeed = aio.feeds(
            'temperature-rpi'
        )  #wichtig: auch wenn man _ im adafruit IO macht, es kennt nur - (Bindestriche)
        humiFeed = aio.feeds('humidity-rpi')
        pressFeed = aio.feeds('pressure-rpi')
        co2Feed = aio.feeds('co2-rpi')
        locationFeed = aio.feeds('gps-rpi')  #gps feed
    except RequestError:  # Doesn't exist, create a new feed
        print(
            'Oh oh, something went wrong with assigning Adafruit.IO Feeds :(')

    print('***********************************')
    print('***     Initializing Sensors    ***')
    print('***********************************')

    #Starting BME Sensor
    print('Initializing BME280 Sensor')
#ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY'
# keep your username and secret key in a shared module
from aoi_key import ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY

# Delay in-between sensor readings, in seconds.
READ_TIMEOUT = 5

# Name of the Adafruit IO feed
FEED_NAME = "tmp75"

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

# Set up Adafruit IO Feeds.
try:
    tmp75_feed = aio.feeds(FEED_NAME)
except errors.RequestError:
    feed = Feed(name=FEED_NAME)
    tmp75_feed = aio.create_feed(feed)
    print("Created feed %s" % FEED_NAME)

# Set up TMP75 Sensor
tmp75_sensor = barbudor_tmp75.TMP75(board.I2C())
tmp75_error = False

while True:
    try:
        if tmp75_error: # if an error occured, re-write config register with 12 bits mode
            # pylint: disable=protected-access
            tmp75_sensor.config = barbudor_tmp75._CONFIG_CONVERTER_12BITS
            # pylint: enable=protected-access
Example #42
0
# 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 = 'e69155097ffa4624ae09d57213e200ed'


# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_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('masterbath')
except RequestError: # create a digital feed
    feed = Feed(name="masterbath")
    digital = aio.create_feed(feed)

count = 0

while count < 5:
    data = aio.receive(digital.key)
    if int(data.value) == 1:
        print('received <- ON\n')
    elif int(data.value) == 0:
        print('received <- OFF\n')

    time.sleep(1)
    count = count +1