forked from kiibohd/controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
1523 lines (1212 loc) · 44.6 KB
/
common.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
'''
Common functions for Host-side KLL tests
'''
# Copyright (C) 2016-2020 by Jacob Alexander
#
# This file is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this file. If not, see <http://www.gnu.org/licenses/>.
### Imports ###
import copy
import inspect
import linecache
import logging
import sys
from collections import namedtuple
import kiilogger
### Logger ###
logger = kiilogger.get_logger('Tests/common.py')
### Classes ###
class KLLTestRunner:
'''
Runs KLLTest classes
Given a list of test classes objects, run the tests and query the result.
'''
def __init__(self, tests):
'''
Initialize KLLTestRunner objects
@param tests: List of KLLTest objects
'''
# Intialize
self.test_results = []
self.tests = tests
self.overall = None
# Prepare each of the tests
for test in self.tests:
logger.info("Initializing: {}", test.__class__.__name__)
if not test.prepare():
logger.warning("'{}' failed prepare step.".format(test.__class__.__name__))
def run(self):
'''
Run list of tests.
@return: Overall test result.
'''
self.overall = True
for test in self.tests:
testname = test.__class__.__name__
passed = True
logger.info("{}: {}", header("Running"), testname)
if not test.run():
logger.error("'{}' failed.", testname)
self.overall = False
passed = False
logger.info("{} has finished", header(testname))
self.test_results.append((testname, passed, test.results()))
return self.overall
def results(self):
'''
Returns a list of KLLTestResult objects for the tests.
Empty list if the self.run() hasn't been called yet.
@return: List of KLLTestResult objects
'''
return self.test_results
def passed(self):
'''
Returns a list of KLLTestResult objects that have passed.
@return: List of passing KLLTestResult objects
'''
passed = []
for test in self.test_results:
if test[2]:
passed.append(test)
return passed
def failed(self):
'''
Returns a list of KLLTestResult objects that have failed.
@return: List of failing KLLTestResult objects
'''
failed = []
for test in self.test_results:
if not test[2]:
failed.append(test)
return failed
class KLLTestUnitResult:
'''
KLLTestUnitResult Container Class
Contains the results of a single test
'''
def __init__(self, parent, result, unit, layer=None):
'''
Constructor
@param parent: Parent class, i.e. the class of the test
@param result: Boolean, True if test passed, False if it didn't
@param unit: Unit test object
@param layer: Layer under test, set to None if not used
'''
self.parent = parent
self.result = result
self.unit = unit
self.layer = layer
class KLLTest:
'''
KLLTest base class
Derive all tests from this class
'''
def __init__(self, tests=None, test=0):
'''
KLLTest base class constructor
@param tests: Specify number of sub-tests to run, None if all of them.
@param test: Specify a specific test to start from
'''
import interface
# kll.json helper file
self.klljson = interface.control.json_input
# Reference to callback datastructure
self.data = interface.control.data
# Artificial limit for sub-tests
self.test = test
self.tests = tests
# Test Results
self.testresults = []
self.overall = None
# Used by sub-test children for debugging
self.cur_test = None
def prepare(self):
'''
Prepare to run test
Does necessary initialization before attempting to run.
Must be done before run.
@return: True if ready to run test, False otherwise
'''
return True
def run(self):
'''
Evaluate tests
Iterates over prepared tests
@return: Result of the test
'''
import interface
overall = True
curtest = 0
for index, test in enumerate(self.testresults):
# Skip tests before specified index
if index < self.test:
continue
if test.unit.key is not None:
logger.info("{}:{} Layer({}) {} {} -> {}",
header("Sub-test"),
index,
test.layer,
blued(test.unit.__class__.__name__),
test.unit.key,
test.unit.entry['kll'],
)
else:
logger.info("{}:{} Layer({}) {} {}",
header("Sub-test"),
index,
test.layer,
blued(test.unit.__class__.__name__),
test.unit.info,
)
# Set current test, used by sub-test children for debugging
self.cur_test = index
## TODO Run Permutation Start
# Make sure we're in NKRO mode
interface.control.cmd('setKbdProtocol')(1)
# Prepare layer setting
# Run loop, to make sure layer is engaged already
interface.control.cmd('lockLayer')(test.layer)
# Clear any pending trigger events
interface.control.cmd('clearMacroTriggerEventBuffer')()
# Run test, and record result
test.result = test.unit.run()
# Check if the animation stack is not empty
self.clean_animation_stack()
# Cleanup layer manipulations
interface.control.cmd('clearLayers')()
## TODO Run Permutation Start
# Check if test has failed
if not test.result:
overall = False
curtest += 1
if self.tests is not None and curtest >= self.tests:
logger.warning("Stopping at test #{}", curtest)
break
return overall
def clean_animation_stack(self):
'''
Clean animation stack (if necessary)
Only runs if PixelMap module is compiled in.
'''
import interface
if 'Pixel_MapEnabled' in self.klljson['Defines'] and int(self.klljson['Defines']['Pixel_MapEnabled']['value']) == 1:
animation_stack = interface.control.cmd('animationStackInfo')()
if animation_stack.size > 0:
# Print out info on the current state of the stack
logger.warning("Animation Stack is not empty! Cleaning... {} animations", animation_stack.size)
for index in range(animation_stack.size):
elem = animation_stack.stack[0][index]
logger.warning("{} >> index={}, pos={}, subpos={}",
self.klljson['AnimationSettingsIndex'][elem.index]['name'],
elem.index,
elem.pos,
elem.subpos,
)
# Set AnimationControl_Stop, update FrameState then run one loop to reset PixelMap state
interface.control.cmd('setAnimationControl')(3) # AnimationControl_Stop
interface.control.cmd('setFrameState')(2) # FrameState_Update
interface.control.loop(1)
def results(self):
'''
Returns a list of KLLTestResult objects
These objects have the results of each test
'''
return self.testresults
class EvalBase:
'''
Base Eval class
'''
def __init__(self, parent):
'''
Constructor
@param parent: Parent object
'''
self.parent = parent
self.key = None
self.info = ""
class TriggerResultEval(EvalBase):
'''
Takes a trigger:result pair and processes it.
Given a pair, it can be specified to do correct *or* incorrect scheduling.
'''
def __init__(self, parent, json_key, json_entry, schedule=None):
'''
Constructor
@param parent: Parent object
@param json_key: String name for trigger:result pair (unique id for layer)
@param json_entry: Dictionary describing trigger:result pair
@param schedule: Alternate Trigger schedule (Defaults to None), used in destructive testing
'''
EvalBase.__init__(self, parent)
self.key = json_key
self.entry = json_entry
self.schedule = schedule
# PositionStep is the "cycle counter"
# For each element of a sequence, this counter is incremented
# When transitioning between trigger to result, the counter is incremented
# It does not have to follow the internal KLL cycle counter as the schedule may be skewed due to timing constraints
self.positionstep = 0
# Set to True when the test has completed
self.done = False
# Prepare trigger
self.trigger = TriggerEval(self, self.entry['trigger'], self.schedule)
# Prepare result
self.result = ResultMonitor(self, self.entry['result'])
def step(self, positionstep=None):
'''
Evaluate a single step of the Trigger:Result pair
@param positionstep: Start from a given positionstep (will set positionstep)
@return: True if successful/valid execution, False for a failure
'''
import interface as i
# Check for positionstep
if positionstep is not None:
self.positionstep = positionstep
# If positionstep is 0, reset trigger step position
if self.positionstep == 0:
self.trigger.reset()
# Trigger Evaluation
if not self.trigger.done():
self.trigger.trigger_permutations()
if not self.trigger.eval():
return False
# Reset result position, if the trigger has finished
if self.trigger.done():
logger.debug("{} Trigger Complete", self.__class__.__name__)
self.result.reset()
# Result Monitoring
elif not self.result.done():
if not self.result.monitor():
return False
# Mark Trigger:Result as done
if self.result.done():
logger.debug("{} Result Complete", self.__class__.__name__)
self.done = True
# Clear callback history, in case this is a sequence
i.control.data.capability_history.unread()
i.control.data.capability_history.prune()
# Increment step position within libkiibohd
i.control.loop(1)
self.positionstep += 1
# Cleanup step, if necessary
self.trigger.cleanup()
if not self.result.monitor_cleanup():
logger.error("{} Cleanup Monitor failure", self.__class__.__name__)
return False
return True
def run(self):
'''
Evaluate/run Trigger:Result pair
@return: True if successful, False if not
'''
while not self.done:
logger.debug("{}:Step {}:{}", self.__class__.__name__, self.positionstep, self.key)
if not self.step():
self.clean()
return False
# Cleanup after test
self.clean()
return True
def clean(self):
'''
Cleanup between tests
Capability history needs to be cleared between tests.
'''
import interface as i
# Read all callbacks
i.control.data.capability_history.unread()
# Prune callback history
i.control.data.capability_history.prune()
class Schedule:
'''
Handles KLL Schedule processing
'''
def __init__(self):
'''
TODO
'''
class ScheduleElem:
'''
Scheduling for an individual element
'''
def __init__(self, json_entry):
'''
TODO
By default, if no schedule is given, it is on press at the start of the cycle
'''
self.entry = json_entry
def initial(self):
'''
TODO
Initial evaluation of schedule.
Resets internal tracking.
@return: True if ready to evaluate/execute
'''
return True
def update(self):
'''
TODO
Updates the internal tracking
@return: True if ready to evaluate/execute
'''
return True
class TriggerEval:
'''
Evaluates a KLL trigger from a trigger:result pair
'''
def __init__(self, parent, json_entry, schedule=None):
'''
Constructor
@param parent: Parent object
@param json_entry: Trigger json entry
@param schedule: Alternate Trigger schedule, if set to None will be determined from json_entry
'''
self.parent = parent
self.entry = json_entry
self.schedule = schedule
# Step determines which part of the sequence we are trying to evaluate
self.step = 0
self.clean = -1
self.cleaned = -1
# Settings
# TODO (HaaTa): Expose these 2 variables somehow, they are useful for testing combos
self.reverse_combo = False
self.delayed_combo = False
self.sub_step = 0 # Used with delayed_combo
# Build sequence of combos
self.trigger = []
for comboindex, combo in enumerate(self.entry):
ncombo = []
for elemindex, elem in enumerate(combo):
# Determine schedule (use external schedule if specified)
elemschedule = ScheduleElem(elem)
if self.schedule is not None:
elemschedule = self.schedule[comboindex][elemindex]
# Append element to combo
ncombo.append(TriggerElem(self, elem, elemschedule))
self.trigger.append(ncombo)
def trigger_permutations(self):
'''
Calculate the number of order permutations the trigger can be initiated with.
For example:
U"RCtrl" + U"RAlt" : U"A";
can be processed 3 ways.
1) RCtrl + RAlt in the same cycle
2) RCtrl in the first cycle, RAlt in the second cycle
3) RAlt in the first cycle, RCtrl in the second cycle
Only triggers need permutation testing.
'''
# TODO
pass
def eval(self):
'''
Attempt to evaluate TriggerEval
Only a single step.
@return: True on valid execution, False if something unexpected ocurred
'''
# Fail test if we have incremented too many steps
if self.step > len(self.trigger):
return False
# Reverse combo
combo = copy.copy(self.trigger[self.step])
if self.reverse_combo:
combo.reverse()
# Delayed combo
if self.delayed_combo:
combo = [combo[self.sub_step]]
self.sub_step += 1
# Attempt to evaluate each element in the current combo
finished = True
for elem in combo:
if not elem.eval():
finished = False
# Only increment if sub_steps are complete
if self.delayed_combo:
finished = finished and self.sub_step >= len(self.trigger[self.step])
# Increment step if finished
if finished:
self.step += 1
self.clean += 1
self.sub_step = 0 # Reset on each combo
# Always return True (even if not finished)
# Only return False on an unexpected error
return True
def cleanup(self):
'''
Cleanup previously evaluated step
Uses the previous step to determine what to cleanup.
Does not cleanup if it's not necessary (i.e. no "double frees")
'''
# Don't bother doing double cleanup
if self.cleaned == self.clean:
return
# Clean for the given step
for elem in self.trigger[self.clean]:
elem.cleanup()
self.cleaned += 1
# Reset the cleaning state
if self.clean >= len(self.trigger):
self.clean = -1
self.cleaned = -1
def reset(self):
'''
Reset step position
'''
logger.debug("{} Reset", self.__class__.__name__)
self.step = 0
def done(self):
'''
Determine if the Trigger Evaluation is complete
@return: True if complete, False otherwise
'''
return self.step >= len(self.trigger)
class ResultMonitor:
'''
Monitors a KLL result from a trigger:result pair
'''
def __init__(self, parent, json_entry):
'''
Constructor
@param parent: Parent object
@param json_entry: Result json entry
'''
self.parent = parent
self.entry = json_entry
# Step determines which part of the sequence we are trying to monitor
self.step = 0
self.clean = -1
self.cleaned = -1
# Build sequence of combos
self.result = []
for comboindex, combo in enumerate(self.entry):
ncombo = []
for elemindex, elem in enumerate(combo):
elemschedule = ScheduleElem(elem)
# Append element to combo
ncombo.append(ResultElem(self, elem, elemschedule))
self.result.append(ncombo)
def monitor(self):
'''
Monitors a single step of the Result.
@return: True if step has completed, False if schedule is out of bounds (failed).
'''
# Fail test if we have incremented too many steps
if self.step > len(self.result):
return False
# Monitor current step in the Result
finished = True
for elem in self.result[self.step]:
if not elem.monitor():
return False
# Increment step if finished
if finished:
self.step += 1
self.clean += 1
# TODO Determine if we are outside the bounds of the schedule
# i.e. when to return False
# Return true even if not finished
return True
def monitor_cleanup(self):
'''
Monitors the cleanup of the previous monitor step
@return: True if cleanup was successful, False otherwise.
'''
# Don't bother doing double cleanup
if self.cleaned == self.clean:
return True
# Clean for the given step
clean_result = True
for elem in self.result[self.clean]:
if not elem.monitor_cleanup():
clean_result = False
self.cleaned += 1
# Reset the cleaning state
if self.clean >= len(self.result):
self.clean = -1
self.cleaned = -1
return clean_result
def reset(self):
'''
Reset step position
'''
logger.debug("{} Reset", self.__class__.__name__)
self.step = 0
def done(self):
'''
Determine if the Result Monitor is complete
@return: True if complete, False otherwise
'''
return self.step >= len(self.result)
class TriggerElem:
'''
Handles individual trigger elements and how to interface with libkiibohd
'''
def __init__(self, parent, elem, schedule):
'''
Intializer
@param parent: Parent object
@param elem: Trigger element
@param schedule: Trigger element conditions
'''
self.parent = parent
self.elem = elem
self.schedule = schedule
def eval(self):
'''
Evaluates TriggerElem
Must satisify schedule in order to complete.
@return: True if evaluated, False if not.
'''
# TODO (HaaTa) Handle scheduling
import interface as i
LayerStateType = i.control.scan.LayerStateType
ScheduleState = i.control.scan.ScheduleState
TriggerType = i.control.scan.TriggerType
logger.debug("TriggerElem eval {} {}", self.elem, self.schedule)
# Determine which kind trigger element
# ScanCode
if self.elem['type'] == 'ScanCode':
# Press given ScanCode
# TODO (HaaTa): Support uids greater than 255
i.control.cmd('addScanCode')(self.elem['uid'], TriggerType.Switch1)
# IndicatorCode
elif self.elem['type'] == 'IndCode':
# Activate Indicator
i.control.cmd('addScanCode')(self.elem['uid'], TriggerType.LED1)
# Layer
elif self.elem['type'] in ['Layer', 'LayerShift', 'LayerLatch', 'LayerLock']:
# Determine which layer type
layer_state = LayerStateType.Shift
if self.elem['type'] == 'LayerLatch':
layer_state = LayerStateType.Latch
elif self.elem['type'] == 'LayerLock':
layer_state = LayerStateType.Lock
# Activate layer
i.control.cmd('applyLayer')(ScheduleState.P, self.elem['uid'], layer_state)
# Generic Trigger
elif self.elem['type'] in ['GenericTrigger']:
# Activate trigger
i.control.cmd('setTriggerCode')(self.elem['uid'], self.elem['idcode'], self.elem['schedule'][0]['state'] )
# Unknown TriggerElem
else:
logger.warning("Unknown TriggerElem {}", self.elem)
return True
def cleanup(self):
'''
Completes the opposing action for a scheduled TriggerElem eval
@return: True, unless there were probablems completing operation
'''
# TODO (HaaTa) Handle scheduling
import interface as i
LayerStateType = i.control.scan.LayerStateType
ScheduleState = i.control.scan.ScheduleState
TriggerType = i.control.scan.TriggerType
logger.debug("TriggerElem cleanup {} {}", self.elem, self.schedule)
# Determine which kind trigger element
# ScanCode
if self.elem['type'] == 'ScanCode':
# Press given ScanCode
# TODO (HaaTa): Support uids greater than 255
i.control.cmd('removeScanCode')(self.elem['uid'], TriggerType.Switch1)
# IndicatorCode
elif self.elem['type'] == 'IndCode':
# Activate Indicator
i.control.cmd('removeScanCode')(self.elem['uid'], TriggerType.LED1)
# Layer Trigger
elif self.elem['type'] in ['Layer', 'LayerShift', 'LayerLatch', 'LayerLock']:
# Determine which layer type
state = ScheduleState.R
layer_state = LayerStateType.Shift
if self.elem['type'] == 'LayerLatch':
state = ScheduleState.P
layer_state = LayerStateType.Latch
elif self.elem['type'] == 'LayerLock':
state = ScheduleState.P
layer_state = LayerStateType.Lock
# Deactivate layer
i.control.cmd('applyLayer')(state, self.elem['uid'], layer_state)
# Generic Trigger
elif self.elem['type'] in ['GenericTrigger']:
# Do nothing as we don't know how to clean up this trigger
# XXX (HaaTa): It can be possible to deduce from the idcode what type of trigger this is
# However, not all triggers have an inverse (some just cleanup on their own such as rotations)
pass
# Unknown TriggerElem
else:
logger.warning("Unknown TriggerElem {}", self.elem)
return True
def __repr__(self):
'''
String representation of TriggerElem
'''
output = "{} {}".format(
self.elem,
self.schedule,
)
return output
class ResultElem:
'''
Handles individual result elements and how to monitor libkiibohd
'''
def __init__(self, parent, elem, schedule):
'''
Intializer
@param parent: Parent object
@param elem: Result element
@param schedule: Result element conditions
'''
self.parent = parent
self.elem = elem
self.schedule = schedule
self.validation = NoVerification(self)
import interface as i
# Lookup Capability (if necessary)
elemtype = self.elem['type']
self.name = i.control.json_input['CodeLookup'][elemtype]
self.expected_args = None
if self.name is None:
# Capability type has the name and arg fields
if elemtype == 'Capability':
self.name = self.elem['name']
self.expected_args = self.elem['args']
new_args = []
# Some args have types
for arg in self.expected_args:
if isinstance(arg, dict):
new_args.append(arg['value'])
# If any processing of args was necessary
if len(new_args) > 0:
self.expected_args = new_args
elif elemtype == 'Animation':
# Expected arg needs to be looked up for Animations
value = i.control.json_input['AnimationSettings'][self.elem['setting']]
self.expected_args = [value]
elif elemtype == 'None':
# None is just usbKeyOut with keycode 0 (which is nothing)
self.name = i.control.json_input['CodeLookup']['USBCode']
self.expected_args = [0] # This is None
else:
# Otherwise uid is used for the arg
self.expected_args = [self.elem['uid']]
logger.debug("ResultElem monitor {} {} {} {}", self.elem, self.schedule, self.name, self.expected_args)
assert self.name is not None, "Invalid Result type {}".format(self.elem)
# Determine if there is capability verification available
if elemtype == 'Animation':
self.validation = AnimationVerification(self)
elif elemtype == 'USBCode':
self.validation = USBCodeVerification(self)
elif elemtype == 'ConsCode':
self.validation = ConsumerCodeVerification(self)
elif elemtype == 'SysCode':
self.validation = SystemCodeVerification(self)
elif elemtype == 'Capability':
# Determine if general capability has verification available
# Layer Verification
if self.name in ['layerShift', 'layerLock', 'layerLatch']:
self.validation = LayerVerification(self)
def monitor_state(self, state):
'''
Monitors result state
@param state: Value of state to monitor
@returns: True if valid, False if not
'''
# TODO (HaaTa) Handle scheduling
import interface as i
TriggerType = i.control.scan.TriggerType
# Lookup capability history, success if any capabilities match
match = None
for cap in i.control.data.capability_history.all():
data = cap.callbackdata
# Validate state and capability name
# Rotations use states beyond 0x0F
if (
data.read_capability()[0] == self.name and (
(data.state & 0x0F) == state or
(data.state == state and data.stateType == TriggerType.Rotation1)
)
):
# Validate args
match_args = True
# XXX Each data argument may consist of multiple bytes
# This can be looked up using kll.json
# Generally 1, 2 and 4 (8-bit, 16-bit and 32-bit)
capability = i.control.json_input['Capabilities'][self.name]
byte_pos = 0
for index in range(capability['args_count']):
value_width = capability['args'][index]['width']
value = 0
if value_width == 1:
value = data.args[byte_pos]
byte_pos += 1
elif value_width == 2:
value = (data.args[byte_pos + 1] << 8) | data.args[byte_pos]
byte_pos += 2
elif value_width == 4:
value = (data.args[byte_pos + 3] << 24) | (data.args[byte_pos + 2] << 16) | (data.args[byte_pos + 1] << 8) | data.args[byte_pos]
byte_pos += 4
# Check read value vs. expected
if value != self.expected_args[index]:
match_args = False
break
# Determine if we've found a match
if match_args:
match = data
logger.debug("Matched History {}", match)
break
# Increment test count with pass/fail
result = True
if match is None:
result = False
# Print out capability history
for cap in i.control.data.capability_history.all():
logger.warning(cap)
return check(result, "test:{} expected:{}({}) state({}) - found:{}".format(
self.parent.parent.parent.cur_test,
self.name,
self.expected_args,
state,
match,
))
def monitor(self):
'''
Monitors for ResultElem
Must satisfy schedule in order to complete.
@return: True if found, False if not.
'''
# TODO (HaaTa) Handle scheduling
if len(self.parent.parent.trigger.entry[-1][-1]['schedule']) > 0:
state = self.parent.parent.trigger.entry[-1][-1]['schedule'][0]['state']
else:
state = 1
# Check capability state
result = self.monitor_state(state)
# Validate capability result
result = result and self.validation.verify(state)
return result
def monitor_cleanup(self):
'''
Cleanup monitor for ResultElem
@return: True if expected cleanup occured, False if not.