1

I want to send data from the firebase stream(pyrebase) via django channels websocket. Web scoket is working fine, But I can't imagine how I can use consumer.py file send message function in init_.py. Here my django channel web socket Consumer.py file.

import json
from random import randint
from asyncio import sleep
from channels.generic.websocket import AsyncWebsocketConsumer
from django.conf import settings

class WSConsumer(AsyncWebsocketConsumer):

    group_name = settings.STREAM_SOCKET_GROUP_NAME

    async def connect(self):
        # Joining group
        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )
        await self.accept()
            
    async def disconnect(self, close_code):
        # Leave group
        await self.channel_layer.group_discard(
            self.group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        print(text_data)
        # Send data to group
        await self.channel_layer.group_send(
            self.group_name,
            {
                'type': 'system_load',
                'data': text_data
            }
        )

    async def system_load(self, event):
        # Receive data from group
        print('sending message to client')
        await self.send(text_data=json.dumps(event['data']))

This file works fine.

This is my inti.py file. In this file, I want to send data to the WebSocket in this stream_handler function.

import pyrebase
from configFiles.config import config


firebase = pyrebase.initialize_app(config)
authe = firebase.auth()
database = firebase.database()

safe_temperature = 20
safe_humidity = 40

def stream_handler(message):
    if "Humidity" in message["path"]:
        if message["data"] > safe_humidity:
            database.child("Controller").child("Light").set(1)
        else:
            database.child("Controller").child("Light").set(0)

    if "Temperature" in message["path"]:
        if message["data"] > safe_humidity:
            database.child("Controller").child("Fan").set(1)
        else:
            database.child("Controller").child("Fan").set(0)
    # Here place I want to send data which is message["data"] to the WebSocket

mystream = database.child("Sensor").stream(stream_handler)

Thank you!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

0 Answers0