-1

In this server.py, I am not understanding how to access "inputData" outside sendmsg(arr) function

I tried many ways but it is not getting.

from client I am sending userdetails and accessing in server. Through mqtt lens, I am sending data to server.py. I am getting data to server.py but I am not understanding how to call function and access data.

In normal we can call function ex: func() ,but her i have arguments in function. How to call this sendmsg() function and get inputData is getting problem. I have used gobal keyword but it is not getting data. After sending message from mqtt only, inputData should access outside.

the below code is html client

If anyone know please suggest me

client.py


<!DOCTYPE html>
<html>

<head>
    <!-- <meta http-equiv="refresh" content="30"> -->
    <title>WebSocket demo</title>
</head>

<body>

    <ul id="received_messages"></ul>

    <script>
        const user_credentials = {
            type: "credentials",
            name: "vinay",
            email: "vinay5678@gmail.com"
        }
        let userHashCode = ''
        const receivedMessages = document.getElementById("received_messages");

        var ws = new WebSocket("ws://127.0.0.1:5678/"),
            messages = document.createElement('ul');

        ws.onopen = function() {
            ws.send(JSON.stringify(user_credentials));
        };

        ws.onmessage = function(event) {
            let message = document.createElement('li');

            console.log(event.data)
            message.innerText = `${event.data}`;

            document.body.appendChild(message);
            
        };
    </script>
</body>

</html>

The below code is server.py

server.py

import asyncio
import datetime
import random
import websockets
import json
import bcrypt
import paho.mqtt.client as mqtt

websocketData = {}
async def time(websocket, path):

    usr_details = await websocket.recv()
    usr_details = json.loads(usr_details)
    usr_name = usr_details['name']

    print(usr_details)    

    usr_name = usr_details['name']
    now = datetime.datetime.utcnow().isoformat() + "Z"
    salt = bcrypt.gensalt(5)
    hashCode = bcrypt.hashpw(bytes(usr_name, 'utf-8'), salt=salt)

    websocketData[hashCode.decode('utf-8')] = websocket
    print(websocketData)

    data = {"name": usr_name, "date": now, "hashCodeOfUser": (hashCode).decode('UTF-8'), "msg": "User Created"}
    print(data)

    await websocket.send(json.dumps(data))


    ############################################################
    broker="broker.emqx.io"

    def on_message(mqttc, obj, msg):
        # print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        message = (msg.payload).decode("utf-8")
        global arr
        arr = message.split()
        # print(arr)
        # print(arr[0])
        sendmsg(arr)

    mqttc = mqtt.Client(client_id="")
    mqttc.on_message = on_message

    mqttc.connect(broker, 1883, 60)
    mqttc.subscribe("vinay/websockets/topic/1",qos=0)
    
    ###############################################################

    
    # function to receive the data
    def sendmsg(arr):
        print("mqtt msg", arr)
        # global inputData
        # global printData
        
        inputData = {
            "type": "dataSend",
            "name": usr_details['name'],
            "accessKey": hashCode.decode('utf-8'),
            "senderKey": arr[0],
            "msg": arr[1]
        }

        printData = {
            "name": usr_details['name'],
            "msg": arr[1]
        }
        # print(inputData)
        # print(printData)
       
    


    mqttc.loop_forever()



start_server = websockets.serve(time, "127.0.0.1", 5678 )
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

One such way is to define the global variables outside the function. Or the better way is to use global keyword. Use of "global" keyword in Python

import asyncio
import datetime
import random
import websockets
import json
import bcrypt
import paho.mqtt.client as mqtt

websocketData = {}
async def time(websocket, path):

    usr_details = await websocket.recv()
    usr_details = json.loads(usr_details)
    usr_name = usr_details['name']

    inputData = {}

    print(usr_details)    

    usr_name = usr_details['name']
    now = datetime.datetime.utcnow().isoformat() + "Z"
    salt = bcrypt.gensalt(5)
    hashCode = bcrypt.hashpw(bytes(usr_name, 'utf-8'), salt=salt)

    websocketData[hashCode.decode('utf-8')] = websocket
    print(websocketData)

    data = {"name": usr_name, "date": now, "hashCodeOfUser": (hashCode).decode('UTF-8'), "msg": "User Created"}
    print(data)

    await websocket.send(json.dumps(data))


    ############################################################
    broker="broker.emqx.io"

    def on_message(mqttc, obj, msg):
        # print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
        message = (msg.payload).decode("utf-8")
        global arr
        arr = message.split()
        # print(arr)
        # print(arr[0])
        sendmsg(arr)

    mqttc = mqtt.Client(client_id="")
    mqttc.on_message = on_message

    mqttc.connect(broker, 1883, 60)
    mqttc.subscribe("vinay/websockets/topic/1",qos=0)
    
    ###############################################################

    
    # function to receive the data
    def sendmsg(arr):
        print("mqtt msg", arr)
        # global inputData
        # global printData
        
        inputData = {
            "type": "dataSend",
            "name": usr_details['name'],
            "accessKey": hashCode.decode('utf-8'),
            "senderKey": arr[0],
            "msg": arr[1]
        }

        printData = {
            "name": usr_details['name'],
            "msg": arr[1]
        }
        # print(inputData)
        # print(printData)
       
    


    mqttc.loop_forever()



start_server = websockets.serve(time, "127.0.0.1", 5678 )
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Prithvi Raj
  • 1,611
  • 1
  • 14
  • 33