Added ASGI server for websocket using the sample chat application as starting point
This commit is contained in:
parent
13cc1c3f57
commit
5cf49b7d47
|
@ -0,0 +1,3 @@
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
# Register your models here.
|
|
@ -0,0 +1,6 @@
|
||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class BookerConfig(AppConfig):
|
||||||
|
default_auto_field = 'django.db.models.BigAutoField'
|
||||||
|
name = 'booker'
|
|
@ -0,0 +1,3 @@
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
# Create your models here.
|
|
@ -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)
|
||||||
|
|
|
@ -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 %}
|
|
@ -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 %}
|
|
@ -0,0 +1,3 @@
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
# Create your tests here.
|
|
@ -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')
|
||||||
|
]
|
|
@ -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
|
||||||
|
})
|
|
@ -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
|
import os
|
||||||
|
|
||||||
|
from channels.auth import AuthMiddlewareStack
|
||||||
|
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||||
from django.core.asgi import get_asgi_application
|
from django.core.asgi import get_asgi_application
|
||||||
|
|
||||||
|
import homelog.routing
|
||||||
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'homelog.settings')
|
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)),
|
||||||
|
})
|
||||||
|
|
|
@ -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()),
|
||||||
|
]
|
|
@ -32,8 +32,10 @@ ALLOWED_HOSTS = []
|
||||||
# Application definition
|
# Application definition
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
'asset.apps.AssetConfig',
|
'channels',
|
||||||
'container.apps.ContainerConfig',
|
'asset',
|
||||||
|
'container',
|
||||||
|
'booker',
|
||||||
'django.contrib.admin',
|
'django.contrib.admin',
|
||||||
'django.contrib.auth',
|
'django.contrib.auth',
|
||||||
'django.contrib.contenttypes',
|
'django.contrib.contenttypes',
|
||||||
|
@ -71,7 +73,13 @@ TEMPLATES = [
|
||||||
]
|
]
|
||||||
|
|
||||||
WSGI_APPLICATION = 'homelog.wsgi.application'
|
WSGI_APPLICATION = 'homelog.wsgi.application'
|
||||||
|
ASGI_APPLICATION = 'homelog.asgi.application'
|
||||||
|
|
||||||
|
CHANNEL_LAYERS = {
|
||||||
|
'default': {
|
||||||
|
'BACKEND': 'channels.layers.InMemoryChannelLayer',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
|
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
|
||||||
|
|
|
@ -55,6 +55,9 @@
|
||||||
<li class="nav-item active">
|
<li class="nav-item active">
|
||||||
<a class="nav-link" href="{% url 'container:container_type_list' %}">Container-Types <span class="visually-hidden">(current)</span></a>
|
<a class="nav-link" href="{% url 'container:container_type_list' %}">Container-Types <span class="visually-hidden">(current)</span></a>
|
||||||
</li>
|
</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">
|
<li class="nav-item">
|
||||||
<a class="nav-link" href="{% url 'about' %}">About</a>
|
<a class="nav-link" href="{% url 'about' %}">About</a>
|
||||||
</li>
|
</li>
|
||||||
|
|
|
@ -19,8 +19,6 @@ from django.views.generic import TemplateView
|
||||||
from homelog import views
|
from homelog import views
|
||||||
from django.contrib.auth import views as auth_views
|
from django.contrib.auth import views as auth_views
|
||||||
|
|
||||||
urlpatterns = [
|
|
||||||
]
|
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('', TemplateView.as_view(template_name="homelog/home.html"), name='index'),
|
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('about/', TemplateView.as_view(template_name="homelog/about.html"), name='about'),
|
||||||
path('container/', include('container.urls')),
|
path('container/', include('container.urls')),
|
||||||
path('asset/', include('asset.urls')),
|
path('asset/', include('asset.urls')),
|
||||||
|
path('booker/', include('booker.urls')),
|
||||||
path('admin/', admin.site.urls),
|
path('admin/', admin.site.urls),
|
||||||
path('accounts/', include('django.contrib.auth.urls')),
|
path('accounts/', include('django.contrib.auth.urls')),
|
||||||
]
|
]
|
||||||
|
|
|
@ -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!'
|
||||||
|
})
|
Loading…
Reference in New Issue