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


Python publish.single方法代碼示例

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


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

示例1: execute

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def execute(self, globalconfig, persondata, weightdata, bodydata):
        """ Publishes weight and body data """

        if not persondata or not weightdata or not bodydata:
            logger.error('Invalid data...')
            return

        person_id = str(persondata[0]['person'])

        # construct payload
        model = globalconfig.get('Scale', 'device_model')
        payload = dict(weightdata[0])
        payload.update(bodydata[0])
        payload.update(persondata[0])
        payload['model'] = model

        logger.info('Publishing data of person {}'.format(person_id))

        publish.single(topic='bs440/person{}/'.format(person_id),
                       payload=json.dumps(payload),
                       **self.mqtt_args) 
開發者ID:keptenkurk,項目名稱:BS440,代碼行數:23,代碼來源:BS440mqtt.py

示例2: mqtt

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def mqtt(msg):
    try:
        mqtt_auth = None
        if len(mqtt_username) > 0:
            mqtt_auth = { 'username': mqtt_username, 'password': mqtt_password }

        mqttpublish.single(mqtt_topic, msg, qos=0, retain=False, hostname=mqtt_hostname,
        port=mqtt_port, client_id=mqtt_clientid, keepalive=60, will=None, auth=mqtt_auth,
        tls=None)
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass 
開發者ID:Shmoopty,項目名稱:rpi-appliance-monitor,代碼行數:15,代碼來源:vibration.py

示例3: discovery

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def discovery():
    for MQTTUser in (USER1_NAME,USER2_NAME,USER3_NAME):
        message = '{"name": "' + MQTTUser + ' Weight",'
        message+= '"state_topic": "miScale/' + MQTTUser + '/weight","value_template": "{{ value_json.Weight }}","unit_of_measurement": "kg",'
        message+= '"json_attributes_topic": "miScale/' + MQTTUser + '/weight","icon": "mdi:scale-bathroom"}'
        publish.single(
                        MQTT_DISCOVERY_PREFIX + '/sensor/' + MQTT_PREFIX + '/' + MQTTUser + '/config',
                        message,
                        retain=True,
                        hostname=MQTT_HOST,
                        port=MQTT_PORT,
                        auth={'username':MQTT_USERNAME, 'password':MQTT_PASSWORD}
                    )
    sys.stdout.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Discovery Completed...\n") 
開發者ID:lolouk44,項目名稱:xiaomi_mi_scale,代碼行數:16,代碼來源:Xiaomi_Scale.py

示例4: toggleFeedbackSounds

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def toggleFeedbackSounds(self, state='On'):
		"""
		Activates or disables the feedback sounds, on all devices
		:param state: str On or off
		"""

		deviceList = self.DeviceManager.getDevicesByType('AliceSatellite', connectedOnly=True)
		deviceList.append(constants.DEFAULT_SITE_ID)

		for device in deviceList:
			device = device.replace('@mqtt', '')
			publish.single(constants.TOPIC_TOGGLE_FEEDBACK.format(state.title()), payload=json.dumps({'siteId': device})) 
開發者ID:project-alice-assistant,項目名稱:ProjectAlice,代碼行數:14,代碼來源:MqttManager.py

示例5: onHotword

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def onHotword():
	global mqttServer, mqttPort, siteId
	publish.single('hermes/hotword/{0}/detected'.format(hotwordId), payload=json.dumps({'siteId': siteId, 'modelId': 'default'}), hostname=mqttServer, port=1883) 
開發者ID:Psychokiller1888,項目名稱:snips-custom-hotword,代碼行數:5,代碼來源:customHotword.py

示例6: thread_publish

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def thread_publish(self, topic, payload):
        mqtt_pub.single(topic, hostname=self.dojo_broker, port=self.dojo_port, payload=payload) 
開發者ID:MobProgramming,項目名稱:MobTimer.Python,代碼行數:4,代碼來源:DojoManager.py

示例7: send

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def send(self, topic, payload):
        logger.debug('Send message to topic {}'.format(topic))
        #logger.debug('Message payload {}'.format(payload))
        publish.single(topic, payload,
                       hostname=self.client.comm_config['broker']['address']) 
開發者ID:DT42,項目名稱:BerryNet,代碼行數:7,代碼來源:__init__.py

示例8: log_dummy

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def log_dummy( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
	pass 
開發者ID:chaeron,項目名稱:thermostat,代碼行數:4,代碼來源:thermostat.py

示例9: log_mqtt

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def log_mqtt( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
	if level >= logLevel:
		ts = datetime.datetime.now().strftime( "%Y-%m-%dT%H:%M:%S%z " ) if LOG_ALWAYS_TIMESTAMP or timestamp else ""
		topic = mqttPubPrefix + "/sensor/log/" + LOG_LEVELS_STR[ level ] + "/" + mqttClientID + "/" + child_device + "/" + msg_type + "/" + msg_subtype 
		payload = ts + msg

		if single:
			publish.single( topic, payload, hostname=mqttServer, port=mqttPort, client_id=mqttClientID )
		else:
			mqttc.publish( topic, payload ) 
開發者ID:chaeron,項目名稱:thermostat,代碼行數:12,代碼來源:thermostat.py

示例10: log_file

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def log_file( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
	if level >= logLevel:
		ts = datetime.datetime.now().strftime( "%Y-%m-%dT%H:%M:%S%z " ) 
		logFile.write( ts + LOG_LEVELS_STR[ level ] + "/" + child_device + "/" + msg_type + "/" + msg_subtype + ": " + msg + "\n" ) 
開發者ID:chaeron,項目名稱:thermostat,代碼行數:6,代碼來源:thermostat.py

示例11: log_print

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def log_print( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
	if level >= logLevel:
		ts = datetime.datetime.now().strftime( "%Y-%m-%dT%H:%M:%S%z " ) if LOG_ALWAYS_TIMESTAMP or timestamp else ""
		print( ts + LOG_LEVELS_STR[ level ] + "/" + child_device + "/" + msg_type + "/" + msg_subtype + ": " + msg ) 
開發者ID:chaeron,項目名稱:thermostat,代碼行數:6,代碼來源:thermostat.py

示例12: restart

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def restart():
	log( LOG_LEVEL_STATE, CHILD_DEVICE_NODE, MSG_SUBTYPE_CUSTOM + "/restart", "Thermostat restarting...", single=True ) 
	GPIO.cleanup()

	if logFile is not None:
		logFile.flush()
		os.fsync( logFile.fileno() )
		logFile.close()

	if mqttEnabled:	
		mqttc.disconnect()

	os.execl( sys.executable, 'python', __file__, *sys.argv[1:] )	# This does not return!!! 
開發者ID:chaeron,項目名稱:thermostat,代碼行數:15,代碼來源:thermostat.py

示例13: __init__

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def __init__(self):
        """ Reads config file """
        logger.info('Initialising plugin: ' + __name__)

        # read ini file from same location as plugin resides, named [pluginname].ini
        configfile = os.path.dirname(os.path.realpath(__file__)) + '/' + __name__ + '.ini'
        plugin_config = SafeConfigParser()
        plugin_config.read(configfile)
        logger.info('Read config from: ' + configfile)

        # create configuration arguments for MQTT client
        mqtt_config = dict(plugin_config.items('MQTT'))
        self.mqtt_args = {'client_id': mqtt_config['client_id'],
                          'hostname': mqtt_config['hostname'],
                          'port': mqtt_config['port'],
                          'retain': True}

        tls = {}
        if 'tls_cert' in mqtt_config:
            tls['ca_certs'] = mqtt_config['tls_cert']
        if 'tls_version' in mqtt_config:
            tls['tls_version'] = ssl.__getattribute__(mqtt_config['tls_version'])
        if len(tls) > 0:
            self.mqtt_args['tls'] = tls

        if 'username' in mqtt_config:
            self.mqtt_args['auth'] = {'username': mqtt_config['username'],
                                      'password': mqtt_config['password']}

        publish.single(topic='bs440/init/', payload='BS440 initialised', **self.mqtt_args) 
開發者ID:keptenkurk,項目名稱:BS440,代碼行數:32,代碼來源:BS440mqtt.py

示例14: _publish

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def _publish(self, weight, unit, mitdatetime, hasImpedance, miimpedance):
        if int(weight) > USER1_GT:
            user = USER1_NAME
            height = USER1_HEIGHT
            age = self.GetAge(USER1_DOB)
            sex = USER1_SEX
        elif int(weight) < USER2_LT:
            user = USER2_NAME
            height = USER2_HEIGHT
            age = self.GetAge(USER2_DOB)
            sex = USER2_SEX
        else:
            user = USER3_NAME
            height = USER3_HEIGHT
            age = self.GetAge(USER3_DOB)
            sex = USER3_SEX
        lib = Xiaomi_Scale_Body_Metrics.bodyMetrics(weight, height, age, sex, 0)
        message = '{'
        message += '"Weight":"' + "{:.2f}".format(weight) + '"'
        message += ',"BMI":"' + "{:.2f}".format(lib.getBMI()) + '"'
        message += ',"Basal Metabolism":"' + "{:.2f}".format(lib.getBMR()) + '"'
        message += ',"Visceral Fat":"' + "{:.2f}".format(lib.getVisceralFat()) + '"'

        if hasImpedance:
            lib = Xiaomi_Scale_Body_Metrics.bodyMetrics(weight, height, age, sex, int(miimpedance))
            bodyscale = ['Obese', 'Overweight', 'Thick-set', 'Lack-exerscise', 'Balanced', 'Balanced-muscular', 'Skinny', 'Balanced-skinny', 'Skinny-muscular']
            message += ',"Lean Body Mass":"' + "{:.2f}".format(lib.getLBMCoefficient()) + '"'
            message += ',"Body Fat":"' + "{:.2f}".format(lib.getFatPercentage()) + '"'
            message += ',"Water":"' + "{:.2f}".format(lib.getWaterPercentage()) + '"'
            message += ',"Bone Mass":"' + "{:.2f}".format(lib.getBoneMass()) + '"'
            message += ',"Muscle Mass":"' + "{:.2f}".format(lib.getMuscleMass()) + '"'
            message += ',"Protein":"' + "{:.2f}".format(lib.getProteinPercentage()) + '"'
            message += ',"Body Type":"' + str(bodyscale[lib.getBodyType()]) + '"'
            message += ',"Metabolic Age":"' + "{:.0f}".format(lib.getMetabolicAge()) + '"'

        message += ',"TimeStamp":"' + mitdatetime + '"'
        message += '}'
        try:
            sys.stdout.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Publishing data to topic {MQTT_PREFIX + '/' + user + '/weight'}: {message}\n")
            publish.single(
                MQTT_PREFIX + '/' + user + '/weight',
                message,
                # qos=1, #Removed qos=1 as incorrect connection details will result in the client waiting for ack from broker
                retain=True,
                hostname=MQTT_HOST,
                port=MQTT_PORT,
                auth={'username':MQTT_USERNAME, 'password':MQTT_PASSWORD}
            )
            sys.stdout.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Data Published ...\n")
        except Exception as error:
            sys.stderr.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Could not publish to MQTT: {error}\n")
            raise 
開發者ID:lolouk44,項目名稱:xiaomi_mi_scale,代碼行數:54,代碼來源:Xiaomi_Scale.py

示例15: continueDialog

# 需要導入模塊: from paho.mqtt import publish [as 別名]
# 或者: from paho.mqtt.publish import single [as 別名]
def continueDialog(self, sessionId: str, text: str, customData: dict = None, intentFilter: list = None, previousIntent: str = '', slot: str = '', currentDialogState: str = '', probabilityThreshold: float = None):
		"""
		Continues a dialog
		:param probabilityThreshold: The probability threshold override for the user's answer to this coming conversation round
		:param currentDialogState: a str representing a state in the dialog, usefull for multiturn dialogs
		:param sessionId: int session id to continue
		:param customData: json str
		:param text: str text spoken
		:param intentFilter: array intent filter for user randomTalk
		:param previousIntent: the previous intent that started the dialog continuation
		:param slot: Optional String, requires intentFilter to contain a single value - If set, the dialogue engine will not run the the intent classification on the user response and go straight to slot filling, assuming the intent is the one passed in the intentFilter, and searching the value of the given slot
		"""

		if previousIntent:
			self.DialogSessionManager.addPreviousIntent(sessionId=sessionId, previousIntent=previousIntent)

		jsonDict = {
			'sessionId': sessionId,
			'text': text,
			'sendIntentNotRecognized': True,
		}

		if customData is not None:
			if isinstance(customData, dict):
				jsonDict['customData'] = json.dumps(customData)
			elif isinstance(customData, str):
				jsonDict['customData'] = customData
			else:
				self.logWarning(f'ContinueDialog was provided customdata of unsupported type: {customData}')
		else:
			customData = dict()

		intentList = list()
		if intentFilter:
			intentList = [str(x).replace('hermes/intent/', '') for x in intentFilter]
			jsonDict['intentFilter'] = intentList

		if slot:
			if intentFilter and len(intentList) > 1:
				self.logWarning('Can\'t specify a slot if you have more than one intent in the intent filter')
			elif not intentFilter:
				self.logWarning('Can\'t use a slot definition without setting an intent filter')
			else:
				jsonDict['slot'] = slot

		session = self.DialogSessionManager.getSession(sessionId=sessionId)
		session.intentFilter = intentFilter
		if probabilityThreshold is not None:
			session.probabilityThreshold = probabilityThreshold

		if currentDialogState:
			session.currentState = currentDialogState

		session.customData = {**session.customData, **customData}

		if self.ConfigManager.getAliceConfigByName('outputOnSonos') != '1' or (self.ConfigManager.getAliceConfigByName('outputOnSonos') == '1' and self.SkillManager.getSkillInstance('Sonos') is None or not self.SkillManager.getSkillInstance('Sonos').anySkillHere(session.siteId)) or not self.SkillManager.getSkillInstance('Sonos').active:
			self._mqttClient.publish(constants.TOPIC_CONTINUE_SESSION, json.dumps(jsonDict))
		else:
			jsonDict['text'] = ''
			self._mqttClient.publish(constants.TOPIC_CONTINUE_SESSION, json.dumps(jsonDict))
			self._speakOnSonos(text, constants.DEFAULT_SITE_ID) 
開發者ID:project-alice-assistant,項目名稱:ProjectAlice,代碼行數:63,代碼來源:MqttManager.py


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