Commit 8f744426 authored by Peter-Bernd Otte's avatar Peter-Bernd Otte

Update mqttWebServer.py

parent 873a913b
......@@ -2,31 +2,39 @@
import json
import time
#from datetime import datetime
import paho.mqtt.client as paho
#import os
#import numbers
import os
import parse
from http.server import HTTPServer, BaseHTTPRequestHandler
import logging, argparse
logging.basicConfig(format="%(asctime)-15s %(levelname)-8s %(message)s")
logger = logging.getLogger("MQTT-HTTP-Server")
parser = argparse.ArgumentParser(description='MQTT <-> HTTP-Server.')
parser.add_argument("-v", "--verbosity", help="increase output verbosity", default=0, action="count")
parser.add_argument("-p", "--http-port", help="TCP port of HTTP server", default=8000)
parser.add_argument("-n", "--http-hostname", help="DNS name or IP address, where HTTP server will be available on. Possible: (empty string), 'localhost', DNS name or IP address", default="")
parser.add_argument("-b", "--mqtt-broker-host", help="MQTT broker hostname", default="localhost")
parser.add_argument("mqtt_client_name", help="MQTT client name. Needs to be unique in the MQTT namespace, eg enocean-http-server.", type=str)
args = parser.parse_args()
logger.setLevel(logging.WARNING-(args.verbosity*10 if args.verbosity <=2 else 20) )
broker="localhost"
HTTPport = 8000
HTTPhost = '' # possible: '', 'localhost', DNS-Name or IP address
mlast = {}
def on_connect(client, userdata, flags, rc):
if rc==0:
print("MQTT connected OK. Return code", rc)
logger.info("MQTT connected OK. Return code"+str(rc))
client.subscribe("#")
print("MQTT: Subscribed to all topics")
logger.info("MQTT: Subscribed to all topics")
else:
print("Bad connection. Return code=",rc)
logger.error("Bad connection. Return code="+str(rc))
def on_disconnect(client, userdata, rc):
if rc != 0:
print ("Unexpected MQTT disconnection. Will auto-reconnect")
logger.warning ("Unexpected MQTT disconnection. Will auto-reconnect")
def on_message(client, userdata, message):
global mlast
......@@ -44,15 +52,15 @@ def on_message(client, userdata, message):
mlast[message.topic] = j
client= paho.Client("actor")
client= paho.Client(args.mqtt_client_name)
client.on_message=on_message
client.on_connect = on_connect
client.on_disconnect = on_disconnect
print("connecting to broker ",broker)
client.connect(broker)
logger.debug("connecting to broker "+args.mqtt_broker_host)
client.connect(args.mqtt_broker_host)
client.loop_start() #start loop to process received messages in separate thread
print ("MQTT Loop started.")
logger.info ("MQTT Loop started.")
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
......@@ -66,23 +74,22 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
#print(erg)
if erg and erg['topic'] in mlast:
if 'value' in erg:
print("publish: ",erg['topic'],"value",erg['value'])
logger.info("publish: "+str(erg['topic'])+" value: "+str(erg['value']) )
client.publish(erg['topic']+"/set", erg['value'], qos=1, retain=False) # send command to Relais
self.wfile.write(str.encode('{"result":"sucess", "topic":"'+erg['topic']+'", "value":'+str(erg['value'])+'}'))
else:
self.wfile.write(str.encode("/*You accessed path: {}*/\n{}".format(erg['topic'],
json.dumps(mlast[erg['topic']]) )) )
else:
self.wfile.write(str.encode("\n{}".format(json.dumps(mlast) )) )
self.wfile.write(str.encode(json.dumps(mlast) ))
try:
httpd = HTTPServer((HTTPhost, HTTPport), SimpleHTTPRequestHandler)
print("Server started on port {} and host {}".format(HTTPport, HTTPhost))
httpd = HTTPServer((args.http_hostname, args.http_port), SimpleHTTPRequestHandler)
logger.info("Server started on port {} and host {}".format(args.http_port, args.http_hostname))
httpd.serve_forever()
except KeyboardInterrupt:
print ('^C received, shutting down the web server')
logger.info ('^C received, shutting down the web server')
httpd.server_close()
client.disconnect()
client.loop_stop()
\ No newline at end of file
client.loop_stop()
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment