44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
#
|
|
#from django.utils.translation import gettext_lazy as _
|
|
#from channels.layers import get_channel_layer
|
|
#from django.conf import settings
|
|
#import asyncio
|
|
#from asgiref.sync import sync_to_async
|
|
import json, logging
|
|
from channels.generic.websocket import AsyncWebsocketConsumer
|
|
#from modules import utils
|
|
|
|
#from .models import Relay
|
|
from .process import redisDB
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class RelayConsumer(AsyncWebsocketConsumer):
|
|
|
|
async def connect(self):
|
|
self.uuid = self.scope["url_route"]["kwargs"].get("uuid")
|
|
self.this_group = f"relay_{self.uuid}"
|
|
await self.channel_layer.group_add(self.this_group, self.channel_name)
|
|
await self.accept()
|
|
#logger.info(f"==== relay {self.uuid} is connected to {self.this_group} group")
|
|
|
|
|
|
async def disconnect(self, close_code):
|
|
await self.channel_layer.group_discard(self.this_group, self.channel_name)
|
|
logger.info( f"Disconnect from {self.this_group}")
|
|
|
|
|
|
# routage channels => type: relay.message
|
|
async def relay_message(self, event):
|
|
await self.send(text_data=json.dumps(event["text"]))
|
|
|
|
|
|
## Receive message from WebSocket
|
|
async def receive(self, text_data):
|
|
data = json.loads(text_data)
|
|
msg_type = data.get("type")
|
|
if msg_type == "relay":
|
|
redisDB.publish(f"{msg_type}_{self.uuid}", json.dumps(data))
|
|
|