Skip to content

Commit 1e2179c

Browse files
committed
removed all globals
removed TPClient and g_log as globals and created a new class called TPClientClass which is referred to as TPC
1 parent beb93af commit 1e2179c

File tree

1 file changed

+80
-76
lines changed

1 file changed

+80
-76
lines changed

src/process_checker.py

Lines changed: 80 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# Created by @Gitago for TouchPortal
33
# Jan, 2023
44

5+
## If users ever want multiple PIDS for the .exe we can make an action take it as an argument and then when user selects .exe it will show all the PIDs for that .exe and user can select which one they want to monitor
6+
57

68
## BUGS
79
## when process is checked with a 0 timer it is still counting as an active monitor although its only checking it once and stopping..
@@ -40,10 +42,6 @@ def add_to_choiceList(self, item):
4042
def add_to_dict(self, key, value):
4143
self.process_monitor_dict[key] = value
4244

43-
PM = ProcessMonitorData()
44-
#process_monitor_choiceList = []
45-
#process_monitor_dict = {}
46-
4745
class ProcessChecker:
4846
def __init__(self, process_name):
4947
self.process_name = process_name
@@ -62,21 +60,16 @@ def time_completion(self, data, the_process):
6260
def the_task(self, process_name, the_process):
6361
process_checked = self.is_running()
6462

65-
66-
# global process_monitor_choiceList
67-
68-
# print("This is process checked the is_running stuff", process_checked)
69-
7063
if process_checked == False:
7164
## Setting Status to blank so it will trigger every time its checked
7265

73-
TPClient.createState(stateId=PLUGIN_ID + f".state.{self.process_name}.process_info.status", description=f"PM | {self.process_name} - status", value="", parentGroup=str(self.process_name))
66+
TPC.TPClient.createState(stateId=PLUGIN_ID + f".state.{self.process_name}.process_info.status", description=f"PM | {self.process_name} - status", value="", parentGroup=str(self.process_name))
7467

7568
for x in ['pid', 'username', 'cpu_percent', 'memory_percent', 'cmdline', 'create_time']:
76-
TPClient.createState(stateId=PLUGIN_ID + f".state.{self.process_name}.process_info.{x}", description=f"PM | {self.process_name} - {x}", value="", parentGroup=str(self.process_name))
69+
TPC.TPClient.createState(stateId=PLUGIN_ID + f".state.{self.process_name}.process_info.{x}", description=f"PM | {self.process_name} - {x}", value="", parentGroup=str(self.process_name))
7770

7871
# Updating Status to "Closed" since the process appears to not be running
79-
TPClient.createState(stateId=PLUGIN_ID + f".state.{self.process_name}.process_info.status", description=f"PM | {self.process_name} - status", value="Closed", parentGroup=str(self.process_name))
72+
TPC.TPClient.createState(stateId=PLUGIN_ID + f".state.{self.process_name}.process_info.status", description=f"PM | {self.process_name} - status", value="Closed", parentGroup=str(self.process_name))
8073

8174
if process_checked:
8275
PM.add_to_dict(self.process_name, the_process)
@@ -87,15 +80,15 @@ def the_task(self, process_name, the_process):
8780
# Checking to see if the Process monitor Choice List is the same, if so we dont update it
8881
if PM.process_monitor_choiceList != the_list:
8982
## submitted a PR for this to be added to the API by default
90-
TPClient.choiceUpdate(choiceId=PLUGIN_ID + ".act.process_name.stop", values=the_list)
83+
TPC.TPClient.choiceUpdate(choiceId=PLUGIN_ID + ".act.process_name.stop", values=the_list)
9184

9285
PM.add_to_choiceList(the_list)
9386
# process_monitor_choiceList = the_list
9487

9588
## update a state showing how many values are in the list minus the "ALL" value
96-
TPClient.stateUpdate(stateId=PLUGIN_ID + ".state.process_monitor.count", stateValue=str(len(the_list) - 1))
89+
TPC.TPClient.stateUpdate(stateId=PLUGIN_ID + ".state.process_monitor.count", stateValue=str(len(the_list) - 1))
9790

98-
g_log.debug(f"{the_process.process_name} is running")
91+
TPC.g_log.debug(f"{the_process.process_name} is running")
9992

