Skip to content

Commit 88448eb

Browse files
committed
2 parents b698541 + 2f423b9 commit 88448eb

File tree

10 files changed

+307
-244
lines changed

10 files changed

+307
-244
lines changed

README.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,10 @@ Loading/Unloading Bus Kernel Modules
161161

162162
System info
163163
-----------
164-
Information about the device, including CPU, RAM, etc., is currently retrieved via several modules including a C library compiled for the Raspberry Pi, though that will be changed to a Python only implementation in the future. To support a different board you may need to update the agent code for the following items, if applicable:
164+
Information about the device, including CPU, RAM, etc., is currently retrieved via a few different modules. To support a different board you may need to update the agent code for the following items, if applicable:
165165

166166
General System Info
167-
General system info, including CPU, RAM, memory, etc. is retrieved via ``myDevices.os.systeminfo.py`` This is mostly implemented via a C library for the Raspberry Pi, though that will be changed to a Python only implementation in the future. If the C library doesn't work on your device you can disable the C library call until the Python implementation is available at which point you can modify it to support your board.
167+
General system info, including CPU, RAM, memory, etc. is retrieved via ``myDevices.os.systeminfo.py`` and ``myDevices.os.cpu.py``. These are mostly implemented using cross platform libraries so they may already provide support for your board. If not, they should be modified or overridden to provide the appropriate system info. If your board does not support all the data values currently implemented you can just provide default values where necessary, though this may affect the data display in the Cayenne dashboard.
168168

169169
Hardware Info
170170
Hardware info, including make, model, etc. is retrieved via ``myDevices.os.hardware.py``. This should be modified or overridden to provide the appropriate hardware info for your board.

libs/libSystemInformation.so

-32.3 KB
Binary file not shown.

myDevices/os/cpu.py

Lines changed: 60 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1,118 +1,69 @@
1-
#!/usr/bin/python
2-
# -*- coding: utf-8 -*-
3-
4-
'''
5-
Created on 04.12.2014
6-
7-
@author: plagtag
8-
'''
1+
import psutil
2+
import os
3+
from glob import glob
94
from time import sleep
5+
from myDevices.utils.logger import exception
106

7+
class CpuInfo(object):
8+
"""Class for retrieving CPU info"""
119

