如何使用 nodejs 和 socketio 在 react 中显示 raspberrypi 传感器数据

How to show raspberrypi sensor data in react using nodejs and socketio

我想显示来自 raspberry pi 的一些传感器数据(使用 python socketio)作为前端,我使用 nodejs 作为后端。数据当前显示在控制台(nodejs)中,但我似乎无法弄清楚它将如何显示在反应中。很抱歉这个基本问题,但我似乎找不到合理的方法来实现它。这是我的 raspberry pi、节点和反应的代码。

#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 代码

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);
    
  });

     });
});

以下是反应代码

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;

我应该怎么做才能让节点的数据在react中显示出来。我也没有收到任何反应错误。感谢您的帮助

我使用 websockets 解决了整个问题。制作了两个 nodejs websocket 服务器。一个通过端口 5000 连接到 raspberry pi,另一个通过端口 4001 连接到 react。下面给出了 raspberrypi python、nodejs 服务器和 react 客户端的代码。 rpi代码:

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代码:

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);

  });
 });
});

反应代码(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;