示例#1
0
文件: feed.py 项目: jerbly/adaiot
 def run(self):
     print "ChartThread connecting"
     aio = Client(self._client_key)
 
     print "ChartThread fetching data"
     data = aio.data(self._feed_name)
 
     today = datetime.datetime.now()
     one_day = datetime.timedelta(days=1)
     yesterday = today - one_day
 
     dates = []
     temps = []
 
     print "ChartThread treating data"
     for d in data:
         ts = datetime.datetime.fromtimestamp(d.created_epoch)
         if ts > yesterday:
             dates.append(ts)
             temps.append(d.value)
 
     print "ChartThread plotting"
     dates = date2num(dates)
 
     fig = plt.figure()
     fig.set_size_inches(4, 3)
     plt.subplots_adjust(left=0.0, right=0.925, bottom=0.0, top=0.948)
     ax = fig.add_subplot(111)
     ax.plot_date(dates, temps, '-')
     ax.axes.get_xaxis().set_visible(False)
     plt.savefig(self._out_dir+'temps.png', dpi = 80, bbox_inches='tight', pad_inches = 0)
     plt.close(fig)
     print "ChartThread done"
示例#2
0
class AdafruitHandler(MessageHandler):

    def __init__(self, api_key, feed, message_field = "value"):
        self.message_field = message_field
        self.client = Client(api_key)
        self.feed = feed

    def send_value(self, value):

        logging.debug("Send value %s to feed %s", value, self.feed)
        self.client.send(self.feed, value)

    def handle(self, message):

        value = message.data[self.message_field]
        self.send_value(value)
示例#3
0
class AioWriter(threading.Thread):

    def __init__(self, queue):
        super().__init__()
        self.queue = queue
        self.aio = Client(AIO_KEY)
        self.daemon = False

    def run(self):
        while True:
            # Get the reading from the queue
            reading = self.queue.get()

            temperature = reading['temp']
            id = reading['id']
            try:
                self.aio.send(id, temperature)
            except AdafruitIOError as e:
                print(e)
示例#4
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.setDaemon(True)
     self._homeDir        = os.path.expanduser("~/.sensomatic")
     self._configFileName = self._homeDir + '/config.ini'
     self._config         = ConfigParser.ConfigParser()
     self._readConfig()
     self._redis          = redis.StrictRedis(host= self._config.get("REDIS", "ServerAddress"),
                                              port= self._config.get("REDIS", "ServerPort"),
                                              db  = 0)
     self._adafruit       = Client(self._config.get("ADAFRUIT", "Id"))
示例#5
0
class IOAdafruitConnector(object):

    def __init__(self, api_key=None):

        if not api_key:
            api_key =  SERVICES['ADAFRUITIO_KEY']

        self.aio = Client(api_key)

    def send(self, data):
        # send data to dweet

        try:
            for key, value in data.iteritems():
                self.aio.send(key, value)

            response = {'status': 'ok'}
        except Exception as exception:
            response = {'error': exception.message}

        return response
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")
示例#7
0
class powermeter():
    def __init__(self,
                 powermeter_IP="localhost",
                 powermeter_PORT=7777,
                 online='6ddea3a7998b483183641022b542826d'):
        self.powermeter_IP = powermeter_IP
        self.powermeter_PORT = powermeter_PORT
        print("powermeter IP:" + str(powermeter_IP))
        print("powermeter port:" + str(powermeter_PORT))
        self.powermeter = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        if online:
            from Adafruit_IO import Client
            self.last_sent = time.time()
            self.aio = Client(online)

    def do(self):
        self.powermeter.sendto("r".encode("ascii"),
                               (self.powermeter_IP, self.powermeter_PORT))
        data, addr = self.powermeter.recvfrom(512)  # buffer size is 1024 bytes

        return int(data.decode("ascii"))

    def read(self, size=10):
        last = []
        for i in range(size):
            last.append(self.do())
        power = np.mean(np.array(last)) / 1000000.0
        std = np.std(np.array(last)) / 1000000.0
        if self.aio:
            if (time.time() - self.last_sent >= 2):
                try:
                    self.aio.send('power', power)
                    self.last_sent = time.time()
                except Exception:
                    pass
        return power
