當前位置: 首頁>>代碼示例>>Python>>正文


Python MQTTClient.publish方法代碼示例

本文整理匯總了Python中Adafruit_IO.MQTTClient.publish方法的典型用法代碼示例。如果您正苦於以下問題:Python MQTTClient.publish方法的具體用法?Python MQTTClient.publish怎麽用?Python MQTTClient.publish使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Adafruit_IO.MQTTClient的用法示例。


在下文中一共展示了MQTTClient.publish方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: dataAdafruitHandler

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
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,代碼行數:16,代碼來源:main.py

示例2: on_message

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
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,代碼行數:16,代碼來源:subscriber_adafruit_proxy.py

示例3: AdafruitNotifier

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
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,代碼行數:47,代碼來源:notifiers.py

示例4: dataNetworkHandler

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
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,代碼行數:22,代碼來源:DataReportingSystem.py

示例5: test_subscribe_and_publish

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
 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,代碼行數:25,代碼來源:test_mqtt_client.py

示例6: listdir

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
#print '\n'.join(str(p) for p in nodelist)

FILES_LIST = [f for f in listdir(DIR_BASE) if isfile(join(DIR_BASE, f))]
print FILES_LIST
print 'Publishing a new message every 15 seconds (press Ctrl-C to quit)...'
while True:
     #sourcefile is instant temperature log file
    for sourcefile in FILES_LIST:
	sourcefile = str(DIR_BASE) + sourcefile
	print "Sourcefile = ", sourcefile
	fh = open(sourcefile)
	for fileread in fh:
		print fileread
		fileread2 = fileread.split("=")
		value = fileread2[1]
		nodemac = fileread2[2]
		print "Node MAC from temperature log file = ", nodemac
		for nodecheck in nodelist:
			nodemaclist = nodecheck[0]
			nodefeed = nodecheck[1]
			if nodemac == nodemaclist:
				feedname = nodefeed
				print "Node MAC from list(config file) = ", nodemaclist
				print "Node feed name = ", nodefeed
		print value
		print 'Publishing {0} to {1} feed.'.format(value, feedname)
		client.publish(feedname, value)
	fh.close()
    time.sleep(15)
開發者ID:sebathorus,項目名稱:Pilot,代碼行數:31,代碼來源:mqtt_pilot.py

示例7: str

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
    message = "unknown_loc  " + str(loops)
    #message = str(loops)
    if Loc == ROCCAMORICE:
        #message = "Roccamorice_heartbeat  " + str(loops)
        message = "Roccamorice_heartbeat  " + str(IP)
    if Loc == COLDIPOZZO:
        #message = "Coldipozzo_heartbeat  " + str(loops)
        message = "Coldipozzo_heartbeat  " + str(IP)
    if Loc == STARLIGHT:
        #message = "Starlight_heartbeat  " + str(loops)
        message = "Starlight_heartbeat  " + str(IP)
    if Loc == WEEHAWKEN:
        #message = "Weehawken_heartbeat  " + str(loops)
        message = "Weehawken_heartbeat  " + str(IP)
    print("Published: ",message)
    client.publish('heartbeat', message)
    time.sleep(300)	#every 5 minutes
    loops = loops + 1
    if loops > 288:	# 5min X 288 = 24 hrs
        loops = 0
	os.system("/home/pi/src/mqtt/trim_file_500 /home/pi/src/mqtt/mqtt_data.log")
	
# Another option is to pump the message loop yourself by periodically calling
# the client loop function.  Notice how the loop below changes to call loop
# continuously while still sending a new message every 10 seconds.  This is a
# good option if you don't want to or can't have a thread pumping the message
# loop in the background.
#last = 0
#print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...'
#while True:
#   # Explicitly pump the message loop.
開發者ID:schenkl,項目名稱:src,代碼行數:33,代碼來源:mqtt-ioadafruit-all.py

示例8: MQTTClient

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
    # 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(cdavalox, 55177304338e4b578dca347c357d3402)

# 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)...'
while True:
    value = random.randint(0, 100)
    print 'Publishing {0} to Welcome feed.'.format(value)
    client.publish('Welcome feed', value)
    time.sleep(10)
開發者ID:cdavalox,項目名稱:TheIoTLearningInitiative,代碼行數:32,代碼來源:adatest.py

示例9: sleep

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
try:

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

	#Run a thread in the background so you can continue doing things in your program.
	client.loop_background()
