Raspberry数据报表自动提交

准备一台Raspberry 公网服务器

在服务器上搭建database 建立表

 

DB
CREATE TABLE `raspberry_basic_log` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`CPU_Use` double DEFAULT NULL,
`RAM_Use` double DEFAULT NULL,
`CPU_Temperature` double DEFAULT NULL,
`DISK_Use` double DEFAULT NULL,
`date` datetime(0) DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 15 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Fixed;

nginx或者apache之类的web服务器上写接受数据的API

这里示例PHP写的

 

PHP
<?php
$con = mysql_connect("127.0.0.1","你的用户名","密码");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("数据库名", $con);
mysql_query("INSERT INTO `hunter_raspberry`.`raspberry_basic_log`(`CPU_Use`, `RAM_Use`, `CPU_Temperature`) VALUES (".$_GET["cpuuse"].",".$_GET["ramuse"].", ".$_GET["cput"].");");
mysql_close($con);
?>

 

保存为api.php

然后看看能不能访问

再用py对Raspberry配置

Python
import os
import httplib
import time
# Return CPU temperature as a character string
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    return(res.replace("temp=","").replace("'C\n",""))
# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
    p = os.popen('free')
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i==2:
            return(line.split()[1:4])
# Return % of CPU used by user as a character string
def getCPUuse():
    return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
# Return information about disk space as a list (unit included)
# Index 0: total disk space
# Index 1: used disk space
# Index 2: remaining disk space
# Index 3: percentage of disk used
def getDiskSpace():
    p = os.popen("df -h /")
    i = 0
    while 1:
        i = i +1
        line = p.readline()
        if i==2:
            return(line.split()[1:5])
while 2 > 1:
    time.sleep(3000)
    # CPU informatiom
    CPU_temp = getCPUtemperature()
    CPU_usage = getCPUuse()
    # RAM information
    # Output is in kb, here I convert it in Mb for readability
    RAM_stats = getRAMinfo()
    RAM_total = round(int(RAM_stats[0]) / 1000,1)
    RAM_used = round(int(RAM_stats[1]) / 1000,1)
    RAM_free = round(int(RAM_stats[2]) / 1000,1)
    # Disk information
    DISK_stats = getDiskSpace()
    DISK_total = DISK_stats[0]
    DISK_used = DISK_stats[1]
    DISK_perc = DISK_stats[3]
    if __name__ == '__main__':
        print('')
        print('CPU Temperature = '+CPU_temp)
        print('CPU Use = '+CPU_usage)
        print('')
        print('RAM Total = '+str(RAM_total)+' MB')
        print('RAM Used = '+str(RAM_used)+' MB')
        print('RAM Free = '+str(RAM_free)+' MB')
        print('')
        print('DISK Total Space = '+str(DISK_total)+'B')
        print('DISK Used Space = '+str(DISK_used)+'B')
        print('DISK Used Percentage = '+str(DISK_perc))
        url = "http://xxxx.com/api.php?cpuuse="+CPU_temp+"&ramuse="+str(RAM_used)+"&cput="+CPU_temp
        print(url)
        conn = httplib.HTTPConnection("xxxx.com")
        conn.request(method="GET",url=url)
        response = conn.getresponse()
        res= response.read()
        print res
引入echarts的js
PHP
<?php
    mysql_connect("127.0.0.1", "你的数据库用户名", "密码") or
        die("Could not connect: " . mysql_error());
    mysql_select_db("hunter_raspberry");
    $result = mysql_query("SELECT * from raspberry_basic_log");
$arr = array();
while($row=mysql_fetch_array($result)){
    array_push($arr,$row);
}
?>
<html>
<script src="echarts.min.js"></script>
<body>
<h1>qwq</h1>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="width: 100%;height:100%;"></div>
    <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));
var timeData = [
    <?php
foreach($arr as $myrow)
    {
        echo "'".date('Y/m/d H:i', strtotime($myrow[5]).PHP_EOL)."',";
}
    ?>
];
timeData = timeData.map(function (str) {
    return str.replace('2009/', '');
});
option = {
    title: {
        text: 'C1en的树莓派运行监控',
        subtext: '',
        x: 'center'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            animation: false
        }
    },
    legend: {
        data:['流量','降雨量'],
        x: 'left'
    },
    toolbox: {
        feature: {
            dataZoom: {
                yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
        }
    },
    axisPointer: {
        link: {xAxisIndex: 'all'}
    },
    dataZoom: [
        {
            show: true,
            realtime: true,
            start: 30,
            end: 70,
            xAxisIndex: [0, 1]
        },
        {
            type: 'inside',
            realtime: true,
            start: 30,
            end: 70,
            xAxisIndex: [0, 1]
        }
    ],
    grid: [{
        left: 50,
        right: 50,
        height: '35%'
    }, {
        left: 50,
        right: 50,
        top: '55%',
        height: '35%'
    }],
    xAxis : [
        {
            type : 'category',
            boundaryGap : false,
            axisLine: {onZero: true},
            data: timeData
        },
        {
            gridIndex: 1,
            type : 'category',
            boundaryGap : false,
            axisLine: {onZero: true},
            data: timeData,
            position: 'top'
        }
    ],
    yAxis : [
        {
            name : 'CPU使用量(%)',
            type : 'value',
            max : 100
        },
        {
            gridIndex: 1,
            name : 'CPU温度(℃)',
            type : 'value',
            inverse: true
        }
    ],
    series : [
        {
            name:'CPU使用量',
            type:'line',
            symbolSize: 8,
            hoverAnimation: false,
            data:[
            <?php
                foreach($arr as $myrow)
    {
        echo "'".$myrow[1]."',";
}
            ?>
            ]
        },
        {
            name:'CPU温度',
            type:'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            symbolSize: 8,
            hoverAnimation: false,
            data: [
                <?php
                foreach($arr as $myrow)
    {
        echo "'".$myrow[3]."',";
}
            ?>
            ]
        }
    ]
};
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    </script>
</body>
</html>

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注