from datetime import datetime from channels.layers import get_channel_layer from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt 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 }) 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"
OK, got {request.POST['scan']} from {scanner_id}
")