-
Notifications
You must be signed in to change notification settings - Fork 121
/
initializer.py
1750 lines (1597 loc) · 67.7 KB
/
initializer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
新的启动函数,支持Batch,schedule操作等。
"""
import multiprocessing
import pathlib
import sys
import time
import traceback
from multiprocessing import Process
from multiprocessing.managers import SyncManager
from queue import PriorityQueue
from random import random
from typing import List, Tuple, Optional, Dict, Union
import adbutils
from automator_mixins._base import Multithreading, ForceKillException, FastScreencutException
from automator_mixins._captcha import CaptionSkip
from core.Automator import Automator
from core.constant import USER_DEFAULT_DICT as UDD
from core.emulator_port import *
from core.launcher import LauncherBase, LDLauncher, BSLauncher
from core.pcr_config import GC, enable_pause, debug, bluestacks5_hyperv_conf_path
from core.pcr_config import enable_auto_find_emulator, emulator_ports, selected_emulator, max_reboot, \
trace_exception_for_debug, sentstate, emulator_console, emulator_id, quit_emulator_when_free, \
max_free_time, adb_dir, add_adb_to_path, captcha_skip, captcha_userstr, ignore_serials, \
restart_adb_during_emulator_launch_delay
from core.safe_u2 import OfflineException, ReadTimeoutException, random_sleep, run_adb
from core.usercentre import AutomatorRecorder, parse_batch, list_all_flags
from core.utils import diffday, PrintToStr
from core.safe_u2 import run_adb
if add_adb_to_path:
if sys.platform == "win32":
abs_dir = os.path.abspath(adb_dir)
# print("添加到环境变量:", abs_dir)
env = os.getenv("path")
env = abs_dir + ";" + env
os.putenv("path", env)
def _connect(): # 连接adb与uiautomator
global FIRST_CONNECT
try:
# 清理日志
pcr_log('admin').handle_logs()
except FileNotFoundError:
pass
try:
if enable_auto_find_emulator:
port_list = set(check_known_emulators())
os.system("taskkill /im adb.exe /f")
# print(port_list)
print("自动搜寻模拟器:" + str(port_list))
for port in port_list:
run_adb(f'connect {emulator_ip}:{str(port)}')
elif selected_emulator == "蓝叠5HyperV":
conf = open(bluestacks5_hyperv_conf_path)
line = conf.readline()
conf_key = "bst.instance.Nougat64.status.adb_port"
while line:
if not line.startswith(conf_key):
line = conf.readline()
continue
run_adb(f'connect {emulator_ip}:{line[len(conf_key) + 2:len(line) - 2]}')
break
conf.close()
elif len(emulator_ports) != 0:
for port in emulator_ports:
run_adb(f'connect {emulator_ip}:{str(port)}')
else:
run_adb("devices") # adb devices = adb start-server
# os.system 函数正常情况下返回是进程退出码,0为正常退出码,其余为异常
"""
if os.system('cd adb & adb connect ' + selected_emulator) != 0:
pcr_log('admin').write_log(level='error', message="连接模拟器失败")
exit(1)
"""
# os.system(f"cd {adb_dir} & adb kill-server")
except Exception as e:
pcr_log('admin').write_log(level='error', message='连接失败, 原因: {}'.format(e))
exit(1)
# https://blog.csdn.net/qq_45587822/article/details/105950260
class MyManager(SyncManager):
pass
class MyPriorityQueue(PriorityQueue):
def get_attribute(self, name):
return getattr(self, name)
def _get_manager():
MyManager.register("PriorityQueue", MyPriorityQueue)
m = MyManager()
m.start()
return m
def time_period_format(tm) -> str:
tm = int(tm)
if tm < 60:
return f"{tm}s"
elif tm < 3600:
return f"{tm // 60}m {tm % 60}s"
elif tm < 3600 * 24:
return f"{tm // 3600}h {(tm % 3600) // 60}m {tm % 60}s"
else:
return f"{tm // (3600 * 24)}d {(tm % (3600 * 24)) // 3600}h {(tm % 3600) // 60}m {tm % 60}s"
class Device:
"""
设备类,存储设备状态等。
之后可以扩充雷电的开关操作
"""
# 设备状态
DEVICE_OFFLINE = 0 # 离线
DEVICE_AVAILABLE = 1 # 可用
DEVICE_BUSY = 2 # 正忙
def __init__(self, serial: Optional[str] = None, id: Optional[int] = None, launcher: Optional[LauncherBase] = None):
assert (serial is not None or (id is not None and launcher is not None)), \
"必须填写serial,或者id与launcher!"
self.serial = serial
self.state = 0
self._in_process = False # 是否已经进入多进程
self.cur_acc = "" # 当前正在处理的账号
self.cur_rec = "" # 当前正在处理的存档目录
self.time_wake = 0 # 上次开机时间
self.time_busy = 0 # 上次忙碌时间
self.a: Optional[Automator] = None # Automator,先不启动,在子进程中启动
self.emulator_id: Optional[int] = id # 模拟器ID
self.emulator_launcher: Optional[LauncherBase] = launcher # 模拟器控制器
if self.emulator_launcher is not None:
if self.serial is None:
self.serial = self.emulator_launcher.id_to_serial(self.emulator_id)
self.device = adbutils.adb.device(self.serial)
def with_emulator(self):
return self.emulator_launcher is not None
def launch_emulator(self, block=False, adb_restart_fun=None):
if self.emulator_launcher is not None:
if not self.emulator_launcher.is_running(self.emulator_id):
self.emulator_launcher.launch(self.emulator_id, block)
if block:
return self.wait_for_healthy(adb_restart_fun=adb_restart_fun)
if self.a is not None:
self.a.fastscreencut_retry = 0 # 重置快速截图次数
return True
def quit_emulator(self):
if self.emulator_launcher is not None:
self.emulator_launcher.quit(self.emulator_id)
def restart_emulator(self, block=False, adb_restart_fun=None):
if self.emulator_launcher is not None:
if self.emulator_launcher is not None:
self.emulator_launcher.restart(self.emulator_id, block)
if block:
self.wait_for_healthy(adb_restart_fun=adb_restart_fun)
def is_connected(self):
try:
self.device.get_state()
except:
return False
else:
return True
def is_healthy(self):
try:
if not self.is_connected():
return False
out = self.device.shell("dumpsys activity | grep mResume", timeout=5)
if "Error" in out:
return False
except:
return False
return True
def wait_for_healthy(self, timeout=360, adb_restart_fun=None):
last = time.time()
cnt = 0
while time.time() - last < timeout:
if self.is_connected():
if self.is_healthy():
return True
time.sleep(1)
cnt += 1
if cnt % 10 == 0 and adb_restart_fun is not None:
adb_restart_fun()
return False
def start_u2(self):
self.device.shell("/data/local/tmp/atx-agent server -d", timeout=5)
def init(self):
self.state = self.DEVICE_AVAILABLE
self.time_busy = 0
self.time_wake = time.time()
def start(self):
if self.state == self.DEVICE_OFFLINE:
self.init()
self.state = self.DEVICE_BUSY
self.time_busy = time.time()
def register(self, acc="", rec=""):
self.cur_acc = acc
self.cur_rec = rec
def stop(self):
self.state = self.DEVICE_AVAILABLE
self.time_busy = 0
self.cur_acc = ""
self.cur_rec = ""
def offline(self):
self.state = self.DEVICE_OFFLINE
self.time_wake = 0
def in_process(self):
self._in_process = True
def out_process(self):
self._in_process = False
class AllDevices:
"""
全部设备控制类,包含了包括connect在内的一些操作。
"""
def __init__(self):
self.devices: Dict[str, Device] = {} # serial : device
self.emulator_launcher: Optional[LauncherBase] = None
self.last_adb_restart_time = 0 # 用于全局adb_restart
def global_restart_adb(self, tm=None):
if tm is None:
tm = restart_adb_during_emulator_launch_delay
if tm == 0:
return
t = time.time()
if t - self.last_adb_restart_time > tm:
if debug:
pcr_log("AllDevices").write_log("debug", f"触发adb重启!冷却时间:{tm}")
random_sleep()
run_adb("kill-server", timeout=60)
random_sleep()
run_adb("devices", timeout=60)
self.last_adb_restart_time = time.time()
else:
pass
def add_from_config(self):
if emulator_console != "":
if selected_emulator in ["雷电", "雷神"]:
self.emulator_launcher = LDLauncher()
elif selected_emulator == "蓝叠":
self.emulator_launcher = BSLauncher()
else:
raise Exception(f"不支持的模拟器类型:{selected_emulator}")
for i in emulator_id:
self.add_device(self.emulator_launcher.id_to_serial(i), i, self.emulator_launcher)
def start_all_emulators(self):
if self.emulator_launcher is not None:
self.emulator_launcher.start_all(adb_restart_fun=self.global_restart_adb)
def quit_all_emulators(self):
if self.emulator_launcher is not None:
self.emulator_launcher.quit_all()
def restart_bad_emulators(self):
# 重启已经关闭或者出现故障的
if self.emulator_launcher is not None:
flag = False
for i in emulator_id:
if not self.devices[i].is_healthy():
self.devices[i].restart_emulator(False, adb_restart_fun=self.global_restart_adb)
flag = True
self.emulator_launcher.wait_for_all(adb_restart_fun=self.global_restart_adb)
self.refrush_device_all()
def add_device(self, serial: str, id: int = None, launcher: LauncherBase = None):
"""
添加一个设备,若该设备不存在,则添加;若该设备的状态为offline但已连接,更新状态为available
"""
if serial in ignore_serials:
return False
if serial not in self.devices:
self.devices[serial] = Device(serial, id, launcher)
if self.devices[serial].is_connected():
self.devices[serial].init()
return True
else:
self.devices[serial].offline()
return False
def refresh_device(self, serial):
if serial in self.devices:
if self.devices[serial].is_healthy():
if self.devices[serial].state == Device.DEVICE_OFFLINE:
self.devices[serial].start()
else:
if self.devices[serial].state != Device.DEVICE_OFFLINE:
self.devices[serial].offline()
def refrush_device_all(self):
for s in self.devices:
self.refresh_device(s)
def connect(self):
_connect()
dl = adbutils.adb.device_list()
self.add_from_config()
for d in dl:
self.add_device(d.serial)
def process_method(self, device_message: dict):
serial = device_message["serial"]
method = device_message["method"]
device = self.devices[serial]
if type(method) is str:
device.__getattribute__(method)()
elif type(method) is tuple:
device.__getattribute__(method[0])(*method[1:])
def get(self):
"""
获取一个空闲的设备,若获取失败,返回None
若获取成功,返回device serial,并且该设备被标记为busy
"""
for s, d in self.devices.items():
if d.state == Device.DEVICE_AVAILABLE:
d.start()
return s
return None
def full(self):
"""
判断是否所有设备均空闲
"""
for d in self.devices.values():
if d.state == Device.DEVICE_BUSY:
return False
return True
def put(self, s):
"""
放回一个用完的设备,更新该设备状态
:param s: 设备的Serial
"""
if self.devices[s].is_connected():
self.devices[s].stop()
else:
self.devices[s].offline()
def count_busy(self):
"""
返回当前busy状态的设备数
"""
cnt = 0
for i in self.devices.values():
if i.state == Device.DEVICE_BUSY:
cnt += 1
return cnt
def count_processed(self):
"""
返回当前_in_process的设备总数
"""
cnt = 0
for i in self.devices.values():
if i._in_process:
cnt += 1
return cnt
def list_all_free_devices(self) -> List[Device]:
"""
返回当前全部空闲的设备
"""
L = []
for i in self.devices.values():
if i.state == Device.DEVICE_AVAILABLE:
L += [i]
return L
def get_device_by_id(self, id):
id = int(id)
L = list(self.devices.keys())
return self.devices[L[id]]
def show(self):
"""
显示当前全部设备状态
"""
print("= 设备信息 =")
for ind, (i, j) in enumerate(self.devices.items()):
print("ID", ind, "-", i, ": ", end="")
if j.state == Device.DEVICE_OFFLINE:
print("离线")
elif j.state == Device.DEVICE_AVAILABLE:
print("空闲", " 开机时间", time_period_format(time.time() - j.time_wake))
elif j.state == Device.DEVICE_BUSY:
tm = time.time()
print("正忙", " 开机时间", time_period_format(tm - j.time_wake), " 本次工作时间",
time_period_format(tm - j.time_busy), end="")
if j.cur_acc != "":
print(" 当前任务:账号", j.cur_acc, AutomatorRecorder.get_user_state(j.cur_acc, j.cur_rec), end="")
if j.emulator_launcher is not None:
print(" [自动控制中]", end="")
print()
class PCRInitializer:
"""
PCR启动器,包含进程池逻辑、任务调度方法等。
"""
def __init__(self):
"""
self.available_devices:multiprocessing.queue类型
用于多进程,存放当前已连接但是空闲中的设备。queue[str]
self.devices_state:字典类型,存储设备信息。
{device_str : state_dict}
self.tasks:queue.PriorityQueue类型,按优先级从高到低排序一系列任务
"""
self.devices = AllDevices()
self.mgr = _get_manager()
self.tasks: MyPriorityQueue = self.mgr.__getattribute__("PriorityQueue")() # 优先级队列
self.out_queue: multiprocessing.Queue = self.mgr.Queue() # 外部接收信息的队列
self.in_queue: Dict[Device, multiprocessing.Queue] = {} # 内部接收信息的队列
self.listening = False # 侦听线程是否开启
self.finished_tasks = [] # 已经完成的任务
self.running_tasks = [] # 正在进行的任务 任务:设备
self.paused_tasks = [] # 暂停的任务
self.log_queue = queue.Queue() # 消息队列
self.emulator_keeper_switch = 0 # 0 关闭 1 开启
def is_free(self):
"""
判断当前是否处于空闲状态(队列中无任务,设备均空闲)
"""
return len(self.tasks.get_attribute("queue")) == 0 and self.devices.count_busy() == 0
def _emulator_keeper(self):
"""
!弃用!
模拟器检查线程
如果模拟器故障,则将其重启
"""
if self.emulator_keeper_switch == 1:
self.write_log("模拟器检查线程开启")
while self.emulator_keeper_switch == 1:
time.sleep(5)
self.devices.restart_bad_emulators()
self.write_log("模拟器检查线程已退出")
def start_emulator_keeper(self):
"""
!弃用!
启动模拟器检查线程
"""
if self.emulator_keeper_switch == 0:
threading.Thread(target=PCRInitializer._emulator_keeper, args=(self,), daemon=True).start()
else:
self.write_log("模拟器检查线程已经启动,请勿重复开启")
def stop_emulator_keeper(self):
"""
!弃用!
关闭模拟器检查线程
"""
self.emulator_keeper_switch = 0
def connect(self):
"""
连接设备,初始化设备
"""
self.devices.connect()
def write_log(self, msg):
self.log_queue.put(msg)
def get_log(self):
try:
return self.log_queue.get(block=False)
except queue.Empty:
return None
def _add_task(self, task):
"""
队列中添加任务6元组
"""
rs = AutomatorRecorder(task[1], task[3]).get_run_status()
if task[5] and rs["finished"]:
if task not in self.finished_tasks:
self.finished_tasks += [task]
else:
try:
if task not in self.tasks.get_attribute("queue"):
self.tasks.put(task)
except Exception as e:
pass
def add_task(self, task: Union[Tuple[int, str, str, dict], Tuple[int, str, str]], continue_, rec_addr,
rand_pri=False):
"""
向优先级队列中增加一个task
该task为六元组,(priority, account, taskname,rec_addr, task, continue_)
"""
if len(task) == 3:
task = (
0 - task[0] - rand_pri * (random() / 2 - 1), task[1], task[2], rec_addr,
AutomatorRecorder.gettask(task[2]),
continue_)
else:
task = (
0 - task[0] - rand_pri * (random() / 2 - 1), task[1], task[2], rec_addr, task[3], continue_) # 最大优先队列
self._add_task(task)
def add_tasks(self, tasks: list, continue_, rec_addr, rand_pri=False):
"""
向优先级队列中增加一系列tasks
该task为六元组,(priority, account, taskname,rec_addr, task, continue_)
rand_pri:随机增加一个0~0.5的优先级
"""
for task in tasks:
self.add_task(task, continue_, rec_addr, rand_pri)
def pause_tasks(self):
"""
清空任务队列
"""
while not self.tasks.empty():
try:
tsk = self.tasks.get(False)
if tsk is not None:
self.paused_tasks += [tsk]
except queue.Empty:
continue
self.tasks.task_done()
@staticmethod
def run_task(device: Device, account: str, task: dict, continue_: bool, rec_addr: str):
"""
让device执行任务:account做task
:param device: 设备名
:param account: 账户名
:param task: 任务名
:param continue_: 是否继续上次中断的位置
:param rec_addr: 进度保存目录
:return 是否成功执行
"""
a = device.a
try:
if sys.platform == "win32":
import keyboard
keyboard.release('p')
Multithreading({}).state_sent_resume()
a.init_device(device.serial)
a.init_account(account, rec_addr)
a.start()
a.log.write_log("info", f"即将登陆: 用户名 {account}") # 显然不需要输出密码啊喂!
a.start_th()
a.start_async()
a.start_shuatu()
out = a.RunTasks(task, continue_, max_reboot, rec_addr=rec_addr)
if a.pause_after_task:
a.pause_after_task = False
a.log.write_log("info", "检测到[任务结束后暂停]flag已经激活,且任务已经结束,已经暂停,并将该flag移除。"
"使用resume命令解除暂停。解除暂停后,脚本将继续执行切换用户的命令。")
a.freeze = True
while a.freeze:
time.sleep(1)
if out:
a.change_acc()
return out
except FastScreencutException as e:
raise e
except ForceKillException as e:
raise e
except OfflineException as e:
pcr_log(account).write_log('error', message=f'initialize-检测到设备离线:{e}')
return False
except ReadTimeoutException as e:
pcr_log(account).write_log('error', message=f'initialize-检测到连接超时:{e}')
return False
except Exception as e:
pcr_log(account).write_log('error', message=f'initialize-检测出异常:{type(e)} {e}')
if trace_exception_for_debug:
tb = traceback.format_exc()
pcr_log(account).write_log('error', message=tb)
try:
if a is not None:
a.fix_reboot(False)
return False
except Exception as e:
pcr_log(account).write_log('error', message=f'initialize-自动重启失败:{type(e)} {e}')
if trace_exception_for_debug:
tb = traceback.format_exc()
pcr_log(account).write_log('error', message=tb)
return False
finally:
if a is not None:
a.stop_th()
@staticmethod
def _do_process(device: Device, task_queue, in_queue, out_queue):
"""
执行run_task的消费者进程
device: 传入的设备信息
task_queue: 任务优先级队列
in_queue: 向内传递消息的队列
out_queue: 向外消息传递的队列
"""
flag = {"exit": False}
def adb_restart_fun():
out_queue.put({"action": {
"serial": device.serial,
"action": "restart_adb",
"tm": None,
}})
time.sleep(1)
run_adb("devices")
def _listener():
while flag["exit"] == False:
msg = in_queue.get()
if msg == "close game at now!!!":
device.a.app_stop('com.bilibili.priconne')
if msg == "quit":
flag["exit"] = True
break
if msg == "forcekill":
flag["exit"] = True
if device.a is not None:
device.a.force_kill()
break
if type(msg) is dict and "method" in msg:
try:
if msg["method"] == "config":
# 修改配置
GC.set(msg["option"], msg["value"])
print(device.serial, "设置", msg["option"], "属性为", msg["value"])
elif msg["method"] == "exec":
# 执行语句
flagg = 0
try:
out = eval(msg['command'])
print(out)
except:
flagg = 1
if flagg:
try:
exec(msg["command"])
except Exception as e:
print("执行语句产生错误:", e)
traceback.print_exc()
elif msg["method"] == "debug":
# 开关debug
if msg["target"] == "__all__":
# 对全部进行操作
GC.set("debug", msg["value"])
print(device.serial, "设置debug属性为", msg["value"])
else:
# 指定某个模块操作
module_name = msg["target"]
if module_name in sys.modules:
module = sys.modules[module_name]
if hasattr(module, "debug"):
setattr(module, "debug", msg["value"])
else:
print(device.serial, "模块", module_name, "不含debug信息。")
else:
print(device.serial, "不存在的模块名:", module_name, "!")
elif msg["method"] == "show_all_module":
mypath = str(pathlib.Path().absolute())
def is_pcr_pack(module, mypath):
file_name = getattr(module, "__file__", "")
if not isinstance(file_name, str):
return False
if file_name.startswith(mypath):
return True
return False
for name, module in sys.modules.items():
if is_pcr_pack(module, mypath):
if hasattr(module, "debug"):
print(device.serial, " - ", name, "DEBUG状态:", getattr(module, "debug"))
elif msg["method"] == "freeze":
if enable_pause:
print(device.serial, " - ", "enable_pause已经启用,请使用shift+P暂停。")
else:
device.a.freeze = msg["value"]
elif msg["method"] == "taskindex":
if not hasattr(device.a, "ms") or device.a.ms is None:
print(device.serial, " - 暂无任务")
continue
cur_id = device.a.ms.current_id
if cur_id in device.a._task_index:
cur_title = device.a._task_index[cur_id]
print(device.serial, " - 当前任务:", cur_title)
print(device.serial, " - 任务列表")
for idx, tit in device.a._task_index.items():
if idx == cur_id:
print("-> ", end="")
else:
print(" ", end="")
print(idx, ":", tit)
elif msg["method"] == "skip":
device.a.SkipTask(msg["to_id"])
elif msg["method"] == "restart":
device.a.RestartTask()
elif msg["method"] == "u2rec":
Q = device.a.d.R.get()
print(device.serial, " - U2 执行记录:")
for q in Q:
print(q)
elif msg["method"] == "rec":
print(device.serial, " - Automator 执行记录:")
for q in device.a.output_debug_info(msg["running"]):
print(q)
elif msg["method"] == "pause_after_task":
device.a.pause_after_task = not device.a.pause_after_task
print(device.serial, " - [任务结束后暂停]flag:", "已激活" if device.a.pause_after_task else "未激活")
else:
print(device.serial, " - 不认识的msg!", msg)
except Exception as e:
print(device.serial, "在执行", msg, "时遇到错误:", e)
time.sleep(1)
serial = device.serial
threading.Thread(target=_listener, daemon=True).start()
last_busy_time = time.time()
device_on = False
app_on = True
while not flag["exit"]:
try:
if app_on and time.time() - last_busy_time > max_free_time:
app_on = False
if device.a is not None:
device.a.app_stop('com.bilibili.priconne')
if quit_emulator_when_free and device_on \
and device.with_emulator() and time.time() - last_busy_time > max_free_time:
device_on = False
device.quit_emulator()
out_queue.put({"device_status": {"serial": serial, "status": "sleep"}})
out_queue.put({"device": {"serial": serial, "method": "offline"}})
_task = task_queue.get(False)
except queue.Empty:
time.sleep(1)
continue
app_on = True
if device.a is None:
device.a = Automator("debug", output_msg_fun=out_queue.put)
priority, account, task_name, rec_addr, task, continue_ = _task
out_queue.put({"task": {"status": "start", "task": _task, "device": serial}})
out_queue.put({"device": {"serial": serial, "method": "start"}})
out_queue.put({"device": {"serial": serial, "method": ("register", account, rec_addr)}})
while not flag["exit"]: # 这个循环控制自动重启模拟器
device_on = True
if device.with_emulator() and not device.is_connected():
out_queue.put({"device_status": {"serial": serial, "status": "launch"}})
if not device.launch_emulator(True, adb_restart_fun=adb_restart_fun):
out_queue.put({"device_status": {"serial": serial, "status": "launch_fail"}})
out_queue.put({"device": {"serial": serial, "method": "offline"}})
out_queue.put({"task": {"status": "retry", "task": _task, "device": serial}})
if device.with_emulator():
device.quit_emulator()
flag["exit"] = True
break
else:
out_queue.put({"device_status": {"serial": serial, "status": "launch_success"}})
try:
res = PCRInitializer.run_task(device, account, task, continue_, rec_addr)
if res: # 任务执行成功
out_queue.put({"task": {"status": "success", "task": _task, "device": serial}})
out_queue.put({"device": {"serial": serial, "method": "stop"}})
break
out_queue.put({"task": {"status": "fail", "task": _task, "device": serial}})
if not device.is_healthy():
# 可能模拟器断开
if device.with_emulator():
out_queue.put({"device_status": {"serial": serial, "status": "restart"}})
out_queue.put({"device": {"serial": serial, "method": "offline"}})
device.restart_emulator(True, adb_restart_fun=adb_restart_fun)
# 尝试重启模拟器
if device.wait_for_healthy(adb_restart_fun=adb_restart_fun):
out_queue.put({"device_status": {"serial": serial, "status": "restart_success"}})
device.start_u2()
continue # 重启成功
else:
out_queue.put({"device_status": {"serial": serial, "status": "restart_fail"}})
# 任务失败,模拟器断开
out_queue.put({"device": {"serial": serial, "method": "offline"}})
out_queue.put({"task": {"status": "retry", "task": _task, "device": serial}})
if device.with_emulator():
device.quit_emulator()
flag["exit"] = True
break
else:
out_queue.put({"device": {"serial": serial, "method": "stop"}})
break
except FastScreencutException:
# 快速截图错误,尝试重启
if device.with_emulator():
out_queue.put({"device_status": {"serial": serial, "status": "restart"}})
out_queue.put({"device": {"serial": serial, "method": "offline"}})
device.restart_emulator(True, adb_restart_fun=adb_restart_fun)
# 尝试重启模拟器
if device.wait_for_healthy(adb_restart_fun=adb_restart_fun):
out_queue.put({"device_status": {"serial": serial, "status": "restart_success"}})
device.start_u2()
continue # 重启成功
else:
out_queue.put({"device_status": {"serial": serial, "status": "restart_fail"}})
# 任务失败,模拟器断开
out_queue.put({"device": {"serial": serial, "method": "offline"}})
out_queue.put({"task": {"status": "retry", "task": _task, "device": serial}})
if device.with_emulator():
device.quit_emulator()
flag["exit"] = True
break
except ForceKillException:
# 强制退出
out_queue.put({"task": {"status": "forcekill", "task": _task, "device": serial}})
if device.is_healthy():
out_queue.put({"device": {"serial": serial, "method": "stop"}})
else:
out_queue.put({"device": {"serial": serial, "method": "offline"}})
flag["exit"] = True
break
last_busy_time = time.time()
out_queue.put({"device": {"serial": serial, "method": "out_process"}})
def process_task_method(self, msg):
priority, account, task_name, rec_addr, task, continue_ = msg["task"]
if msg["status"] in ["fail", "success"]:
self.finished_tasks += [msg["task"]]
if msg["task"] in self.running_tasks:
del self.running_tasks[self.running_tasks.index(msg["task"])]
if msg["status"] == "fail":
self.write_log(
f"账号{account}执行失败!设备:{msg['device']} 状态:{AutomatorRecorder.get_user_state(account, rec_addr)}")
else:
self.write_log(f"账号{account}执行成功!")
elif msg["status"] == "start":
self.write_log(f"账号{account}开始执行,设备:{msg['device']} 进度存储目录 {rec_addr}")
if msg["task"] not in self.running_tasks:
self.running_tasks += [msg["task"]]
elif msg["status"] == "retry":
if msg["task"] in self.running_tasks:
del self.running_tasks[self.running_tasks.index(msg["task"])]
self._add_task(msg["task"])
self.write_log(f"账号{account}重新进入任务队列,进度存储目录 {rec_addr}")
elif msg["status"] == "forcekill":
if msg["task"] in self.running_tasks:
del self.running_tasks[self.running_tasks.index(msg["task"])]
self.write_log(
f"账号{account}强制退出!设备:{msg['device']} 状态:{AutomatorRecorder.get_user_state(account, rec_addr)}")
self.paused_tasks += msg["task"]
def process_status_msg(self, msg):
serial = msg["serial"]
status = msg["status"]
if status == "restart":
self.write_log(f"设备 {serial} 重启中……")
elif status == "launch":
self.write_log(f"设备 {serial} 启动中……")
elif status == "restart_success":
self.write_log(f"设备 {serial} 重启成功!")
elif status == "restart_fail":
self.write_log(f"设备 {serial} 重启失败!")
elif status == "sleep":
self.write_log(f"设备 {serial} 闲置,自动关闭")
elif status == "launch_success":
self.write_log(f"设备 {serial} 启动成功!")
elif status == "launch_fail":
self.write_log(f"设备 {serial} 启动失败!")
def process_action_msg(self, msg):
serial = msg.setdefault("serial", "???")
action = msg["action"]
if action == "restart_adb":
tm = msg.setdefault("tm", 2)
self.devices.global_restart_adb(tm)
def _listener(self):
"""
侦听线程,获取子进程从out_queue中返回的消息
"""
self.listening = True
while True:
msg = self.out_queue.get()
# print("listen",msg)
if msg is None:
break
if "device" in msg:
self.devices.process_method(msg["device"])
if "task" in msg:
self.process_task_method(msg["task"])
if "device_status" in msg:
self.process_status_msg(msg["device_status"])
if "action" in msg:
self.process_action_msg(msg["action"])
self.listening = False
def start(self):
"""
进入分配任务给空闲设备的循环
"""
if not self.listening:
# 打开侦听线程
threading.Thread(target=PCRInitializer._listener, args=(self,), daemon=True).start()
while self.listening == 0:
pass
for d in self.devices.devices.values():
if not d._in_process:
d._in_process = True
self.in_queue[d] = self.mgr.Queue()
Process(target=PCRInitializer._do_process,
kwargs=dict(device=d, task_queue=self.tasks, in_queue=self.in_queue[d],
out_queue=self.out_queue), daemon=True).start()
def send_message(self, device: Optional[Device] = None, msg=None):
if device is None:
# BoardCast
for d in self.in_queue:
self.send_message(d, msg)
if device not in self.in_queue:
return
target = self.in_queue[device]
target.put(msg)
def stop_device(self, device=None):
self.send_message(device, "quit")
def forcekill_device(self, device=None):
self.send_message(device, "forcekill")
def change_config(self, option, value, device=None):
self.send_message(device, {"method": "config", "option": option, "value": value})
def start_debug(self, value, module="__all__", device=None):
self.send_message(device, {"method": "debug", "value": value, "target": module})
def show_all_module_debug(self, device=None):
self.send_message(device, {"method": "show_all_module"})
def exec_command(self, command, device=None):
self.send_message(device, {"method": "exec", "command": command})
def exec_script(self, script_file, device=None):
try:
command = open(script_file, "r", encoding="utf-8").read()
self.send_message(device, {"method": "exec", "command": command})
except Exception as e:
print("读取文件错误!", e)
def set_freeze(self, value, device=None):
self.send_message(device, {"method": "freeze", "value": value})
def pause_after_task(self, device=None):
self.send_message(device, {"method": "pause_after_task"})
def show_task_index(self, device=None):
self.send_message(device, {"method": "taskindex"})
def skip_task(self, to_id=None, device=None):
self.send_message(device, {"method": "skip", "to_id": to_id})
def restart_task(self, device=None):
self.send_message(device, {"method": "restart"})
def show_u2_record(self, device=None):
self.send_message(device, {'method': 'u2rec'})
def show_debug_record(self, running=False, device=None):
self.send_message(device, {'method': 'rec', 'running': running})
def close_game(self, device=None):
self.send_message(device, "close game at now!!!")