最近老闆給提出一個須要,項目需求大體以下:前端
1、用樹莓派做爲網關,底層接多個ZigBee傳感節點,網關把ZigBee傳感節點採集到的信息經過串口接收匯總,而且發送給上層的HTTP Server;2、要有數據的反向控制通道,即網關與Server間要保持長鏈接,採用websocket實現,以此實現給ZigBee傳感節點發送控制命令,來實現對ZigBee節點的遠程配置操做;
3、樹莓派網關自己要與上層Server實現交互,上層Server可以看到網關實時的cpu、內存以及網絡上行與下行的帶寬等等;
前兩條需求在前一段時間已經基本實現,等後續有時間完善以後在整理,今天記錄一下第三條的實現過程。python
git
#!/usr/bin/env python # -*- coding:utf-8 -*- ############################# #__author__ = 'webber' # #create at 2016/12/12 # ############################# import os import sys import time def cpuinfo(): """ get cpuinfo from '/proc/stat' and calculate the percentage of the cpu occupy. """ f = open('/proc/stat','r') cpu = f.readline() f.close() #print "cpuinfo: ", cpu cpu = cpu.split(" ") total = 0 usr = float(cpu[2]) #用戶態cpu佔用率 _sys = float(cpu[4]) #內核態cpu佔用率 for info in cpu: if info.isdigit(): total += float(info) print '\033[31mcpu info: \033[0m', print 'usr: %.5f%%' % ((usr/total)*100), print ' sys: %.5f%%' % ((_sys/total)*100) def meminfo(): """ get meminfo from '/proc/meminfo' and calculate the percentage of the mem occupy used = total - free - buffers - cached """ f = open('/proc/meminfo','r') mem = f.readlines() f.close() #print "meminfo", mem total, free, buffers, cached = 0, 0, 0, 0 for info in mem: mem_item = info.lower().split() #print mem_item if mem_item[0] == 'memtotal:': total = float(mem_item[1]) if mem_item[0] == 'memfree:': free = float(mem_item[1]) if mem_item[0] == 'buffers:': buffers = float(mem_item[1]) if mem_item[0] == 'cached:': cached = float(mem_item[1]) used = total - free - buffers - cached print "\033[31mmeminfo: \033[0m", print "total: %.2f GB" % (total/1024/1024), print " used: %.5f%%" % (used/total) def netinfo(): """ get real-time bandwidth """ f = open('/proc/net/dev','r') net = f.readlines() f.close() net_item = [] for info in net: if info.strip().startswith("eth0"): net_item = info.strip().split() break # print net_item recv = float(net_item[1]) send = float(net_item[9]) #print "recv:%s " % recv #print "send:%s " % send time.sleep(1) f2 = open('/proc/net/dev','r') _net = f2.readlines() f2.close() _net_item = [] for info in _net: if info.strip().startswith("eth0"): _net_item = info.strip().split() break recv_2 = float(_net_item[1]) send_2 = float(_net_item[9]) #print "recv_2:%s " % recv_2 #print "send_2:%s " % send_2 print "\033[31m network info: \033[0m" print "received: %.3f Kb/s" % (recv_2/1024 - recv/1024) print "transmit: %.3f kb/s" % (send_2/1024 - send/1024) def loadavg(): pass def disk(): pass if __name__ == '__main__': while True: try: os.system('clear') cpuinfo() print "==============================================" meminfo() print "##############################################" netinfo() time.sleep(5) except KeyboardInterrupt, e: # 這裏也能夠用信號函數來處理 print '' print "BYE-BYE" sys.exit(0)