Skip to content

Commit 53a6239

Browse files
committed
Efficiency Updates
Changed from using for loops to get CPU / Mem usage to using Regex and or grep directly Changed how to get sleep state of device and now only use Grep instead of a for loop If `MEMAVAILABLE` isnt found then we will use MemFree instead, this may result in inaccurate memory calculation.
1 parent c6ef9e8 commit 53a6239

File tree

2 files changed

+184
-106
lines changed

2 files changed

+184
-106
lines changed

src/device_states.py

Lines changed: 141 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -97,50 +97,89 @@ def get_screen_info(device_choice):
9797
-------------------------------------------------
9898
"""
9999

100+
101+
import re
102+
100103
def get_mem_info(device):
101104
""" Returns Dictionary with Memory Details"""
102-
memavail = 0
103-
memfree = 0
104-
memtotal = 0
105+
memdict = {}
105106

106-
try:
107-
mem_check = device.shell("cat /proc/meminfo")
108-
split = mem_check.splitlines(-1)
109-
memdict ={}
110-
for line in split:
111-
if 'MemTotal:' in line:
112-
size = kb2mb(int(line.split(" ")[-2]))
113-
memdict['MemTotal'] = f"{size}"
114-
memtotal = memdict['MemTotal']
115-
116-
if 'MemFree:' in line:
117-
size = kb2mb(line.split(" ")[-2])
118-
memdict['MemFree'] = f"{size}"
119-
memfree = memdict['MemFree']
120-
121-
if 'MemAvailable:' in line:
122-
size = kb2mb(line.split(" ")[-2])
123-
memdict['MemAvailable'] = f"{size}"
124-
memavail = memdict['MemAvailable']
125-
126-
127-
# print(memdict)
128-
"""Had to do this to get it to round?"""
129-
perce= int(memavail) / int(memtotal) * 100
130-
memdict['Percentage']= round(perce)
131-
132-
for x in device_list:
133-
if device_list[x]['ID'] == device:
134-
device_list[x].update({'MemAvailable':memavail})
135-
device_list[x].update({'MemFree':memfree})
136-
device_list[x].update({'Percentage':perce})
137-
# print(f"{x} Dictionary Updated with Memory Usage")
138-
139-
return memdict
107+
# Use regular expressions to extract the relevant values from the output of the "cat /proc/meminfo" command
108+
output = device.shell("cat /proc/meminfo")
109+
match = re.search(r'MemTotal:\s+(\d+)\skB\nMemFree:\s+(\d+)\skB\nMemAvailable:\s+(\d+)\skB', output)
110+
if match:
111+
memtotal, memfree, memavail = map(int, match.groups())
112+
else:
113+
# If the MemAvailable value is not found, use the MemFree value as a fallback
114+
match = re.search(r'MemTotal:\s+(\d+)\skB\nMemFree:\s+(\d+)\skB', output)
115+
memtotal, memfree = map(int, match.groups())
116+
memavail = memfree
140117

141-
except Exception as e:
142-
print(f"Error Getting Memory Info: {e}")
143-
return None
118+
# Convert the values from kB to MB
119+
memtotal_mb = kb2mb(memtotal)
120+
memfree_mb = kb2mb(memfree)
121+
memavail_mb = kb2mb(memavail)
122+
123+
# Calculate the percentage of available memory
124+
percent = memavail_mb / memtotal_mb * 100
125+
126+
# Update the dictionary with the calculated values
127+
memdict['MemTotal'] = int(memtotal_mb)
128+
memdict['MemFree'] = int(memfree_mb)
129+
memdict['MemAvailable'] = int(memavail_mb)
130+
memdict['Percentage'] = round(percent)
131+
132+
# Update the device list with the calculated values
133+
for x in device_list:
134+
if device_list[x]['ID'] == device:
135+
device_list[x].update({'MemAvailable': memavail_mb})
136+
device_list[x].update({'MemFree': memfree_mb})
137+
device_list[x].update({'Percentage': percent})
138+
# print(f"{x} Dictionary Updated with Memory Usage")
139+
return memdict
140+
141+
142+
# get mem info old
143+
# get mem info olddef get_mem_info(device):
144+
# get mem info old """ Returns Dictionary with Memory Details"""
145+
# get mem info old memavail = 0
146+
# get mem info old memfree = 0
147+
# get mem info old memtotal = 0
148+
# get mem info old
149+
# get mem info old try:
150+
# get mem info old mem_check = device.shell("cat /proc/meminfo")
151+
# get mem info old split = mem_check.splitlines(-1)
152+
# get mem info old memdict ={}
153+
# get mem info old for line in split:
154+
# get mem info old if 'MemTotal:' in line:
155+
# get mem info old size = kb2mb(int(line.split(" ")[-2]))
156+
# get mem info old memdict['MemTotal'] = f"{size}"
157+
# get mem info old memtotal = memdict['MemTotal']
158+
# get mem info old
159+
# get mem info old if 'MemFree:' in line:
160+
# get mem info old size = kb2mb(line.split(" ")[-2])
161+
# get mem info old
162+
# get mem info old memdict['MemFree'] = f"{size}"
163+
# get mem info old memfree = memdict['MemFree']
164+
# get mem info old
165+
# get mem info old
166+
# get mem info old
167+
# get mem info old
168+
# get mem info old perce= int(memavail) / int(memtotal) * 100
169+
# get mem info old memdict['Percentage']= round(perce)
170+
# get mem info old
171+
# get mem info old for x in device_list:
172+
# get mem info old if device_list[x]['ID'] == device:
173+
# get mem info old device_list[x].update({'MemAvailable':memavail})
174+
# get mem info old device_list[x].update({'MemFree':memfree})
175+
# get mem info old device_list[x].update({'Percentage':perce})
176+
# get mem info old # print(f"{x} Dictionary Updated with Memory Usage")
177+
# get mem info old
178+
# get mem info old return memdict
179+
# get mem info old
180+
# get mem info old except Exception as e:
181+
# get mem info old print(f"Error Getting Memory Info: {e}")
182+
# get mem info old return None
144183

145184

146185

@@ -152,39 +191,71 @@ def get_mem_info(device):
152191
-------------------------------------------------
153192
"""
154193

