Exemple #1
0
def on_message(client, userdata, msg):
    print(
        str(datetime.datetime.now()) + ": " + msg.topic + " " +
        str(msg.payload))
    #
    # Forward the data to Adafruit IO. Replace topic with a valid feed name
    #
    feedname = msg.topic.replace("/", "_")
    print("Publish to Adafruit feedname: " + feedname)
    # Initialize the client that should connect to io.adafruit.com
    adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME,
                                ADAFRUIT_IO_KEY,
                                service_port=1883)
    adafruitClient.on_connect = adafruit_connected
    adafruitClient.connect()
    adafruitClient.loop()
    adafruitClient.publish(feedname, msg.payload)
    adafruitClient.disconnect()

    def try_connect_to_local_broker(client):
        print("trying to connect to local broker")
        connOK = False

        while (connOK == False):
            try:
                client.connect("192.168.1.16", 1883, 60)
                connOK = True

            except:
                connOK = False
            time.sleep(2)
def create_aio_mqtt_client():
    mclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    # Setup the callback functions defined above.
    mclient.on_connect = aio_connected
    mclient.on_message = aio_message
    mclient.connect()

    return mclient
Exemple #3
0
def inicia_cliente():
    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    client.on_connect = connected
    client.on_disconnect = disconnected
    client.on_message = message
    client.connect()
    client.loop_background()
    return client
Exemple #4
0
def start_client_loop():
	client = MQTTClient(USER_FEED_NAME, USER_FEED_KEY)

	client.on_connect = connect_to_feeds
	client.on_disconnect = disconnect
	client.on_message = feed_actions

	feed_loop(client)
Exemple #5
0
 def adafruit_mqtt_start(self):
     if configuration['ADAFRUIT_IO']['ADAFRUIT_IO_CONTROL']=='Enabled':
         client = MQTTClient(configuration['ADAFRUIT_IO']['ADAFRUIT_IO_USERNAME'], configuration['ADAFRUIT_IO']['ADAFRUIT_IO_KEY'])
         client.on_connect    = self.adafruit_connected
         client.on_disconnect = self.adafruit_disconnected
         client.on_message    = self.adafruit_message
         client.connect()
         client.loop_blocking()
     else:
         print("Adafruit_io MQTT client not enabled")
def main():
    _init_influxdb_database()

    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    client.on_connect = connected
    client.on_disconnect = disconnected
    client.on_message = message
    client.on_subscribe = subscribe
    client.connect()
    client.loop_blocking()
def startService():
    print(">> Assitant Listner service started!")
    
    ADAFRUIT_IO_KEY = '8c61ee1ac0f0421f96512e30be6b30dc'
    ADAFRUIT_IO_USERNAME = '******'
    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    client.on_connect    = connected
    client.on_message    = message
    client.connect()
    client.loop_blocking()
 def test_connect(self):
     # Create MQTT test client.
     client = MQTTClient(self.get_test_username(), self.get_test_key())
     # Verify on_connect handler is called and expected client is provided.
     def on_connect(mqtt_client):
         self.assertEqual(mqtt_client, client)
     client.on_connect = on_connect
     # Connect and wait until on_connect event is fired.
     client.connect()
     self.wait_until_connected(client)
     # Verify connected.
     self.assertTrue(client.is_connected())
def get_client():
    mqtt_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    mqtt_client.on_disconnect = disconnected
    mqtt_client.on_message = message
    mqtt_client.on_connect = connected

    mqtt_client.connect()
    mqtt_client.loop_background()

    print("Connected to remote mqtt server")

    return mqtt_client
Exemple #10
0
def init_client():
	util.log_info('connecting to adafruit.io. username={}'.format(ADAFRUIT_IO_USERNAME))
	client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Setup the callback functions defined above.
	client.on_connect = connected
	client.on_disconnect = disconnected
	client.on_message = message

	client.connect()
	client.loop_background()

	return client
Exemple #11
0
    def test_connect(self):
        # Create MQTT test client.
        client = MQTTClient(self.get_test_username(), self.get_test_key())

        # Verify on_connect handler is called and expected client is provided.
        def on_connect(mqtt_client):
            self.assertEqual(mqtt_client, client)

        client.on_connect = on_connect
        # Connect and wait until on_connect event is fired.
        client.connect()
        self.wait_until_connected(client)
        # Verify connected.
        self.assertTrue(client.is_connected())
