增加了mqtt接口用于远程控制灭蚊灯

This commit is contained in:
Jay Huang 2023-11-27 17:48:29 +08:00
parent 65c33bbec5
commit 967b2727f2
4 changed files with 28 additions and 4 deletions

View File

@ -245,6 +245,7 @@ class DeviceInfoSerializer(serializers.ModelSerializer):
fields = [ fields = [
'device_id', 'device_id',
'device_name', 'device_name',
'chip_type',
'status', 'status',
'count', 'count',
'signal', 'signal',

View File

@ -6,6 +6,7 @@ from .views import (
WeatherLogListAPIView, WeatherLogListAPIView,
DeviceInfoAPIView, DeviceInfoAPIView,
WeatherStationInfoAPIView, WeatherStationInfoAPIView,
remote_control,
) )
@ -17,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('devicemqtt/remotecontrol/<str:device_id>/', remote_control, name='remote_control'),
] ]

View File

@ -1,5 +1,8 @@
import re import re
import pytz import pytz
import json
import paho.mqtt.publish as publish
from rest_framework.decorators import api_view
from rest_framework.generics import ( from rest_framework.generics import (
ListAPIView, ListAPIView,
RetrieveAPIView, RetrieveAPIView,
@ -208,3 +211,21 @@ class DeviceInfoAPIView(ListAPIView, RoleMixin):
queryset_list = queryset_list.filter(device_id__in=device_ids) queryset_list = queryset_list.filter(device_id__in=device_ids)
return queryset_list return queryset_list
@api_view(['POST'])
def remote_control(request, device_id):
command = request.data.get('command')
if command == 'ledOn':
message = {'RemoteControl': {'LED': 'ON'}}
elif command == 'ledOff':
message = {'RemoteControl': {'LED': 'OFF'}}
elif command == 'countClear':
message = {'count': 0}
else:
return Response({'error': 'Invalid command'}, status=400)
topic = f'solarmosquitolamp/devices/{device_id}/control'
publish.single(topic, payload=json.dumps(message), hostname='8.217.112.255', port=1883)
return Response({'success': True})

View File

@ -168,9 +168,9 @@ REST_FRAMEWORK = {
'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.BrowsableAPIRenderer',
), ),
# 'DEFAULT_PARSER_CLASSES': ( 'DEFAULT_PARSER_CLASSES': (
# 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.JSONParser',
# ), ),
'DEFAULT_AUTHENTICATION_CLASSES': ( 'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.SessionAuthentication',