#	client.loop_blocking()
	sleep(2)

	# Now send new values every X seconds. This is done simply to keep the connection alive
	print 'Publishing a new message periodically to keep the connection alive (press Ctrl-C to quit)...'
	while True:
		value = random.randint(0, 100)
		print 'Publishing {0} to outbound feed.'.format(value)
		client.publish(conf["adafruit"]["outboundFeed"], value)
		time.sleep(conf["adafruit"]["MQQTPublishingDelay"])

except KeyboardInterrupt:
	pass
	
except Exception, e:
	print e
	logging.error('Exception raise', exc_info=True)
	emailServer.setMailList(conf["log"]["developerEmail"])
	emailServer.sendErrorMessage(e)
	
finally:
	dispenser.cleanupTreatDispenser()
	logging.info('Program terminated at ' + str(datetime.datetime.now()))
開發者ID:bigchewy,項目名稱:PicklesTreatMachine,代碼行數:32,代碼來源:listenMQTT.py

示例10: MQTTClient

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
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.loop_background()
client.connect()


signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
time.sleep(2)

try:
    while True:
       temperature = tempSensor.readTemperature()
       #print("temperature "+str(temperature))
       (result,mid)=client.publish("bedroom",temperature)
       if (result != 0):
            client.disconnect()
            time.sleep(2)
            client.connect()
       else:
            time.sleep(30)
finally:
    client.disconnect()
    print("disconnect from server")

開發者ID:vorasilp,項目名稱:adafruitio-temperature,代碼行數:30,代碼來源:adafruitio_ssl2.py

示例11: seconds

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
# 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)...'
while True:
    value = random.randint(0, 1)
    print 'Publishing {0} to Door State.'.format(value)
    client.publish('doorstate', value)
    time.sleep(10)

# Another option is to pump the message loop yourself by periodically calling
# the client loop function.  Notice how the loop below changes to call loop
# continuously while still sending a new message every 10 seconds.  This is a
# good option if you don't want to or can't have a thread pumping the message
# loop in the background.
#last = 0
#print 'Publishing a new message every 10 seconds (press Ctrl-C to quit)...'
#while True:
#   # Explicitly pump the message loop.
#   client.loop()
#   # Send a new message every 10 seconds.
#   if (time.time() - last) >= 10.0:
#       value = random.randint(0, 100)
開發者ID:robingreig,項目名稱:raspi-git,代碼行數:33,代碼來源:mqtt_client.py

示例12: print

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
    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()
開發者ID:vorasilp,項目名稱:adafruitio-temperature,代碼行數:32,代碼來源:adafruitio_ssl.py

示例13: print

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
client.tls_set("/home/vorasilp/adafruitio-temperature/certs/geotrust.pem")
print("connecting to adafruit")
client.connect()
client.loop_background()
print("init signal handler")
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
time.sleep(2)
print("start sending")
# 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))
try:
    while True:
        if (running == False):
            break
        client.publish("photocell",12)
        print("data sent")        
        time.sleep(30)
finally:
    #client.disconnect()
    print("exiting")        
    
開發者ID:vorasilp,項目名稱:adafruitio-temperature,代碼行數:31,代碼來源:atest2.py

示例14: print

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
    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()

client.loop_background()
print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...')

while True:
    value = random.randint(0, 100)
    print('Publishing {0} to {1}.'.format(value, IO_FEED))
    client.publish(IO_FEED, value, IO_FEED_USERNAME)
    time.sleep(10)
開發者ID:adafruit,項目名稱:io-client-python,代碼行數:32,代碼來源:mqtt_shared_feeds.py

示例15: MQTTClient

# 需要導入模塊: from Adafruit_IO import MQTTClient [as 別名]
# 或者: from Adafruit_IO.MQTTClient import publish [as 別名]
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY,service_host='io.adafruit.com',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/vorasilp/adafruitio-temperature/certs/geotrust.pem")
client.connect()
client.loop_background()

signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
#time.sleep(4)

try:
    while True:
       temperature = 12
       #print("temperature "+str(temperature))
       (result,mid)=client.publish("photocell",temperature)
       if (result != 0):
            #client.disconnect()
            time.sleep(30)
            #client.connect()
       else:
            print("data sent OK")
            time.sleep(30)
finally:
    #client.disconnect()
    print("disconnect from server")

開發者ID:vorasilp,項目名稱:adafruitio-temperature,代碼行數:30,代碼來源:atest.py


注:本文中的Adafruit_IO.MQTTClient.publish方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。