• 树莓派4B_温湿度_传感器_WEB折线图


    1.用 apache 呈现网页前端,网页去访问 python3.x 提供的 温湿度接口,

    2.获取数据后, 前端用vue.js 绑定数据,用echarts.js 进行绘图.

    python3.x  获取 温湿度的接口

    Server.py

    from http.server import HTTPServer, BaseHTTPRequestHandler
    import json
    import urllib
    import datetime
    import Adafruit_DHT
    from http.server import BaseHTTPRequestHandler, HTTPServer
    from json import dumps
    
    sensor = Adafruit_DHT.DHT22
    pin = 24
    
    """ my function"""
    def getData():
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        temperature = round(temperature,1)
        humidity = round(humidity,1)
        result = {"state":"success","value":str(temperature) +","+str(humidity),"time":datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        print(result)
        return result
    
    """ The HTTP request handler """
    class RequestHandler(BaseHTTPRequestHandler):
      def _send_cors_headers(self):
          """ Sets headers required for CORS """
          self.send_header("Access-Control-Allow-Origin", "*")
          self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
          self.send_header("Access-Control-Allow-Headers", "x-api-key,Content-Type")
    
      def send_dict_response(self, d):
          """ Sends a dictionary (JSON) back to the client """
          self.wfile.write(bytes(dumps(d), "utf8"))
    
      def do_OPTIONS(self):
          self.send_response(200)
          self._send_cors_headers()
          self.end_headers()
    
      def do_GET(self):
          try:
             self.send_response(200)
             self._send_cors_headers()
             self.end_headers()
             # response = {}
             # response["status"] = "OK"
             result = getData()
             self.send_dict_response(result)
          except:
             print("error")
    
      # def do_POST(self):
      #     self.send_response(200)
      #     self._send_cors_headers()
      #     self.send_header("Content-Type", "application/json")
      #     self.end_headers()
      #     dataLength = int(self.headers["Content-Length"])
      #     data = self.rfile.read(dataLength)
      #     print(data)
      #     response = {}
      #     response["status"] = "OK"
      #     self.send_dict_response(response)
    if __name__ == '__main__':
        print("Starting server")
        httpd = HTTPServer(("", 8787), RequestHandler)
        print("Hosting server on port 8787")
        httpd.serve_forever()
    

      

    index.html (显示数据的 静态网页)

    <!DOCTYPE html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>v-charts</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/v-charts/lib/style.min.css"></script>
    </head>
    <body>
     <div id="app">
      <ve-line :data="chartData" :extend="extend"></ve-line>
    </div>
     
    </body>
    <script  src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/v-charts/lib/index.min.js"></script>
    <script type="text/javascript">
    var mainData =new Vue({
      el: '#app',
      data () {
        this.extend = {
           //x轴文本设置
            // 'xAxis.0.axisLabel.rotate': 45,//x轴文本倾斜
            // 'xAxis.0.axisLine.lineStyle.color': "red",//x轴文本改变颜色
            // 'xAxis.0.axisLabel.color': 'red',//x轴文本颜色
            // 'xAxis.0.axisLabel.fontSize': 16,//x轴文本字体大小
            // 'xAxis.0.axisLabel.fontFamily': 'Arial',//x轴文本字体系列
            // 'xAxis.0.axisLabel.fontWeight': 'bold',//x轴文本字体粗细
            // 'xAxis.0.axisLabel.align': 'center',//x轴文本字体位置
     
           'yAxis.0.axisLabel.color': "green",
          
           yAxis:[{
                  type: 'value',
                  min: 0,
                  max: 100,
               }],
            series: {
              label: {
                normal: {
                  show: true
                }
              }
            }
          }
        return {
          chartData: {
            label: {show:true},
            columns: ['时间','温度', '湿度'],
            rows: [
            ]
          }
        }
      },
      // components: { VeLine }
    })
    </script>
    <script type="text/javascript">
     
     
    function getDate(res) {
        res = JSON.parse(res);
        if (res.state=="success") {
     
      var timeSplit = res.time.split(" ")[1].split(":");
      var ws = res.value.split(",");
      var dataRos =mainData.$data.chartData.rows
      if (dataRos.length>=10) {
        dataRos.shift();
      }
      dataRos.push({ '时间':timeSplit[0]+"."+timeSplit[1]+"."+timeSplit[2], '温度': ws[0], '湿度': ws[1] });
      mainData.$data.chartData.rows=dataRos;
     }
    };
     
    setInterval(function() {
      $.ajax({
                type: 'get',
                url: 'http://192.168.12.1:8787',
                headers: {
                'Content-type': "application/json"
                 },
                success: function (res) {
                  getDate(res);
                  
                },
                error(err) {
                    console.error(err)
                }
            });
    }, 5000)
    </script>
    </html>
    

      

    静态网页 放入 apache 目录. 为了做成离线的,可以把 js ,css 下载到本地.

     

    启动 apache 服务,

     

    启动,python3.x  获取 温湿度的接口

     

    我们进行网页 访问

     

  • 相关阅读:
    Grumpy: Go 上运行 Python!
    Qt5.7.0配置选项(configure非常详细的参数)
    vs2010 2013 2015+ 必备插件精选(15个)
    solr与.net主从复制
    MVC5模板部署到mono
    solr主从复制
    CentOS 5.5安装图解教程
    VMware7安装CentOS6.5教程
    VMware安装CentOS 图文教程
    在VirtualBox下安装CentOS教程(截图版)
  • 原文地址:https://www.cnblogs.com/likehc/p/14514876.html
Copyright © 2020-2023  润新知