Issue
I want to display some sensors data from raspberry pi (using python socketio) in react as frontend and I am using nodejs as backend. Data is currently displaying in the console (nodejs) but I can't seem to figure out how it will displayed in react. Sorry for this basic question but I can't seem to find a reasonable way to implement this. Here are my codes for raspberry pi, node and react.
#raspberrypi code
import asyncio
import socketio
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('connection established')
@sio.event
async def message(data):
print('message received with ', data)
await sio.emit('fromAPI', {'msgFromPy': 'my response'})
@sio.event
async def disconnect():
print('disconnected from server')
async def main():
await sio.connect('http://localhost:5000')
await sio.wait()
if __name__ == '__main__':
asyncio.run(main())
Nodejs code
const io = require("socket.io")(5000);
io.on("connection", socket => {
// either with send()
console.log('Connected');
socket.send("Hello!");
// handle the event sent with socket.send()
socket.on("fromAPI", (data) => {
console.log(data);
socket.emit("fromAPI", data);
});
});
});
Following is react code
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:5000";
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("fromAPI", data => {
setResponse(data);
});
}, []);
return (
<p>
It's {response.msgFromPy}
</p>
);
}
export default App;
What should I do so that data from the node can be displayed in react. I am not getting any error in react as well. Thanks for helping
Solution
I solve this whole thing using websockets. Made two nodejs websocket servers. One is connected with raspberry pi via port 5000 and other is connected to react via port 4001. Code for raspberrypi python, nodejs server and react client is given below. rpi code:
import asyncio
import socketio
import random
import time
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('connection established')
@sio.event
async def message(data):
print('message received with ', data)
while True:
await sio.emit('fromAPI', {"id": 1, "Temprature" : random.randint(0,9), "Humidity": random.randint(0,9)})
await sio.sleep(3)
@sio.on('my_message')
async def on_message(data):
#while True:
print('I received a message!', data)
await sio.sleep(1)
@sio.event
async def disconnect():
print('disconnected from server')
async def main():
await sio.connect('http://localhost:5000')
await sio.wait()
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(message(data))
asyncio.ensure_future(on_message(data))
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("closing thread")
loop.close()
if __name__ == '__main__':
asyncio.run(main())
nodejs code:
const io = require("socket.io")(5000);
const io1 = require("socket.io")(4001);
let interval;
let dataFromReact;
io.on("connection", (socket) => {
io1.on("connection", (socket1) => {
socket1.on("rcvdFromReact", data1 => {
dataFromReact = data1;
socket.emit("my_message", data1);
});
});
});
io.on("connection", socket => {
socket.send("hello");
io1.on("connection", socket1 => {
// either with send()
console.log('Connected');
socket.on("fromAPI", (data) => {
console.log(data);
socket1.emit("fromNodejs", data);
});
});
});
react code (App.js):
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:4001";
function App() {
const [response, setResponse] = useState("");
const [title, setTitle] = useState('')
const handleSubmit = (e) => {
e.preventDefault();
var temps = e.target.temp.value;
var humids = e.target.humid.value;
console.log(temps + humids);
setTitle(temps);
const socket = socketIOClient(ENDPOINT);
socket.emit("rcvdFromReact", temps);
console.log("Temprature is " + temps);
}
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("fromNodejs", data => {
setResponse(data);
console.log(data);
//console.log("Temprature is " + temps);
});
}, []);
return (
<div>
<p>
It's {response.Temprature} and {response.Humidity}
</p>
<form onSubmit={handleSubmit}>
<input placeholder = "Temprature" name = "temp" />
<input placeholder = "Humidity" name = "humid" />
<button>Click Me</button>
</form>
</div>
);
}
export default App;
Answered By - Ali Muqtadir Answer Checked By - Willingham (WPSolving Volunteer)