示例#8
0
    def run(self):
        print "ChartThread connecting"
        aio = Client(self._client_key)

        print "ChartThread fetching data"
        data = aio.data(self._feed_name)

        today = datetime.datetime.now()
        one_day = datetime.timedelta(days=1)
        yesterday = today - one_day

        dates = []
        temps = []

        print "ChartThread treating data"
        for d in data:
            ts = datetime.datetime.fromtimestamp(d.created_epoch)
            if ts > yesterday:
                dates.append(ts)
                temps.append(d.value)

        print "ChartThread plotting"
        dates = date2num(dates)

        fig = plt.figure()
        fig.set_size_inches(4, 3)
        plt.subplots_adjust(left=0.0, right=0.925, bottom=0.0, top=0.948)
        ax = fig.add_subplot(111)
        ax.plot_date(dates, temps, '-')
        ax.axes.get_xaxis().set_visible(False)
        plt.savefig(self._out_dir + 'temps.png',
                    dpi=80,
                    bbox_inches='tight',
                    pad_inches=0)
        plt.close(fig)
        print "ChartThread done"
示例#9
0
def demarrage_adafruit():
    global etat_chaudiere_html_old
    #parametrage de l'adafruit
    aio = Client('ducjul', 'e076463fcb1446c3aea3184b44285d1a')

    while 1:
        data = aio.receive('chaudiere-action')
        etat_chaudiere_html = format(data.value)
        #Affichage de l'état réel
        variable_input = "etat_chaudiere"
        lecture_db(variable_input)
        etat_chaudiere = lecture_db(variable_input)
        #envoi info adafruit
        if etat_chaudiere == 1:
            aio.send('etat-de-la-chaudiere', 'Allumée')
        else:
            aio.send('etat-de-la-chaudiere', 'Eteinte')

        #lecture temperature interieur db
        variable_input = "temperature_interieur"
        lecture_db(variable_input)
        etat_temperature = lecture_db(variable_input)
        etat_temperature = str(etat_temperature)
        aio.send('temperature-exterieur', etat_temperature)
        print(etat_temperature + " send")

        if etat_chaudiere_html == "ON" and etat_chaudiere_html_old != etat_chaudiere_html:
            #ecriture de la variable sur la base
            variable_input = "mode_manu"
            variable_etat = 1
            update_db(variable_input, variable_etat)
            etat_chaudiere_html_old = etat_chaudiere_html

        if etat_chaudiere_html == "OFF" and etat_chaudiere_html_old != etat_chaudiere_html:
            #ecriture de la variable sur la base
            variable_input = "mode_manu"
            variable_etat = 0
            update_db(variable_input, variable_etat)
            etat_chaudiere_html_old = etat_chaudiere_html

        time.sleep(5)
示例#10
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'
                    })
示例#11
0
class IagPlugin:
    def __init__(self, username, key):
        self.IndoorTemp = 0
        self._hasData = False
        self._aio = Client(username, key)

    def GetIntervalSeconds(_):
        return 60  # 1 min

    def Execute(self):
        self.Refresh()

    def Refresh(self):
        try:
            self.IndoorTemp = round(float(self._aio.data('temp')[0].value))
        except:
            e = sys.exc_info()
            print("Failed to load IAQ data - " + str(e))
