manafa 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/__init__.py +0 -0
  2. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/batteryStats/BatteryStatsConstants.py +103 -0
  3. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/batteryStats/BatteryStatsParser.py +437 -0
  4. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/batteryStats/__init__.py +0 -0
  5. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/emanafa.py +223 -0
  6. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/perfetto/__init__.py +0 -0
  7. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/perfetto/perfettoParser.py +132 -0
  8. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/powerProfile/PowerProfile.py +89 -0
  9. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/powerProfile/__init__.py +0 -0
  10. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/services/__init__.py +0 -0
  11. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/services/batteryStatsService.py +40 -0
  12. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/services/perfettoService.py +44 -0
  13. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/services/service.py +25 -0
  14. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/tests/__init__.py +0 -0
  15. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/tests/batterystats/__init__.py +0 -0
  16. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/tests/batterystats/test_batteryStatsService.py +7 -0
  17. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/tests/perfetto/__init__.py +0 -0
  18. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/tests/perfetto/test_perfettoService.py +15 -0
  19. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/utils/Logger.py +36 -0
  20. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/utils/Utils.py +14 -0
  21. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/utils/__init__.py +0 -0
  22. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa/utils/dateUtils.py +52 -0
  23. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa-0.2.2-py3.8.egg-info/PKG-INFO +103 -0
  24. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa-0.2.2-py3.8.egg-info/SOURCES.txt +43 -0
  25. Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa-0.2.2-py3.8.egg-info/top_level.txt +1 -0
  26. manafa-0.2.0/PKG-INFO +0 -81
  27. manafa-0.2.0/README.md +0 -64
  28. manafa-0.2.0/manafa/manafa.egg-info/PKG-INFO +0 -81
  29. manafa-0.2.0/manafa/manafa.egg-info/SOURCES.txt +0 -8
  30. manafa-0.2.0/manafa/manafa.egg-info/top_level.txt +0 -1
  31. manafa-0.2.0/setup.cfg +0 -4
  32. manafa-0.2.0/setup.py +0 -50
  33. {manafa-0.2.0/manafa/manafa.egg-info → Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa-0.2.2-py3.8.egg-info}/dependency_links.txt +0 -0
  34. {manafa-0.2.0/manafa/manafa.egg-info → Users/ruirua/repos/emanafa/venv/lib/python3.8/site-packages/manafa-0.2.2-py3.8.egg-info}/requires.txt +0 -0
@@ -0,0 +1,103 @@
1
+
2
+
3
+ # Battery related : https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/BatteryManager.java
4
+
5
+ # https://android.googlesource.com/platform/hardware/interfaces/+/oreo-m5-release/health/1.0/types.hal
6
+ BATTERY_STATUS= {
7
+ "unknown" : 1, # "BATTERY_STATUS_UNKNOWN",
8
+ "charging": 2, # "BATTERY_STATUS_CHARGING",
9
+ "discharging": 3, #; "BATTERY_STATUS_DISCHARGING",
10
+ "not-charging": 4, # "BATTERY_STATUS_NOT_CHARGING",
11
+ "full": 5 # "BATTERY_STATUS_FULL",
12
+ }
13
+ BATTERY_HEALTH= {
14
+ "unknown":1, # "BATTERY_HEALTH_UNKNOWN",
15
+ "good":2, # "BATTERY_HEALTH_GOOD",
16
+ "overheat":3, # "BATTERY_HEALTH_OVERHEAT",
17
+ "dead":4, # "BATTERY_HEALTH_DEAD",
18
+ "over-voltage":5, # "BATTERY_HEALTH_OVER_VOLTAGE",
19
+ "failure":6, # "BATTERY_HEALTH_UNSPECIFIED_FAILURE",
20
+ "cold":7, # "BATTERY_HEALTH_COLD",
21
+ }
22
+
23
+ BATTERY_PLUGGED= {
24
+ "none": 0 , # : "BATTERY_PLUGGED_NONE"
25
+ "ac": 1 , # "BATTERY_PLUGGED_AC",
26
+ "usb": 2 , # "BATTERY_PLUGGED_USB",
27
+ "wireless": 4 , # "BATTERY_PLUGGED_WIRELESS",
28
+ }
29
+
30
+
31
+
32
+ # Battery related : https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/BatteryManager.java
33
+
34
+ # https://android.googlesource.com/platform/hardware/interfaces/+/oreo-m5-release/health/1.0/types.hal
35
+
36
+
37
+ #Display
38
+ #https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/Display.java
39
+ DISPLAY_STATE= {
40
+ 1: "STATE_OFF",
41
+ 2: "STATE_ON",
42
+ 3: "STATE_DOZE",
43
+ 4: "STATE_DOZE_SUSPEND",
44
+ 5: "STATE_DOZE_VR",
45
+ 6: "DISPLAY_STATE_ON_SUSPEND"
46
+ }
47
+
48
+ GENERIC_CONSTANTS = {
49
+ 1 :"WAKE_TYPE_FULL" ,
50
+ 2 :"WAKE_TYPE_WINDOW" ,
51
+ 3 :"SENSOR" ,
52
+ 4 :"WIFI_RUNNING" ,
53
+ 5 :"FULL_WIFI_LOCK" ,
54
+ 6 :"WIFI_SCAN" ,
55
+ 7 :"WIFI_MULTICAST_ENABLED" ,
56
+ 8 :"VIDEO_TURNED_ON" ,
57
+ 9 :"VIBRATOR_ON" ,
58
+ 10 :"FOREGROUND_ACTIVITY" ,
59
+ 11 :"WIFI_BATCHED_SCAN" ,
60
+ 12 :"PROCESS_STATE" ,
61
+ 13 :"SYNC" ,
62
+ 14 :"JOB" ,
63
+ 15 :"AUDIO_TURNED_ON" ,
64
+ 16 :"FLASHLIGHT_TURNED_ON" ,
65
+ 17 :"CAMERA_TURNED_ON" ,
66
+ 18 :"WAKE_TYPE_DRAW" ,
67
+ 19 :"BLUETOOTH_SCAN_ON" ,
68
+ 20 :"AGGREGATED_WAKE_TYPE_PARTIAL" ,
69
+ 21 :"BLUETOOTH_UNOPTIMIZED_SCAN_ON" ,
70
+ 22 :"FOREGROUND_SERVICE" ,
71
+ 23 :"WIFI_AGGREGATE_MULTICAST_ENABLED" ,
72
+ }
73
+
74
+ STATS={
75
+ 0 : "STATS_SINCE_CHARGED",
76
+ 1 : "STATS_CURRENT",
77
+ 2 : "STATS_SINCE_UNPLUGGED"
78
+ }
79
+
80
+ EVENT_NAMES= {
81
+ "null",
82
+ "proc",
83
+ "fg",
84
+ "top",
85
+ "sync",
86
+ "wake_lock_in",
87
+ "job",
88
+ "user",
89
+ "userfg",
90
+ "conn",
91
+ "active",
92
+ "pkginst",
93
+ "pkgunin",
94
+ "alarm",
95
+ "stats",
96
+ "pkginactive",
97
+ "pkgactive",
98
+ "tmpwhitelist",
99
+ "screenwake",
100
+ "wakeupap",
101
+ "longwake",
102
+ "est_capacity"
103
+ }
@@ -0,0 +1,437 @@
1
+ import re,json
2
+ #sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
3
+ from collections import Iterable
4
+
5
+ from manafa.powerProfile.PowerProfile import PowerProfile
6
+ from manafa.utils.dateUtils import convertBatStatTimeToTimeStamp,batStatResetTimeToTimeStamp
7
+ import copy
8
+
9
+ DEFAULT_JSON_PATH = "manafa/batteryStats/BatteryStatus.json"
10
+
11
+
12
+ KNOWN_VALUES=set(
13
+ "screen.on"
14
+ #TODO put here all values in https://source.android.com/devices/tech/power/values
15
+ )
16
+
17
+
18
+ def areInMinCPUFreq( cpu_freq , possible_cpu_states ):
19
+ possible_freqs = possible_cpu_states["speeds"] if "speeds" in possible_cpu_states else []
20
+ if len(possible_freqs)==0:
21
+ possible_freqs = possible_cpu_states["core_speeds"] if "core_speeds" in possible_cpu_states else []
22
+ if len(possible_freqs)>0:
23
+ possible_freqs = sum(possible_freqs.values(),[])
24
+
25
+ #tem que ser os 2 tempos absolutos
26
+ #print(possible_freqs)
27
+ return False
28
+
29
+ def safe_division(a,b):
30
+ z = 1 if b==0 else b
31
+ return a / z
32
+
33
+ class BatteryEvent(object):
34
+ """docstring for BatteryEvent"""
35
+ def __init__(self,time=0.0,vals={}):
36
+ self.time=time
37
+ self.updates = {}
38
+ self.currents = {}
39
+ self.concurrentUpdates={}
40
+ self.concurrentUpdates["tmpwhitelist"]=[]
41
+ self.concurrentUpdates["job"]=[]
42
+ self.concurrentUpdates["sync"]=[]
43
+ self.concurrentUpdates["top"]=[]
44
+ self.concurrentUpdates["longwake"]=[]
45
+ self.concurrentUpdates["fg"]=[]
46
+ self.concurrentUpdates["proc"]=[]
47
+ self.concurrentUpdates["screenwake"]=[]
48
+ self.concurrentUpdates["pkgactive"]=[]
49
+ self.concurrentUpdates["user"]=[]
50
+ self.concurrentUpdates["userfg"]=[]
51
+ self.concurrentUpdates["wake_lock_in"]=[]
52
+ self.concurrentUpdates["alarm"]=[]
53
+ self.addEvents(vals)
54
+
55
+ def __str__(self):
56
+ return "time:%f vals = %s , concs= %s " % (self.time,str(self.updates),str(self.concurrentUpdates))
57
+
58
+ def __repr__(self):
59
+ return str(self)
60
+
61
+ def isConcurrent(self,state):
62
+ #return re.match(r"(\+|\-)?(tmpwhitelist|job|sync|top|longwake|fg|proc)", state)
63
+ return state in self.concurrentUpdates
64
+
65
+ def getCurrentOfBatStatEvent(self):
66
+ currs = {}
67
+ total = 0
68
+ for v, x in self.currents.items():
69
+ try:
70
+ z = float(x)
71
+ currs[v] = z / 1000
72
+ total += z
73
+ except ValueError:
74
+ currs[v]=0
75
+ continue
76
+ return total/1000, currs
77
+
78
+ def getVoltageValue(self):
79
+ return float(self.updates["volt"]) / 1000 if "volt" in self.updates else 0
80
+
81
+ def addEvents(self,event1):
82
+ for ev in event1.keys():
83
+ #print("->"+ev + "--")
84
+ if ev.startswith("-"):
85
+ conc_update_state = ev.replace("-","",1)
86
+ if self.isConcurrent(conc_update_state):
87
+ #print("vou tirar conc "+ev)
88
+ self.concurrentUpdates[conc_update_state] = [n for n in self.concurrentUpdates[conc_update_state] if ( n["val"] != event1[ev]["val"] and n["val2"] != event1[ev]["val2"] ) ]
89
+ else:
90
+ #print("vou tirar ev "+ev)
91
+ self.updates.pop(conc_update_state,None)
92
+ else:
93
+ ev_def = ev.replace("+","",1)
94
+ if self.isConcurrent(ev_def):
95
+ self.concurrentUpdates[ev_def].append(event1[ev])
96
+ else:
97
+ self.updates[ev_def]=event1[ev]
98
+
99
+
100
+ class BatteryStatsParser(object):
101
+ """docstring for BatteryStatsParser"""
102
+ def __init__(self, powerProfile=None , timezone="EST", def_file=DEFAULT_JSON_PATH, android_version=10):
103
+ self.events = []
104
+ self.definitions = self.loadDefinitionFile(def_file)
105
+ self.powerProfile = self.loadPowerProfile(powerProfile) if powerProfile is not None else {}
106
+ self.android_version = android_version
107
+ self.start_time = 0
108
+ self.timezone = timezone # adb shell date +"%Z %z"
109
+
110
+ def loadPowerProfile(self, xml_profile ):
111
+ return PowerProfile(xml_profile)
112
+
113
+ def loadDefinitionFile(self,def_file):
114
+ with open(def_file,"r") as dff:
115
+ return json.load(dff)
116
+
117
+ def getDefinitionVal(self,key,val=""):
118
+ if re.sub(r"\+|\-", "", key) in self.definitions["monoval"]:
119
+ return 0 if "-" in key else 1
120
+ elif re.sub(r"\+|\-", "", key) in self.definitions["trival"]:
121
+ return key
122
+ elif re.sub(r"\+|\-", "", key) in self.definitions["numerical"]:
123
+ return val
124
+ elif re.sub(r"\+|\-", "", key) in self.definitions["nominal"]:
125
+ return self.definitions["nominal"][str(key)][val]
126
+ return None
127
+
128
+ def isTrival(self,key):
129
+ return re.sub(r"\+|\-", "", key) in self.definitions["trival"]
130
+
131
+ def parseStates(self,states):
132
+ accum=False
133
+ accumulator = ""
134
+ latest_state=None
135
+ events={}
136
+ for state in re.sub(r"^ ","",states).split(" "):
137
+ #print("->" +state)
138
+ if accum:
139
+ accumulator+=state
140
+ if state.count('\"')%2 != 0:
141
+ accum = not accum
142
+ accumulator = ""
143
+ continue
144
+ if "=" in state:
145
+ if state.count('\"')%2 != 0:
146
+ accum = True
147
+ accumulator+=state
148
+ continue
149
+ else:
150
+ key = state.split("=")[0]
151
+ val = state.split("=")[1]
152
+ state = self.getDefinitionVal(key,val)
153
+ if self.isTrival(key):
154
+ #print("TODO: split in trival")
155
+ #print("%s - %s -%s" %(key,val.split(":")[0],val.split(":")[1]))
156
+ #return key,val.split(":")[0],val.split(":")[1]
157
+ events[key]= {"val": val.split(":")[0] , "val2": val.split(":")[1]}
158
+ else:
159
+ #print("%s = %s" %(key,state))
160
+ events[key]=state
161
+ elif state != "" and state != " ":
162
+ st = self.getDefinitionVal(state)
163
+ #print("%s - %s" %(state,st))
164
+ #print("val "+str(self.getDefinitionVal(state)))
165
+ events[state]=st
166
+ return events
167
+
168
+ def parseHistory(self,lines_list):
169
+ for i, line in enumerate(lines_list):
170
+ if re.match(r"^Battery History \([0-9]", line):
171
+ #header, ignore
172
+ continue
173
+ if re.match(r"^Per-PID Stats", line)or len(line)==0:
174
+ return
175
+ elif re.match(r"^\s*([^\s]+) (\(\d+\)) (\d+)(.*)?$", line):
176
+ x = re.match(r"^\s*([^\s]+) (\(\d+\)) (\d+)(.*)?$", line)
177
+ time = convertBatStatTimeToTimeStamp(x.groups()[0], timezone=self.timezone)
178
+ time += self.start_time
179
+ #print(time)
180
+ events = self.parseStates(x.groups()[3])
181
+ self.addUpdate(time, events)
182
+ elif re.match(r"^\s*0 (\(\d+\)) (.*)?$", line):
183
+ x = re.match(r"^\s*0 (\(\d+\)) (.*)?$", line)
184
+ if "RESET:TIME" in x.groups()[1]:
185
+ self.start_time= batStatResetTimeToTimeStamp((x.groups()[1]).replace("RESET:TIME: ",""), self.timezone )
186
+ #print(epochToDate(self.start_time))
187
+ else:
188
+ # TODO Handle DcpuStats and DpstStats
189
+ print("linha invalida" + line)
190
+
191
+ def addUpdate(self, time,bat_events):
192
+ if len(self.events)==0:
193
+ bt = BatteryEvent( time,bat_events )
194
+ self.estimateCurrentConsumption(bt)
195
+ self.events.append(bt )
196
+ else:
197
+ last_added = self.events[-1]
198
+ if last_added.time == time:
199
+ self.events[-1].addEvents(bat_events)
200
+
201
+ else:
202
+ # todo try to replace with shallow copy
203
+ bt = copy.deepcopy(self.events[-1])
204
+ bt.time = time
205
+ bt.addEvents(bat_events)
206
+ self.estimateCurrentConsumption(bt)
207
+ self.events.append(bt)
208
+
209
+
210
+ def estimateCurrentConsumption(self,bt_event):
211
+ power={}
212
+ for p,v in self.powerProfile.components.items():
213
+ st = self.determinateComponentCurrent(bt_event,p,v)
214
+ power[p]=st
215
+ #print("%s %s" %(p , str(st)))
216
+ bt_event.currents=power
217
+
218
+
219
+ def getCPUSamplesInBetween(self,start_time, end_time ):
220
+ l =[]
221
+ last_ev = self.events[0] if len(self.events)>0 else None
222
+ last_time = start_time
223
+ for x in self.events:
224
+ if x.time > start_time and x.time < end_time:
225
+ delta = x.time - last_time
226
+ state = last_ev.currents["cpu"]
227
+ voltage = last_ev.getVoltageValue() #float(last_ev.updates["volt"])
228
+ pair = (delta, state,voltage)
229
+ l.append(pair)
230
+ last_time= x.time
231
+ last_ev = x
232
+ #
233
+ last_delta = end_time - last_time
234
+ last_state = last_ev.currents["cpu"]
235
+ last_voltage = last_ev.getVoltageValue() #float(last_ev.updates["volt"])
236
+ last_pair = ( last_delta, last_state,last_voltage)
237
+ l.append(last_pair)
238
+ return l
239
+
240
+ def determinateComponentCurrent(self,bt_event,comp_name, possible_states):
241
+ current = 0.0
242
+ curravg=0
243
+ avg_ct=0
244
+ # screen
245
+ if comp_name == "screen" and "screen" in bt_event.updates:
246
+ on_current = possible_states["on"]
247
+ brightness_level = bt_event.updates["brightness"] if "brightness" in bt_event.updates else 1
248
+ relative_full_current = ( brightness_level * possible_states["full"] / ( len( self.definitions["nominal"]["brightness"] ) -1) )
249
+ current+= on_current + relative_full_current
250
+
251
+ elif comp_name == "ambient" and "screen_doze" in bt_event.updates:
252
+ # power profile might have a defined value for ambient/doze screen consumpri
253
+ doze_current = possible_states["on"]
254
+ current+=doze_current
255
+
256
+ # camera/flashlight
257
+ elif comp_name == "camera":
258
+ if "camera" in bt_event.updates:
259
+ #usually available as avg consumption (Intended as a rough estimate for an application running a preview and capturing approximately 10 full-resolution pictures per minute.)
260
+ cam_current = possible_states["avg"]
261
+ current+=cam_current
262
+
263
+ if "flashlight" in bt_event.updates:
264
+ flash_curr = possible_states["flashlight"]
265
+ current+=flash_curr
266
+ # dsp
267
+ elif comp_name == "dsp":
268
+ if "video" in bt_event.updates:
269
+ video_curr = possible_states["video"] if comp_name == "dsp" else possible_states
270
+ current+=video_curr
271
+
272
+ if "audio" in bt_event.updates:
273
+
274
+ audio_curr = possible_states["audio"] if comp_name == "dsp" else possible_states
275
+ current+=audio_curr
276
+
277
+ # audio
278
+ elif comp_name == "video" and "video" in bt_event.updates:
279
+ video_curr = possible_states
280
+ current += video_curr
281
+ # video
282
+ elif comp_name == "audio" and "audio" in bt_event.updates:
283
+ audio_curr = possible_states
284
+ current += audio_curr
285
+
286
+ # wifi
287
+ elif comp_name == "wifi" and "wifi_running" in bt_event.updates:
288
+ on_current = possible_states["on"] if "on" in possible_states else 0
289
+ on_current += possible_states["controller"]["idle"] if ( "controller" in possible_states and "idle" in possible_states["controller"] ) else 0
290
+ current+= on_current
291
+ if "wifi_scan" in bt_event.updates:
292
+ if "scan" in possible_states:
293
+ current+= possible_states["scan"]
294
+ if "controller" in possible_states:
295
+ curravg=0
296
+ avg_ct =0
297
+ if "tx" in possible_states["controller"]:
298
+ curravg+=possible_states["controller"]["tx"]
299
+ avg_ct+=1
300
+ if "rx" in possible_states["controller"]:
301
+ curravg+=possible_states["controller"]["rx"]
302
+ avg_ct+=1
303
+ current += safe_division(curravg, avg_ct)
304
+ elif "wifi_radio" in bt_event.updates:
305
+ current+= possible_states["active"] if "active" in possible_states else 0
306
+ if "controller" in possible_states:
307
+ curravg=0
308
+ avg_ct =0
309
+ if "tx" in possible_states["controller"]:
310
+ curravg+=possible_states["controller"]["tx"]
311
+ avg_ct+=1
312
+ if "rx" in possible_states["controller"]:
313
+ curravg+=possible_states["controller"]["rx"]
314
+ avg_ct+=1
315
+ current += safe_division(curravg, avg_ct)
316
+
317
+ # gps
318
+ elif comp_name == "gps":
319
+ if "signalqualitybased" in possible_states: # and "gps_signal_quality" in bt_event.updates:
320
+ # considerate gps signal quality
321
+ if "gps_signal_quality" in bt_event.updates:
322
+ val = 1 if bt_event.updates["gps_signal_quality"] == "good" else 0
323
+ current+= possible_states["signalqualitybased"][val]
324
+ if "on" in possible_states and "gps" in bt_event.updates:
325
+ current+= possible_states["on"]
326
+
327
+ #bluetooth
328
+ elif comp_name == "bluetooth":
329
+ if self.android_version<7 or "controller" not in possible_states:
330
+ #account blue on and active vals
331
+ if "ble_scan" in bt_event.updates:
332
+ current+= possible_states["active"] if "active" in possible_states else 0
333
+ current+= possible_states["on"] if "on" in possible_states else 0
334
+ elif "bluetooth" in bt_event.updates:
335
+ current+= possible_states["on"] if "on" in possible_states else 0
336
+ elif "controller" in possible_states:
337
+ current += possible_states["controller"]["idle"] if ( "idle" in possible_states["controller"] ) else 0
338
+ if "ble_scan" in bt_event.updates:
339
+ if "tx" in possible_states["controller"]:
340
+ curravg+=possible_states["controller"]["tx"]
341
+ avg_ct+=1
342
+ if "rx" in possible_states["controller"]:
343
+ curravg+=possible_states["controller"]["rx"]
344
+ avg_ct+=1
345
+ current += safe_division(curravg, avg_ct)
346
+
347
+ # radio = modem
348
+ elif comp_name == "radio":
349
+ #radio.on
350
+ if "phone_scanning" in bt_event.updates:
351
+ # radio.scanning
352
+ current += possible_states["scanning"] if "scanning" in possible_states else 0
353
+
354
+ elif "mobile_radio" in bt_event.updates:
355
+ on_vals = list(possible_states["on"]) if "on" in possible_states else []
356
+ signal_stren = bt_event.updates["phone_signal_strength"] if "phone_signal_strength" in bt_event.updates else 0
357
+ if signal_stren > len(on_vals) and len(on_vals)>0:
358
+ current+= on_vals[-1]
359
+ elif len(on_vals)>0:
360
+ current+= on_vals[signal_stren]
361
+ # radio.active == mobile_radio - transmiting
362
+
363
+ elif comp_name == "modem":
364
+ #same as radio
365
+ if "phone_scanning" in bt_event.updates:
366
+ curravg=0
367
+ avg_ct=0
368
+ if "tx" in possible_states["controller"]:
369
+ on_vals = possible_states["controller"]["tx"] if "tx" in possible_states["controller"] else []
370
+ signal_stren = bt_event.updates["phone_signal_strength"] if "phone_signal_strength" in bt_event.updates else 0
371
+ if signal_stren > len(on_vals) and len(on_vals)>0:
372
+ curravg+= on_vals[-1]
373
+ elif len(on_vals)>0:
374
+ curravg+= on_vals[signal_stren]
375
+
376
+ avg_ct+=1
377
+ if "rx" in possible_states["controller"]:
378
+ curravg+=possible_states["controller"]["rx"]
379
+ avg_ct+=1
380
+ current += safe_division(curravg, avg_ct)
381
+ elif "mobile_radio" in bt_event.updates:
382
+ current+= possible_states["idle"] if "idle" in possible_states else 0
383
+ # cpu
384
+ elif comp_name == "cpu":
385
+ # retrieve just the component state
386
+ #if phone has multiple cpu_clusters and that info is present in power profile file
387
+ # only for devices with heterogeneous CPU architectures.
388
+ #print(possible_states)
389
+ #has_multiple_cpu_clusters= "clusters" in possible_states and "cores" in possible_states["clusters"] and len(possible_states["clusters"]["cores"])>1
390
+ #if has_multiple_cpu_clusters:
391
+ #cores_per_cluster = possible_states["clusters"]["cores"]
392
+ # calculate energy per cluster
393
+ #if areInMinCPUFreq(bt_event.updates["cpufreq"] , possible_states):
394
+ # assume is just awake
395
+
396
+ # current += possible_states["awake"]
397
+ # else:
398
+
399
+ # calculate active state
400
+ # current += 0 # possible_states["awake"] if "awake" in possible_states else 0
401
+ # print("TODO Calculate power according to freq")
402
+
403
+
404
+
405
+ # else:
406
+ if "running" in bt_event.updates:
407
+ # is active or just awake
408
+ #if "awake" in possible_states and areInMinCPUFreq(bt_event.updates["cpufreq"] , possible_states):
409
+ #if areInMinCPUFreq(bt_event.updates["cpufreq"] , possible_states):
410
+ # assume is just awake
411
+
412
+ # current += possible_states["awake"]
413
+ #else:
414
+ # calculate active state
415
+ # current += 0 # possible_states["awake"] if "awake" in possible_states else 0
416
+ # print("TODO Calculate power according to freq")
417
+ current = "active"
418
+ else:
419
+ #cpu in idle state
420
+ #current+= possible_states["idle"] if "idle" in possible_states else 0
421
+ current = "idle"
422
+
423
+ return current
424
+
425
+ def parseFile(self,filename):
426
+ with open(filename, 'r') as filehandle:
427
+ lines=filehandle.read().splitlines()
428
+ self.parseHistory(lines)
429
+
430
+ #if __name__ == '__main__':
431
+ #if len(sys.argv)>1:
432
+ #pp = "samples/profiles/power_profile.xml"
433
+ #pp = "samples/profiles/power_profile_pixel3a_grapheneos.xml"
434
+ #x = BatteryStatsParser(powerProfile=pp,timezone="WET")
435
+ #x.parseFile(sys.argv[1])
436
+
437
+