def dataAdafruitHandler():
    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    client.on_connect    = connected
    client.on_disconnect = disconnected
    client.on_message    = message

    client.connect()
    client.loop_background()
    while True:
        value = random.randint(0, 100)
        print 'Publishing {0} to my-data.'.format(value)
        client.publish('my-data', value)
        time.sleep(5)
def on_message(client, userdata, msg):
    print(str(datetime.datetime.now()) + ": " + msg.topic + " " + str(msg.payload))    
    #
    # Forward the data to Adafruit IO. Replace topic with a valid feed name
    #
    feedname=msg.topic.replace("/","_")
    print("Publish to Adafruit feedname: " + feedname)

    # Initialize the client that should connect to io.adafruit.com
    adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_port=1883)
    adafruitClient.on_connect = adafruit_connected
    adafruitClient.connect()
    adafruitClient.loop()
    adafruitClient.publish(feedname,msg.payload)
 def test_secure_connect(self):
     """Test a secure (port 8883, TLS enabled) AIO connection
     """
     # Create MQTT-Secure test client.
     client = MQTTClient(self.get_test_username(), self.get_test_key())
     # Verify on_connect handler is called and expected client is provided.
     def on_connect(mqtt_client):
         self.assertEqual(mqtt_client, client)
     client.on_connect = on_connect
     # Connect and wait until on_connect event is fired.
     client.connect()
     self.wait_until_connected(client)
     # Verify connected.
     self.assertTrue(client.is_connected())
     self.assertTrue(client._secure)
def start():
    # Create an MQTT client instance.
    client = MQTTClient(IO_USERNAME, IO_KEY)

    # Setup the callback functions defined above.
    client.on_connect = connected
    client.on_disconnect = disconnected
    client.on_message = message

    # Connect to the Adafruit IO server.
    client.connect()

    # Now the program needs to use a client loop function to ensure messages
    # are sent and received. This command will block foreground processing and
    # let the MQTT library do its work.
    client.loop_blocking()
def task2():
    # Create an MQTT client instance.
    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Setup the callback functions defined above.
    client.on_connect = connected2
    client.on_disconnect = disconnected
    client.on_message = message2

    # Connect to the Adafruit IO server.
    client.connect()

    # Start a message loop that blocks forever waiting for MQTT messages to be
    # received.  Note there are other options for running the event loop like doing
    # so in a background thread--see the mqtt_client.py example to learn more.
    client.loop_blocking()
 def test_insecure_connect(self):
     """Test an insecure (port 1883, TLS disabled) AIO connection
     """
     # Create MQTT-Insecure (non-SSL) test client.
     client = MQTTClient(self.get_test_username(), self.get_test_key(), secure=False)
     # Verify on_connect handler is called and expected client is provided.
     def on_connect(mqtt_client):
         self.assertEqual(mqtt_client, client)
     client.on_connect = on_connect
     # Connect and wait until on_connect event is fired.
     client.connect()
     self.wait_until_connected(client)
     # Verify connected.
     self.assertTrue(client.is_connected())
     # Verify insecure connection established
     self.assertFalse(client._secure)
Exemple #18
0
    def __connect_adafruit(self):
        username = self.config.get('adafruit_io', 'username')
        key = self.config.get('adafruit_io', 'key')

        print('Connecting to Adafruit.IO...')
        client = MQTTClient(username, key)
        client.on_connect = self.__on_connected
        client.on_disconnect = self.__on_disconnected
        client.on_message = self.__on_message

        try:
            client.connect()
            client.loop_blocking()
        except Exception as err:
            print('Error with Adafruit client: %s' % err)
            client.disconnect()
Exemple #19
0
def loop():
	gbl = Vars()
	
	while True:
		try:
			print("Client loop begun")
			client = MQTTClient(gbl.name, gbl.key)

			client.on_connect = connect
			client.on_disconnect = disconnect
			client.on_message = action

			client.connect()

			client.loop_blocking()
		except:
			print("Error", time())
			sleep(5)
