当前位置: 首页>>代码示例>>Python>>正文


Python Adafruit_IO.MQTTClient类代码示例

本文整理汇总了Python中Adafruit_IO.MQTTClient的典型用法代码示例。如果您正苦于以下问题:Python MQTTClient类的具体用法?Python MQTTClient怎么用?Python MQTTClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了MQTTClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_connect

 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())
开发者ID:Mecabot,项目名称:io-client-python,代码行数:12,代码来源:test_mqtt_client.py

示例2: dataAdafruitHandler

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)
开发者ID:brahamcosoX3,项目名称:TheIoTLearningInitiative,代码行数:14,代码来源:main.py

示例3: test_secure_connect

 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)
开发者ID:adafruit,项目名称:io-client-python,代码行数:15,代码来源:test_mqtt_client.py

示例4: test_insecure_connect

 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)
开发者ID:adafruit,项目名称:io-client-python,代码行数:16,代码来源:test_mqtt_client.py

示例5: dataNetworkHandler

def dataNetworkHandler():
    global idDevice 
    idDevice = GetMACAddress() # Make this a global variable
    mqttclient = paho.Client()
    mqttclient.on_publish = on_publish
    adaclient = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
    mqttclient.connect("test.mosquitto.org", 1883, 60)
    adaclient.connect()
    #adaclient.loop_background()
    while True:
        packets = dataNetwork()    
    	global message 
        message = idDevice + " " + str(packets)
    	#pdb.set_trace()
        print "dataNetworkHandler " + message
    	mqttclient.publish("IoT101/"+idDevice+"/Network", message)
    	adaclient.publish("IoT101/"+idDevice+"/Network", message)
	json = {'id':idDevice,'packets':int(packets)}
        dweepy.dweet_for('DataReportingSystem',json)
        time.sleep(3)
开发者ID:marcelarosalesj,项目名称:TheIoTLearningInitiative,代码行数:20,代码来源:DataReportingSystem.py

示例6: on_message

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)
开发者ID:abacuspix,项目名称:MQTT_IoT,代码行数:14,代码来源:subscriber_adafruit_proxy.py

示例7: test_subscribe_and_publish

 def test_subscribe_and_publish(self):
     # Create MQTT test client.
     client = MQTTClient(self.get_test_username(), self.get_test_key())
     # Save all on_message handler responses.
     messages = []
     def on_message(mqtt_client, feed, payload):
         self.assertEqual(mqtt_client, client)
         messages.append((feed, payload))
     client.on_message = on_message
     # Connect and wait until on_connect event is fired.
     client.connect()
     self.wait_until_connected(client)
     # Subscribe to changes on a feed.
     client.subscribe('testfeed')
     # Publish a message on the feed.
     client.publish('testfeed', 42)
     # Wait for message to be received or timeout.
     start = time.time()
     while len(messages) == 0 and (time.time() - start) < TIMEOUT_SEC:
         client.loop()
         time.sleep(0)
     # Verify one update message with payload is received.
     self.assertListEqual(messages, [('testfeed', '42')])
开发者ID:adafruit,项目名称:io-client-python,代码行数:23,代码来源:test_mqtt_client.py

示例8: instance_start

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
开发者ID:mgroseman,项目名称:mqtt-repeater,代码行数:37,代码来源:mqtt_repeater.py

示例9: initialize

    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()
开发者ID:dmreiland,项目名称:thingpin,代码行数:15,代码来源:notifiers.py

示例10: AdafruitNotifier

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'])
开发者ID:dmreiland,项目名称:thingpin,代码行数:45,代码来源:notifiers.py

示例11: main

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)
开发者ID:FlorianDr,项目名称:bee-observation,代码行数:44,代码来源:main.py

示例12: test_disconnect

 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())
开发者ID:adafruit,项目名称:io-client-python,代码行数:15,代码来源:test_mqtt_client.py

示例13: MQTTClient

#          MQTT: io-client-python/examples/mqtt_client.py
#   
# Run:   $ python jbd_uart_mqtt_service.py

import sys
from Adafruit_IO import MQTTClient
import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import UART

ADAFRUIT_IO_KEY      = <KEY>
ADAFRUIT_IO_USERNAME = <USERNAME>
FEED_PUB = 'thing2'
FEED_SUB = 'thing1'

ble = Adafruit_BluefruitLE.get_provider()
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
msg = None

def ble_main():
    global msg
    ble.clear_cached_data()
    adapter = ble.get_default_adapter()
    adapter.power_on()
    print('Using adapter: {0}'.format(adapter.name))
    print('Disconnecting any connected UART devices...')
    UART.disconnect_devices()
    print('Searching for UART device...')

    try:
        adapter.start_scan()
        # Search for the first UART device found (will time out after 60 seconds
开发者ID:jbdamask,项目名称:Adafruit,代码行数:31,代码来源:jbd_uart_mqtt_service.py

示例14: disconnected

    client.subscribe('DemoFeed')

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)


# 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.
开发者ID:cdavalox,项目名称:TheIoTLearningInitiative,代码行数:31,代码来源:1.py

示例15: print

    print('Subscribing to Feed {0}'.format(FEED_ID))
    client.subscribe(FEED_ID)
    print('Waiting for feed data...')

def disconnected(client):
    """Disconnected function will be called when the client disconnects."""
    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()

# The first option is to run a thread in the background so you can continue
# doing things in your program.
client.loop_blocking()
开发者ID:robingreig,项目名称:raspi-git,代码行数:30,代码来源:subscribe02.py


注:本文中的Adafruit_IO.MQTTClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。