• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python publish.single函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: run

    def run(self, topic, message=None, qos=0, retain=False):
        if self._username:
            self._auth_payload = {
                'username': self._username,
                'password': self._password,
            }

        if self._ssl:
            if not self._ssl_cacert:
                raise ValueError('Missing "ssl_cacert" config option')

            if not self._ssl_cert:
                raise ValueError('Missing "ssl_cert" config option')

            if not self._ssl_key:
                raise ValueError('Missing "ssl_key" config option')

            self._ssl_payload = {
                'ca_certs': self._ssl_cacert,
                'certfile': self._ssl_cert,
                'keyfile': self._ssl_key,
            }

        publish.single(topic, payload=message, qos=qos, retain=retain,
                       hostname=self._hostname, port=self._port,
                       client_id=self._client_id, keepalive=60,
                       auth=self._auth_payload, tls=self._ssl_payload,
                       protocol=self._protocol)
开发者ID:AlexeyDeyneko,项目名称:st2contrib,代码行数:28,代码来源:publish.py


示例2: checkEvent

def checkEvent(onlyEv=False):
	if debug:
		print("[checkEvent]")
	global link_map
	#warte auf mouseup
	try:
		for ev in p.event.get(6):
			#hole coords
			pos = ev.pos
			
			if onlyEv:
				return True
		
			#vergleiche mit linkmap
			for ln in link_map:
			#fuehle ersten treffer aus
				if ln["pos1"][0] <= pos[0] and ln["pos2"][0] >= pos[0] and ln["pos1"][1] <= pos[1] and ln["pos2"][1] >= pos[1]:
					if debug:
						print(pos)
						print(ln)
						#exit()

					if "exec" in ln.keys():
						call('bin/'+ln["exec"])
						
					if "screen" in ln.keys():
						updateScreen(ln["screen"])
						
					if "mqttt" in ln.keys():
						mospub.single(ln["mqttt"], payload=ln["mqttp"], hostname=c.mSERVER)
					#verwerfe rest
					return True
	except:
		pass
	return False
开发者ID:electronicfreak,项目名称:HomeDisplay,代码行数:35,代码来源:homeDisplay.py


示例3: publish

 def publish(self, msg):
     try:
         publish.single(
             topic=self.topic, payload=msg, hostname=self.host, auth=self.auth, tls=self.tls, port=self.port
         )
     except Exception, ex:
         print ex
开发者ID:apoorvajagadeesh,项目名称:ohiostate_ece_proj,代码行数:7,代码来源:sendbin.py


示例4: sendND

def sendND():
	try:
		while(True):
			publish.single("testbed/nodeDiscover/command/", 'START', hostname=BROKER_NAME)
			time.sleep(30)
	except:
		print "Publish ND command failed. Trying again in 30 seconds..."
开发者ID:oujoseph,项目名称:DLTSN_Network_Code,代码行数:7,代码来源:scheduler.py


示例5: contingency_plan

def contingency_plan(contingency):
	global nodeList
	print "in contingency_plan"
	print nodeList
	# For each mac address (appliance)


	for i in nodeList:
		if contingency < 0:
			if nodeList[i] < abs(contingency):
				# Disable everything in the appliance
				countp1 = i.split(',')[1] # get A=X
				countp2 = countp1.split('=')[1] # get X
				j = 0
				while j < int(countp2):
					publish.single("testbed/gateway/mqtt/" + i.split(',')[0], 'AO' + str(j) + '=0', hostname=BROKER_NAME)
					print 'AO' + str(j)
					j = j + 1
					time.sleep(1)
					# Need to wait due to limitation of the arduino

		if contingency > 0:
			if nodeList[i] < abs(contingency):
				# Disable everything in the appliance
				countp1 = i.split(',')[1] # get A=X
				countp2 = countp1.split('=')[1] # get X
				j = 0
				while j < int(countp2):
					publish.single("testbed/gateway/mqtt/" + i.split(',')[0], 'AO' + str(j) + '=1', hostname=BROKER_NAME)
					print 'AO' + str(j)
					j = j + 1
					time.sleep(1)
开发者ID:oujoseph,项目名称:DLTSN_Network_Code,代码行数:32,代码来源:scheduler.py


示例6: publish_msg

def publish_msg(args):
    print 'publish >>> topic:', args.topic, 'payload:', args.payload
    if args.username and args.password:
        auth = {'username':args.username, 'password':args.password}
    else:
        auth = None
    publish.single(args.topic, args.payload, hostname=args.host, port=args.port, auth=auth)