def on_message(client, userdata, msg):
    print(
        str(datetime.datetime.now()) + ": " + msg.topic + " " +
        str(msg.payload))
    #
    # Forward the data to Adafruit IO. Replace topic with a valid feed name
    #
    feedname = msg.topic.replace("/", "_")
    print("Publish to Adafruit feedname: " + feedname)

    # Initialize the client that should connect to io.adafruit.com
    adafruitClient = MQTTClient(ADAFRUIT_IO_USERNAME,
                                ADAFRUIT_IO_KEY,
                                service_port=1883)
    adafruitClient.on_connect = adafruit_connected
    adafruitClient.connect()
    adafruitClient.loop()
    adafruitClient.publish(feedname, msg.payload)
Exemple #21
0
def main():

    # Create a mqttclient
    client = MQTTClient(IO_USERNAME, IO_KEY)

    # Assign handlers for events
    client.on_connect    = connected
    client.on_disconnect = disconnected
    client.on_message    = message

    logger.debug('Connect to Adafruit IO server')
    client.connect()

    logger.debug('Start background thread for messaging')
    client.loop_background()

    temp_buffer = []
    hum_buffer = []
    while True:
        humidity, temperature = measure()
        if humidity is not None and temperature is not None:
            logger.info('Temperature={0:0.1f}, Humidity={1:0.1f}'.format(temperature, humidity))
            temp_buffer.append(temperature)
            hum_buffer.append(humidity)

        # Send median of last three records
        if len(temp_buffer) == BUFFER_SIZE:
            temp_buffer = sorted(temp_buffer)
            temp_median = temp_buffer[BUFFER_SIZE // 2]
            temp_median = round(temp_median, 1)
            logger.debug('Rounded median of temp_buffer({}) is {}'.format(temp_buffer, temp_median))
            publish(client, 'temperature', temp_median)
            temp_buffer = []

        # Send median of last three records
        if len(hum_buffer) == BUFFER_SIZE:
            hum_buffer = sorted(hum_buffer)
            hum_median = hum_buffer[BUFFER_SIZE // 2]
            hum_median = round(hum_median, 1)
            logger.debug('Rounded median of hum_buffer({}) is {}'.format(hum_buffer, hum_median))
            publish(client, 'humidity', hum_median)
            hum_buffer = []

        sleep(TIME_INTERVAL)
Exemple #22
0
    def subscribe(self):
        def connected(client):
            print('Connected to Adafruit IO!  Listening for {0} changes...'.
                  format(self.feed_id))
            client.subscribe(self.feed_id)

        def subscribe(client, userdata, mid, granted_qos):
            print('Subscribed to {0} with QoS {1}'.format(
                self.feed_id, granted_qos[0]))

        def disconnected(client):
            print('Disconnected from Adafruit IO!')
            sys.exit(1)

        def message(client, feed_id, payload):
            print('Feed {0} received new value: {1}'.format(feed_id, payload))
            # Update device database
            print('Update database ...')
            res = json.loads(payload)
            device = Device(id=str(res["id"]),
                            data=res["data"],
                            name=res["name"],
                            unit=res["unit"])
            device.save()
            print('Data updated')
            # Device.objects.filter(id=device["id"]).update(data=device["data"], name=device["name"], unit=device["unit"]))
            # Update weather info
            # update_weatherinfo()
            # TODO: Handle value change event ( > 100, < 100)

        # Create an MQTT client instance.
        client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

        # Setup the callback functions defined above.
        client.on_connect = connected
        client.on_disconnect = disconnected
        client.on_message = message
        client.on_subscribe = subscribe

        # Connect to the Adafruit IO server.
        client.connect()

        client.loop_background()
Exemple #23
0
	def _loop_process(self):
		username = os_getenv("ADAFRUIT_IO_USERNAME");
		key = os_getenv("ADAFRUIT_IO_KEY");
		print(f"AdafruitFeed::_loop_process::username, key: {username}, {key}");
		assert(username);
		assert(key);

		ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL

		client = MQTTClient(username, key, secure=False);

		client.on_connect = self._connect;
		client.on_disconnect = self._disconnect;
		client.on_message = self._activate;
		client.on_subscribe  = self._null;
		
		print("Adafruit::_loop_process");

		client.connect();
		client.loop_blocking();
def instance_start(c, name):
 # Using 'c' instead of 'client' for easier reading/writing
 #Last field 'name' of client will be used to set '_instance_name' so we can read a unique name inside callback functions
 logger.info('Setting up instance and connecting: %s', name)
 c['instance'] = MQTTClient(c['USERNAME'], c['PASSWORD'], c['SERVER'], int(c['PORT']), c['CLIENTID'], c['TOPIC_FMT'], name)  # Create MQTTClient instance
 logger.debug("New instance: %s *PASSWORD* %s %s %s %s %s ",c['USERNAME'], c['SERVER'], int(c['PORT']), c['CLIENTID'], c['TOPIC_FMT'], name)
 # Setup the callback functions defined below.
 c['instance'].on_connect    = connected
 c['instance'].on_disconnect = disconnected
 c['instance'].on_message    = message
 #Setup TLS for basic connection encryption (like a web browser using HTTPS)
 # - You can probably do other TLS connection types like pre-shared key authentication if you modify this code and add setting variables
 # For Adafruit, just use normal OS CA lookup bundle file in /etc/ssl/certs/:  (Probably OS-dependent location)
 if c['TLS_SET'] == "1":
   logger.debug("Set TLS: %s", c['CACERT'])
   c['instance'].tls_set(c['CACERT'])  # If you need more of the TLS settings, feel free to add to config file and here.
 # Connect to servers
 # Need to convert these from strings to integers to use for counting
 c['RETRY_COUNTER'] = int(c['RETRY_COUNTER'])
 c['MAX_RETRIES'] = int(c['MAX_RETRIES'])
 while True:   #Loop until complete or retry limit hit
   try:
     c['instance'].connect()  # Try to connect.  Some errors might be fatal.
   except:  # Have only seen 'socket.errors', but could be other kinds
     if c['RETRY_COUNTER'] > c['MAX_RETRIES']:
       logger.critical('Giving up retries to %s (%s).  Terminating process.', c['instance']._service_host, c['instance']._instance_name)
       for name in settings_dict:
        if 'instance' in settings_dict[name]:  #For each existing instance besides this one
         settings_dict[name]['instance'].disconnect()  # Terminate instance
       sys.exit(1)
     logger.error('%s connect error for %s. Retry # %s', str(sys.exc_info()[0]), c['instance']._instance_name, str(c['RETRY_COUNTER']))
     c['RETRY_COUNTER'] += 1;  # Iterate try
     time.sleep(5)  # Delay before retry
   else:
     # Connection Worked.  Reset counter and break loop
     c['RETRY_COUNTER'] = 1;
     break
Exemple #25
0
    def subscribe(self):
        def connected(client):
            print('Connected to Adafruit IO!  Listening for {0} changes...'.
                  format(self.feed_id))
            client.subscribe(self.feed_id)

        def subscribe(client, userdata, mid, granted_qos):
            print('Subscribed to {0} with QoS {1}'.format(
                self.feed_id, granted_qos[0]))

        def disconnected(client):
            print('Disconnected from Adafruit IO!')
            sys.exit(1)

        def message(client, feed_id, payload):
            print('Feed {0} received new value: {1}'.format(feed_id, payload))
            # Update device database
            print('Update database ...')
            # Device.objects.filter(key=feed_id).update(value=payload)
            # Update weather info
            # update_weatherinfo()
            # TODO: Handle value change event ( > 100, < 100)

        # Create an MQTT client instance.
        client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

        # Setup the callback functions defined above.
        client.on_connect = connected
        client.on_disconnect = disconnected
        client.on_message = message
        client.on_subscribe = subscribe

        # Connect to the Adafruit IO server.
        client.connect()

        client.loop_blocking()
Exemple #26
0
def main():
    #TimeRealSuelo()
    #TimeRealAmbiente()

    if (len(sys.argv) != 3):

        sys.stderr.write(
            'Usage: "{}" $AdafruitIOusername $AdafruitIOkey , los feed estan quemados en el codigo xD\n'
            .format(sys.argv[0]))
        os._exit(1)

    #se leen de los sensores
    hiloSuelo = threading.Thread(target=TimeRealSuelo)
    hiloAmbiente = threading.Thread(target=TimeRealAmbiente)

    hiloSuelo.start()
    hiloAmbiente.start()
    #----------------------------------------------

    username = sys.argv[1]
    skey = sys.argv[2]

    feeds["username"] = username
    feeds["skey"] = skey

    client = MQTTClient(username=username, key=skey)

    client.on_connect = on_connect
    client.on_disconnect = on_disconnect

    client.connect()
    client.loop_background()

    feeds["client"] = client

    send_message()
Exemple #27
0
    print 'Disconnected from Adafruit IO!'
    sys.exit(1)


def message(client, feed_id, payload):
    # Message function will be called when a subscribed feed has a new value.
    # The feed_id parameter identifies the feed, and the payload parameter has
    # the new value.
    print 'Feed {0} received new value: {1}'.format(feed_id, payload)


# Create an MQTT client instance.
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Setup the callback functions defined above.
client.on_connect = connected
client.on_disconnect = disconnected
client.on_message = message

# Connect to the Adafruit IO server.
client.connect()

# Now the program needs to use a client loop function to ensure messages are
# sent and received.  There are a few options for driving the message loop,
# depending on what your program needs to do.

# The first option is to run a thread in the background so you can continue
# doing things in your program.
client.loop_background()
# Now send new values every 10 seconds.
print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...'
Exemple #28
0
    p.text("voting experience!\n")
    p.text("Take me to the booth\n")
    p.text("and select either general,\n")
    p.text("if voting in a general\n")
    p.text("or the party whose primary\n")
    p.text("you are voting for.\n")
    p.text("Then, scan the QR code into\n")
    p.text("the box.  Thanks!\n")
    p.text("If that doesn't work,\n")
    p.text("try typing this manually:\n")
    p.text(payload)
    p.cut()
    print(payload)

vote_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
vote_client.on_connect    = vote_connected
vote_client.on_disconnect = disconnected
vote_client.on_message = vote_message
vote_client.connect()
vote_client.loop_background()

voter_client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
voter_client.on_connect    = voter_connected
voter_client.on_disconnect = disconnected
voter_client.on_message = voter_message
voter_client.connect()
voter_client.loop_background()

while True:
    pass
def disconnected(client):
    # Disconnected function will be called when the client disconnects.
    print 'Disconnected from Adafruit IO!'
    sys.exit(1)

def message(client, feed_id, payload):
    # Message function will be called when a subscribed feed has a new value.
    # The feed_id parameter identifies the feed, and the payload parameter has
    # the new value.
    print 'Feed {0} received new value: {1}'.format(feed_id, payload)
    # Set a global var with the payload then check for it above
    global msg
    msg = payload

# Create an MQTT client instance
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Setup the callback functions defined above
client.on_connect = connected
client.on_disconnect = disconnected
client.on_message = message

# Connect to the Adafruit IO server
client.connect()

ble.initialize()

ble.run_mainloop_with(ble_main)

# Define Functions for Threading
def send_message(client):
    while True:
        if (client.messageSend is not None):
            client.publish(feed_id=AdafruitIOFeedKey,
                           value=client.messageSend,
                           feed_user=AdafruitIOFeedUsername)
            time.sleep(10)


if __name__ == "__main__":
    # Create an MQTT client instance.
    client = MQTTClient(username=AdafruitIOFeedUsername, key=AdafruitIOKey)

    # Setup the callback functions
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect

    # Setup Control Vars
    client.messageSend = "0"

    # Connect to the Adafruit IO server.
    client.connect()
    client.loop_background()
    while not client.is_connected():
        print("Esperando conexión")
        time.sleep(1)

    # Setup Threading, to publish message every 10 seconds
    hilo0 = threading.Thread(target=send_message, args=(client, ))
    hilo0.start()
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    #client.subscribe("$SYS/#")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

def on_publish(client, userdata, mid):
    print("data sent")

def on_disconnect(client, userdata, rc):
    print("disconnect")

client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_port=8883)
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.on_disconnect = on_disconnect
client.tls_set("/home/pi/adafruitio-temperature/certs/geotrust.pem")
client.connect()
#client.loop_background()

# Get temperature from sensor
#byte1 = 29
#byte2 = 0x00
#temperature = ((byte1 << 8) + byte2) >> 4
#if (temperature & 0x800):
#    temperature = (temperature & 0x7FF) - 0x800
#temperature = temperature * 0.0625
#temperature = 30
def dash_board(GPIO):
    #def dash_board():
    # Set to your Adafruit IO key & username below
    lock = threading.Lock()

    #GPIO.setmode(GPIO.BCM) # Use physical pin numbering
    #GPIO.setup(17, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)
    # Define callback functions which will be called when certain events happen.
    def connected(client):
        # Connected function will be called when the client is connected to Adafruit IO.
        # This is a good place to subscribe to feed changes.  The client parameter
        # passed to this function is the Adafruit IO MQTT client so you can make
        # calls against it easily.
        #print('Connected to Adafruit IO!  Listening for {0} changes...'.format(FEED_ID))
        # Subscribe to changes on a feed named DemoFeed.
        client.subscribe(ACTEM)
        client.subscribe(AUTO)
        client.subscribe(ACON)
        client.subscribe(DOOR)
        client.subscribe(HUMID)
        client.subscribe(SYSTEMON)
        client.subscribe(LIGHT)

    def disconnected(client):
        # Disconnected function will be called when the client disconnects.
        print('Disconnected from Adafruit IO!')
        sys.exit(1)

    def message(client, feed_id, payload):
        # Message function will be called when a subscribed feed has a new value.
        # The feed_id parameter identifies the feed, and the payload parameter has
        # the new value.
        print('Feed {0} received new value: {1}'.format(feed_id, payload))

        if feed_id == 'onoffbutton':
            print(payload)
            if payload == "ON":
                publish_init()
                glo.start_system = True
            else:
                glo.start_system = False
                publish_off()

        elif feed_id == 'auto':
            if payload == 'Auto':
                print("System has been changed to Auto model")
                glo.auto_start = True
            elif payload == 'Manual':
                print("System has been changed to Manual model")
                glo.auto_start = False

        if glo.start_system and not glo.auto_start:
            if feed_id == "ac":
                print("feed_id == ac : {} ac_on: {}".format(
                    feed_id == "ac", glo.ac_on))
                if glo.ac_on:
                    glo.set_temp = int(payload)
                    print("AC has been changed to " + payload)
                    period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16)
                    glo.ac.ChangeFrequency(1000 / period)
                    glo.ac.ChangeDutyCycle(100 * (period - 20) / period)
            elif feed_id == "aconoff":
                if payload == 'ON':
                    glo.ac_on = True
                    client.publish(ACTEM, glo.set_temp)
                    period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16)
                    glo.ac.ChangeFrequency(1000 / period)
                    glo.ac.ChangeDutyCycle(100 * (period - 20) / period)
                    print("AC ON")
                elif payload == 'OFF':
                    glo.ac_on = False
                    print("AC OFF")
                    glo.ac.ChangeDutyCycle(0)

            elif feed_id == 'door':
                if payload == 'Close':
                    print("close door")
                    glo.door.ChangeFrequency(1000 / 21.6)
                    glo.door.ChangeDutyCycle(100 * 1.6 / 21.6)
                    time.sleep(0.37)
                    glo.door.ChangeDutyCycle(0)
                elif payload == 'Open':
                    glo.door.ChangeFrequency(1000 / 21.4)
                    glo.door.ChangeDutyCycle(100 * 1.4 / 21.4)
                    time.sleep(0.65)
                    glo.door.ChangeDutyCycle(0)
            elif feed_id == 'light':
                if payload == 'ON':
                    print(feed_id)
                    print("ON")
                    GPIO.output(26, GPIO.HIGH)  #Turn ON
                elif payload == 'OFF':
                    print(feed_id)
                    print("OFF")
                    GPIO.output(26, GPIO.LOW)
            elif feed_id == "humidifier":
                #print(payload)
                if payload == "0":
                    print(payload)
                    glo.hum.ChangeDutyCycle(0)
                    #GPIO.output(17, GPIO.HIGH) # Turn on
                elif payload == "1":
                    print(payload)
                    glo.hum.ChangeFrequency(5)
                    glo.hum.ChangeDutyCycle(50)
                elif payload == "2":
                    glo.hum.ChangeFrequency(8)
                    glo.hum.ChangeDutyCycle(50)
                elif payload == "3":
                    glo.hum.ChangeFrequency(10)
                    glo.hum.ChangeDutyCycle(50)
                elif payload == "4":
                    glo.hum.ChangeFrequency(15)
                    glo.hum.ChangeDutyCycle(50)
                else:
                    glo.hum.ChangeFrequency(20)
                    glo.hum.ChangeDutyCycle(50)

    def publish_init():
        time.sleep(1)
        lock.acquire()
        glo.ac_on = True
        client.publish(ACTEM, 26)
        client.publish(AUTO, "Auto")
        time.sleep(1)
        #client.publish(ACON, "OFF")
        client.publish(DOOR, "OFF")
        #client.publish("humidity", glo.humid)
        time.sleep(1)
        client.publish(HUMID, 0)
        glo.hum.ChangeDutyCycle(0)
        lock.release()

    def publish_off():
        time.sleep(1)
        #client.publish(SYSTEMON, "ON")
        client.publish(AUTO, "Manual")
        glo.auto_start = False
        lock.acquire()

        time.sleep(1)
        client.publish(ACON, "OFF")

        glo.ac_on = False
        glo.ac.ChangeDutyCycle(0)

        time.sleep(1)
        client.publish(DOOR, "OFF")

        time.sleep(1)
        client.publish(LIGHT, "OFF")
        GPIO.output(26, GPIO.LOW)

        time.sleep(1)
        client.publish(HUMID, 0)
        glo.hum.ChangeDutyCycle(0)

        lock.release()

    # Create an MQTT client instance.
    client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Setup the callback functions defined above.
    client.on_connect = connected
    client.on_disconnect = disconnected
    client.on_message = message

    # Connect to the Adafruit IO server.
    client.connect()
    client.loop_background()

    time.sleep(1)
    client.publish(SYSTEMON, "ON")

    def update_status():
        while glo.code_run:
            client.publish("humidity", glo.humid)
            time.sleep(10)
            client.publish("temperature", glo.temp)
            time.sleep(10)
            client.publish("lux", glo.light)
            time.sleep(10)

    time.sleep(0.3)

    t_dash = threading.Thread(target=update_status, name='status')
    t_dash.start()

    while glo.code_run:
        print("system" + str(glo.start_system))
        print("auto: " + str(glo.auto_start))

        if glo.start_system and glo.auto_start:
            print("temp: " + str(glo.temp))
            lock.acquire()
            if glo.temp > 30:
                glo.set_temp = 22
                glo.ac_on = True
                client.publish(ACON, "ON")
                period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16)
                glo.ac.ChangeFrequency(1000 / period)
                glo.ac.ChangeDutyCycle(100 * (period - 20) / period)
                client.publish(ACTEM, 22)
            elif glo.temp > 24:
                glo.set_temp = 25
                glo.ac_on = True
                client.publish(ACON, "ON")
                period = 21.5 + 0.2 * ((33 - glo.set_temp) / 16)
                glo.ac.ChangeFrequency(1000 / period)
                glo.ac.ChangeDutyCycle(100 * (period - 20) / period)
                client.publish(ACTEM, 25)
            else:
                print("Close the AC")
                client.publish(ACON, "OFF")
                glo.ac_on = False
                glo.ac.ChangeDutyCycle(0)
            time.sleep(1)
            print("humid: " + str(glo.humid))
            if glo.humid < 10:
                print("Level1")
                client.publish(HUMID, 5)
                glo.hum.ChangeFrequency(20)
                glo.hum.ChangeDutyCycle(50)
            elif glo.humid < 20:
                print("Level2")
                client.publish(HUMID, 3)
                glo.hum.ChangeFrequency(10)
                glo.hum.ChangeDutyCycle(50)
            elif glo.humid < 30:
                client.publish(HUMID, 1)
                glo.hum.ChangeFrequency(5)
                glo.hum.ChangeDutyCycle(50)
            else:
                client.publish(HUMID, 0)
                glo.hum.ChangeDutyCycle(0)

            time.sleep(1)
            print("Light: " + str(glo.light))
            if glo.light < 500:
                client.publish(LIGHT, "ON")
                GPIO.output(26, GPIO.HIGH)
            else:
                client.publish(LIGHT, "OFF")
                GPIO.output(26, GPIO.LOW)
            lock.release()
        time.sleep(10)

    GPIO.cleanup()
def mqtt_disconnected(client):
    eprint('mqtt disconnected')


def mqtt_message(client, feed_id, payload):
    eprint('mqtt message {}'.format(payload))
    if payload == 'work exited':
        switch_script('mini.fxb')


IO_USERNAME = os.environ['IO_USERNAME']
IO_API_KEY = os.environ['IO_API_KEY']

mqtt_client = MQTTClient(IO_USERNAME, IO_API_KEY)
mqtt_client.on_connect = mqtt_connected
mqtt_client.on_disconnect = mqtt_disconnected
mqtt_client.on_message = mqtt_message
mqtt_client.connect()
mqtt_client.loop_background()

dimmer_update_rate = datetime.timedelta(minutes=1)
last_dimmer_update_time = datetime.datetime.now()

try:
    blue.light_on()
    time.sleep(0.33)
    blue.light_off()
    red.light_on()
    time.sleep(0.33)
    red.light_off()
Exemple #34
0
    print('Feed {0} received new value: {1}'.format(feed_id, payload))
    if feed_id == 'relay1':
       if payload == 'ON':
          GPIO.output(relay1,True)
       if payload == 'OFF':
          GPIO.output(relay1,False)
    if feed_id == 'relay2':
       if payload == 'ON':
          GPIO.output(relay2,True)
       if payload == 'OFF':
          GPIO.output(relay2,False)
    if feed_id == 'relay1':
       if payload == 'ON':
          GPIO.output(relay1,True)
       if payload == 'OFF':
          GPIO.output(relay1,False)