12-
class GetCpuLoad(object):
13-
'''
14-
classdocs
15-
'''
16-
17-
18-
def __init__(self, percentage=True, sleeptime = 1):
19-
'''
20-
@parent class: GetCpuLoad
21-
@date: 04.12.2014
22-
@author: plagtag
23-
@info:
24-
@param:
25-
@return: CPU load in percentage
26-
'''
27-
self.percentage = percentage
28-
self.cpustat = '/proc/stat'
29-
self.sep = ' '
30-
self.sleeptime = sleeptime
31-
32-
def getcputime(self):
33-
'''
34-
http://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux
35-
read in cpu information from file
36-
The meanings of the columns are as follows, from left to right:
37-
0cpuid: number of cpu
38-
1user: normal processes executing in user mode
39-
2nice: niced processes executing in user mode
40-
3system: processes executing in kernel mode
41-
4idle: twiddling thumbs
42-
5iowait: waiting for I/O to complete
43-
6irq: servicing interrupts
44-
7softirq: servicing softirqs
45-
46-
#the formulas from htop
47-
user nice system idle iowait irq softirq steal guest guest_nice
48-
cpu 74608 2520 24433 1117073 6176 4054 0 0 0 0
49-
50-
51-
Idle=idle+iowait
52-
NonIdle=user+nice+system+irq+softirq+steal
53-
Total=Idle+NonIdle # first line of file for all cpus
54-
55-
CPU_Percentage=((Total-PrevTotal)-(Idle-PrevIdle))/(Total-PrevTotal)
56-
'''
57-
cpu_infos = {} #collect here the information
58-
with open(self.cpustat,'r') as f_stat:
59-
lines = [line.split(self.sep) for content in f_stat.readlines() for line in content.split('\n') if line.startswith('cpu')]
60-
61-
#compute for every cpu
62-
for cpu_line in lines:
63-
if '' in cpu_line: cpu_line.remove('')#remove empty elements
64-
cpu_line = [cpu_line[0]]+[float(i) for i in cpu_line[1:]]#type casting
65-
cpu_id,user,nice,system,idle,iowait,irq,softrig,steal,guest,guest_nice = cpu_line
66-
67-
Idle=idle+iowait
68-
NonIdle=user+nice+system+irq+softrig+steal
69-
busy = user + nice + system + irq + softrig
70-
71-
Total=Idle+NonIdle
72-
#update dictionionary
73-
cpu_infos.update({cpu_id:{'total':Total,'idle':Idle, 'irq': irq, 'softirq': softrig, 'system': system, 'user': user, 'nice': nice, 'busy': busy,'iowait': iowait }})
74-
return cpu_infos
75-
76-
def getcpuload(self):
77-
'''
78-
CPU_Percentage=((Total-PrevTotal)-(Idle-PrevIdle))/(Total-PrevTotal)
79-
'''
80-
start = self.getcputime()
81-
#wait a second
82-
sleep(self.sleeptime)
83-
stop = self.getcputime()
84-
cpu_load = {}
85-
for cpu in start:
86-
Total = stop[cpu]['total']
87-
PrevTotal = start[cpu]['total']
88-
Idle = stop[cpu]['idle']
89-
PrevIdle = start[cpu]['idle']
90-
CPU_Percentage=((Total-PrevTotal)-(Idle-PrevIdle))/(Total-PrevTotal)*100
91-
CPU_Percentage=float('{0:.1f}'.format(CPU_Percentage))
92-
cpu_load.update({cpu: CPU_Percentage})
93-
del CPU_Percentage
94-
CPU_Percentage = None
95-
start = None
96-
stop = None
97-
return cpu_load
98-
def build_info(self):
10+
def get_cpu_info(self):
11+
"""Return CPU temperature, load average and usage info as a dict"""
9912
info = {}
10013
info['temperature'] = self.get_cpu_temp()
101-
info["loadavg"] = self.get_loadavg()
102-
info["usage"] = self.getcputime()['cpu']
14+
info["loadavg"] = self.get_load_avg()
15+
info["usage"] = self.get_cpu_usage()
10316
return info
17+
18+
def get_cpu_usage(self):
19+
"""Return dict with overall CPU usage"""
20+
usage = {}
21+
try:
22+
fields = ('user', 'system', 'idle', 'nice', 'iowait', 'irq', 'softirq', 'steal')
23+
usage = {key: value for key, value in psutil.cpu_times()._asdict().items() if key in fields}
24+
usage['total'] = round(sum(usage.values()), 2)
25+
except:
26+
exception('Error getting CPU usage info')
27+
return usage
28+
29+
def get_cpu_load(self, interval = 1):
30+
"""Return CPU load
31+
32+
:param interval: time interval in seconds to wait when calculating CPU usage
33+
:returns: dict containing overall CPU load, as a percentage
34+
"""
35+
cpu_load = {}
36+
try:
37+
cpu_load['cpu'] = psutil.cpu_percent(interval)
38+
except:
39+
exception('Error getting CPU load info')
40+
return cpu_load
41+
10442
def get_cpu_temp(self):
43+
"""Get CPU temperature"""
10544
info = {}
106-
file = "/sys/class/thermal/thermal_zone0/temp"
45+
thermal_dirs = glob('/sys/class/thermal/thermal_zone*')
46+
thermal_dirs.sort()
10747
temp = 0.0
10848
try:
109-
with open(file, 'r') as f_stat:
110-
content = int(f_stat.read().strip())
111-
temp = content/1000.0
112-
except Exception as e:
113-
print('Temp exception:' + str(e))
49+
for thermal_dir in thermal_dirs:
50+
try:
51+
thermal_type = ''
52+
with open(thermal_dir + '/type', 'r') as type_file:
53+
thermal_type = type_file.read().strip()
54+
if thermal_type != 'gpu_thermal':
55+
with open(thermal_dir + '/temp', 'r') as temp_file:
56+
content = int(temp_file.read().strip())
57+
temp = content / 1000.0
58+
break
59+
except:
60+
pass
61+
except Exception:
62+
exception('Error getting CPU temperature')
11463
return temp
115-
def get_loadavg(self):
64+
65+
def get_load_avg(self):
66+
"""Get CPU average load for the last one, five, and 10 minute periods"""
11667
info = {}
11768
file = "/proc/loadavg"
11869
one = 0
@@ -121,15 +72,13 @@ def get_loadavg(self):
12172
try:
12273
with open(file, 'r') as f_stat:
12374
content = f_stat.read().strip().split(' ')
124-
one = content[0]
125-
five = content[1]
126-
ten = content[2]
127-
except Exception as e:
128-
print('Cpu Loadavg exception:' + str(e))
75+
one = float(content[0])
76+
five = float(content[1])
77+
ten = float(content[2])
78+
except Exception:
79+
exception('Error getting CPU load average')
12980
info['one'] = one
13081
info['five'] = five
13182
info['ten'] = ten
13283
return info
13384

134-
# gpl = GetCpuLoad()
135-
# print(gpl.build_info())

myDevices/os/getsysteminfo.py

Lines changed: 0 additions & 5 deletions
This file was deleted.

myDevices/os/memory.py

Lines changed: 0 additions & 81 deletions
This file was deleted.

0 commit comments

Comments
 (0)