194+
## OLD WAY TO GET CPU USAGE with For loops..
195+
# def get_cpu_usge(device):
196+
# """
197+
# Get the CPU Usage of the Device(s)
198+
# - if cpuz doesnt calculate cpu then why should we???
199+
# """
200+
#
201+
# build = {}
202+
# thelist = {"cpu", "user", "nice", "sys", "idle"}
203+
# ok = device.shell("top -n1")
204+
#
205+
# split = ok.splitlines(-1)
206+
# complete = False
207+
# for line in split:
208+
# if not complete:
209+
# if "cpu" in line:
210+
# newline = line.split(" ")
211+
# complete = True
212+
# for x in newline:
213+
# if x:
214+
# final_split = x.split("%")
215+
# if final_split[-1] in thelist:
216+
# build[final_split[-1]] = final_split[0]
217+
#
218+
# result= int(build['user']) + int(build['sys'])
219+
# result = result / int(build['cpu'])
220+
# result=result*100
221+
# result = str(result)[0:2]
222+
#
223+
# if "." in result:
224+
# result = result.replace(".", "")
225+
#
226+
# """ Updating CPU Usage for Devices"""
227+
# for x in device_list:
228+
# if device_list[x]['ID'] == device:
229+
# device_list[x].update({'CPU USAGE':result})
230+
# # print(f"{x} Dictionary Updated with CPU Usage")
231+
# print(ok)
232+
#
233+
# print("---------")
234+
# return result
235+
236+
237+
155238
def get_cpu_usge(device):
156239
"""
157240
Get the CPU Usage of the Device(s)
241+
- if cpuz doesnt calculate cpu then why should we???
158242
"""
159243

160-
build = {}
161-
thelist = {"cpu", "user", "nice", "sys", "idle"}
162-
ok = device.shell("top -n1")
163-
split = ok.splitlines(-1)
164-
complete = False
165-
for line in split:
166-
if not complete:
167-
if "cpu" in line:
168-
newline = line.split(" ")
169-
complete = True
170-
for x in newline:
171-
if x:
172-
final_split = x.split("%")
173-
if final_split[-1] in thelist:
174-
build[final_split[-1]] = final_split[0]
175-
176-
result= int(build['user']) + int(build['sys'])
177-
result = result / int(build['cpu'])
178-
result=result*100
179-
result = str(result)[0:2]
180-
181-
if "." in result:
182-
result = result.replace(".", "")
183-
184-
""" Updating CPU Usage for Devices"""
185-
for x in device_list:
186-
if device_list[x]['ID'] == device:
187-
device_list[x].update({'CPU USAGE':result})
188-
# print(f"{x} Dictionary Updated with CPU Usage")
189-
244+
output = device.shell("top -n1")
245+
246+
match = re.search(r'(\d+%)cpu\s+(\d+%)user\s+(\d+%)nice\s+(\d+%)sys\s+(\d+%)idle', output)
247+
248+
if match:
249+
## assigning the values to variables
250+
cpu, user, nice, sys, idle = match.groups()
251+
252+
## stripping the '%' and splitting the values
253+
cpu = int(cpu.strip('%').split()[0])
254+
user = int(user.strip('%').split()[0])
255+
sys = int(sys.strip('%').split()[0])
256+
257+
## calculating the Approximate CPU usage on Device
258+
result = (int(user) + int(sys)) / int(cpu) * 100
259+
result = str(result)[:2]
260+
190261
return result

