def setup_client(self):
if self.client is None:
if not HAVE_MQTT:
print("Please install paho-mqtt 'pip install paho-mqtt' "
"to use this library")
return False
self.client = mqtt.Client(
client_id=self.blid, clean_session=self.clean,
protocol=mqtt.MQTTv311)
# Assign event callbacks
self.client.on_message = self.on_message
self.client.on_connect = self.on_connect
self.client.on_publish = self.on_publish
self.client.on_subscribe = self.on_subscribe
self.client.on_disconnect = self.on_disconnect
# Uncomment to enable debug messages
# client.on_log = self.on_log
# set TLS, self.cert_name is required by paho-mqtt, even if the
# certificate is not used...
# but v1.3 changes all this, so have to do the following:
self.log.info("Seting TLS")
try:
self.client.tls_set(
self.cert_name, cert_reqs=ssl.CERT_NONE,
tls_version=ssl.PROTOCOL_TLSv1)
except ValueError: # try V1.3 version
self.log.warn("TLS Setting failed - trying 1.3 version")
self.client._ssl_context = None
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
context.load_default_certs()
self.client.tls_set_context(context)
# disables peer verification
self.client.tls_insecure_set(True)
self.client.username_pw_set(self.blid, self.password)
return True
return False
python类MQTTv311()的实例源码
def setup_client(self):
if self.client is None:
if not HAVE_MQTT:
print("Please install paho-mqtt 'pip install paho-mqtt' "
"to use this library")
return False
self.client = mqtt.Client(
client_id=self.blid, clean_session=self.clean,
protocol=mqtt.MQTTv311)
# Assign event callbacks
self.client.on_message = self.on_message
self.client.on_connect = self.on_connect
self.client.on_publish = self.on_publish
self.client.on_subscribe = self.on_subscribe
self.client.on_disconnect = self.on_disconnect
# Uncomment to enable debug messages
# client.on_log = self.on_log
# set TLS, self.cert_name is required by paho-mqtt, even if the
# certificate is not used...
# but v1.3 changes all this, so have to do the following:
self.log.info("Seting TLS")
try:
self.client.tls_set(
self.cert_name, cert_reqs=ssl.CERT_NONE,
tls_version=ssl.PROTOCOL_TLSv1)
except ValueError: # try V1.3 version
self.log.warn("TLS Setting failed - trying 1.3 version")
self.client._ssl_context = None
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
context.load_default_certs()
self.client.tls_set_context(context)
# disables peer verification
self.client.tls_insecure_set(True)
self.client.username_pw_set(self.blid, self.password)
return True
return False
def publishRaceTimes(hexUID, name, completionTime):
try:
# setup the log manager
myLog = logManager.logManager("main.py", "./log/")
myLog.disableFileOutput()
myLog.enableConsolePrint()
# setup the mqttCore variable
myPythonMQTTCore = mqttCore.mqttCore("rfid-aws", True, mqtt.MQTTv311, myLog)
myPythonMQTTCore.setConnectDisconnectTimeoutSecond(90)
myPythonMQTTCore.setMQTTOperationTimeoutSecond(10)
myPythonMQTTCore.config(thingHost, 8883, rootCA[0], privateKey[0], certificate[0])
# connect to the IoT service
myPythonMQTTCore.connect()
# get the current date and time and set the publish payload
now = datetime.datetime.now(pytz.timezone(timezone)).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
payload = json.dumps({'uid' : hexUID, 'name' : name, 'raceTime' : completionTime, 'createdDateTime' : now })
# publish to the topic
myPythonMQTTCore.publish(publishTopic, payload, 0, False)
# disconnect from the IoT service
myPythonMQTTCore.disconnect()
# display a success message
displayPublishSuccess()
except AWSIoTExceptions.publishTimeoutException:
print "Syncing reported data: A Publish Timeout Exception happened."
except AWSIoTExceptions.publishError:
print "Syncing reported data: A Publish Error happened."
except Exception as e:
print e
# Function to display a success message to the user
# after the race time is published to the AWS IoT service.
def __init__(self, client_id="", clean_session=True, protocol=None, transport="tcp"):
"""Initialize ClientArgs with default or passed-in values."""
self._default_client_id = ("paho-" + str(random.randrange(1000, 10000)) + "-" + socket.gethostname())[:23]
self.client_id = client_id
self.clean_session = clean_session
self._default_protocol = mqtt.MQTTv311
self.protocol = protocol
self.transport = transport
def connect_device(self):
"""
Connects to device using provided connection arguments
Returns: True/False depending on the result of connection
"""
if not self.config:
self.parse_config()
self.client = mqtt.Client(clean_session=True, protocol=mqtt.MQTTv311, userdata=self)
self.client.username_pw_set(self.serial_number, self._hashed_password())
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
self.client.on_message = self.on_message
self.client.connect(self.ip_address, port=self.port_number)
self.client.loop_start()
try:
if self.connected.get(timeout=self.connectivity_timeout):
self._request_state()
try:
self.state_data = self.state_data_available.get(timeout=5)
self.sensor_data = self.sensor_data_available.get(timeout=5)
# Return True in case of successful connect and data retrieval
return True
except Empty:
self.errors.append(DataRetrieveError())
except Empty:
self.errors.append(ConnectionError(99))
# If any issue occurred return False
self.client = None
return False
def send_data(self, data):
final_data = {}
for name, datum in data.items():
names = name.split('.')
if 'avg_value' in datum:
if names[0] in final_data:
final_data[names[0]][names[1]] = datum['avg_value']
else:
final_data[names[0]] = {names[1]: datum['avg_value']}
for name, datum in final_data.items():
topic = "{0}/{1}".format(self._publish_topic, name)
if self._username is not None:
auth = {
'username': self._username,
'password': self._password
}
else:
auth = None
publish.single(topic,
payload=self._to_string(datum),
hostname=self._host,
client_id=self._manager._name,
auth=auth,
# tls=tls,
port=self._port,
protocol=mqtt.MQTTv311)
self._log.debug(
"Published message {0} to {1}/{2}.".format(datum, self._host, topic))
def __init__(self, sm):
self.rtuid = ""
self.name = ""
self.broker_name = None
self.broker_ip = None
self.client = mqtt.Client(clean_session=True, userdata=None, protocol=mqtt.MQTTv311)
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.on_disconnect = self.on_disconnect
self.smart_module = sm
self.is_connected = False
self.scheduler_found = False
self.broker_connections = -1
Log.info("Communicator initialized")
def single(topic, payload=None, qos=0, retain=False, hostname="localhost",
port=1883, client_id="", keepalive=60, will=None, auth=None,
tls=None, protocol=paho.MQTTv311, transport="tcp"):
"""Publish a single message to a broker, then disconnect cleanly.
This function creates an MQTT client, connects to a broker and publishes a
single message. Once the message has been delivered, it disconnects cleanly
from the broker.
topic : the only required argument must be the topic string to which the
payload will be published.
payload : the payload to be published. If "" or None, a zero length payload
will be published.
qos : the qos to use when publishing, default to 0.
retain : set the message to be retained (True) or not (False).
hostname : a string containing the address of the broker to connect to.
Defaults to localhost.
port : the port to connect to the broker on. Defaults to 1883.
client_id : the MQTT client id to use. If "" or None, the Paho library will
generate a client id automatically.
keepalive : the keepalive timeout value for the client. Defaults to 60
seconds.
will : a dict containing will parameters for the client: will = {'topic':
"<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
Topic is required, all other parameters are optional and will
default to None, 0 and False respectively.
Defaults to None, which indicates no will should be used.
auth : a dict containing authentication parameters for the client:
auth = {'username':"<username>", 'password':"<password>"}
Username is required, password is optional and will default to None
if not provided.
Defaults to None, which indicates no authentication is to be used.
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">}
ca_certs is required, all other parameters are optional and will
default to None if not provided, which results in the client using
the default behaviour - see the paho.mqtt.client documentation.
Defaults to None, which indicates that TLS should not be used.
Alternatively, tls input can be an SSLContext object, which will be
processed using the tls_set_context method.
transport : set to "tcp" to use the default setting of transport which is
raw TCP. Set to "websockets" to use WebSockets as the transport.
"""
msg = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain}
multiple([msg], hostname, port, client_id, keepalive, will, auth, tls,
protocol, transport)
def __init__(self, hass, broker, port, client_id, keepalive, username,
password, certificate, client_key, client_cert,
tls_insecure, protocol, will_message, birth_message):
"""Initialize Home Assistant MQTT client."""
import paho.mqtt.client as mqtt
self.hass = hass
self.topics = {}
self.progress = {}
self.birth_message = birth_message
if protocol == PROTOCOL_31:
proto = mqtt.MQTTv31
else:
proto = mqtt.MQTTv311
if client_id is None:
self._mqttc = mqtt.Client(protocol=proto)
else:
self._mqttc = mqtt.Client(client_id, protocol=proto)
if username is not None:
self._mqttc.username_pw_set(username, password)
if certificate is not None:
self._mqttc.tls_set(certificate, certfile=client_cert,
keyfile=client_key)
if tls_insecure is not None:
self._mqttc.tls_insecure_set(tls_insecure)
self._mqttc.on_subscribe = self._mqtt_on_subscribe
self._mqttc.on_unsubscribe = self._mqtt_on_unsubscribe
self._mqttc.on_connect = self._mqtt_on_connect
self._mqttc.on_disconnect = self._mqtt_on_disconnect
self._mqttc.on_message = self._mqtt_on_message
if will_message:
self._mqttc.will_set(will_message.get(ATTR_TOPIC),
will_message.get(ATTR_PAYLOAD),
will_message.get(ATTR_QOS),
will_message.get(ATTR_RETAIN))
self._mqttc.connect(broker, port, keepalive)