开发者ID:sakurahilljp,项目名称:pyraspi,代码行数:7,代码来源:mqtt_pub.py


示例7: publish_single

    def publish_single(self, topic, payload=None, qos=0, retain=False,
            hostname="localhost", port=1883, client_id="", keepalive=60,
            will=None, auth=None, tls=None, protocol=mqtt.MQTTv31):

        """ Publish a single message and disconnect. This keyword uses the
        [http://eclipse.org/paho/clients/python/docs/#single|single]
        function of publish module.
        `topic` topic to which the message will be published
        `payload` message payload to publish (default None)
        `qos` qos of the message (default 0)
        `retain` retain flag (True or False, default False)
        `hostname` MQTT broker host (default localhost)
        `port` broker port (default 1883)
        `client_id` if not specified, a random id is generated
        `keepalive` keepalive timeout value for client
        `will` a dict containing will parameters for client:
            will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>,
                'retain':<retain>}
        `auth` a dict containing authentication parameters for the client:
            auth = {'username':"<username>", 'password':"<password>"}
        `tls` a dict containing TLS configuration parameters for the client:
            dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
                'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
                'ciphers':"<ciphers">}
        `protocol` MQTT protocol version (MQTTv31 or MQTTv311)
        Example:
        Publish a message on specified topic and disconnect:
        | Publish Single | topic=t/mqtt | payload=test | hostname=127.0.0.1 |
        """
        logger.info('Publishing to: %s:%s, topic: %s, payload: %s, qos: %s' %
                    (hostname, port, topic, payload, qos))
        publish.single(topic, payload, qos, retain, hostname, port,
                        client_id, keepalive, will, auth, tls, protocol)
开发者ID:wucangji,项目名称:Mqtt_Robot_Test,代码行数:33,代码来源:mqttlib.py


示例8: sales_forecast

def sales_forecast():
    #forecast
    s = requests.Session()
    r = s.get("https://login.salesforce.com/?un={}&pw={}".format(sf_id, sf_pw))

    #forecast
    r = s.get("https://na3.salesforce.com/00O50000003OCM5?view=d&snip&export=1&enc=UTF-8&xf=csv")
    
    content = r.content.decode('UTF-8')
    sf_data = csv.reader(StringIO(content))

    sf_data = [row for row in sf_data if len(row)>10]
    if not sf_data:
        return
    sf_data.pop(0)

    forecast = sum(map(float, [row[11] for row in sf_data]))
    forecast = "${:,d}".format(round(forecast))
    print("forecast =", forecast)

    #closed
    closed = sum(map(float, [row[10] for row in sf_data]))
    closed = "${:,d}".format(round(closed))
    print("closed =", closed)

    data = {"header":"Forecast", "text":["forecast: {}".format(forecast), "closed: {}".format(closed)], "pos":5} #expects a list
    mqtt_publish.single('esp_tft', json.dumps(data), hostname=aws_host, retain=False, port=1883, keepalive=60)
开发者ID:slzatz,项目名称:sonos-companion,代码行数:27,代码来源:esp_tft_mqtt_sf.py


示例9: main

def main(args):
    
    if args.https:
        conn = http.client.HTTPSConnection("data.jkoolcloud.com", timeout=10)
        conn.connect()
        
        msg = "<access-request><token>" + args.https + "</token></access-request>"
        headers = {"Content-Type": "text/plain"}
        conn.request("POST", "", msg, headers)
        response = conn.getresponse()
        data = response.read()
        
        headers = {"Content-Type":"application/json"}
        msg = {"operation":"tnt4py", "type":"EVENT", "msg-text":args.msg}
        msg = json.dumps(msg)
        conn.request("POST", "", msg, headers)
        response = conn.getresponse()
        data = response.read()
        print(response.status, response.reason)
        conn.close()
        
    if args.mqtt:
        topic = "tnt4py"
        if args.topic:
            topic = args.topic
        publish.single(topic, args.msg, hostname=args.mqtt[0], auth={"username":args.mqtt[1], "password":args.mqtt[2]})  
开发者ID:Nastel,项目名称:tnt4py,代码行数:26,代码来源:streaming.py


示例10: iterateNodes