src/main.py

Lines changed: 43 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""
22
Gitago - TouchPortal Android ADB
33
"""
4-
__version__ = "1.0"
54

65
from adb_globals import *
76
import device_states
@@ -105,9 +104,9 @@ def create_states():
105104
temp_formatted = format_temperature(device, "Fahrenheit")
106105

107106
cpu_usage = device.get('CPU USAGE')
108-
memfree=""
109-
first_math = (int(device['MemTotal']) / int(device['MemFree']))
110-
memfree = first_math*10
107+
# memfree=""
108+
# first_math = (int(device['MemTotal']) / int(device['MemFree']))
109+
# memfree = first_math*10
111110

112111

113112
TPClient.createStateMany([
@@ -184,9 +183,9 @@ def create_states():
184183
'parentGroup': device['Model']
185184
},
186185
{
187-
"id": PLUGIN_ID + f'.device.{device["Model"]}.MemoryFree',
188-
"desc": f"{device['Model']} Memory Free",
189-
"value": str(round(memfree)),
186+
"id": PLUGIN_ID + f'.device.{device["Model"]}.MemoryAvailable',
187+
"desc": f"{device['Model']} Memory Available",
188+
"value": device['MemAvailable'],
190189
'parentGroup': device['Model']
191190
},
192191
{
@@ -326,36 +325,44 @@ def adjust_brightness(device:object, level)-> None:
326325

327326

328327
""" Check Sleep State """
328+
329329
def check_sleep(device:object):
330-
try:
331-
# ok=(device.shell('dumpsys power | grep "mHolding"'))
332-
### we could find out phone boot time here also.... so if phone has been on more than X hours they can reboot maybe?
333-
334-
sleep_state =(device.shell("dumpsys nfc | grep 'mScreenState='"))
335-
336-
if not sleep_state:
337-
sleep_state = device.shell("dumpsys nfc | grep 'Screen State'")
338-
sleep_state = sleep_state.split(":")[-1]
339-
buf = StringIO(sleep_state)
340-
changes = 0
341-
342-
""" This was used when grep mHolding"""
343-
### for line2 in buf.readlines():
344-
### line = line2.strip()
345-
### for state, value in sleep_states.items():
346-
### m = re.search(r'{}=(.*)'.format(state), line)
347-
### if m:
348-
### if value != m.group(1):
349-
### changes += 1
350-
### # print("SLEEP STATE CHANGED: state={} old={} new={}".format(state, value, m.group(1)))
351-
### sleep_states[state] = m.group(1)
352-
### if changes > 0:
353-
#pass
354-
### print("---- {} Sleepstate changes".format(changes))
355-
### return sleep_states
356-
return sleep_state
357-
except RuntimeError as err:
358-
print(" error on check_sleep... ", err)
330+
#output = device.shell('dumpsys power | grep -e "mWakefulness=" -e "Display Power"')
331+
output = device.shell('dumpsys power | grep -e "mWakefulness="')
332+
output = output.split("=")[-1]
333+
return output
334+
335+
# def check_sleep2(device:object):
336+
# try:
337+
# # ok=(device.shell('dumpsys power | grep "mHolding"'))
338+
# ### we could find out phone boot time here also.... so if phone has been on more than X hours they can reboot maybe?
339+
#
340+
# sleep_state =(device.shell("dumpsys nfc | grep 'mScreenState='"))
341+
# print(sleep_state)
342+
# if not sleep_state:
343+
#
344+
# sleep_state = device.shell("dumpsys nfc | grep 'Screen State'")
345+
# sleep_state = sleep_state.split(":")[-1]
346+
# buf = StringIO(sleep_state)
347+
# changes = 0
348+
#
349+
# """ This was used when grep mHolding"""
350+
# ### for line2 in buf.readlines():
351+
# ### line = line2.strip()
352+
# ### for state, value in sleep_states.items():
353+
# ### m = re.search(r'{}=(.*)'.format(state), line)
354+
# ### if m:
355+
# ### if value != m.group(1):
356+
# ### changes += 1
357+
# ### # print("SLEEP STATE CHANGED: state={} old={} new={}".format(state, value, m.group(1)))
358+
# ### sleep_states[state] = m.group(1)
359+
# ### if changes > 0:
360+
# #pass
361+
# ### print("---- {} Sleepstate changes".format(changes))
362+
# ### return sleep_states
363+
# return sleep_state
364+
# except RuntimeError as err:
365+
# print(" error on check_sleep... ", err)
359366

360367

361368

0 commit comments

Comments
 (0)