简介:
最近有一个需求是前端APP需要通过mqtt发布消息,让硬件接收APP发送过来的消息,实现一个点播视频的功能。但是前端视乎不太会在APP上搭建mqtt。于是想到用FastAPI做一个消息中转站,具体原理如下:前端将需要发送的消息发给FastAPI,FastAPI在作为mqtt发布端将消息发布出去。
遇到的问题:
但是,在我写这个接口的时候遇到了一个问题:APP传过来的数据我是以参数的形式去接收的,结果就是这里出现了问题。这个消息看似可以发布出去,实际上,订阅端更本接收不到数据。
错误代码如下:
@router.post("/MqttWeb", summary="Mqtt请求中转站", tags=['xxx接口'])
async def MqttWeb(topic: str, message: str): client_id = f'python-mqtt-subscribe-{random.randint(0, 1000)}' # 可自定义,但要注意客户端id不能重复mqtt_broker = 'xxx.xxx.x..x.x'mqtt_port = 1883mqtt_keepalive = 600username = "xxxxx"password = "xxxxx"publisher = MqttPublisher(mqtt_broker, mqtt_port, mqtt_keepalive, client_id, topic, username, password)try:publisher.publish_message(.message)publisher.disconnect()return {'msg': True}except BaseException as e:print('error:', str(e))publisher.disconnect()return {'msg': False, 'error': str(e)}
正确示例代码:
class Item(BaseModel):message: strtopic: str@router.post("/MqttWeb", summary="Mqtt请求中转站", tags=['xxxxx接口'])
async def MqttWeb(item: Item): client_id = f'python-mqtt-subscribe-{random.randint(0, 1000)}' # 可自定义,但要注意客户端id不能重复mqtt_broker = 'xxxx'mqtt_port = 1883mqtt_keepalive = 600username = "xxx"password = "xxx"publisher = MqttPublisher(mqtt_broker, mqtt_port, mqtt_keepalive, client_id, item.topic, username, password)try:publisher.publish_message(item.message)publisher.disconnect()return {'msg': True}except BaseException as e:print('error:', str(e))publisher.disconnect()return {'msg': False, 'error': str(e)}
这里的参数必须要用官方的BaseModel来实现,具体原因我也不知道。。。