homelog/booker/views.py

73 lines
2.3 KiB
Python
Raw Normal View History

from datetime import datetime
from channels.layers import get_channel_layer
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
2022-05-24 15:53:31 +00:00
from django.views.generic import ListView, TemplateView
from gmqtt import Client
from rest_framework.utils import json
from homelog import settings
from homelog.system_user import get_system_user
from .models import Scanner
from django.http import HttpResponse
import logging
LOGGER = logging.getLogger(__name__)
class IndexView(ListView):
model = Scanner
template_name = 'booker/index.html'
def scanner_view(request, scanner_id):
return render(request, 'booker/scanner.html', {
'scanner_id': scanner_id
})
2022-05-24 15:53:31 +00:00
2022-05-24 15:53:31 +00:00
class SmartphoneScannerView(TemplateView):
template_name = 'booker/smartphone_scanner.html'
class ChromeScannerView(TemplateView):
template_name = 'booker/chrome_scanner.html'
@csrf_exempt
def web_scanner_view(request, scanner_id):
def get_or_create_scanner(named_id):
scanner, created = Scanner.objects.get_or_create(named_id=named_id, defaults={
# 'lwt_topic': topic,
'description': 'WebAPI scanner',
'last_online_ts': datetime.now(),
'created_by': get_system_user(),
'changed_by': get_system_user()
})
if created:
LOGGER.debug(f"Created new scanner entry for {named_id}")
else:
LOGGER.debug(f"Updated scanner entry for {named_id}")
return scanner
print(f"Got {request.POST['scan']} from scanner {scanner_id}")
get_or_create_scanner(scanner_id)
topic = f"barcodescanner/{scanner_id}/scan"
'''
client = Client('homelog-webscanner')
client.set_auth_credentials(username=settings.MQTT_USER, password=settings.MQTT_PASSWORD)
client.connect(settings.MQTT_HOST, 1883, keepalive=60, version=settings.MQTT_VERSION)
client.publish(topic, request.POST['scan'])
client.disconnect()
# MqttConsumer().mqtt_publish({'topic': topic, 'payload': request.POST['scan'], 'retain': False})
'''
channel_layer = get_channel_layer()
channel_layer.group_send(
'mqtt', # scanner_id,
{"type": "distribute", "text": json.dumps({'message': request.POST['scan'], 'topic': topic})}
)
'''
'''
return HttpResponse(f"<html><body><p>OK, got {request.POST['scan']} from {scanner_id}</p></body></html>")