76 lines
1.9 KiB
Python
76 lines
1.9 KiB
Python
import sys
|
|
import socket
|
|
import time
|
|
import ssl
|
|
import paho.mqtt.client as mqtt
|
|
|
|
# TODO: make port a constant? 80 for http
|
|
# 443 for https
|
|
def servertest(argv):
|
|
host = argv[1]
|
|
port = int(argv[2])
|
|
|
|
print (host)
|
|
print (port)
|
|
|
|
args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
|
|
for family, socktype, proto, canonname, sockaddr in args:
|
|
s = socket.socket(family, socktype, proto)
|
|
|
|
print (sockaddr)
|
|
try:
|
|
s.connect_ex(sockaddr)
|
|
except socket.error:
|
|
return False
|
|
else:
|
|
s.close()
|
|
return True
|
|
|
|
def on_log(client, userdata, level, buf):
|
|
print("log: ", buf)
|
|
|
|
def on_connect(client, userdata, flags, rc):
|
|
if rc == 0:
|
|
client.connected_flag = True
|
|
print("connected to mqtt server")
|
|
else:
|
|
client.bad_connection_flag = True
|
|
if rc == 5:
|
|
print("broker requires authentication")
|
|
|
|
def on_message(client, userdata, message):
|
|
print("message received " ,str(message.payload.decode("utf-8")))
|
|
print("message topic=",message.topic)
|
|
print("message qos=",message.qos)
|
|
print("message retain flag=",message.retain)
|
|
|
|
if __name__ == "__main__":
|
|
if servertest(sys.argv):
|
|
print("Server is up")
|
|
else:
|
|
print("Server is down")
|
|
|
|
broker_address = "205.185.116.243"
|
|
print ("creating new mqtt client instance")
|
|
client = mqtt.Client("dev-client")
|
|
|
|
# initialize flags
|
|
client.connected_flag = False
|
|
client.bad_connection_flag = False
|
|
|
|
|
|
client.on_log = on_log
|
|
client.on_connect = on_connect
|
|
client.tls_set(ca_certs="/root/mqtt_certs/chain.pem", certfile="/root/mqtt_certs/cert.pem", tls_version=ssl.PROTOCOL_TLSv1_2)
|
|
client.on_message=on_message #attach function to callback
|
|
print ("connecting to broker")
|
|
|
|
client.connect(broker_address, 8883)
|
|
client.loop_start()
|
|
#print("Subscribing to topic", "/rider/+/location")
|
|
#client.subscribe("/rider/+/location")
|
|
|
|
time.sleep(4)
|
|
client.loop_stop()
|
|
|
|
|