2015-07-07 20:48:53 +00:00
|
|
|
import asyncio
|
2024-12-19 19:34:09 +00:00
|
|
|
import logging
|
2015-08-29 19:25:59 +00:00
|
|
|
import os
|
2025-07-04 20:35:46 +00:00
|
|
|
from pathlib import Path
|
2024-12-19 19:34:09 +00:00
|
|
|
|
2021-03-27 12:59:48 +00:00
|
|
|
from amqtt.broker import Broker
|
2015-07-07 20:48:53 +00:00
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
"""
|
|
|
|
This sample shows how to run a broker without stacktraces on keyboard interrupt
|
|
|
|
"""
|
|
|
|
|
2015-07-07 20:48:53 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-08-06 19:08:22 +00:00
|
|
|
config = {
|
2021-03-14 21:16:51 +00:00
|
|
|
"listeners": {
|
|
|
|
"default": {
|
|
|
|
"type": "tcp",
|
|
|
|
"bind": "0.0.0.0:1883",
|
2015-08-06 19:08:22 +00:00
|
|
|
},
|
2021-03-14 21:16:51 +00:00
|
|
|
"ws-mqtt": {
|
|
|
|
"bind": "127.0.0.1:8080",
|
|
|
|
"type": "ws",
|
|
|
|
"max_connections": 10,
|
2015-08-06 19:08:22 +00:00
|
|
|
},
|
2015-08-08 11:57:48 +00:00
|
|
|
},
|
2025-07-04 20:35:46 +00:00
|
|
|
"plugins": {
|
|
|
|
'amqtt.plugins.authentication.AnonymousAuthPlugin': { 'allow_anonymous': True},
|
|
|
|
'amqtt.plugins.authentication.FileAuthPlugin': {
|
|
|
|
'password_file': Path(__file__).parent / 'passwd',
|
|
|
|
},
|
|
|
|
'amqtt.plugins.sys.broker.BrokerSysPlugin': { "sys_interval": 10},
|
|
|
|
}
|
2015-08-06 19:08:22 +00:00
|
|
|
}
|
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
async def main_loop():
|
|
|
|
broker = Broker(config)
|
|
|
|
try:
|
|
|
|
await broker.start()
|
|
|
|
while True:
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
await broker.shutdown()
|
2017-08-06 22:06:57 +00:00
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
async def main():
|
|
|
|
t = asyncio.create_task(main_loop())
|
|
|
|
try:
|
|
|
|
await t
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
2015-07-07 20:48:53 +00:00
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
def __main__():
|
2015-07-07 20:48:53 +00:00
|
|
|
|
2015-09-03 20:20:31 +00:00
|
|
|
formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
|
2015-10-15 19:57:21 +00:00
|
|
|
logging.basicConfig(level=logging.INFO, format=formatter)
|
2025-05-28 11:45:12 +00:00
|
|
|
|
2025-06-17 21:03:40 +00:00
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
|
|
|
|
task = loop.create_task(main())
|
|
|
|
|
|
|
|
try:
|
|
|
|
loop.run_until_complete(task)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
logger.info("KeyboardInterrupt received. Stopping server...")
|
|
|
|
task.cancel()
|
|
|
|
loop.run_until_complete(task) # Ensure task finishes cleanup
|
|
|
|
finally:
|
|
|
|
logger.info("Server stopped.")
|
|
|
|
loop.close()
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
__main__()
|