def iterateNodes(xbee, runningNodes, uniqueDict):
    # while True:
    print "in iterator nodes"
    for key in runningNodes:
        # InfoIdConv just sets the info_id as the destination address
        status = None
        t = 9999
        #defaults to temperature sensor

        try:
            xbee.tx(frame_id='2', dest_addr=key, data='\x54\x3F\x0A')
            # xbee.tx(frame_id='2', dest_addr=key, data='\x4C\x3F\x0A')
            print '[WAITING ON DATA]'
            status=xbee.wait_read_frame(timeout=1)
            # if status['sdz']:
            #     print "hi"
            print status
            print 'RECEIVED DATA]'
            status=xbee.wait_read_frame(timeout=1)
            print status
            t=status['rf_data'].split('/r/n')[0]
            t=t.split('\n')[0]
            t=t.split('=')[1]
            print 'RECEIVED RF DATA: ' + t
            mqttUploadString = ('testbed/' + key.encode('hex'))
            print "Sending message to broker on topic: " + mqttUploadString
            publish.single(mqttUploadString, t, hostname=BROKER_NAME)
        except:
            print "EXCEPTION IN ITERATE NODES"
开发者ID:oujoseph,项目名称:DLTSN_Network_Code,代码行数:29,代码来源:xbeeAggregateGateway.py


示例11: sendmessage

def sendmessage(request):
    Topic = request.REQUEST.get('topic','')
    Message = request.REQUEST.get('message','')
    if Topic =='' or Message =='':
        return HttpResponse(returnCode(1004))#"{'error':1004,'message':'missing some part'}")
    publish.single(Topic, Message,qos=2, hostname=Hostname,port=Port)
    return HttpResponse(returnCode(2000))#"{'error':2000,'message':'Success!'}")
开发者ID:Komey,项目名称:Toupiao,代码行数:7,代码来源:views.py


示例12: process

def process(csv):
    """ Split the CSV, transform to OwnTracks JSON and publish via MQTT"""

    try:
        tst, lat, lon, soc, interval = csv.split(",")
        if int(tst) < 1:
            print "Ignoring zeroed results:", result
        payload = {
            "_type": "location",
            "tst": int(tst),
            "lat": float(lat),
            "lon": float(lon),
            "tid": device_id[-2:],
            "batt": float(soc),  # State of Charge in %
            "_interval": int(interval),
        }

        mqtt.single(
            topic,
            json.dumps(payload),
            qos=2,
            retain=True,
            hostname=hostname,
            port=int(port),
            client_id=clientid,
            auth=auth,
            will=will,
            tls=tls,
            protocol=int(protocol),
        )

    except Exception, e:
        print str(e)
开发者ID:owntracks,项目名称:electron,代码行数:33,代码来源:obtain.py


示例13: lo

def lo():
    """ The program turns on LED
    """

    # Set up logging
    syslog.syslog('Lo Starting')
    logging.basicConfig(filename='ha-conn.log',level=logging.DEBUG)
    logging.info('Lo starting')

    # set up the MQTT environment
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect("127.0.0.1", 1883, 60)

    topic = "homeassistant/2/101/1/P"
    msgDict = {}
    msgDict['action'] = "P"
    msgDict['result'] = 0
    msgDict['req_ID'] = 4
    msgDict['deviceID'] = 101
    msgDict['instance'] = 1
    msgDict['float1'] = 300 

    msg = json.dumps(msgDict) 
    print(topic + " " + msg)

    logging.info(topic + " " + msg)
    publish.single(topic, msg, hostname="127.0.0.1")
开发者ID:Jimboeri,项目名称:bee-monitor,代码行数:30,代码来源:d300.py


示例14: balance_thread

def balance_thread():
    if not os.path.isfile("mqtt_config.txt"):
        raise Exception("MQTT is not configured. "
                        "Create mqtt_config.txt with first line mqtt server IP address and "
                        "second line with user name and"
                        "third line with your password and"
                        "forth line with your topic for account balance.")

    with open("mqtt_config.txt") as fp:
        ip = fp.readline().strip()
        user = fp.readline().strip()
        password = fp.readline().strip()
        topic = fp.readline().strip()

    while True:
        balance = exchange.get_balance()
        publish.single(topic,
                       payload="{0}".format(sum([coin['usdtValue'] for coin in balance])),
                       qos=0,
                       retain=True,
                       hostname=ip,
                       port=1883,
                       client_id="",
                       keepalive=60,
                       will=None,
                       auth={'username': user, 'password': password},
                       tls=None)

        time.sleep(20)
开发者ID:0x1001,项目名称:StockMarket,代码行数:29,代码来源:notifier.py


示例15: mqtt_monitor

def mqtt_monitor():
    """ The main program that links the gateway Moteino to the MQTT system
    """
    global reqList

    # set up the MQTT environment
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect("127.0.0.1", 1883, 60)
    client.loop_start()

    req_Ref = 1              # a unique reference number to include in each request
    reqList = []            # a list to hold outstanding requests
    inpString = ''
    myReq = remoteRequest("")       # create an empty request object
    myReq.topic = 'homeassistant/jim'
    myReq.node=1
    myReq.device=1
    myReq.instance=1
    myReq.action='Z'
    myReq.result=12
    myReq.float1=13
    myReq.float2=14
    myReq.req_ID=15
    myReq.Topic()                     # Create the topic & message to send to mqtt
    myReq.Msg()
    
    while True:
      time.sleep(5)
      #publish.single(myReq.topic, myReq.msg, hostname="127.0.0.1")  # send to mqtt  # send to mqtt
      publish.single("Jim/topic", "Test", hostname="127.0.0.1")  # send to mqtt  # send to mqtt
开发者ID:Jimboeri,项目名称:gateway,代码行数:33,代码来源:mqtt-gen.py


示例16: publish_mqtt

def publish_mqtt(payload):
    topic = "/plc1"
    try:
        publish.single(topic, payload, hostname="broker_ip_address", port=1883, retain=False, qos=0)
    except Exception as err:
        print "Couldn't publish :" + str(err)
        pass
开发者ID:pumanzor,项目名称:modbus,代码行数:7,代码来源:mqtt_modbus.py


示例17: send

def send(uid, addr, req, token):
    broker = get_broker(addr)
    buf = codec.encode(req, token, uid)
    if QOS >= 0:
        publish.single(addr, buf, hostname=broker, port=SIGNALING_PORT, qos=QOS)
    else:
        publish.single(addr, buf, hostname=broker, port=SIGNALING_PORT)
开发者ID:virtdev,项目名称:virtdev,代码行数:7,代码来源:signaling.py


示例18: publish

	def publish(self, msg):
		try:
			publish.single(topic=self.topic, payload=msg, hostname=self.host, auth=self.auth, tls=self.tls, port=self.port)
			#print "MQTT message published:", self.topic, msg, self.host, self.auth, self.tls, self.port
			logging.info( "MQTT message published: " + msg)
		except Exception, ex:
			logging.error(ex)
开发者ID:sushilshah,项目名称:iot_supplychain_gateway,代码行数:7,代码来源:atl_pahomqtt.py


示例19: analyzer

def analyzer(response):
    result = {}
    res = [hex(i) for i in response]
    print len(res)
    result['header'] = header_analyser(res)
    result['command'] = command_analyzer(res)
    result['parameters'] = paramaters_analyzer(res)
    timestamp = datetime.now().time()
    print 'header: ' + str(antenna_code)
    print 'command: ' + result['command']
    if len(res)>50:
        print '-'.join(res[26:42])
        print 'Antenna: ' + str(antenna_code) #'-'.join(res[24:25])
        print 'Tag: '+ '-'.join(res[26:42])
        msg = json.dumps({'tag': '-'.join(res[26:42]), 'antenna': str(antenna_code) , 'timestamp': str(timestamp) }, sort_keys=True,indent=4, separators=(',', ': '))
        try:
            publish.single("input/" + get_antenna_code(), msg , hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None)
            print "LED ON"
        except:
            print "LED OFF"
            pass
    else:
        print '-'.join(result['parameters'])
    print ''
    return result
开发者ID:donMichaelL,项目名称:e-pres,代码行数:25,代码来源:response.py


示例20: handle

def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, by sending a
        mosquitto publish event
        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    words = text.split(' ')
    if words[0] not in DEVICES:
        return mic.say(words[0]+" not found in the list of devices")
    if words[1] not in NUMBERS:
        return mic.say(words[1]+" not found in the list of valid indexes")
    if words[2] not in PAYLOADS:
        return mic.say(words[2]+" is not found in the list of valid payloads")
    topic = '/'.join(['hal9000']+words[0:2])
    payload = words[2]
    if payload == 'OF':
        payload = 'OFF'
    if 'protocol' in profile['mqtt'] and profile['mqtt']['protocol'] == 'MQTTv311':
        protocol = mqtt.MQTTv311
    else:
        protocol = mqtt.MQTTv31
    publish.single(topic.lower(), payload=payload.lower(), client_id='hal9000',
                   hostname=profile['mqtt']['hostname'], port=profile['mqtt']['port'],
                   protocol=protocol)
开发者ID:ArtBIT,项目名称:jasper-module-mqtt,代码行数:28,代码来源:Mqtt.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python paho_test.gen_connect函数代码示例发布时间:2022-05-27
下一篇:
Python client.topic_matches_sub函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap