当前位置: 首页>>代码示例>>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;未经允许,请勿转载。