# Create an MQTT client instance.
client2 = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Setup the callback functions defined above.
client2.on_connect    = connected
client2.on_disconnect = disconnected
client2.on_message    = message
# Connect to the Adafruit IO server.
client2.connect()

# Start a message loop that blocks forever waiting for MQTT messages to be
# received.  Note there are other options for running the event loop like doing
# so in a background thread--see the mqtt_client.py example to learn more.
client2.loop_blocking()
    elif message.topic == 'dryot/temperature':
        if _temperature_count == publish_max:
            _temperature_count = 0
            # print('Temperature = ' + payload_str)
            aio_client.publish('dryot.temperature', payload_str)
        else:
            _temperature_count += 1
    else:
        print('Unknown message')


# Create an MQTT client instance.
aio_client = MQTTClient(adafruit_io_username, adafruit_io_key)

# Setup the callback functions defined above.
aio_client.on_connect = aio_connected
aio_client.on_disconnect = aio_disconnected
aio_client.on_message = aio_message

# Connect to the Adafruit IO server.
aio_client.connect()

# Use a client loop function to ensure messages are doing things in the program
# In this case we need to subscribe to local MQTT topics and receive data from them
aio_client.loop_background()

# connect to the Mosquitto MQTT broker
mqtt_client = mqtt.Client("DRYOT2AIO")
mqtt_client.on_message = mqtt_on_message
mqtt_client.connect(mqtt_broker_address)
Exemple #36
0