示例#12
0
 def readAndSend(self):
     #login details passed to SetUp class. dht output set to gpio 24
     newSetUp = SetUp(adafruit_dht.DHT11(board.D24), "Ddoy",
                      "aio_OqZD42C9OM09r2wiYNAVoyK1K9yC",
                      Client("Ddoy", "aio_OqZD42C9OM09r2wiYNAVoyK1K9yC"))
     #feeds passed to SetFeed class
     newFeed = SetFeed(newSetUp.aio.feeds('temperature'),
                       newSetUp.aio.feeds('humidity'),
                       newSetUp.aio.feeds('light'))
     #setting up adc spi communication with raspberry pi
     spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
     #setting adc output to gpio 22 on pi
     cs = digitalio.DigitalInOut(board.D22)
     mcp = MCP.MCP3008(spi, cs)
     #setting LDR analog output to mcp3008 pin 1
     chan1 = AnalogIn(mcp, MCP.P1)
     #while loop reads and sends sensor values every 0.5 sec, also handles errors
     while True:
         try:
             #getting values of DHT11 and ACD
             temperature = newSetUp.dhtDevice.temperature
             humidity = newSetUp.dhtDevice.humidity
             #voltage value converted to lumen
             light = chan1.voltage * 40
             #prints light, temp and humidity to console
             print("Light level: " + str(light) + " lux")
             print("Temp: " + str(temperature) + "C   " + "Humidity: " +
                   str(humidity) + "%")
             #sends sensor values to feeds on webclient
             newSetUp.aio.send(newFeed.temperature_feed.key,
                               str(temperature))
             newSetUp.aio.send(newFeed.humidity_feed.key, str(humidity))
             newSetUp.aio.send(newFeed.light_feed.key, str(light))
             #displays error causing runtime then continues while loop
         except RuntimeError as error:
             print(error.args[0])
             time.sleep(0.5)
             continue
         except Exception as error:
             raise error
         #closes program when keyboard interrupted
         except (KeyboardInterrupt, SystemExit):
             interrupt()
         time.sleep(0.5)
示例#13
0
def main():
    """ main """

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

    parser = argparse.ArgumentParser(description='CPU Utilisation')
    parser.add_argument('--interval', help='reporting interval in seconds')
    args = parser.parse_args()

    reporting_interval = int(args.interval) if args.interval else REPORTING_INTERVAL_DEFAULT_SECS

    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    hostname = platform.node().lower()
    feed_name = "cpu-" + hostname

    report_cpu(aio, feed_name, reporting_interval)
示例#14
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)
示例#15
0
def mqtt_send():
    if ((check_mqtt.get() == 1)):
        aio = Client(mqtt_username.get(), mqtt_api_key.get())
        mqtt_sending_df = mqtt_sending_data.append(all_country_df[all_country_df['country'] == custome_country], ignore_index=True)
        for country in mqtt_sending_df["country"]:
            country_pos = pd.Index(list(mqtt_sending_df.country))
            mqtt_sending_df_transpose = mqtt_sending_df[mqtt_sending_df["country"]==country].transpose()
            mqtt_sending_df_transpose.columns = ['Data']
            data_for_send = str(country_pos.get_loc(country)+1)+"_"+str(mqtt_sending_df_transpose['Data'][0])+"_"+str(mqtt_sending_df_transpose['Data'][1])+"_"+str(mqtt_sending_df_transpose['Data'][2])+"_"+str(mqtt_sending_df_transpose['Data'][3])+"_"+str(mqtt_sending_df_transpose['Data'][4])+"_"+str(mqtt_sending_df_transpose['Data'][5])+"_"+str(mqtt_sending_df_transpose['Data'][6])+"_"+str('{0:.2f}'.format(mqtt_sending_df_transpose['Data'][8]))
            aio.send('covid-19', data_for_send)
            aio.send('last-updated-time', last_time)
            sleep(1)
            print(mqtt_sending_df_transpose)
            print(data_for_send)
示例#16
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)
def update_adafruitio(weather_forecast):
    aio_username = os.environ['AIO_USERNAME']
    aio_api_key = os.environ['AIO_API_KEY']
    aio_feeds = [
        'weather-station.darksky-minutely', 'weather-station.darksky-hourly'
    ]

    # Setting up the aio connection
    aio = Client(aio_username, aio_api_key)

    # Retrieving a list of all forecast data values and deleting them as we don't need that data to persist
    for feed in aio_feeds:
        d = aio.data(feed)
        for data in d:
            aio.delete(feed, data.id)

    # Now send the forecasts to Adafruit
    for i in range(0, 2):  # 0 == Minutely, 1 == Hourly
        aio.send_data(aio_feeds[i], weather_forecast[i])
