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)
Exemple #2
0
class AdafruitNotifier(Notifier):
    # TODO: consider supporting this directly in thingamon and not using
    # the adafruit package. both have the same paho mqtt connection logic.
    # adafruit does not lock the connected state variable, thingamon does
    # not sure which is right yet
    def __init__(self,
                 username=None,
                 api_key=None,
                 host='io.adafruit.com',
                 port=1883):
        """
        Create an Adafruit MQTT notifier

        Args:
            host (str): host name of Adafruit MQTT broker
            port (int): port of Adafruit MQTT broker
            username (str): Adafruit IO username
            api_key (str): Adafruit IO API key
        """
        self.log = logging.getLogger('thingpin')
        self.username = username
        self.api_key = api_key
        self.host = host
        self.port = port
        self.client = None

    def initialize(self):
        self.client = MQTTClient(self.username,
                                 self.api_key,
                                 service_host=self.host,
                                 service_port=self.port)

        def on_disconnect(client):
            if client.disconnect_reason != 0:
                self.log.info('client disconnected, exiting')
                os._exit(1)

        self.client.on_disconnect = on_disconnect

        self.client.connect()
        self.log.info('connected to Adafruit')
        self.client.loop_background()

    def cleanup(self):
        self.client.disconnect()

    def notify(self, name, value):
        self.log.info('Adafruit IO: publish({}={})'.format(name, value))
        self.client.publish(name, value['state'])
 def test_disconnect(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_disconnect(mqtt_client):
         self.assertEqual(mqtt_client, client)
     client.on_disconnect = on_disconnect
     # Connect and wait until on_connect event is fired.
     client.connect()
     self.wait_until_connected(client)
     # Now disconnect and wait until disconnection event occurs.
     client.disconnect()
     self.wait_until_connected(client, connect_value=False)
     # Verify diconnected.
     self.assertFalse(client.is_connected())
Exemple #4
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 #5
0
class AdafruitNotifier(Notifier):
    # TODO: consider supporting this directly in thingamon and not using
    # the adafruit package. both have the same paho mqtt connection logic.
    # adafruit does not lock the connected state variable, thingamon does
    # not sure which is right yet
    def __init__(self, username=None, api_key=None, host='io.adafruit.com',
                 port=1883):
        """
        Create an Adafruit MQTT notifier

        Args:
            host (str): host name of Adafruit MQTT broker
            port (int): port of Adafruit MQTT broker
            username (str): Adafruit IO username
            api_key (str): Adafruit IO API key
        """
        self.log = logging.getLogger('thingpin')
        self.username = username
        self.api_key = api_key
        self.host = host
        self.port = port
        self.client = None

    def initialize(self):
        self.client = MQTTClient(self.username, self.api_key,
                                 service_host=self.host,
                                 service_port=self.port)

        def on_disconnect(client):
            if client.disconnect_reason != 0:
                self.log.info('client disconnected, exiting')
                os._exit(1)

        self.client.on_disconnect = on_disconnect

        self.client.connect()
        self.log.info('connected to Adafruit')
        self.client.loop_background()

    def cleanup(self):
        self.client.disconnect()

    def notify(self, name, value):
        self.log.info('Adafruit IO: publish({}={})'.format(name, value))
        self.client.publish(name, value['state'])

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()

    # Mod publish value
    while client.messageSend != "x":  # char 'x' to exit
        client.messageSend = input("Nuevo valor para el tanque\n")

    client.loop_background(stop=True)
    client.disconnect()
    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
temperature = tempSensor.readTemperature()
print("temperature "+str(temperature))
client.publish("bedroom",temperature)

client.disconnect()