def disconnected(client):  #action when disconnected
    print('Disconnected from Adafruit IO!')
    sys.exit(1)


def message(client, feed_id, payload):  #action when message received
    print('Success!')
    global mn  #get global mean variable
    mn = int(payload)  #set it to an integer from data received
    print(mn)


client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)  #initialize MQTT
client.on_connect = connected  #setup connect action
client.on_disconnect = disconnected  #setup disconnect action
client.on_message = message  #setup message action
client.connect()  #connect to MQTT
client.loop_background()  #continue a loop in background

while True:  #forever loop
    mean = mn * 4  #set variable mean to the actual mean times 4
    if mn > 7:  #if actual mean is greater than seven, set colour to green
        r = 0
        g = 255
        b = 0
    else:  #if not greater than seven, set colour to red
        r = 255
        g = 0
        b = 0
        if payload == "1":
            print('BULB1 is ON')
            GPIO.output(BULB1, GPIO.HIGH)
            a = u.urlopen(api + str(1))
        else:
            print('BULB1 is OFF')
            GPIO.output(BULB1, GPIO.LOW)
            a = u.urlopen(api + str(0))
    if Feed_id == "bulb2":
        if payload == "1":
            print('BULB2 is ON')
            GPIO.output(BULB2, GPIO.HIGH)
            a = u.urlopen(api2 + str(1))
        else:
            print('BULB2 is OFF')
            GPIO.output(BULB2, GPIO.LOW)
            a = u.urlopen(api2 + str(0))


#Create an MQTT client instance.
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

#Setup the callback functions defined above.
client.on_connect = connected_to_adafruit
client.on_disconnect = disconnected_from_adafruit
client.on_message = message_from_user

#Connect to the Adafruit IO server.
client.connect()
client.loop_blocking()