示例#18
0
    def connect_to_aio(self):
        """Connect to Adafruit.IO"""
        # Create an instance of the REST client.
        if self.ADAFRUIT_IO_USERNAME is None or self.ADAFRUIT_IO_KEY is None:
            print("Adafruit IO keys not found, aborting connection")
            return False

        try:
            print("Atempting to connect to AIO as " +
                  self.ADAFRUIT_IO_USERNAME)
            self.__client = AIO_Client(self.ADAFRUIT_IO_USERNAME,
                                       self.ADAFRUIT_IO_KEY)
            print("Connected to Adafruit.IO")
            self.AIO_CONNECTION_STATE = True
            return True

        except Exception as e:
            print("Failed to connect to AIO, disabling it")
            print(e)
            self.AIO_CONNECTION_STATE = False
            return False
示例#19
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)
示例#20
0
def handler(event, context):
    aio = Client(ADAFRUIT_USERNAME, ADAFRUIT_KEY)
    check_dates = last_few_days(days=PRECIPITATION_DAYS)
    precipitation = total_precipitation(check_dates)
    duration = aio_watering_duration(aio)
    summary = "Total precipitation in past {0:d} days : {1:.2f}mm"
    print(summary.format(len(check_dates), precipitation))

    if precipitation > PRECIPITATION_SKIP:
        print("Skip watering {}min for today (more than {}mm).".format(
            duration, PRECIPITATION_SKIP))
    else:
        print("Will be watering {}min today (less than {}mm).".format(
            duration, PRECIPITATION_SKIP))

        if is_watering_period(duration, 0):
            print("Watering NOW!")
            aio_set_pump(aio, 1)
        elif is_watering_period(duration, 5):
            print("Stopping watering (up to 5 minutes after schedule)")
            aio_set_pump(aio, 1)
        else:
            print("Not watering right now, outside target period.")
示例#21
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=""
示例#22
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
示例#23
0
#!/usr/bin/python

# Import Library & create instance of REST client
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Send the value of 1 to BlockHeat02
aio.send('BlockHeat02',0)

# Retrieve the most recent value from 'Outside-Temp'
#data = aio.receive('BlockHeat02')
#print('Received Value: {0}'.format(data.value))

示例#24
0
#!/usr/bin/python

# Import Library & create instance of REST client
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Send the value of 1 to BlockHeat02
aio.send('blockheat02',0)

# Retrieve the most recent value from 'BlockHeat02'
data = aio.receive('BlockHeat02')
print('Received Value: {0}'.format(data.value))

# get the host and build a path for the logfile and make the file name individual
host = socket.gethostname()
path = '/home/pi/RPI-Weather-Log/logs/rpi_weather_data_{}.log'.format(host)
LOG_FILENAME = path

# Set up a specific logger with our desired output level
weather_logger = logging.getLogger('WeatherLogger')
weather_logger.setLevel(logging.INFO)

# Add the log message handler to the logger and make a log-rotation of 100 files with max. 10MB per file
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=LOG_SIZE, backupCount=BACKUP_COUNT,)
weather_logger.addHandler(handler)

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

# Every refresh_interval seconds we'll refresh the weather data
pause = 0.1
ticks_per_second = 1 / pause
refresh_interval = 60 * REFRESH_RATE

# reed brightness slider from adafruit io feed
brightness = aio.receive('brightness')
brightness = int(brightness.value)


# get location for weather requests
def get_location():
    location_request_url = 'http://ip-api.com/json'
    location_data = requests.get(location_request_url).json()
示例#26
0
#====================================================================
# Import subfiles
#====================================================================
import datetime
import glob
import os
import re
#import serial
import subprocess
import sys
import time
import warnings

# Import library and create instance of REST client.
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Set Variables
DEBUG = 1

# Add a delay for boot
time.sleep(1)

# Continuously append data
while(True):

  os.system('modprobe w1-gpio')
  os.system('modprobe w1-therm')
 
  base_dir = '/sys/bus/w1/devices/'