10093
for x in process_checked:
10194
if x == 'memory_percent':
@@ -110,7 +103,7 @@ def the_task(self, process_name, the_process):
110103
process_checked[x] = create_time_datetime.strftime("%m/%d/%Y [%I:%M:%S %p]")
111104

112105
## use a thread to create sttes as fast as possible
113-
TPClient.createState(stateId=PLUGIN_ID + f".state.{the_process.process_name}.process_info.{x}", description=f"PM | {the_process.process_name} - {x}", value=str(process_checked.get(x, "None")), parentGroup=str(the_process.process_name))
106+
TPC.TPClient.createState(stateId=PLUGIN_ID + f".state.{the_process.process_name}.process_info.{x}", description=f"PM | {the_process.process_name} - {x}", value=str(process_checked.get(x, "None")), parentGroup=str(the_process.process_name))
114107

115108

116109
def is_running(self):
@@ -132,7 +125,7 @@ def is_running(self):
132125

133126
def check_continuously(self, interval, process_name, the_process):
134127
while self.should_continue:
135-
g_log.debug("Checking if " + self.process_name + " is running")
128+
TPC.g_log.debug("Checking if " + self.process_name + " is running")
136129

137130
self.the_task(process_name = process_name, the_process=the_process)
138131
time.sleep(interval)
@@ -145,26 +138,49 @@ def stop(self):
145138

146139

147140

148-
### The TP Client
149-
try:
150-
TPClient = TP.Client(
151-
pluginId = PLUGIN_ID,
152-
sleepPeriod = 0.05,
153-
autoClose = True,
154-
checkPluginId = True,
155-
maxWorkers = 4,
156-
updateStatesOnBroadcast = False,
157-
)
158-
except Exception as e:
159-
sys.exit(f"Could not create TP Client, exiting. Error was:\n{repr(e)}")
141+
## ### The TP Client
142+
## try:
143+
## TPClient = TP.Client(
144+
## pluginId = PLUGIN_ID,
145+
## sleepPeriod = 0.05,
146+
## autoClose = True,
147+
## checkPluginId = True,
148+
## maxWorkers = 4,
149+
## updateStatesOnBroadcast = False,
150+
## )
151+
## except Exception as e:
152+
## sys.exit(f"Could not create TP Client, exiting. Error was:\n{repr(e)}")
153+
class TPClientClass:
154+
def __init__(self, pluginId, sleepPeriod=0.05, autoClose=True, checkPluginId=True, maxWorkers=4, updateStatesOnBroadcast=False):
155+
self.pluginId = pluginId
156+
self.sleepPeriod = sleepPeriod
157+
self.autoClose = autoClose
158+
self.checkPluginId = checkPluginId
159+
self.maxWorkers = maxWorkers
160+
self.updateStatesOnBroadcast = updateStatesOnBroadcast
161+
try:
162+
self.TPClient = TP.Client(
163+
pluginId=self.pluginId,
164+
sleepPeriod=self.sleepPeriod,
165+
autoClose=self.autoClose,
166+
checkPluginId=self.checkPluginId,
167+
maxWorkers=self.maxWorkers,
168+
updateStatesOnBroadcast=self.updateStatesOnBroadcast
169+
)
170+
self.g_log = getLogger()
171+
except Exception as e:
172+
sys.exit(f"Could not create TP Client, exiting. Error was:\n{repr(e)}")
173+
174+
160175

176+
TPC = TPClientClass(PLUGIN_ID)
161177

162178
# Crate the global logger
163-
g_log = getLogger()
179+
#g_log = getLogger()
164180

165181

166182

167-
@TPClient.on(TP.TYPES.onNotificationOptionClicked)
183+
@TPC.TPClient.on(TP.TYPES.onNotificationOptionClicked)
168184
def check_noti(data):
169185
if data['optionId'] == PLUGIN_ID+ '.update.download':
170186
github_check = TP.Tools.updateCheck("GitagoGaming",GITHUB_URL)
@@ -173,31 +189,30 @@ def check_noti(data):
173189

174190

175191

