Python paho.mqtt.publish.single() Examples

The following are 16 code examples of paho.mqtt.publish.single(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paho.mqtt.publish , or try the search function .
Example #1
Source File: vibration.py    From rpi-appliance-monitor with MIT License 6 votes vote down vote up
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 
Example #2
Source File: BS440mqtt.py    From BS440 with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: Xiaomi_Scale.py    From xiaomi_mi_scale with MIT License 5 votes vote down vote up
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") 
Example #4
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
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})) 
Example #5
Source File: customHotword.py    From snips-custom-hotword with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #6
Source File: DojoManager.py    From MobTimer.Python with MIT License 5 votes vote down vote up
def thread_publish(self, topic, payload):
        mqtt_pub.single(topic, hostname=self.dojo_broker, port=self.dojo_port, payload=payload) 
Example #7
Source File: __init__.py    From BerryNet with GNU General Public License v3.0 5 votes vote down vote up
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']) 
Example #8
Source File: thermostat.py    From thermostat with MIT License 5 votes vote down vote up
def log_dummy( level, child_device, msg_subtype, msg, msg_type=MSG_TYPE_SET, timestamp=True, single=False ):
	pass 
Example #9
Source File: thermostat.py    From thermostat with MIT License 5 votes vote down vote up
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 ) 
Example #10
Source File: thermostat.py    From thermostat with MIT License 5 votes vote down vote up
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" ) 
Example #11
Source File: thermostat.py    From thermostat with MIT License 5 votes vote down vote up
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 ) 
Example #12
Source File: thermostat.py    From thermostat with MIT License 5 votes vote down vote up
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!!! 
Example #13
Source File: BS440mqtt.py    From BS440 with MIT License 5 votes vote down vote up
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) 
Example #14
Source File: Xiaomi_Scale.py    From xiaomi_mi_scale with MIT License 4 votes vote down vote up
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 
Example #15
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 4 votes vote down vote up
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) 
Example #16
Source File: mq_pub_15.py    From tuya-convert with MIT License 4 votes vote down vote up
def main(argv=None):
	broker='127.0.0.1'
	localKey = "0000000000000000"
	deviceID = ""
	protocol = "2.1"
	if argv is None:
		argv = sys.argv
	try: #getopt
		try:
			opts, args = getopt.getopt(argv[1:], "hl:i:vb:p:", ["help", "localKey=", "deviceID=", "broker=", "protocol="])
		except:
			raise Usage(help_message)
	
		# option processing
		for option, value in opts:
			if option == "-v":
				verbose = True
			if option in ("-h", "--help"):
				raise Usage(help_message)
			if option in ("-l", "--localKey"):
				localKey = value
			if option in ("-i", "--deviceID"):
				deviceID = value
			if option in ("-b", "--broker"):
				broker = value
			if option in ("-p", "--protocol"):
				protocol = value

		if (len(localKey)<10):
			raise Usage(help_message)
		if (len(deviceID)<10):
			raise Usage(help_message) #
	except Usage:
		print (sys.argv[0].split("/")[-1] + ": ")
		print ("\t for help use --help")
		print (help_message)
		return 2
	
	if protocol == "2.1":
		message = '{"data":{"gwId":"%s"},"protocol":15,"s":%d,"t":%d}'  %(deviceID, 1523715, time.time())
	else:
		message = '{"data":{"gwId":"%s"},"protocol":15,"s":"%d","t":"%d"}'  %(deviceID, 1523715, time.time())
	print("encoding", message, "using protocol", protocol)
	m1 = iot_enc(message, localKey, protocol)

	publish.single("smart/device/in/%s" % (deviceID), m1, hostname=broker)