#  device_folder1 = glob.glob(base_dir + '*27c2')[0]
示例#27
0
    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 \
        ')
示例#28
0
import logging
import os

from Adafruit_IO import Data
YOUR_AIO_USERNAME = os.getenv('YOUR_AIO_USERNAME')  #ADAFRUIT_IO_USERNAME
YOUR_AIO_KEY = os.getenv('YOUR_AIO_KEY')  #ADAFRUIT_IO_KEY
from Adafruit_IO import Client, Feed
aio = Client(YOUR_AIO_USERNAME, YOUR_AIO_KEY)

#create feed
new = Feed(name='chatbot1')
result = aio.create_feed(new)

#logging exception handler
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)
logger = logging.getLogger(__name__)

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import requests  #Getting the data from the cloud


def ledoff(bot, update):
    value = Data(value=0)  #Sending a value to a feed
    value_send = aio.create_data('chatbot1', value)
    chat_id = bot.message.chat_id
    update.bot.sendPhoto(
        chat_id=chat_id,
        photo=
        "https://tse3.mm.bing.net/th?id=OIP.dTmDdvOWEO-0s7t0Z3Yr4gHaJ4&pid=Api&P=0&w=300&h=300",
示例#29
0
#====================================================================
# Import subfiles
#====================================================================
import datetime
import glob
import os
import re
import serial
import subprocess
import sys
import time
import warnings

# Import library and create instance of REST client.
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Set Variables
DEBUG = 1

# Add a delay for boot
time.sleep(1)

# Continuously append data
while(True):

  time.sleep(1)

  # Read the Current Garage Temperature
  def read_CurrentMapleHouseTemp():
    f = open("/home/robin/MapleHouseTemp.txt", "r")
示例#30
0
 def __init__(self, queue):
     super().__init__()
     self.queue = queue
     self.aio = Client(AIO_KEY)
     self.daemon = False
示例#31
0
import board

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

# 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:
示例#32
0
import time

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

# 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
示例#33
0
# TODO: Incorporate Python logging Module into controls
# TODO: Find a logging website other than io.adafruit for greater logging capabilities
# TODO: Find a decent light sensor and incorporate it into program
# TODO: Devise a means of checking the battery state before operating the fans
# TODO: Incorporate PowerSwitch Tail to turn a heater on and off
# TODO: Modify fan code so both fans only come on during daylight
# TODO: Create a warning message system for events such as high/low temp, low bat. etc...

# Global config stuff
#tsl = TSL2561()
config = SafeConfigParser()
config.read('/home/pi/Projects/Greenhouse/config.cfg')
interval = config.getint('defaults', 'interval')  # Get sensor updating interval
debug = config.getboolean('defaults', 'debug')  # debug print to console
ADAFRUIT_IO_KEY = config.get('defaults', 'aio_key')  # Import Adafruit aio Key
aio = Client(ADAFRUIT_IO_KEY)
DHT_TYPE = Adafruit_DHT.DHT22
DHT_PIN = config.getint('defaults', 'dht_pin')
mysqlUpdate = config.getboolean('database', 'mysqlUpdate')  # Are we using database?
max_cpu_temp = config.getint('defaults', 'max_cpu_temp')
exhaustOn = config.getint('environment', 'exhaust_fan_on')
exhaustOff = config.getint('environment', 'exhaust_fan_off')
circulate_temp = config.getint('environment', 'circulate_temp')
message_service = config.getboolean('email', 'send_email')
dayTempHigh = config.getint('environment', 'day_temp_high')
dayTempLow = config.getint('environment', 'day_temp_low')
nightTempHigh = config.getint('environment', 'night_temp_high')
nightTempLow = config.getint('environment', 'night_temp_low')
heaterPin = config.getint('defaults', 'heaterPin')

# Setup and initiate fans on GPIO pins.  Fans should be connected to a relay board.
示例#34
0
文件: loop.py 项目: mampersat/minions
def write_to_adafruit(t,h):
    try:
        aio = Client('3f755fc33a12977916bcbb1b518c8772ee16faaf')
        aio.send('minion1', t)
    except:
        print "request error"
示例#35
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 = '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')
示例#36
0
import time
import Adafruit_MCP9808.MCP9808 as MCP9808
from Adafruit_IO import Client