176-
@TPClient.on(TP.TYPES.onConnect)
192+
@TPC.TPClient.on(TP.TYPES.onConnect)
177193
def onConnect(data):
178-
g_log.info(f"Connected to TP v{data.get('tpVersionString', '?')}, plugin v{data.get('pluginVersion', '?')}.")
179-
g_log.debug(f"Connection: {data}")
194+
TPC.g_log.info(f"Connected to TP v{data.get('tpVersionString', '?')}, plugin v{data.get('pluginVersion', '?')}.")
195+
TPC.g_log.debug(f"Connection: {data}")
180196
if settings := data.get('settings'):
181197
handleSettings(settings, True)
182198

183199
plugin_update_check(data)
184-
TPClient.stateUpdate(stateId=PLUGIN_ID + ".state.process_monitor.count", stateValue="0")
200+
TPC.TPClient.stateUpdate(stateId=PLUGIN_ID + ".state.process_monitor.count", stateValue="0")
185201

186202

187203

188-
@TPClient.on(TP.TYPES.onSettingUpdate)
204+
@TPC.TPClient.on(TP.TYPES.onSettingUpdate)
189205
def onSettingUpdate(data):
190-
g_log.debug(f"Settings: {data}")
206+
TPC.g_log.debug(f"Settings: {data}")
191207
if (settings := data.get('values')):
192208
handleSettings(settings, False)
193209

194210

195211

196212

197-
@TPClient.on(TP.TYPES.onAction)
213+
@TPC.TPClient.on(TP.TYPES.onAction)
198214
def onAction(data):
199-
# global process_monitor_dict
200-
g_log.debug(f"Action: {data}")
215+
TPC.g_log.debug(f"Action: {data}")
201216

202217

203218
if not (action_data := data.get('data')) or not (aid := data.get('actionId')):
@@ -211,7 +226,7 @@ def onAction(data):
211226
the_process = ProcessChecker(data['data'][0]['value'])
212227
the_process.the_task(process_name=data['data'][0]['value'], the_process=the_process)
213228
else:
214-
g_log.info('Checking every ' + str(data['data'][1]['value']) + ' seconds for ' + data['data'][0]['value'])
229+
TPC.g_log.info('Checking every ' + str(data['data'][1]['value']) + ' seconds for ' + data['data'][0]['value'])
215230
the_process = ProcessChecker(data['data'][0]['value'])
216231

217232
if data['data'][0]['value'] not in PM.process_monitor_dict.keys():
@@ -228,21 +243,21 @@ def onAction(data):
228243
try:
229244
if the_process =="ALL":
230245
for x in PM.process_monitor_dict:
231-
g_log.info(f"Stopping the process monitor for: {x}")
246+
TPC.g_log.info(f"Stopping the process monitor for: {x}")
232247
if x != "ALL":
233248
PM.process_monitor_dict[x].stop()
234-
g_log.info(f"Stopping the process monitor for: {x}")
249+
TPC.g_log.info(f"Stopping the process monitor for: {x}")
235250

236251
PM.process_monitor_dict = {}
237252
else:
238253
PM.process_monitor_dict[the_process].stop()
239254
## delete the key from the dict
240-
g_log.info(f"Stopping the process monitor for: {the_process}")
255+
TPC.g_log.info(f"Stopping the process monitor for: {the_process}")
241256
PM.process_monitor_dict.pop(the_process)
242257

243-
TPClient.stateUpdate(stateId=PLUGIN_ID + ".state.process_monitor.count", stateValue=str(len(PM.process_monitor_dict.keys())))
258+
TPC.TPClient.stateUpdate(stateId=PLUGIN_ID + ".state.process_monitor.count", stateValue=str(len(PM.process_monitor_dict.keys())))
244259
except Exception as e:
245-
g_log.error(f"Error stopping the process: {e}")
260+
TPC.g_log.error(f"Error stopping the process: {e}")
246261

247262

248263

@@ -268,7 +283,7 @@ def plugin_update_check(data):
268283
r = requests.get(f"https://api.github.com/repos/GitagoGaming/{GITHUB_URL}/contents/recent_patchnotes.txt")
269284
message = base64.b64decode(r.json()['content']).decode('ascii')
270285

