每个人都有自己的知识体系。
Toggle navigation
Home
随笔
C#/.Net
树莓派 / Raspberry
皓月汉化组
Beego
Golang
OxideMod
apache
haproxy
windows
Java
Objective-C
日语/罗马音歌词/日语常识
MongoDB
python
电学
公告
Minecraft服务器-公告
NanoPi
C4D (CINEMA 4D)
生活
推流/m3u8/rtmp/rtsp
Unity3d
ffmpeg
数据结构
区块链
tarui
UnityForPSVita
About Me
Archives
Tags
定时提交“树莓派CPU、温度、内存使用率等数据”到服务器、并做网页监控图表
2017-07-27 21:40:14
474
0
0
akiragatsu
这个只是用于举例、 比如你可以用类似方式提交树莓派采集其他数据、诸如土壤温度、家用电器数据等等提交到服务器进行记录。 准备: 家里的树莓派、 你的服务器、 (这里以公网数据库服务器和网站服务器为例) 首先在你的服务器搭建数据库用于存储数据 然后创建纪录树莓派CPU、温度、内存使用率等数据的表 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为例,让树莓派以get方式提交数据、并写入到数据库 <?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); ?> 然后、比如我们把以上php代码保存到我们的站点目录里 保存为api.php 确认我们的网站http://xxxxx.com/api.php 可以正常访问 接下来就用python在树莓派上编写获取和请求代码 简单思路:循环使用sleep延迟3600秒获取一次、并构造get请求、提交一次 实现每个小时采集一次 代码如下: 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 然后 不是需要一个美观的折线图吗?233333 那就用php读取数据库 折线图的话、 就用百度开源的前端炫酷框架echarts好了 官方地址: http://echarts.baidu.com/examples.html 下载下来 引入他的js 然后就开工吧 php读取数据库 然后写入到前端呈现的数据里就ok 最终效果是这样: 地址:http://raspberry.axibug.com:8801/ 截图: ![图片标题](/api/file/getImage?fileId=597a09a727a7eb192c000102) 下面的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>-201707027晚上闲得慌写的数据采集 实现方式分享<a href='http://note.axibug.com/blog/post/akiragatsu/7612d5bcc53f'>【点这里】</a> </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: '皓月的树莓派运行监控', 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>
Pre:
《渝物语》
Next:
树莓派 python调用已编译的 ffmpeg推流到B站等直播间
0
likes
474
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.