aio = Client('SECRET')
  
sensor = MCP9808.MCP9808()
sensor.begin()

def get_temperature():
        temp = sensor.readTempC()
        return '{0:0.3F}'.format(temp)

while True:
    try:
        aio.send('deck-temp', get_temperature() )
    except:
        print "Failed to send"
    time.sleep(30)
from Adafruit_IO import Client
import tempSensor

ADAFRUIT_IO_KEY = 'f48251f19a88f21b5e7f9e97e2c81428d2120958'

aio = Client(ADAFRUIT_IO_KEY)
temperature = tempSensor.readTemperature()
res = aio.send('bedroom', temperature)
print res.created_at, res.value
示例#38
0
    def __init__(self, api_key=None):

        if not api_key:
            api_key =  SERVICES['ADAFRUITIO_KEY']

        self.aio = Client(api_key)
示例#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)
示例#40
0
#Import library and create new REST client
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Get a list of feeds
data = aio.receive('Lamp')

# Print out feed metadata
print('Data Value: {0}'.format(data.value))
示例#41
0
Author: Brent Rubell
"""
# Import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, Data, 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)

print('---Adafruit IO REST API Time Helpers---')

print('Seconds: aio.receive_time(seconds)')
secs_val = aio.receive_time('seconds')
print('\t' + secs_val)

print('Milliseconds: aio.receive_time(millis)')
ms_val = aio.receive_time('millis')
print('\t' + ms_val)

print('ISO-8601: aio.receive_time(ISO-8601)')
iso_val = aio.receive_time('ISO-8601')
print('\t' + iso_val)
示例#42
0
#??import Adafruit IO REST client
from Adafruit_IO import Client
config = {}

#adjust this filename to suit the config file you have created in the same directory
execfile("aio_config.py", config)
aio = Client(config["app_key"])

#allow the Python to access the GPIO pins
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)        #set board numbering counting left to ri$
GPIO.setup(12, GPIO.OUT)        #set pin 12 (GPIO OUT 18) as an 0utput
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP) #set pin 11 (GPIO 17) as an input pullup

#import the time and random functions
import time              
import random

#receive the 'ready' status of P1 and P2 from AIO
p1ready = aio.receive("P1 Ready").value 	# .value takes only the value from the aio
p2ready = aio.receive("P2 Ready").value

#check which computer got their first and sent various strings appropriate
if p1ready == "Not Ready" and p2ready == "Not Ready":	#if bpth players aren't ready then this Pi is the first and becomes P1
	print "You are player 1"
	aio.send("P1 Ready", "Ready")			#let AIO that this Pi is now P1
	playerscore = "P1 Score"
	otherPlayerReady = "P2 Ready"
	myPlayerReady = "P1 Ready"
	otherPlayer = "P2"
	myPlayer = "P1"
示例#43
0
from flask import Flask, render_template, request
from Adafruit_IO import Client

# Configuração do adafruit
adafruit_Username = "******"  # change to your username
adafruit_Key = "aio_ClzS14KFNXbYHWmoD7jmqr0qnbXf"  # change to your adafruit key
adafruit_Feed = "testrpi"  # change to the name of your feed
# Inicializa o cliente mqtt com minhas informações do adafruit
client = Client(username=adafruit_Username, key=adafruit_Key)
client.send(adafruit_Feed, "1on")

app = Flask(__name__)


@app.route("/", methods=["GET"])
def index():
    return render_template("form.html")


@app.route("/", methods=["POST"])
def submit():
    comando = request.form["comando"]
    print(comando)
    client.send(adafruit_Feed, comando)

    return render_template("form.html")


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0")
示例#44
0
DHT_READ_TIMEOUT = 60

# Pin connected to DHT22 data pin
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)
示例#45
0
# Import library and create instance of REST client.
from Adafruit_IO import Client
import datetime

# Wifi dessen Signal aufgezeichnet werden soll
# Hier die eignene ESSID eingeben
ap_essid = "Lorelei"
# MAC Addresse, um bei mehreren Access Points eindeutig zu sein
# Hier die MAC Adresse des eigenen AP eingeben
ap1_mac = "50:C7:BF:58:C8:60"

aio = Client('Hier Dein Adafruit_IO API Schlüssel')

now = datetime.datetime.now()

with open('/tmp/wifisig.log', 'r') as f:
    for line in f:
        items = line.split(';')
        timestamp = items[0]
        ap = items[1]
        essid = items[2]
        if ((ap == ap1_mac) and (essid == ap_essid)):
            ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
            diff = int(now.strftime("%s")) - int(ts.strftime("%s"))
            if (diff < 900):
                print "%s signals: %f" % (timestamp, float(items[3]))
                aio.send('LoreleiAP1', float(items[3]))
示例#46
0
        'masterTemp': db.dbGetLast(1003)[0][2] - 7.5,
        'masterHumidity': db.dbGetLast(1004)[0][2] + 10.3,
        'familyTemp': (db.dbGetLast(2003)[0][2]) * 1.8 + 32. - 9.4,
        'familyHumidity': db.dbGetLast(2004)[0][2] + 7.74,
        'outsideTemp': db.dbGetLast(1005)[0][2] * 1.8 + 32.0,
        'garageTemp': db.dbGetLast(3001)[0][2] * 1.8 + 32.0,
        'door1': door1,
        'door2': door2,
        'door3': door3
    }

    return currentData


if __name__ == "__main__":

    # Set up adafruit IO
    aio = Client('cubbagesj20879', '6a76fbbf0c46e84971cf5529f166c3ae3fde2b1d')

    #Loop forever
    while True:
        # Get the current readings
        currentData = get_current()

        # Post to adafruit
        for key in currentData.keys():
            aio.send(key.lower(), currentData[key])
            #print(key.lower(), currentData[key])

        time.sleep(300)
示例#47
0
 def __init__(self, api_key, feed, message_field = "value"):
     self.message_field = message_field
     self.client = Client(api_key)
     self.feed = feed
示例#48
0
from Adafruit_BluefruitLE.services import UART

print("starting up")

# Get the BLE provider for the current platform.
ble = Adafruit_BluefruitLE.get_provider()


#time
t0=time.time()
t0_climate=0
t_climate=30

#Adafruit IO
ADAFRUIT_IO_KEY = '954a29c4a56787437186d8c39c57a61d6c079867'
aio = Client(ADAFRUIT_IO_KEY)
data = aio.receive('Omnibot')

GPIO.setmode(GPIO.BCM)

#Thermal Printer
printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)

#pwm
pwm2 = PWM(0x70)

#Motor Config
motor = Adafruit_MotorHAT(addr=0x63)
RMotor = motor.getMotor(1)
LMotor = motor.getMotor(2)
RMotor.setSpeed(50)
示例#49
0
#!/usr/bin/python

# Import Library & create instance of REST client
from Adafruit_IO import Client

import time
import os
import RPi.GPIO as GPIO

aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

last = 0
inputNum = 20
outputNum = 21
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(outputNum,GPIO.OUT)
GPIO.setup(inputNum,GPIO.IN)


while True:
  if (time.time() - last) >= 7:
    # Retrieve the most recent value from BlockHeat01
    data = aio.receive('blockheat01')
    print('Received Value: {0}'.format(data.value))
    if data.value == "1":
      print('data = 1')
      GPIO.output(outputNum,GPIO.HIGH)
    else:
      print('data = 0')
      GPIO.output(outputNum,GPIO.LOW)
示例#50
0
from flask_cors import CORS
import time
import atexit
from apscheduler.schedulers.background import BackgroundScheduler

app = Flask(__name__)
CORS(app)
mydb = mysql.connector.connect(host="localhost",
                               user="******",
                               password="",
                               database="myapp")
############## CSE_BBC ##################################
ADAFRUIT_IO_KEY = '...'
ADAFRUIT_IO_USERNAME = '******'

aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

############## CSE_BBC1 ##################################
ADAFRUIT_IO_KEY1 = '...'
ADAFRUIT_IO_USERNAME1 = 'huytran'

aio1 = Client(ADAFRUIT_IO_USERNAME1, ADAFRUIT_IO_KEY1)


############################################################   receive data     ################################
def receive_light():
    feed_name = "bk-iot-light"
    try:
        temp = aio1.feeds(feed_name)
    except RequestError:
        feed = Feed(name=feed_name)
示例#51
0
"""
`time.py`
==========================================
Don't have a RTC handy and need
accurate time measurements?

