feat: TODO mqtt pub/sub

This commit is contained in:
xianfx 2024-03-12 23:54:13 +08:00
parent c6bfaad911
commit b540314a7b
3 changed files with 16 additions and 4 deletions

View File

@ -1,3 +1,5 @@
from django.test import TestCase import paho.mqtt.subscribe as subscribe
# Create your tests here. topic = f'solarmosquitolamp/devices/861959064988699/state'
msg = subscribe.simple(topic, hostname='8.217.112.255', port=1883)
print("%s %s" % (msg.topic, msg.payload))

View File

@ -18,5 +18,6 @@ urlpatterns = [
path('weather/', WeatherLogListAPIView.as_view(), name='weather-log'), path('weather/', WeatherLogListAPIView.as_view(), name='weather-log'),
path('deviceinfo/', DeviceInfoAPIView.as_view(), name='device-info'), path('deviceinfo/', DeviceInfoAPIView.as_view(), name='device-info'),
path('weatherstationinfo/', WeatherStationInfoAPIView.as_view(), name='weather-station-info'), path('weatherstationinfo/', WeatherStationInfoAPIView.as_view(), name='weather-station-info'),
path('device/<device_id>/remote/', DeviceRemoteViewSet.as_view({'post': 'remote'}), name='device-remote'), path('device/<device_id>/mqtt/pub/', DeviceRemoteViewSet.as_view({'post': 'pub'}), name='device-mqtt-pub'),
path('device/<device_id>/mqtt/sub/', DeviceRemoteViewSet.as_view({'get': 'sub'}), name='device-mqtt-sub'),
] ]

View File

@ -2,6 +2,7 @@ import re
import pytz import pytz
import json import json
import paho.mqtt.publish as publish import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
# import paho.mqtt.subscribe as subscribe # import paho.mqtt.subscribe as subscribe
from rest_framework import decorators, mixins from rest_framework import decorators, mixins
@ -225,7 +226,7 @@ class DeviceRemoteViewSet(mixins.ListModelMixin,
filter_backends = [SearchFilter, OrderingFilter] filter_backends = [SearchFilter, OrderingFilter]
@decorators.action(methods='POST', detail=True) @decorators.action(methods='POST', detail=True)
def remote(self, request, device_id=None): def pub(self, request, device_id=None):
command = request.data.get('command') command = request.data.get('command')
speed = request.data.get('speed') speed = request.data.get('speed')
@ -244,3 +245,11 @@ class DeviceRemoteViewSet(mixins.ListModelMixin,
publish.single(topic, payload=json.dumps(message), hostname='8.217.112.255', port=1883) publish.single(topic, payload=json.dumps(message), hostname='8.217.112.255', port=1883)
return Response({'success': True}) return Response({'success': True})
@decorators.action(methods='POST', detail=True)
def sub(self, request, device_id=None):
topic = f'solarmosquitolamp/devices/{device_id}/state'
msg = subscribe.simple(topic, hostname='8.217.112.255', port=1883)
print("%s %s" % (msg.topic, msg.payload))
return Response({'code': 0, 'data': None, 'msg': 'success'})