D901 #2

Merged
bmartin5692 merged 34 commits from D901 into dev 2019-02-22 05:37:44 +01:00
3 changed files with 26 additions and 35 deletions
Showing only changes of commit 99508f25dc - Show all commits

View file

@ -9,11 +9,11 @@ import time
args = sys.argv args = sys.argv
if len(args) > 0: if len(args) > 0:
if '--debug' in args: if '--debug' in args:
logging.basicConfig(level=logging.DEBUG, logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s') format="[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s")
else: else:
logging.basicConfig(level=logging.INFO, logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s') format="[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s")
#conf_address = (socket.gethostbyname(socket.gethostname()), 443) #conf_address = (socket.gethostbyname(socket.gethostname()), 443)
conf_address = ("0.0.0.0", 443) conf_address = ("0.0.0.0", 443)

View file

@ -49,9 +49,7 @@ class ConfServer():
loop.run_forever() loop.run_forever()
async def start_server(self): async def start_server(self):
#formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
#logging.basicConfig(level=logging.INFO, format=formatter)
app = web.Application() app = web.Application()
app.add_routes([ app.add_routes([
@ -68,7 +66,7 @@ class ConfServer():
]) ])
runner = web.AppRunner(app, access_log=None) runner = web.AppRunner(app, access_log=None) #access_log=None so the output isn't nuts
await runner.setup() await runner.setup()
if self.usessl: if self.usessl:
@ -105,11 +103,7 @@ class ConfServer():
return web.json_response(body) return web.json_response(body)
async def handle_getAuthCode(self, request):
async def handle_getAuthCode(self, request):
#Could implement basic auth if you wanted, or just accept anything
countrycode = request.match_info.get('country', "us") countrycode = request.match_info.get('country', "us")
body = { body = {
"code": "0000", "code": "0000",
@ -176,8 +170,7 @@ class ConfServer():
body = {"code":0,"data":[{"classid":"dl8fht","product":{"_id":"5acb0fa87c295c0001876ecf","name":"DEEBOT 600 Series","icon":"5acc32067c295c0001876eea","UILogicId":"dl8fht","ota":False,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea"}},{"classid":"02uwxm","product":{"_id":"5ae1481e7ccd1a0001e1f69e","name":"DEEBOT OZMO Slim10 Series","icon":"5b1dddc48bc45700014035a1","UILogicId":"02uwxm","ota":False,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1"}},{"classid":"y79a7u","product":{"_id":"5b04c0227ccd1a0001e1f6a8","name":"DEEBOT OZMO 900","icon":"5b04c0217ccd1a0001e1f6a7","UILogicId":"y79a7u","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7"}},{"classid":"jr3pqa","product":{"_id":"5b43077b8bc457000140363e","name":"DEEBOT 711","icon":"5b5ac4cc8d5a56000111e769","UILogicId":"jr3pqa","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769"}},{"classid":"uv242z","product":{"_id":"5b5149b4ac0b87000148c128","name":"DEEBOT 710","icon":"5b5ac4e45f21100001882bb9","UILogicId":"uv242z","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9"}},{"classid":"ls1ok3","product":{"_id":"5b6561060506b100015c8868","name":"DEEBOT 900 Series","icon":"5ba4a2cb6c2f120001c32839","UILogicId":"ls1ok3","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839"}}]} body = {"code":0,"data":[{"classid":"dl8fht","product":{"_id":"5acb0fa87c295c0001876ecf","name":"DEEBOT 600 Series","icon":"5acc32067c295c0001876eea","UILogicId":"dl8fht","ota":False,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5acc32067c295c0001876eea"}},{"classid":"02uwxm","product":{"_id":"5ae1481e7ccd1a0001e1f69e","name":"DEEBOT OZMO Slim10 Series","icon":"5b1dddc48bc45700014035a1","UILogicId":"02uwxm","ota":False,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b1dddc48bc45700014035a1"}},{"classid":"y79a7u","product":{"_id":"5b04c0227ccd1a0001e1f6a8","name":"DEEBOT OZMO 900","icon":"5b04c0217ccd1a0001e1f6a7","UILogicId":"y79a7u","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b04c0217ccd1a0001e1f6a7"}},{"classid":"jr3pqa","product":{"_id":"5b43077b8bc457000140363e","name":"DEEBOT 711","icon":"5b5ac4cc8d5a56000111e769","UILogicId":"jr3pqa","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4cc8d5a56000111e769"}},{"classid":"uv242z","product":{"_id":"5b5149b4ac0b87000148c128","name":"DEEBOT 710","icon":"5b5ac4e45f21100001882bb9","UILogicId":"uv242z","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5b5ac4e45f21100001882bb9"}},{"classid":"ls1ok3","product":{"_id":"5b6561060506b100015c8868","name":"DEEBOT 900 Series","icon":"5ba4a2cb6c2f120001c32839","UILogicId":"ls1ok3","ota":True,"iconUrl":"https://portal-ww.ecouser.net/api/pim/file/get/5ba4a2cb6c2f120001c32839"}}]}
return web.json_response(body) return web.json_response(body)
async def handle_usersapi(self, request): async def handle_usersapi(self, request):
#Could implement basic auth if you wanted, or just accept anything
json_body = json.loads(await request.text()) json_body = json.loads(await request.text())
todo = json_body['todo'] todo = json_body['todo']
if todo == 'FindBest': if todo == 'FindBest':

View file

@ -3,9 +3,8 @@
import logging import logging
import asyncio import asyncio
import os import os
from hbmqtt.broker import Broker
from hbmqtt.client import MQTTClient
import hbmqtt import hbmqtt
from hbmqtt.broker import Broker
import pkg_resources import pkg_resources
import contextvars import contextvars
import time import time
@ -26,9 +25,7 @@ class BumperMQTTPlugin:
self.bots = self.context.config['bots'] self.bots = self.context.config['bots']
except KeyError: except KeyError:
self.context.logger.warning("'bots' section not found in context configuration") self.context.logger.warning("'bots' section not found in context configuration")
logging.debug('Bumper Plugin Initialized')
async def on_broker_client_connected(self, client_id): async def on_broker_client_connected(self, client_id):
logging.debug('Bumper Connection: %s connected' % client_id) logging.debug('Bumper Connection: %s connected' % client_id)
@ -55,7 +52,16 @@ class BumperMQTTPlugin:
async def on_broker_client_disconnected(self, client_id): async def on_broker_client_disconnected(self, client_id):
logging.debug('Bumper Connection: %s disconnected' % client_id) logging.debug('Bumper Connection: %s disconnected' % client_id)
#To do handle removing bot connected_bots = self.bots['connected_bots'].get()
didsplit = str(client_id).split("@")
#If the did is in the list, remove it
for bot in connected_bots:
if didsplit[0] == bot['did']:
logging.debug("Removing bot from list: {}".format(bot))
connected_bots.remove(bot)
self.bots['connected_bots'].set(connected_bots)
logging.debug('Connected Bots: %s' %self.bots['connected_bots'].get())
class MQTTHelperBot(ClientMQTT): class MQTTHelperBot(ClientMQTT):
@ -83,8 +89,6 @@ class MQTTHelperBot(ClientMQTT):
pass pass
def run_helperbot(self, loop): def run_helperbot(self, loop):
#formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
#logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
loop.run_until_complete(self.start_helper_bot()) loop.run_until_complete(self.start_helper_bot())
@ -121,15 +125,14 @@ class MQTTHelperBot(ClientMQTT):
def get_msg(self, client, userdata, message): def get_msg(self, client, userdata, message):
logging.debug("HelperBot MQTT Received Message on Topic: {} - Message: {}".format(message.topic, str(message.payload.decode("utf-8")))) #logging.debug("HelperBot MQTT Received Message on Topic: {} - Message: {}".format(message.topic, str(message.payload.decode("utf-8"))))
logging.debug(str(message.payload.decode("utf-8")))
cresp = self.command_responses.get() cresp = self.command_responses.get()
#Cleanup "expired messages" > 60 seconds from time #Cleanup "expired messages" > 60 seconds from time
for msg in cresp: for msg in cresp:
expire_time = (datetime.fromtimestamp(msg['time']) + timedelta(seconds=10)).timestamp() expire_time = (datetime.fromtimestamp(msg['time']) + timedelta(seconds=10)).timestamp()
if time.time() > expire_time: if time.time() > expire_time:
logging.debug("Pruning Message Time: {}, MsgTime: {}, MsgTime+60: {}".format(time.time(), msg['time'], expire_time)) #logging.debug("Pruning Message Time: {}, MsgTime: {}, MsgTime+60: {}".format(time.time(), msg['time'], expire_time))
cresp.remove(msg) cresp.remove(msg)
cresp.append({"time": time.time() ,"topic": message.topic,"payload":str(message.payload.decode("utf-8"))}) cresp.append({"time": time.time() ,"topic": message.topic,"payload":str(message.payload.decode("utf-8"))})
@ -145,12 +148,11 @@ class MQTTHelperBot(ClientMQTT):
for msg in responses: for msg in responses:
topic = str(msg['topic']).split("/") topic = str(msg['topic']).split("/")
if (topic[6] == "helper1" and topic[10] == requestid): if (topic[6] == "helper1" and topic[10] == requestid):
logging.debug('Vac Responses MQTT: Topic: %s Payload: %s' % (msg['topic'], msg['payload'])) logging.debug('VacBot MQTT Response: Topic: %s Payload: %s' % (msg['topic'], msg['payload']))
if topic[11] == "j": if topic[11] == "j":
resppayload = json.loads(msg['payload']) resppayload = json.loads(msg['payload'])
else: else:
resppayload = str(msg['payload']) resppayload = str(msg['payload'])
logging.debug("Resp Payload: %s" % resppayload)
resp = { resp = {
"id": requestid, "id": requestid,
"ret": "ok", "ret": "ok",
@ -169,20 +171,17 @@ class MQTTHelperBot(ClientMQTT):
self.publish(ttopic, str(cmdjson["payload"])) self.publish(ttopic, str(cmdjson["payload"]))
resp = await self.wait_for_resp(requestid) resp = await self.wait_for_resp(requestid)
logging.debug(resp)
return resp return resp
class MQTTServer(): class MQTTServer():
exit_flag = False
default_config = {} default_config = {}
bumper_clients = [] bumper_clients = []
async def broker_coro(self): async def broker_coro(self):
broker = hbmqtt.broker.Broker(config=self.default_config) broker = hbmqtt.broker.Broker(config=self.default_config)
logging.debug(broker.plugins_manager.plugins)
await broker.start() await broker.start()
logging.debug("Removing Plugin: broker_sys") logging.debug("Removing Plugin: broker_sys")
@ -203,6 +202,7 @@ class MQTTServer():
logging.debug('Connected bots: %s' % self.bumper_clients.get()) logging.debug('Connected bots: %s' % self.bumper_clients.get())
def __init__(self, address, run_async=False, bumper_clients=contextvars.ContextVar): def __init__(self, address, run_async=False, bumper_clients=contextvars.ContextVar):
#The below adds a plugin to the hbmqtt.broker.plugins without having to futz with setup.py #The below adds a plugin to the hbmqtt.broker.plugins without having to futz with setup.py
distribution = pkg_resources.Distribution("hbmqtt.broker.plugins") distribution = pkg_resources.Distribution("hbmqtt.broker.plugins")
bumper_plugin = pkg_resources.EntryPoint.parse('bumper = bumper.mqttserver:BumperMQTTPlugin', dist=distribution) bumper_plugin = pkg_resources.EntryPoint.parse('bumper = bumper.mqttserver:BumperMQTTPlugin', dist=distribution)
@ -257,8 +257,6 @@ class MQTTServer():
def run_server(self, loop): def run_server(self, loop):
#formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
#logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
loop.run_until_complete(self.broker_coro()) loop.run_until_complete(self.broker_coro())
#loop.run_until_complete(self.active_bot_listing()) #loop.run_until_complete(self.active_bot_listing())