271-
TPClient.showNotification(
286+
TPC.TPClient.showNotification(
272287
notificationId=PLUGIN_ID + ".update.check",
273288
title=f"{PLUGIN_NAME} Plugin {github_check} is available",
274289
msg=f"A new version of {PLUGIN_NAME} is available and ready to Download. This may include Bug Fixes and or New Features\n\nPatch Notes\n{message} ",
@@ -277,27 +292,15 @@ def plugin_update_check(data):
277292
"title":"Click to Update!"
278293
}])
279294
except Exception as e:
280-
g_log.error("[UPDATE CHECK] Something went wrong checking update", e)
295+
TPC.g_log.error("[UPDATE CHECK] Something went wrong checking update", e)
281296

282297

283298

284299

285300
# Shutdown handler
286-
@TPClient.on(TP.TYPES.onShutdown)
301+
@TPC.TPClient.on(TP.TYPES.onShutdown)
287302
def onShutdown(data):
288-
g_log.info('Received shutdown event from TP Client.')
289-
290-
291-
292-
293-
294-
295-
296-
297-
298-
299-
300-
303+
TPC.g_log.info('Received shutdown event from TP Client.')
301304

302305

303306

@@ -307,7 +310,7 @@ def onShutdown(data):
307310

308311
## The Main + Logging System
309312
def main():
310-
global TPClient, g_log
313+
global g_log
311314
ret = 0 # sys.exit() value
312315

313316
# handle CLI arguments
@@ -329,50 +332,51 @@ def main():
329332
# set up logging
330333
if opts.q:
331334
# no logging at all
332-
g_log.addHandler(NullHandler())
335+
TPC.g_log.addHandler(NullHandler())
333336
else:
334337
# set up pretty log formatting (similar to TP format)
335338
fmt = Formatter(
336339
fmt="{asctime:s}.{msecs:03.0f} [{levelname:.1s}] [{filename:s}:{lineno:d}] {message:s}",
337340
datefmt="%H:%M:%S", style="{"
338341
)
339342
# set the logging level
340-
if opts.d: g_log.setLevel(DEBUG)
341-
elif opts.w: g_log.setLevel(WARNING)
342-
else: g_log.setLevel(INFO)
343+
if opts.d: TPC.g_log.setLevel(DEBUG)
344+
elif opts.w: TPC.g_log.setLevel(WARNING)
345+
else: TPC.g_log.setLevel(INFO)
343346
# set up log destination (file/stdout)
344347
if opts.l:
345348
try:
346349
# note that this will keep appending to any existing log file
347350
fh = FileHandler(str(opts.l))
348351
fh.setFormatter(fmt)
349-
g_log.addHandler(fh)
352+
TPC.g_log.addHandler(fh)
350353
except Exception as e:
351354
opts.s = True
352355
print(f"Error while creating file logger, falling back to stdout. {repr(e)}")
353356
#if not opts.l or opts.s:
354357
# sh = StreamHandler(sys.stdout)
355358
# sh.setFormatter(fmt)
356-
# g_log.addHandler(sh)
359+
# TPC.g_log.addHandler(sh)
357360

358361

359362
try:
360-
TPClient.connect()
361-
g_log.info('TP Client closed.')
363+
TPC.TPClient.connect()
364+
TPC.g_log.info('TP Client closed.')
362365
except KeyboardInterrupt:
363-
g_log.warning("Caught keyboard interrupt, exiting.")
366+
TPC.g_log.warning("Caught keyboard interrupt, exiting.")
364367
except Exception:
365368
from traceback import format_exc
366-
g_log.error(f"Exception in TP Client:\n{format_exc()}")
369+
TPC.g_log.error(f"Exception in TP Client:\n{format_exc()}")
367370
ret = -1
368371
finally:
369-
TPClient.disconnect()
372+
TPC.TPClient.disconnect()
370373

371-
del TPClient
374+
del TPC.TPClient
372375

373-
# g_log.info(f"{TP_PLUGIN_INFO['name']} stopped.")
376+
# TPC.g_log.info(f"{TP_PLUGIN_INFO['name']} stopped.")
374377
return ret
375378

376379

377380
if __name__ == "__main__":
381+
PM = ProcessMonitorData()
378382
sys.exit(main())

0 commit comments

Comments
 (0)