SolarManager unter Versionsverwaltung
Erster Stand der Hintergrundprozesse, die auf der Synology unter /volume1/homes/wagner/SolarManager laufen: der Manager selbst, die Sammler je Geraet, die MQTT-Bruecke, der Wecker und - neu hinzugezogen - der AutoAction-Runner, der als Hintergrundprozess hierher gehoert und nicht ins Web-Verzeichnis. Zugangsdaten stehen nicht mehr im Quelltext, sondern in config.ini, die nicht mit eingecheckt wird. Vorlage ist config.ini.example, gelesen wird sie von konfig.py. Betroffen waren solarManager.py (Datenbank und Wattpilot), zeit.py, gatherWaterData.py, wecker.py und skoda_testdaten.py, das sich das Passwort bisher aus dem Quelltext eines anderen Moduls herausgesucht hat. Die Kia-Anbindung ist mit dem Fahrzeug entfallen: kiaTest.py, gatherCarData.py und hyundai_kia_connect_api sind nicht mehr dabei, ebenso gatherInverterData.py, auf das nur noch eine auskommentierte Zeile zeigte. Die mitgelieferten Bibliotheken bleiben im Repository - die NAS hat kein pip, sie muessen neben den Skripten liegen. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
import base64
|
||||
import datetime
|
||||
import functools
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from paho.mqtt.client import Client, CallbackAPIVersion
|
||||
|
||||
|
||||
def get_amazon_auth_headers(access_key, secret_key, region, host, port, headers=None):
|
||||
""" Get the amazon auth headers for working with the amazon websockets
|
||||
protocol
|
||||
|
||||
Requires a lot of extra stuff:
|
||||
|
||||
http://docs.aws.amazon.com/general/latest/gr//sigv4-create-canonical-request.html
|
||||
http://docs.aws.amazon.com/general/latest/gr//signature-v4-examples.html#signature-v4-examples-pythonw
|
||||
http://docs.aws.amazon.com/general/latest/gr//sigv4-signed-request-examples.html#sig-v4-examples-get-auth-header
|
||||
|
||||
Args:
|
||||
access_key (str): Amazon access key (AWS_ACCESS_KEY_ID)
|
||||
secret_key (str): Amazon secret access key (AWS_SECRET_ACCESS_KEY)
|
||||
region (str): aws region
|
||||
host (str): iot endpoint (xxxxxxxxxxxxxx.iot.<region>.amazonaws.com)
|
||||
headers (dict): a dictionary of the original headers- normally websocket headers
|
||||
|
||||
Returns:
|
||||
dict: A string containing the headers that amazon expects in the auth
|
||||
request for the iot websocket service
|
||||
"""
|
||||
|
||||
# pylint: disable=unused-variable,unused-argument
|
||||
|
||||
def sign(key, msg):
|
||||
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
|
||||
|
||||
def getSignatureKey(key, dateStamp, regionName, serviceName):
|
||||
kDate = sign(("AWS4" + key).encode("utf-8"), dateStamp)
|
||||
kRegion = sign(kDate, regionName)
|
||||
kService = sign(kRegion, serviceName)
|
||||
kSigning = sign(kService, "aws4_request")
|
||||
return kSigning
|
||||
|
||||
service = "iotdevicegateway"
|
||||
algorithm = "AWS4-HMAC-SHA256"
|
||||
|
||||
t = datetime.datetime.utcnow()
|
||||
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
|
||||
datestamp = t.strftime("%Y%m%d") # Date w/o time, used in credential scope
|
||||
|
||||
if headers is None:
|
||||
headers = {
|
||||
"Host": "{0:s}:443".format(host),
|
||||
"Upgrade": "websocket",
|
||||
"Connection": "Upgrade",
|
||||
"Origin": "https://{0:s}:443".format(host),
|
||||
"Sec-WebSocket-Key": base64.b64encode(uuid.uuid4().bytes),
|
||||
"Sec-Websocket-Version": "13",
|
||||
"Sec-Websocket-Protocol": "mqtt",
|
||||
}
|
||||
|
||||
headers.update({
|
||||
"X-Amz-Date": amzdate,
|
||||
})
|
||||
|
||||
# get into 'canonical' form - lowercase, sorted alphabetically
|
||||
canonical_headers = "\n".join(sorted("{}:{}".format(i.lower(), j).strip() for i, j in headers.items()))
|
||||
# Headers to sign - alphabetical order
|
||||
signed_headers = ";".join(sorted(i.lower().strip() for i in headers.keys()))
|
||||
|
||||
# No payload
|
||||
payload_hash = hashlib.sha256("").hexdigest().lower()
|
||||
|
||||
request_parts = [
|
||||
"GET",
|
||||
"/mqtt",
|
||||
# no query parameters
|
||||
"",
|
||||
canonical_headers + "\n",
|
||||
signed_headers,
|
||||
payload_hash,
|
||||
]
|
||||
|
||||
canonical_request = "\n".join(request_parts)
|
||||
|
||||
# now actually hash request and sign
|
||||
hashed_request = hashlib.sha256(canonical_request).hexdigest()
|
||||
|
||||
credential_scope = "{datestamp:s}/{region:s}/{service:s}/aws4_request".format(**locals())
|
||||
string_to_sign = "{algorithm:s}\n{amzdate:s}\n{credential_scope:s}\n{hashed_request:s}".format(**locals())
|
||||
|
||||
signing_key = getSignatureKey(secret_key, datestamp, region, service)
|
||||
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
|
||||
|
||||
# create auth header
|
||||
authorization_header = "{algorithm:s} Credential={access_key:s}/{credential_scope:s}, SignedHeaders={signed_headers:s}, Signature={signature:s}".format(**locals())
|
||||
|
||||
# get final header string
|
||||
headers["Authorization"] = authorization_header
|
||||
|
||||
return headers
|
||||
|
||||
|
||||
def example_use():
|
||||
access_key = os.environ["AWS_ACCESS_KEY_ID"]
|
||||
secret_key = os.environ["AWS_SECRET_ACCESS_KEY"]
|
||||
port = 8883
|
||||
|
||||
region = "eu-west-1"
|
||||
|
||||
# This is specific to your AWS account
|
||||
host = "abc123def456.iot.{0:s}.amazonaws.com".format(region)
|
||||
|
||||
extra_headers = functools.partial(
|
||||
get_amazon_auth_headers,
|
||||
access_key,
|
||||
secret_key,
|
||||
region,
|
||||
host,
|
||||
port,
|
||||
)
|
||||
|
||||
client = Client(CallbackAPIVersion.VERSION2, transport="websockets")
|
||||
|
||||
client.ws_set_options(headers=extra_headers)
|
||||
|
||||
# Use client as normal from here
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2016 James Myatt <james@jamesmyatt.co.uk>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# James Myatt - initial implementation
|
||||
|
||||
# This shows a simple example of standard logging with an MQTT subscriber client.
|
||||
|
||||
import logging
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# If you want to use a specific client id, use
|
||||
# mqttc = mqtt.Client("client-id")
|
||||
# but note that the client id must be unique on the broker. Leaving the client
|
||||
# id parameter empty will generate a random id for you.
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
mqttc.enable_logger(logger)
|
||||
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
mqttc.subscribe("$SYS/#", 0)
|
||||
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2013 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org>
|
||||
# All rights reserved.
|
||||
|
||||
# This shows an example of an MQTT client that clears all of the retained messages it receives.
|
||||
|
||||
import getopt
|
||||
import sys
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
final_mid = 0
|
||||
|
||||
|
||||
def on_connect(mqttc, userdata, flags, reason_code, properties):
|
||||
if userdata:
|
||||
print(f"reason_code: {reason_code}")
|
||||
|
||||
|
||||
def on_message(mqttc, userdata, msg):
|
||||
global final_mid
|
||||
if msg.retain == 0:
|
||||
pass
|
||||
# sys.exit()
|
||||
else:
|
||||
if userdata:
|
||||
print("Clearing topic " + msg.topic)
|
||||
(rc, final_mid) = mqttc.publish(msg.topic, None, 1, True)
|
||||
|
||||
|
||||
def on_publish(mqttc, userdata, mid, reason_code, properties):
|
||||
global final_mid
|
||||
if mid == final_mid:
|
||||
sys.exit()
|
||||
|
||||
|
||||
def on_log(mqttc, userdata, level, string):
|
||||
print(string)
|
||||
|
||||
|
||||
def print_usage():
|
||||
print(
|
||||
"mqtt_clear_retain.py [-d] [-h hostname] [-i clientid] [-k keepalive] [-p port] [-u username [-P password]] [-v] -t topic")
|
||||
|
||||
|
||||
def main(argv):
|
||||
debug = False
|
||||
host = "mqtt.eclipseprojects.io"
|
||||
client_id = None
|
||||
keepalive = 60
|
||||
port = 1883
|
||||
password = None
|
||||
topic = None
|
||||
username = None
|
||||
verbose = False
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(argv, "dh:i:k:p:P:t:u:v",
|
||||
["debug", "id", "keepalive", "port", "password", "topic", "username", "verbose"])
|
||||
except getopt.GetoptError:
|
||||
print_usage()
|
||||
sys.exit(2)
|
||||
for opt, arg in opts:
|
||||
if opt in ("-d", "--debug"):
|
||||
debug = True
|
||||
elif opt in ("-h", "--host"):
|
||||
host = arg
|
||||
elif opt in ("-i", "--id"):
|
||||
client_id = arg
|
||||
elif opt in ("-k", "--keepalive"):
|
||||
keepalive = int(arg)
|
||||
elif opt in ("-p", "--port"):
|
||||
port = int(arg)
|
||||
elif opt in ("-P", "--password"):
|
||||
password = arg
|
||||
elif opt in ("-t", "--topic"):
|
||||
topic = arg
|
||||
print(topic)
|
||||
elif opt in ("-u", "--username"):
|
||||
username = arg
|
||||
elif opt in ("-v", "--verbose"):
|
||||
verbose = True
|
||||
|
||||
if not topic:
|
||||
print("You must provide a topic to clear.\n")
|
||||
print_usage()
|
||||
sys.exit(2)
|
||||
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id)
|
||||
mqttc._userdata = verbose
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_publish = on_publish
|
||||
mqttc.on_connect = on_connect
|
||||
if debug:
|
||||
mqttc.on_log = on_log
|
||||
|
||||
if username:
|
||||
mqttc.username_pw_set(username, password)
|
||||
mqttc.connect(host, port, keepalive)
|
||||
mqttc.subscribe(topic)
|
||||
mqttc.loop_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2010-2013 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org>
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a simple example of waiting for a message to be published.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
print("reason_code: " + str(reason_code))
|
||||
|
||||
|
||||
def on_message(mqttc, obj, msg):
|
||||
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
def on_publish(mqttc, obj, mid, reason_code, properties):
|
||||
print("mid: " + str(mid))
|
||||
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
|
||||
# If you want to use a specific client id, use
|
||||
# mqttc = mqtt.Client("client-id")
|
||||
# but note that the client id must be unique on the broker. Leaving the client
|
||||
# id parameter empty will generate a random id for you.
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_publish = on_publish
|
||||
# Uncomment to enable debug messages
|
||||
# mqttc.on_log = on_log
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
|
||||
mqttc.loop_start()
|
||||
|
||||
print("tuple")
|
||||
(rc, mid) = mqttc.publish("tuple", "bar", qos=2)
|
||||
print("class")
|
||||
infot = mqttc.publish("class", "bar", qos=2)
|
||||
|
||||
infot.wait_for_publish()
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Jon Levell <levell@uk.ibm.com>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a example of an MQTT publisher with the ability to use
|
||||
# user name, password CA certificates based on command line arguments
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument('-H', '--host', required=False, default="mqtt.eclipseprojects.io")
|
||||
parser.add_argument('-t', '--topic', required=False, default="paho/test/opts")
|
||||
parser.add_argument('-q', '--qos', required=False, type=int,default=0)
|
||||
parser.add_argument('-c', '--clientid', required=False, default=None)
|
||||
parser.add_argument('-u', '--username', required=False, default=None)
|
||||
parser.add_argument('-d', '--disable-clean-session', action='store_true', help="disable 'clean session' (sub + msgs not cleared when client disconnects)")
|
||||
parser.add_argument('-p', '--password', required=False, default=None)
|
||||
parser.add_argument('-P', '--port', required=False, type=int, default=None, help='Defaults to 8883 for TLS or 1883 for non-TLS')
|
||||
parser.add_argument('-N', '--nummsgs', required=False, type=int, default=1, help='send this many messages before disconnecting')
|
||||
parser.add_argument('-S', '--delay', required=False, type=float, default=1, help='number of seconds to sleep between msgs')
|
||||
parser.add_argument('-k', '--keepalive', required=False, type=int, default=60)
|
||||
parser.add_argument('-s', '--use-tls', action='store_true')
|
||||
parser.add_argument('--insecure', action='store_true')
|
||||
parser.add_argument('-F', '--cacerts', required=False, default=None)
|
||||
parser.add_argument('--tls-version', required=False, default=None, help='TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1\n')
|
||||
parser.add_argument('-D', '--debug', action='store_true')
|
||||
|
||||
args, unknown = parser.parse_known_args()
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
print("connect reason_code: " + str(reason_code))
|
||||
|
||||
|
||||
def on_message(mqttc, obj, msg):
|
||||
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
def on_publish(mqttc, obj, mid, reason_code, properties):
|
||||
print("mid: " + str(mid))
|
||||
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
usetls = args.use_tls
|
||||
|
||||
if args.cacerts:
|
||||
usetls = True
|
||||
|
||||
port = args.port
|
||||
if port is None:
|
||||
if usetls:
|
||||
port = 8883
|
||||
else:
|
||||
port = 1883
|
||||
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, args.clientid, clean_session = not args.disable_clean_session)
|
||||
|
||||
if usetls:
|
||||
if args.tls_version == "tlsv1.2":
|
||||
tlsVersion = ssl.PROTOCOL_TLSv1_2
|
||||
elif args.tls_version == "tlsv1.1":
|
||||
tlsVersion = ssl.PROTOCOL_TLSv1_1
|
||||
elif args.tls_version == "tlsv1":
|
||||
tlsVersion = ssl.PROTOCOL_TLSv1
|
||||
elif args.tls_version is None:
|
||||
tlsVersion = None
|
||||
else:
|
||||
print ("Unknown TLS version - ignoring")
|
||||
tlsVersion = None
|
||||
|
||||
if not args.insecure:
|
||||
cert_required = ssl.CERT_REQUIRED
|
||||
else:
|
||||
cert_required = ssl.CERT_NONE
|
||||
|
||||
mqttc.tls_set(ca_certs=args.cacerts, certfile=None, keyfile=None, cert_reqs=cert_required, tls_version=tlsVersion)
|
||||
|
||||
if args.insecure:
|
||||
mqttc.tls_insecure_set(True)
|
||||
|
||||
if args.username or args.password:
|
||||
mqttc.username_pw_set(args.username, args.password)
|
||||
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_publish = on_publish
|
||||
|
||||
if args.debug:
|
||||
mqttc.on_log = on_log
|
||||
|
||||
print("Connecting to "+args.host+" port: "+str(port))
|
||||
mqttc.connect(args.host, port, args.keepalive)
|
||||
|
||||
mqttc.loop_start()
|
||||
|
||||
for x in range (0, args.nummsgs):
|
||||
msg_txt = '{"msgnum": "'+str(x)+'"}'
|
||||
print("Publishing: "+msg_txt)
|
||||
infot = mqttc.publish(args.topic, msg_txt, qos=args.qos)
|
||||
infot.wait_for_publish()
|
||||
|
||||
time.sleep(args.delay)
|
||||
|
||||
mqttc.disconnect()
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2020 Frank Pagliughi <fpagliughi@mindspring.com>
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program and the accompanying materials are made available
|
||||
# under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Frank Pagliughi - initial implementation
|
||||
#
|
||||
|
||||
# This shows an example of an MQTTv5 Remote Procedure Call (RPC) client.
|
||||
# You should run the server_rpc_math.py before.
|
||||
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
from paho.mqtt.packettypes import PacketTypes
|
||||
|
||||
# These will be updated with the server-assigned Client ID
|
||||
client_id = "mathcli"
|
||||
reply_to = ""
|
||||
|
||||
# This correlates the outbound request with the returned reply
|
||||
corr_id = b"1"
|
||||
|
||||
# This is sent in the message callback when we get the response
|
||||
reply = None
|
||||
|
||||
# The MQTTv5 callback takes the additional 'props' parameter.
|
||||
def on_connect(mqttc, userdata, flags, reason_code, props):
|
||||
global client_id, reply_to
|
||||
|
||||
print(f"Connected: '{flags}', '{reason_code}', '{props}'")
|
||||
if hasattr(props, 'AssignedClientIdentifier'):
|
||||
client_id = props.AssignedClientIdentifier
|
||||
reply_to = "replies/math/" + client_id
|
||||
mqttc.subscribe(reply_to)
|
||||
|
||||
|
||||
# An incoming message should be the reply to our request
|
||||
def on_message(mqttc, userdata, msg):
|
||||
global reply
|
||||
|
||||
print(msg.topic+" "+str(msg.payload)+" "+str(msg.properties))
|
||||
props = msg.properties
|
||||
if not hasattr(props, 'CorrelationData'):
|
||||
print("No correlation ID")
|
||||
|
||||
# Match the response to the request correlation ID.
|
||||
if props.CorrelationData == corr_id:
|
||||
reply = msg.payload
|
||||
|
||||
|
||||
if len(sys.argv) < 3:
|
||||
print("USAGE: client_rpc_math.py [add|mult] n1 n2 ...")
|
||||
sys.exit(1)
|
||||
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="", protocol=mqtt.MQTTv5)
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
|
||||
mqttc.connect(host="mqtt.eclipseprojects.io", clean_start=True)
|
||||
mqttc.loop_start()
|
||||
|
||||
# Wait for connection to set `client_id`, etc.
|
||||
while not mqttc.is_connected():
|
||||
time.sleep(0.1)
|
||||
|
||||
# Properties for the request specify the ResponseTopic and CorrelationData
|
||||
props = mqtt.Properties(PacketTypes.PUBLISH)
|
||||
props.CorrelationData = corr_id
|
||||
props.ResponseTopic = reply_to
|
||||
|
||||
# Uncomment to see what got set
|
||||
#print("Client ID: "+client_id)
|
||||
#print("Reply To: "+reply_to)
|
||||
#print(props)
|
||||
|
||||
# The requested operation, 'add' or 'mult'
|
||||
func = sys.argv[1]
|
||||
|
||||
# Gather the numeric parameters as an array of numbers
|
||||
# These can be int's or float's
|
||||
args = []
|
||||
for s in sys.argv[2:]:
|
||||
args.append(float(s))
|
||||
|
||||
# Send the request
|
||||
topic = "requests/math/" + func
|
||||
payload = json.dumps(args)
|
||||
mqttc.publish(topic, payload, qos=1, properties=props)
|
||||
|
||||
# Wait for the reply
|
||||
while reply is None:
|
||||
time.sleep(0.1)
|
||||
|
||||
# Extract the response and print it.
|
||||
rsp = json.loads(reply)
|
||||
print("Response: "+str(rsp))
|
||||
|
||||
mqttc.loop_stop()
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
# All rights reserved.
|
||||
|
||||
# This demonstrates the session present flag when connecting.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
if obj == 0:
|
||||
print("First connection:")
|
||||
elif obj == 1:
|
||||
print("Second connection:")
|
||||
elif obj == 2:
|
||||
print("Third connection (with clean session=True):")
|
||||
print(" Session present: " + str(flags.session_present))
|
||||
print(" Connection result: " + str(reason_code))
|
||||
mqttc.disconnect()
|
||||
|
||||
|
||||
def on_disconnect(mqttc, obj, flags, reason_code, properties):
|
||||
mqttc.user_data_set(obj + 1)
|
||||
if obj == 0:
|
||||
mqttc.reconnect()
|
||||
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="asdfj", clean_session=False)
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_disconnect = on_disconnect
|
||||
# Uncomment to enable debug messages
|
||||
# mqttc.on_log = on_log
|
||||
mqttc.user_data_set(0)
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
|
||||
mqttc.loop_forever()
|
||||
|
||||
# Clear session
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="asdfj", clean_session=True)
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.user_data_set(2)
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2013 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This example shows how you can use the MQTT client in a class.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
class MyMQTTClass(mqtt.Client):
|
||||
|
||||
def on_connect(self, mqttc, obj, flags, reason_code, properties):
|
||||
print("rc: "+str(reason_code))
|
||||
|
||||
def on_connect_fail(self, mqttc, obj):
|
||||
print("Connect failed")
|
||||
|
||||
def on_message(self, mqttc, obj, msg):
|
||||
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
|
||||
|
||||
def on_publish(self, mqttc, obj, mid, reason_codes, properties):
|
||||
print("mid: "+str(mid))
|
||||
|
||||
def on_subscribe(self, mqttc, obj, mid, reason_code_list, properties):
|
||||
print("Subscribed: "+str(mid)+" "+str(reason_code_list))
|
||||
|
||||
def on_log(self, mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
def run(self):
|
||||
self.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
self.subscribe("$SYS/#", 0)
|
||||
|
||||
rc = 0
|
||||
while rc == 0:
|
||||
rc = self.loop()
|
||||
return rc
|
||||
|
||||
|
||||
# If you want to use a specific client id, use
|
||||
# mqttc = MyMQTTClass("client-id")
|
||||
# but note that the client id must be unique on the broker. Leaving the client
|
||||
# id parameter empty will generate a random id for you.
|
||||
mqttc = MyMQTTClass(mqtt.CallbackAPIVersion.VERSION2)
|
||||
rc = mqttc.run()
|
||||
|
||||
print("rc: "+str(rc))
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a simple example of an MQTT subscriber using a per-subscription message handler.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
def on_message_msgs(mosq, obj, msg):
|
||||
# This callback will only be called for messages with topics that match
|
||||
# $SYS/broker/messages/#
|
||||
print("MESSAGES: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
def on_message_bytes(mosq, obj, msg):
|
||||
# This callback will only be called for messages with topics that match
|
||||
# $SYS/broker/bytes/#
|
||||
print("BYTES: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
def on_message(mosq, obj, msg):
|
||||
# This callback will be called for messages that we receive that do not
|
||||
# match any patterns defined in topic specific callbacks, i.e. in this case
|
||||
# those messages that do not have topics $SYS/broker/messages/# nor
|
||||
# $SYS/broker/bytes/#
|
||||
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||
|
||||
# Add message callbacks that will only trigger on a specific subscription match.
|
||||
mqttc.message_callback_add("$SYS/broker/messages/#", on_message_msgs)
|
||||
mqttc.message_callback_add("$SYS/broker/bytes/#", on_message_bytes)
|
||||
mqttc.on_message = on_message
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
mqttc.subscribe("$SYS/#", 0)
|
||||
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2010-2013 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org>
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a simple example of an MQTT subscriber using connect_srv method.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
print("Connected to %s:%s" % (mqttc.host, mqttc.port))
|
||||
|
||||
def on_message(mqttc, obj, msg):
|
||||
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
|
||||
|
||||
def on_subscribe(mqttc, obj, mid, reason_code_list, properties):
|
||||
print("Subscribed: "+str(mid)+" "+str(reason_code_list))
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
# If you want to use a specific client id, use
|
||||
# mqttc = mqtt.Client("client-id")
|
||||
# but note that the client id must be unique on the broker. Leaving the client
|
||||
# id parameter empty will generate a random id for you.
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_subscribe = on_subscribe
|
||||
# Uncomment to enable debug messages
|
||||
#mqttc.on_log = on_log
|
||||
mqttc.connect_srv("eclipseprojects.io", 60)
|
||||
mqttc.subscribe("$SYS/broker/version", 0)
|
||||
|
||||
|
||||
rc = 0
|
||||
while rc == 0:
|
||||
rc = mqttc.loop()
|
||||
|
||||
print("rc: "+str(rc))
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2010-2013 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org>
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a simple example of an MQTT subscriber.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
print("reason_code: "+str(reason_code))
|
||||
|
||||
def on_message(mqttc, obj, msg):
|
||||
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
|
||||
|
||||
def on_subscribe(mqttc, obj, mid, reason_code_list, properties):
|
||||
print("Subscribed: "+str(mid)+" "+str(reason_code_list))
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
# If you want to use a specific client id, use
|
||||
# mqttc = mqtt.Client("client-id")
|
||||
# but note that the client id must be unique on the broker. Leaving the client
|
||||
# id parameter empty will generate a random id for you.
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, transport="websockets")
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_subscribe = on_subscribe
|
||||
# Uncomment to enable debug messages
|
||||
mqttc.on_log = on_log
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 80, 60)
|
||||
mqttc.subscribe("$SYS/broker/version", 0)
|
||||
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2010-2013 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org>
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a simple example of an MQTT subscriber.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
print("reason_code: " + str(reason_code))
|
||||
|
||||
|
||||
def on_message(mqttc, obj, msg):
|
||||
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
def on_subscribe(mqttc, obj, mid, reason_code_list, properties):
|
||||
print("Subscribed: " + str(mid) + " " + str(reason_code_list))
|
||||
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
|
||||
# If you want to use a specific client id, use
|
||||
# mqttc = mqtt.Client("client-id")
|
||||
# but note that the client id must be unique on the broker. Leaving the client
|
||||
# id parameter empty will generate a random id for you.
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_subscribe = on_subscribe
|
||||
# Uncomment to enable debug messages
|
||||
# mqttc.on_log = on_log
|
||||
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
|
||||
mqttc.subscribe("$SYS/#")
|
||||
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Jon Levell <levell@uk.ibm.com>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# All rights reserved.
|
||||
|
||||
# This shows a example of an MQTT subscriber with the ability to use
|
||||
# user name, password CA certificates based on command line arguments
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import ssl
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument('-H', '--host', required=False, default="mqtt.eclipseprojects.io")
|
||||
parser.add_argument('-t', '--topic', required=False, default="$SYS/#")
|
||||
parser.add_argument('-q', '--qos', required=False, type=int, default=0)
|
||||
parser.add_argument('-c', '--clientid', required=False, default=None)
|
||||
parser.add_argument('-u', '--username', required=False, default=None)
|
||||
parser.add_argument('-d', '--disable-clean-session', action='store_true', help="disable 'clean session' (sub + msgs not cleared when client disconnects)")
|
||||
parser.add_argument('-p', '--password', required=False, default=None)
|
||||
parser.add_argument('-P', '--port', required=False, type=int, default=None, help='Defaults to 8883 for TLS or 1883 for non-TLS')
|
||||
parser.add_argument('-k', '--keepalive', required=False, type=int, default=60)
|
||||
parser.add_argument('-s', '--use-tls', action='store_true')
|
||||
parser.add_argument('--insecure', action='store_true')
|
||||
parser.add_argument('-F', '--cacerts', required=False, default=None)
|
||||
parser.add_argument('--tls-version', required=False, default=None, help='TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1\n')
|
||||
parser.add_argument('-D', '--debug', action='store_true')
|
||||
|
||||
args, unknown = parser.parse_known_args()
|
||||
|
||||
|
||||
def on_connect(mqttc, obj, flags, reason_code, properties):
|
||||
print("reason_code: " + str(reason_code))
|
||||
|
||||
|
||||
def on_message(mqttc, obj, msg):
|
||||
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
|
||||
|
||||
|
||||
def on_publish(mqttc, obj, mid):
|
||||
print("mid: " + str(mid))
|
||||
|
||||
|
||||
def on_subscribe(mqttc, obj, mid, reason_code_list, properties):
|
||||
print("Subscribed: " + str(mid) + " " + str(reason_code_list))
|
||||
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
usetls = args.use_tls
|
||||
|
||||
if args.cacerts:
|
||||
usetls = True
|
||||
|
||||
port = args.port
|
||||
if port is None:
|
||||
if usetls:
|
||||
port = 8883
|
||||
else:
|
||||
port = 1883
|
||||
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, args.clientid,clean_session = not args.disable_clean_session)
|
||||
|
||||
if usetls:
|
||||
if args.tls_version == "tlsv1.2":
|
||||
tlsVersion = ssl.PROTOCOL_TLSv1_2
|
||||
elif args.tls_version == "tlsv1.1":
|
||||
tlsVersion = ssl.PROTOCOL_TLSv1_1
|
||||
elif args.tls_version == "tlsv1":
|
||||
tlsVersion = ssl.PROTOCOL_TLSv1
|
||||
elif args.tls_version is None:
|
||||
tlsVersion = None
|
||||
else:
|
||||
print ("Unknown TLS version - ignoring")
|
||||
tlsVersion = None
|
||||
|
||||
if not args.insecure:
|
||||
cert_required = ssl.CERT_REQUIRED
|
||||
else:
|
||||
cert_required = ssl.CERT_NONE
|
||||
|
||||
mqttc.tls_set(ca_certs=args.cacerts, certfile=None, keyfile=None, cert_reqs=cert_required, tls_version=tlsVersion)
|
||||
|
||||
if args.insecure:
|
||||
mqttc.tls_insecure_set(True)
|
||||
|
||||
if args.username or args.password:
|
||||
mqttc.username_pw_set(args.username, args.password)
|
||||
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
mqttc.on_publish = on_publish
|
||||
mqttc.on_subscribe = on_subscribe
|
||||
|
||||
if args.debug:
|
||||
mqttc.on_log = on_log
|
||||
|
||||
print("Connecting to "+args.host+" port: "+str(port))
|
||||
mqttc.connect(args.host, port, args.keepalive)
|
||||
mqttc.subscribe(args.topic, args.qos)
|
||||
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,28 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Ensure can import paho package
|
||||
try:
|
||||
import paho
|
||||
|
||||
except ImportError:
|
||||
# This part is only required to run the examples from within the examples
|
||||
# directory when the module itself is not installed.
|
||||
import inspect
|
||||
import os
|
||||
import sys
|
||||
|
||||
cmd_subfolder = os.path.realpath(
|
||||
os.path.abspath(
|
||||
os.path.join(
|
||||
os.path.split(
|
||||
inspect.getfile(inspect.currentframe())
|
||||
)[0],
|
||||
"..",
|
||||
"src"
|
||||
)
|
||||
)
|
||||
)
|
||||
if cmd_subfolder not in sys.path:
|
||||
sys.path.insert(0, cmd_subfolder)
|
||||
|
||||
import paho
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import uuid
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
client_id = 'paho-mqtt-python/issue72/' + str(uuid.uuid4())
|
||||
topic = client_id
|
||||
print("Using client_id / topic: " + client_id)
|
||||
|
||||
|
||||
class AsyncioHelper:
|
||||
def __init__(self, loop, client):
|
||||
self.loop = loop
|
||||
self.client = client
|
||||
self.client.on_socket_open = self.on_socket_open
|
||||
self.client.on_socket_close = self.on_socket_close
|
||||
self.client.on_socket_register_write = self.on_socket_register_write
|
||||
self.client.on_socket_unregister_write = self.on_socket_unregister_write
|
||||
|
||||
def on_socket_open(self, client, userdata, sock):
|
||||
print("Socket opened")
|
||||
|
||||
def cb():
|
||||
print("Socket is readable, calling loop_read")
|
||||
client.loop_read()
|
||||
|
||||
self.loop.add_reader(sock, cb)
|
||||
self.misc = self.loop.create_task(self.misc_loop())
|
||||
|
||||
def on_socket_close(self, client, userdata, sock):
|
||||
print("Socket closed")
|
||||
self.loop.remove_reader(sock)
|
||||
self.misc.cancel()
|
||||
|
||||
def on_socket_register_write(self, client, userdata, sock):
|
||||
print("Watching socket for writability.")
|
||||
|
||||
def cb():
|
||||
print("Socket is writable, calling loop_write")
|
||||
client.loop_write()
|
||||
|
||||
self.loop.add_writer(sock, cb)
|
||||
|
||||
def on_socket_unregister_write(self, client, userdata, sock):
|
||||
print("Stop watching socket for writability.")
|
||||
self.loop.remove_writer(sock)
|
||||
|
||||
async def misc_loop(self):
|
||||
print("misc_loop started")
|
||||
while self.client.loop_misc() == mqtt.MQTT_ERR_SUCCESS:
|
||||
try:
|
||||
await asyncio.sleep(1)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
print("misc_loop finished")
|
||||
|
||||
|
||||
class AsyncMqttExample:
|
||||
def __init__(self, loop):
|
||||
self.loop = loop
|
||||
|
||||
def on_connect(self, client, userdata, flags, reason_code, properties):
|
||||
print("Subscribing")
|
||||
client.subscribe(topic)
|
||||
|
||||
def on_message(self, client, userdata, msg):
|
||||
if not self.got_message:
|
||||
print("Got unexpected message: {}".format(msg.decode()))
|
||||
else:
|
||||
self.got_message.set_result(msg.payload)
|
||||
|
||||
def on_disconnect(self, client, userdata, flags, reason_code, properties):
|
||||
self.disconnected.set_result(reason_code)
|
||||
|
||||
async def main(self):
|
||||
self.disconnected = self.loop.create_future()
|
||||
self.got_message = None
|
||||
|
||||
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=client_id)
|
||||
self.client.on_connect = self.on_connect
|
||||
self.client.on_message = self.on_message
|
||||
self.client.on_disconnect = self.on_disconnect
|
||||
|
||||
aioh = AsyncioHelper(self.loop, self.client)
|
||||
|
||||
self.client.connect('mqtt.eclipseprojects.io', 1883, 60)
|
||||
self.client.socket().setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
|
||||
|
||||
for c in range(3):
|
||||
await asyncio.sleep(5)
|
||||
print("Publishing")
|
||||
self.got_message = self.loop.create_future()
|
||||
self.client.publish(topic, b'Hello' * 40000, qos=1)
|
||||
msg = await self.got_message
|
||||
print("Got response with {} bytes".format(len(msg)))
|
||||
self.got_message = None
|
||||
|
||||
self.client.disconnect()
|
||||
print("Disconnected: {}".format(await self.disconnected))
|
||||
|
||||
|
||||
print("Starting")
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_until_complete(AsyncMqttExample(loop).main())
|
||||
loop.close()
|
||||
print("Finished")
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import socket
|
||||
import uuid
|
||||
from select import select
|
||||
from time import time
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
client_id = 'paho-mqtt-python/issue72/' + str(uuid.uuid4())
|
||||
topic = client_id
|
||||
print("Using client_id / topic: " + client_id)
|
||||
|
||||
|
||||
class SelectMqttExample:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def on_connect(self, client, userdata, flags, reason_code, properties):
|
||||
print("Subscribing")
|
||||
client.subscribe(topic)
|
||||
|
||||
def on_message(self, client, userdata, msg):
|
||||
if self.state not in {1, 3, 5}:
|
||||
print("Got unexpected message: {}".format(msg.decode()))
|
||||
return
|
||||
|
||||
print("Got message with len {}".format(len(msg.payload)))
|
||||
self.state += 1
|
||||
self.t = time()
|
||||
|
||||
def on_disconnect(self, client, userdata, flags, reason_code, properties):
|
||||
self.disconnected = True, reason_code
|
||||
|
||||
def do_select(self):
|
||||
sock = self.client.socket()
|
||||
if not sock:
|
||||
raise Exception("Socket is gone")
|
||||
|
||||
print("Selecting for reading" + (" and writing" if self.client.want_write() else ""))
|
||||
r, w, e = select(
|
||||
[sock],
|
||||
[sock] if self.client.want_write() else [],
|
||||
[],
|
||||
1
|
||||
)
|
||||
|
||||
if sock in r:
|
||||
print("Socket is readable, calling loop_read")
|
||||
self.client.loop_read()
|
||||
|
||||
if sock in w:
|
||||
print("Socket is writable, calling loop_write")
|
||||
self.client.loop_write()
|
||||
|
||||
self.client.loop_misc()
|
||||
|
||||
def main(self):
|
||||
self.disconnected = (False, None)
|
||||
self.t = time()
|
||||
self.state = 0
|
||||
|
||||
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=client_id)
|
||||
self.client.on_connect = self.on_connect
|
||||
self.client.on_message = self.on_message
|
||||
self.client.on_disconnect = self.on_disconnect
|
||||
|
||||
self.client.connect('mqtt.eclipseprojects.io', 1883, 60)
|
||||
print("Socket opened")
|
||||
self.client.socket().setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
|
||||
|
||||
while not self.disconnected[0]:
|
||||
self.do_select()
|
||||
|
||||
if self.state in {0, 2, 4}:
|
||||
if time() - self.t >= 5:
|
||||
print("Publishing")
|
||||
self.client.publish(topic, b'Hello' * 40000)
|
||||
self.state += 1
|
||||
|
||||
if self.state == 6:
|
||||
self.state += 1
|
||||
self.client.disconnect()
|
||||
|
||||
print("Disconnected: {}".format(self.disconnected[1]))
|
||||
|
||||
|
||||
print("Starting")
|
||||
SelectMqttExample().main()
|
||||
print("Finished")
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import socket
|
||||
import uuid
|
||||
|
||||
import trio
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
client_id = 'paho-mqtt-python/issue72/' + str(uuid.uuid4())
|
||||
topic = client_id
|
||||
print("Using client_id / topic: " + client_id)
|
||||
|
||||
|
||||
class TrioAsyncHelper:
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
self.sock = None
|
||||
self._event_large_write = trio.Event()
|
||||
|
||||
self.client.on_socket_open = self.on_socket_open
|
||||
self.client.on_socket_register_write = self.on_socket_register_write
|
||||
self.client.on_socket_unregister_write = self.on_socket_unregister_write
|
||||
|
||||
async def read_loop(self):
|
||||
while True:
|
||||
await trio.lowlevel.wait_readable(self.sock)
|
||||
self.client.loop_read()
|
||||
|
||||
async def write_loop(self):
|
||||
while True:
|
||||
await self._event_large_write.wait()
|
||||
await trio.lowlevel.wait_writable(self.sock)
|
||||
self.client.loop_write()
|
||||
|
||||
async def misc_loop(self):
|
||||
print("misc_loop started")
|
||||
while self.client.loop_misc() == mqtt.MQTT_ERR_SUCCESS:
|
||||
await trio.sleep(1)
|
||||
print("misc_loop finished")
|
||||
|
||||
def on_socket_open(self, client, userdata, sock):
|
||||
print("Socket opened")
|
||||
self.sock = sock
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
|
||||
|
||||
def on_socket_register_write(self, client, userdata, sock):
|
||||
print('large write request')
|
||||
self._event_large_write.set()
|
||||
|
||||
def on_socket_unregister_write(self, client, userdata, sock):
|
||||
print("finished large write")
|
||||
self._event_large_write = trio.Event()
|
||||
|
||||
|
||||
class TrioAsyncMqttExample:
|
||||
def on_connect(self, client, userdata, flags, reason_code, properties):
|
||||
print("Subscribing")
|
||||
client.subscribe(topic)
|
||||
|
||||
def on_message(self, client, userdata, msg):
|
||||
print("Got response with {} bytes".format(len(msg.payload)))
|
||||
|
||||
def on_disconnect(self, client, userdata, flags, reason_code, properties):
|
||||
print('Disconnect result {}'.format(reason_code))
|
||||
|
||||
async def test_write(self, cancel_scope: trio.CancelScope):
|
||||
for c in range(3):
|
||||
await trio.sleep(5)
|
||||
print("Publishing")
|
||||
self.client.publish(topic, b'Hello' * 40000, qos=1)
|
||||
cancel_scope.cancel()
|
||||
|
||||
async def main(self):
|
||||
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=client_id)
|
||||
self.client.on_connect = self.on_connect
|
||||
self.client.on_message = self.on_message
|
||||
self.client.on_disconnect = self.on_disconnect
|
||||
|
||||
trio_helper = TrioAsyncHelper(self.client)
|
||||
|
||||
self.client.connect('mqtt.eclipseprojects.io', 1883, 60)
|
||||
|
||||
async with trio.open_nursery() as nursery:
|
||||
nursery.start_soon(trio_helper.read_loop)
|
||||
nursery.start_soon(trio_helper.write_loop)
|
||||
nursery.start_soon(trio_helper.misc_loop)
|
||||
nursery.start_soon(self.test_write, nursery.cancel_scope)
|
||||
|
||||
self.client.disconnect()
|
||||
print("Disconnected")
|
||||
|
||||
|
||||
print("Starting")
|
||||
trio.run(TrioAsyncMqttExample().main)
|
||||
print("Finished")
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This shows an example of using the publish.multiple helper function.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.publish as publish
|
||||
|
||||
msgs = [{'topic': "paho/test/multiple", 'payload': "multiple 1"}, ("paho/test/multiple", "multiple 2", 0, False)]
|
||||
publish.multiple(msgs, hostname="mqtt.eclipseprojects.io")
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This shows an example of using the publish.single helper function.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.publish as publish
|
||||
|
||||
publish.single("paho/test/single", "boo", hostname="mqtt.eclipseprojects.io")
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This shows an example of using the publish.single helper function with unicode topic and payload.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.publish as publish
|
||||
|
||||
topic = u"paho/test/single/ô"
|
||||
payload = u"bôô"
|
||||
publish.single(topic, payload, hostname="mqtt.eclipseprojects.io")
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This shows an example of using the publish.single helper function with unicode topic and payload.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.publish as publish
|
||||
|
||||
topic = u"paho/test/single/ô"
|
||||
payload = u'German umlauts like "ä" ü"ö" are not supported'
|
||||
publish.single(topic, payload, hostname="mqtt.eclipseprojects.io")
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2020 Frank Pagliughi <fpagliughi@mindspring.com>
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program and the accompanying materials are made available
|
||||
# under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Frank Pagliughi - initial implementation
|
||||
#
|
||||
|
||||
# This shows an example of an MQTTv5 Remote Procedure Call (RPC) server.
|
||||
|
||||
import json
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
from paho.mqtt.packettypes import PacketTypes
|
||||
|
||||
# The math functions exported
|
||||
|
||||
def add(nums):
|
||||
sum = 0
|
||||
for x in nums:
|
||||
sum += x
|
||||
return sum
|
||||
|
||||
def mult(nums):
|
||||
prod = 1
|
||||
for x in nums:
|
||||
prod *= x
|
||||
return prod
|
||||
|
||||
# Remember that the MQTTv5 callback takes the additional 'props' parameter.
|
||||
def on_connect(mqttc, userdata, flags, reason_code, props):
|
||||
print(f"Connected: '{flags}', '{reason_code}', '{props}'")
|
||||
if not flags.session_present:
|
||||
print("Subscribing to math requests")
|
||||
mqttc.subscribe("requests/math/#")
|
||||
|
||||
# Each incoming message should be an RPC request on the
|
||||
# 'requests/math/#' topic.
|
||||
def on_message(mqttc, userdata, msg):
|
||||
print(msg.topic + " " + str(msg.payload))
|
||||
|
||||
# Get the response properties, abort if they're not given
|
||||
props = msg.properties
|
||||
if not hasattr(props, 'ResponseTopic') or not hasattr(props, 'CorrelationData'):
|
||||
print("No reply requested")
|
||||
return
|
||||
|
||||
corr_id = props.CorrelationData
|
||||
reply_to = props.ResponseTopic
|
||||
|
||||
# The command parameters are in the payload
|
||||
nums = json.loads(msg.payload)
|
||||
|
||||
# The requested command is at the end of the topic
|
||||
res = 0
|
||||
if msg.topic.endswith("add"):
|
||||
res = add(nums)
|
||||
elif msg.topic.endswith("mult"):
|
||||
res = mult(nums)
|
||||
|
||||
# Now we have the result, res, so send it back on the 'reply_to'
|
||||
# topic using the same correlation ID as the request.
|
||||
print("Sending response "+str(res)+" on '"+reply_to+"': "+str(corr_id))
|
||||
props = mqtt.Properties(PacketTypes.PUBLISH)
|
||||
props.CorrelationData = corr_id
|
||||
|
||||
payload = json.dumps(res)
|
||||
mqttc.publish(reply_to, payload, qos=1, properties=props)
|
||||
|
||||
def on_log(mqttc, obj, level, string):
|
||||
print(string)
|
||||
|
||||
|
||||
# Typically with an RPC service, you want to make sure that you're the only
|
||||
# client answering requests for specific topics. Using a known client ID
|
||||
# might help.
|
||||
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="paho_rpc_math_srvr", protocol=mqtt.MQTTv5)
|
||||
mqttc.on_message = on_message
|
||||
mqttc.on_connect = on_connect
|
||||
|
||||
# Uncomment to enable debug messages
|
||||
#mqttc.on_log = on_log
|
||||
|
||||
mqttc.connect(host="mqtt.eclipseprojects.io", clean_start=False)
|
||||
mqttc.loop_forever()
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2016 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This shows an example of using the subscribe.callback helper function.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.subscribe as subscribe
|
||||
|
||||
|
||||
def print_msg(client, userdata, message):
|
||||
print("%s : %s" % (message.topic, message.payload))
|
||||
|
||||
subscribe.callback(print_msg, "#", hostname="mqtt.eclipseprojects.io")
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2016 Roger Light <roger@atchoo.org>
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Distribution License v1.0
|
||||
# which accompanies this distribution.
|
||||
#
|
||||
# The Eclipse Distribution License is available at
|
||||
# http://www.eclipse.org/org/documents/edl-v10.php.
|
||||
#
|
||||
# Contributors:
|
||||
# Roger Light - initial implementation
|
||||
|
||||
# This shows an example of using the subscribe.simple helper function.
|
||||
|
||||
import context # Ensures paho is in PYTHONPATH
|
||||
|
||||
import paho.mqtt.subscribe as subscribe
|
||||
|
||||
topics = ['#']
|
||||
|
||||
m = subscribe.simple(topics, hostname="mqtt.eclipseprojects.io", retained=False, msg_count=2)
|
||||
for a in m:
|
||||
print(a.topic)
|
||||
print(a.payload)
|
||||
Reference in New Issue
Block a user