Let Adafruit IO serve up real-time values
based off your device's IP-address!

Author: Brent Rubell
"""
# Import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, Data, 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)

# Get the time from Adafruit IO
time = aio.receive_time()
# Time is returned as a `struct_time`
# https://docs.python.org/3.7/library/time.html#time.struct_time
print(time)
!pip install adafruit-io
import os
x = os.getenv('x')
y = os.getenv('y')  #Use your own Adafruit Active Key
from Adafruit_IO import Client, Feed
aio = Client(x,y)
new = Feed(name='bot123')     #Creating a new feed
result = aio.create_feed(new)
result
from Adafruit_IO import Data
!pip install python-telegram-bot
from Adafruit_IO import Client,Data
from telegram.ext import Updater,CommandHandler
def on(bot,update):
  chat_id = update.message.chat_id    
  aio.create_data('bot123',Data(value = 1))
  bot.send_message(chat_id =chat_id,text ="Lights On")

def off(bot,update):
  chat_id = update.message.chat_id
  aio.create_data('bot123',Data(value = 0))
  bot.send_message(chat_id =chat_id,text ="Lights Off")

updater = Updater('1314501154:AAFupk7zdBSYmGlY2cDaSUdYLO4RAfF3TXs')     #Use Telegram Token HTTP API
dp =updater.dispatcher
dp.add_handler(CommandHandler('on',on))
dp.add_handler(CommandHandler('off',off))
updater.start_polling()
updater.idle()
示例#53
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)
示例#54
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))
示例#55
0
#====================================================================
# Import subfiles
#====================================================================
import datetime
import glob
import os
import re
import serial
import subprocess
import sys
import time
import warnings

# Import library and create instance of REST client.
from Adafruit_IO import Client
aio = Client('7e01e8b5e56360efc48a27682324fc353e18d14f')

# Set Variables
DEBUG = 1

# Add a delay for boot
time.sleep(1)

# Continuously append data
while(True):

  time.sleep(1)

  # Read the Current Garage Temperature
  def read_CurrentGarageTemp():
    f = open("/home/robin/CurrentGarageTemp", "r")
示例#56
0
from Adafruit_IO import Client
aio = Client('io_key')
hum = aio.receive('Luftfeuchte')
print("{0}".format(hum.value))
示例#57
0
# PWM Pins
RED_PIN = 6
GREEN_PIN = 5
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'
# Set to your Adafruit IO username.
# Set to your Adafruit IO key.
# Remember, your key is a secret,
#ADAFRUIT_IO_USERNAME = '******'
#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:
示例#59
0
Dark Sky Hyperlocal for IO Plus
with Adafruit IO API

Author(s): Brent Rubell for Adafruit Industries
"""
# Import JSON for forecast parsing
import json
# Import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, RequestError

# Set to your Adafruit IO key.
ADAFRUIT_IO_USERNAME = '******'
ADAFRUIT_IO_KEY = 'YOUR_IO_PASSWORD'

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

# Grab the weather JSON
weather = aio.receive_weather(1234)
weather = json.dumps(weather)
forecast = json.loads(weather)

# Parse the current forecast
current = forecast['current']
print('Current Forecast')
print('It is {0} and {1}.'.format(current['summary'], current['temperature']))

# Parse the two day forecast
forecast_days_2 = forecast['forecast_days_2']
print('\nWeather in Two Days')
print('It will be {0} with a high of {1}F and a low of {2}F.'.format(