Added ASGI server for websocket using the sample chat application as starting point

This commit is contained in:
Dirk Jahnke 2022-04-02 19:30:58 +02:00
parent 13cc1c3f57
commit 5cf49b7d47
17 changed files with 209 additions and 14 deletions

0
booker/__init__.py Normal file
View File

3
booker/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
booker/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class BookerConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'booker'

View File

3
booker/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

48
booker/mqtt_collector.py Normal file
View File

@ -0,0 +1,48 @@
from channels.generic.websocket import AsyncWebsocketConsumer
import json
'''
class ScannerCollector(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
self.send(text_data=json.dumps({
'message': message
}))
'''
class ScannerCollector(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = 'scanner'
# join to group
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self):
# leave group
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def receive(self, text_data):
print('>>>', text_data)
msg = '{"message":"pong!"}' if text_data == '{"message":"ping"}' else text_data
print('<<<', msg)
await self.channel_layer.group_send(
self.group_name,
{
'type': 'distribute',
'text': msg
}
)
async def distribute(self, event):
valother = event['text']
await self.send(text_data=valother)

View File

@ -0,0 +1,24 @@
{% extends "base.html" %}
{% load static %}
{% block title %}Scanner Index{% endblock %}
{% block content %}
What chat room would you like to enter?<br>
<input id="room-name-input" type="text" size="100"><br>
<input id="room-name-submit" type="button" value="Enter">
<script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#room-name-submit').click();
}
};
document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/booker/' + roomName + '/';
};
</script>
{% endblock %}

View File

@ -0,0 +1,47 @@
{% extends "base.html" %}
{% load static %}
{% block title %}Scanner: {{ scanner_id }}{% endblock %}
{% block content %}
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ scanner_id|json_script:"room-name" }}
<script>
const roomName = JSON.parse(document.getElementById('room-name').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/scannerdata/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
{% endblock %}

3
booker/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

9
booker/urls.py Normal file
View File

@ -0,0 +1,9 @@
from django.urls import path
from . import views
app_name = 'booker'
urlpatterns = [
path('', views.index, name='index'),
path('<str:scanner_id>/', views.scanner, name='scanner')
]

10
booker/views.py Normal file
View File

@ -0,0 +1,10 @@
from django.shortcuts import render
def index(request):
return render(request, 'booker/index.html')
def scanner(request, scanner_id):
return render(request, 'booker/scanner.html', {
'scanner_id': scanner_id
})

View File

@ -1,16 +1,17 @@
"""
ASGI config for homelog project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import homelog.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'homelog.settings')
application = get_asgi_application()
django_application = get_asgi_application()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(URLRouter(homelog.routing.websocket_urlpatterns)),
})

12
homelog/routing.py Normal file
View File

@ -0,0 +1,12 @@
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path, re_path
from booker.mqtt_collector import ScannerCollector
from django.core.asgi import get_asgi_application
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'homelog.settings')
websocket_urlpatterns = [
re_path(r'ws/scannerdata/(?P<scanner_id>\w+)/$', ScannerCollector.as_asgi()),
]

View File

@ -32,8 +32,10 @@ ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'asset.apps.AssetConfig',
'container.apps.ContainerConfig',
'channels',
'asset',
'container',
'booker',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
@ -71,7 +73,13 @@ TEMPLATES = [
]
WSGI_APPLICATION = 'homelog.wsgi.application'
ASGI_APPLICATION = 'homelog.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
}
}
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

View File

@ -55,6 +55,9 @@
<li class="nav-item active">
<a class="nav-link" href="{% url 'container:container_type_list' %}">Container-Types <span class="visually-hidden">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{% url 'booker:index' %}">Booker <span class="visually-hidden">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'about' %}">About</a>
</li>

View File

@ -19,8 +19,6 @@ from django.views.generic import TemplateView
from homelog import views
from django.contrib.auth import views as auth_views
urlpatterns = [
]
urlpatterns = [
path('', TemplateView.as_view(template_name="homelog/home.html"), name='index'),
@ -28,6 +26,7 @@ urlpatterns = [
path('about/', TemplateView.as_view(template_name="homelog/about.html"), name='about'),
path('container/', include('container.urls')),
path('asset/', include('asset.urls')),
path('booker/', include('booker.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
]

19
homelog/websocket.py Normal file
View File

@ -0,0 +1,19 @@
# websocket.py
async def websocket_application(scope, receive, send):
while True:
event = await receive()
if event['type'] == 'websocket.connect':
await send({
'type': 'websocket.accept'
})
if event['type'] == 'websocket.disconnect':
break
if event['type'] == 'websocket.receive':
if event['text'] == 'ping':
await send({
'type': 'websocket.send',
'text': 'pong!'
})