python-socketio websocket传感器仪表板无法实时更新到新数据

时间:2020-03-26 07:49:40

标签: javascript python python-3.x websocket socket.io

我正在RPI上创建一个Web仪表板,以显示实时传感器数据,该数据实时记录到文本文件(log.txt)中。在main.py中,我从log.txt中实时获取此数据,并尝试通过python-socketio显示它。但是,当我在页面上显示数据时,似乎每次我想从log.txt显示新数据时,都需要重新运行客户端WebSocket代码的js <script>。但是,不需要重新加载页面即可完成此操作,如果我仅触发另一个启用了WebSocket的按钮来发送console.log的服务器端,它将显示新数据。

想知道是否有一种方法可以自动显示这些新的实时数据,而无需用户干预。

谢谢!

代码(并非此处的所有内容对于传感器都是必需的,某些代码功能仅用于测试):

main.py

from aiohttp import web
import socketio


path = '/home/pi/pysocket/log.txt'

data = open(path,'r')
# data.read()


sio = socketio.AsyncServer(cors_allowed_origins='http://192.168.0.194:8080')

app = web.Application()

sio.attach(app)



async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')


@sio.on('message')
async def print_message(sid, message):

    print("Socket ID: " , sid)
    print(message)

    await sio.emit('message', data.read())


# We bind our aiohttp endpoint to our app
# router
app.router.add_get('/', index)

# We kick off our server
if __name__ == '__main__':
    web.run_app(app)

index.html

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button onClick="sendMsg()">Hit Me</button>
    <p id="demo"></p>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
      const socket = io("http://localhost:8080");

      function sendMsg() {
             socket.emit("message", "working");
      }



      var div = document.getElementById("demo");
      socket.on("message", function(data){
          div.innerHTML += "<p>"+data+"</p>";
      });


    </script>
  </body>
</html>

0 个答案:

没有答案