-
-
Notifications
You must be signed in to change notification settings - Fork 519
/
device_base.py
1296 lines (1025 loc) · 46.4 KB
/
device_base.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
# SPDX-License-Identifier: GPL-2.0-or-later
"""
Hardware base class
"""
import configparser
import re
import os
import types
import inspect
import logging
import time
import json
import random
from openrazer_daemon.dbus_services.service import DBusService
import openrazer_daemon.dbus_services.dbus_methods
from openrazer_daemon.misc import effect_sync
from openrazer_daemon.misc.battery_notifier import BatteryManager as _BatteryManager
# pylint: disable=too-many-instance-attributes
# pylint: disable=E1102
# See https://github.com/PyCQA/pylint/issues/1493
class RazerDevice(DBusService):
"""
Base class
Sets up the logger, sets up DBus
"""
OBJECT_PATH = '/org/razer/device/'
METHODS = []
EVENT_FILE_REGEX = None
USB_VID = None
USB_PID = None
HAS_MATRIX = False
DEDICATED_MACRO_KEYS = False
MATRIX_DIMS = None
POLL_RATES = None
DPI_MAX = None
WAVE_DIRS = (1, 2)
ZONES = ('backlight', 'logo', 'scroll', 'left', 'right', 'charging', 'fast_charging', 'fully_charged', 'channel1', 'channel2', 'channel3', 'channel4', 'channel5', 'channel6')
DEVICE_IMAGE = None
def __init__(self, device_path, device_number, config, persistence, testing, additional_interfaces, additional_methods):
self.logger = logging.getLogger('razer.device{0}'.format(device_number))
self.logger.info("Initialising device.%d %s", device_number, self.__class__.__name__)
# Serial cache
self._serial = None
# Local storage key name
self.storage_name = "UnknownDevice"
self._observer_list = []
self._effect_sync_propagate_up = False
self._disable_notifications = False
self._disable_persistence = False
self.additional_interfaces = []
if additional_interfaces is not None:
self.additional_interfaces.extend(additional_interfaces)
self._battery_manager = None
self.config = config
self.persistence = persistence
self._testing = testing
self._parent = None
self._device_path = device_path
self._device_number = device_number
self.serial = self.get_serial()
if self.USB_PID == 0x0f07:
self.storage_name = "ChromaMug"
elif self.USB_PID == 0x0013:
self.storage_name = "Orochi2011"
elif self.USB_PID == 0x0016:
self.storage_name = "DeathAdder35G"
elif self.USB_PID == 0x0029:
self.storage_name = "DeathAdder35GBlack"
elif self.USB_PID == 0x0024 or self.USB_PID == 0x0025:
self.storage_name = "Mamba2012"
else:
self.storage_name = self.serial
self.zone = dict()
for i in self.ZONES:
self.zone[i] = {
"present": False,
"active": True,
"brightness": 75.0,
"effect": 'spectrum',
"colors": [0, 255, 0, 0, 255, 255, 0, 0, 255],
"speed": 1,
"wave_dir": 1,
}
# Check for a DPI X only device since they need a Y value of 0
if 'available_dpi' in self.METHODS:
self.dpi = [1800, 0]
else:
self.dpi = [1800, 1800]
self.poll_rate = 500
if 'set_poll_rate' in self.METHODS and not self.POLL_RATES:
self.POLL_RATES = [125, 500, 1000]
self._effect_sync = effect_sync.EffectSync(self, device_number)
self._is_closed = False
# device methods available in all devices
self.methods_internal = ['get_firmware', 'get_matrix_dims', 'has_matrix', 'get_device_name']
self.methods_internal.extend(additional_methods)
# Find event files in /dev/input/by-id/ by matching against regex
self.event_files = []
if self._testing:
search_dir = os.path.join(device_path, 'input')
else:
search_dir = '/dev/input/by-id/'
if os.path.exists(search_dir):
for event_file in os.listdir(search_dir):
if self.EVENT_FILE_REGEX is not None and self.EVENT_FILE_REGEX.match(event_file) is not None:
self.event_files.append(os.path.join(search_dir, event_file))
object_path = os.path.join(self.OBJECT_PATH, self.serial)
super().__init__(object_path)
# Set up methods to suspend and restore device operation
self.suspend_args = {}
self.method_args = {}
methods = {
# interface, method, callback, in-args, out-args
('razer.device.misc', 'getSerial', self.get_serial, None, 's'),
('razer.device.misc', 'suspendDevice', self.suspend_device, None, None),
('razer.device.misc', 'getDeviceMode', self.get_device_mode, None, 's'),
('razer.device.misc', 'getDeviceImage', self.get_device_image, None, 's'),
('razer.device.misc', 'setDeviceMode', self.set_device_mode, 'yy', None),
('razer.device.misc', 'resumeDevice', self.resume_device, None, None),
('razer.device.misc', 'getVidPid', self.get_vid_pid, None, 'ai'),
('razer.device.misc', 'getDriverVersion', openrazer_daemon.dbus_services.dbus_methods.version, None, 's'),
('razer.device.misc', 'hasDedicatedMacroKeys', self.dedicated_macro_keys, None, 'b'),
# Deprecated API, but kept for backwards compatibility
('razer.device.misc', 'getRazerUrls', self.get_image_json, None, 's'),
('razer.device.lighting.chroma', 'restoreLastEffect', self.restore_effect, None, None),
}
effect_methods = {
"backlight_chroma": {
('razer.device.lighting.chroma', 'getEffect', self.get_current_effect, None, 's'),
('razer.device.lighting.chroma', 'getEffectColors', self.get_current_effect_colors, None, 'ay'),
('razer.device.lighting.chroma', 'getEffectSpeed', self.get_current_effect_speed, None, 'i'),
('razer.device.lighting.chroma', 'getWaveDir', self.get_current_wave_dir, None, 'i'),
},
"backlight": {
# Intentionally using the same underlying methods as backlight_chroma.
# Both refer to the 'backlight' LED internally but partially exist separately due to historical reasons.
('razer.device.lighting.backlight', 'getBacklightEffect', self.get_current_effect, None, 's'),
('razer.device.lighting.backlight', 'getBacklightEffectColors', self.get_current_effect_colors, None, 'ay'),
('razer.device.lighting.backlight', 'getBacklightEffectSpeed', self.get_current_effect_speed, None, 'i'),
('razer.device.lighting.backlight', 'getBacklightWaveDir', self.get_current_wave_dir, None, 'i'),
},
"logo": {
('razer.device.lighting.logo', 'getLogoEffect', self.get_current_logo_effect, None, 's'),
('razer.device.lighting.logo', 'getLogoEffectColors', self.get_current_logo_effect_colors, None, 'ay'),
('razer.device.lighting.logo', 'getLogoEffectSpeed', self.get_current_logo_effect_speed, None, 'i'),
('razer.device.lighting.logo', 'getLogoWaveDir', self.get_current_logo_wave_dir, None, 'i'),
},
"scroll": {
('razer.device.lighting.scroll', 'getScrollEffect', self.get_current_scroll_effect, None, 's'),
('razer.device.lighting.scroll', 'getScrollEffectColors', self.get_current_scroll_effect_colors, None, 'ay'),
('razer.device.lighting.scroll', 'getScrollEffectSpeed', self.get_current_scroll_effect_speed, None, 'i'),
('razer.device.lighting.scroll', 'getScrollWaveDir', self.get_current_scroll_wave_dir, None, 'i'),
},
"left": {
('razer.device.lighting.left', 'getLeftEffect', self.get_current_left_effect, None, 's'),
('razer.device.lighting.left', 'getLeftEffectColors', self.get_current_left_effect_colors, None, 'ay'),
('razer.device.lighting.left', 'getLeftEffectSpeed', self.get_current_left_effect_speed, None, 'i'),
('razer.device.lighting.left', 'getLeftWaveDir', self.get_current_left_wave_dir, None, 'i'),
},
"right": {
('razer.device.lighting.right', 'getRightEffect', self.get_current_right_effect, None, 's'),
('razer.device.lighting.right', 'getRightEffectColors', self.get_current_right_effect_colors, None, 'ay'),
('razer.device.lighting.right', 'getRightEffectSpeed', self.get_current_right_effect_speed, None, 'i'),
('razer.device.lighting.right', 'getRightWaveDir', self.get_current_right_wave_dir, None, 'i'),
},
"charging": {
('razer.device.lighting.charging', 'getChargingEffect', self.get_current_charging_effect, None, 's'),
('razer.device.lighting.charging', 'getChargingEffectColors', self.get_current_charging_effect_colors, None, 'ay'),
('razer.device.lighting.charging', 'getChargingEffectSpeed', self.get_current_charging_effect_speed, None, 'i'),
('razer.device.lighting.charging', 'getChargingWaveDir', self.get_current_charging_wave_dir, None, 'i'),
},
"fast_charging": {
('razer.device.lighting.fast_charging', 'getFastChargingEffect', self.get_current_fast_charging_effect, None, 's'),
('razer.device.lighting.fast_charging', 'getFastChargingEffectColors', self.get_current_fast_charging_effect_colors, None, 'ay'),
('razer.device.lighting.fast_charging', 'getFastChargingEffectSpeed', self.get_current_fast_charging_effect_speed, None, 'i'),
('razer.device.lighting.fast_charging', 'getFastChargingWaveDir', self.get_current_fast_charging_wave_dir, None, 'i'),
},
"fully_charged": {
('razer.device.lighting.fully_charged', 'getFullyChargedEffect', self.get_current_fully_charged_effect, None, 's'),
('razer.device.lighting.fully_charged', 'getFullyChargedEffectColors', self.get_current_fully_charged_effect_colors, None, 'ay'),
('razer.device.lighting.fully_charged', 'getFullyChargedEffectSpeed', self.get_current_fully_charged_effect_speed, None, 'i'),
('razer.device.lighting.fully_charged', 'getFullyChargedWaveDir', self.get_current_fully_charged_wave_dir, None, 'i'),
}
}
for m in methods:
self.logger.debug("Adding {}.{} method to DBus".format(m[0], m[1]))
self.add_dbus_method(m[0], m[1], m[2], in_signature=m[3], out_signature=m[4])
# this check is separate from the rest because backlight effects don't have prefixes in their names
if 'set_static_effect' in self.METHODS or 'bw_set_static' in self.METHODS:
self.zone["backlight"]["present"] = True
for m in effect_methods["backlight_chroma"]:
self.logger.debug("Adding {}.{} method to DBus".format(m[0], m[1]))
self.add_dbus_method(m[0], m[1], m[2], in_signature=m[3], out_signature=m[4])
for i in self.ZONES:
if 'set_' + i + '_static_classic' in self.METHODS \
or 'set_' + i + '_static' in self.METHODS \
or 'set_' + i + '_active' in self.METHODS \
or 'set_' + i + '_on' in self.METHODS:
self.zone[i]["present"] = True
for m in effect_methods[i]:
self.logger.debug("Adding {}.{} method to DBus".format(m[0], m[1]))
self.add_dbus_method(m[0], m[1], m[2], in_signature=m[3], out_signature=m[4])
# Load additional DBus methods
self.load_methods()
# load last DPI/poll rate state
if self.persistence.has_section(self.storage_name):
if 'set_dpi_xy' in self.METHODS or 'set_dpi_xy_byte' in self.METHODS:
try:
self.dpi[0] = int(self.persistence[self.storage_name]['dpi_x'])
self.dpi[1] = int(self.persistence[self.storage_name]['dpi_y'])
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get DPI from persistence storage, using default.")
if 'set_poll_rate' in self.METHODS:
try:
self.poll_rate = int(self.persistence[self.storage_name]['poll_rate'])
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get poll rate from persistence storage, using default.")
# load last effects
for i in self.ZONES:
if self.zone[i]["present"]:
# check if we have the device in the persistence file
if self.persistence.has_section(self.storage_name):
# try reading the effect name from the persistence
try:
self.zone[i]["effect"] = self.persistence[self.storage_name][i + '_effect']
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get " + i + " effect from persistence storage, using default.")
# zone active status
try:
self.zone[i]["active"] = self.persistence.getboolean(self.storage_name, i + '_active')
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get " + i + " active from persistence storage, using default.")
# brightness
try:
self.zone[i]["brightness"] = float(self.persistence[self.storage_name][i + '_brightness'])
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get " + i + " brightness from persistence storage, using default.")
# colors.
# these are stored as a string that must contain 9 numbers, separated with spaces.
try:
for index, item in enumerate(self.persistence[self.storage_name][i + '_colors'].split(" ")):
self.zone[i]["colors"][index] = int(item)
# check if the color is in range
if not 0 <= self.zone[i]["colors"][index] <= 255:
raise ValueError('Color out of range')
# check if we have exactly 9 colors
if len(self.zone[i]["colors"]) != 9:
raise ValueError('There must be exactly 9 colors')
except ValueError:
# invalid colors. reinitialize
self.zone[i]["colors"] = [0, 255, 0, 0, 255, 255, 0, 0, 255]
self.logger.info("%s: Invalid colors; restoring to defaults.", self.__class__.__name__)
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get " + i + " colors from persistence storage, using default.")
# speed
try:
self.zone[i]["speed"] = int(self.persistence[self.storage_name][i + '_speed'])
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get " + i + " speed from persistence storage, using default.")
# wave direction
try:
self.zone[i]["wave_dir"] = int(self.persistence[self.storage_name][i + '_wave_dir'])
except (KeyError, configparser.NoOptionError):
self.logger.info("Failed to get " + i + " wave direction from persistence storage, using default.")
# Initialize battery manager if the device has support
if 'get_battery' in self.METHODS:
self._init_battery_manager()
self.restore_dpi_poll_rate()
self.restore_brightness()
if self.config.getboolean('Startup', "restore_persistence") is True:
self.restore_effect()
def send_effect_event(self, effect_name, *args):
"""
Send effect event
:param effect_name: Effect name
:type effect_name: str
:param args: Effect arguments
:type args: list
"""
payload = ['effect', self, effect_name]
payload.extend(args)
self.notify_observers(tuple(payload))
def dedicated_macro_keys(self):
"""
Returns if the device has dedicated macro keys
:return: Macro keys
:rtype: bool
"""
return self.DEDICATED_MACRO_KEYS
def restore_dpi_poll_rate(self):
"""
Set the device DPI & poll rate to the saved value
"""
dpi_func = getattr(self, "setDPI", None)
if dpi_func is not None:
# Constrain value in case the max has changed, e.g. wired/wireless might different maximums
if self.dpi[0] > self.DPI_MAX:
self.logger.warning("Constraining DPI X to maximum of " + str(self.DPI_MAX) + " because stored value " + str(self.dpi[0]) + " is larger.")
self.dpi[0] = self.DPI_MAX
if self.dpi[1] > self.DPI_MAX:
self.logger.warning("Constraining DPI Y to maximum of " + str(self.DPI_MAX) + " because stored value " + str(self.dpi[1]) + " is larger.")
self.dpi[1] = self.DPI_MAX
dpi_func(self.dpi[0], self.dpi[1])
poll_rate_func = getattr(self, "setPollRate", None)
if poll_rate_func is not None:
# Constrain value in case the available values have changed, e.g. wired/wireless might different values available
if self.poll_rate not in self.POLL_RATES:
self.logger.warning("Constraining poll rate because stored value " + str(self.poll_rate) + " is not available.")
self.poll_rate = min(self.POLL_RATES, key=lambda x: abs(x - self.poll_rate))
poll_rate_func(self.poll_rate)
def restore_brightness(self):
"""
Set the device to the current brightness/active state.
This is used at launch time.
"""
for i in self.ZONES:
if self.zone[i]["present"]:
# load active state
if 'set_' + i + '_active' in self.METHODS:
active_func = getattr(self, "set" + self.capitalize_first_char(i) + "Active", None)
if active_func is not None:
active_func(self.zone[i]["active"])
# load brightness level
bright_func = None
if i == "backlight":
bright_func = getattr(self, "setBrightness", None)
elif 'set_' + i + '_brightness' in self.METHODS:
bright_func = getattr(self, "set" + self.capitalize_first_char(i) + "Brightness", None)
if bright_func is not None:
bright_func(self.zone[i]["brightness"])
def disable_brightness(self):
"""
Set brightness to 0 and/or active state to false.
"""
for i in self.ZONES:
if self.zone[i]["present"]:
# set active state
if 'set_' + i + '_active' in self.METHODS:
active_func = getattr(self, "set" + self.capitalize_first_char(i) + "Active", None)
if active_func is not None:
active_func(False)
# set brightness level
bright_func = None
if i == "backlight":
bright_func = getattr(self, "setBrightness", None)
elif 'set_' + i + '_brightness' in self.METHODS:
bright_func = getattr(self, "set" + self.capitalize_first_char(i) + "Brightness", None)
if bright_func is not None:
bright_func(0)
def restore_effect(self):
"""
Set the device to the current effect
This is used at launch time and can be called by applications
that use custom matrix frames after they exit
"""
for i in self.ZONES:
if self.zone[i]["present"]:
# prepare the effect method name
# yes, we need to handle the backlight zone separately too.
# the backlight effect methods don't have a prefix.
if i == "backlight":
effect_func_name = 'set' + self.capitalize_first_char(self.zone[i]["effect"])
else:
effect_func_name = 'set' + self.handle_underscores(self.capitalize_first_char(i)) + self.capitalize_first_char(self.zone[i]["effect"])
# find the effect method
effect_func = getattr(self, effect_func_name, None)
# check if the effect method exists only if we didn't look for spectrum (because resetting to Spectrum when the effect is Spectrum is in vain)
if effect_func == None and not self.zone[i]["effect"] == "spectrum":
# not found. restoring to Spectrum
self.logger.info("%s: Invalid effect name %s; restoring to Spectrum.", self.__class__.__name__, effect_func_name)
self.zone[i]["effect"] = 'spectrum'
if i == "backlight":
effect_func_name = 'setSpectrum'
else:
effect_func_name = 'set' + self.capitalize_first_char(i) + 'Spectrum'
effect_func = getattr(self, effect_func_name, None)
# we check again here because there is a possibility the device may not even have Spectrum
if effect_func is not None:
effect = self.zone[i]["effect"]
colors = self.zone[i]["colors"]
speed = self.zone[i]["speed"]
wave_dir = self.zone[i]["wave_dir"]
if self.get_num_arguments(effect_func) == 0:
effect_func()
elif self.get_num_arguments(effect_func) == 1:
# there are 2 effects which require 1 argument.
# these are: Starlight (Random) and Wave.
if effect == 'starlightRandom':
effect_func(speed)
elif effect == 'wave':
effect_func(wave_dir)
elif effect == 'wheel':
effect_func(wave_dir)
elif effect == 'rippleRandomColour':
# do nothing. this is handled in the ripple manager.
pass
else:
self.logger.error("%s: Effect requires 1 argument but don't know how to handle it!", self.__class__.__name__)
elif self.get_num_arguments(effect_func) == 3:
effect_func(colors[0], colors[1], colors[2])
elif self.get_num_arguments(effect_func) == 4:
# starlight/reactive have different arguments.
if effect == 'starlightSingle' or effect == 'reactive':
effect_func(colors[0], colors[1], colors[2], speed)
elif effect == 'ripple':
# do nothing. this is handled in the ripple manager.
pass
else:
self.logger.error("%s: Effect requires 4 arguments but don't know how to handle it!", self.__class__.__name__)
elif self.get_num_arguments(effect_func) == 6:
effect_func(colors[0], colors[1], colors[2], colors[3], colors[4], colors[5])
elif self.get_num_arguments(effect_func) == 7:
effect_func(colors[0], colors[1], colors[2], colors[3], colors[4], colors[5], speed)
elif self.get_num_arguments(effect_func) == 9:
effect_func(colors[0], colors[1], colors[2], colors[3], colors[4], colors[5], colors[6], colors[7], colors[8])
else:
self.logger.error("%s: Couldn't detect effect argument count!", self.__class__.__name__)
def set_persistence(self, zone, key, value):
"""
Set a device's current state for persisting across sessions.
:param zone: Zone
:type zone: string
:param key: Key
:type key: string
:param value: Value
:type value: string
"""
if self._disable_persistence:
return
self.logger.debug("Set persistence (%s, %s, %s)", zone, key, value)
self.persistence.status["changed"] = True
if zone:
self.zone[zone][key] = value
else:
self.zone[key] = value
def get_current_effect(self):
"""
Get the device's current effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_effect")
return self.zone["backlight"]["effect"]
def get_current_effect_colors(self):
"""
Get the device's current effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_effect_colors")
return self.zone["backlight"]["colors"]
def get_current_effect_speed(self):
"""
Get the device's current effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_effect_speed")
return self.zone["backlight"]["speed"]
def get_current_wave_dir(self):
"""
Get the device's current wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_wave_dir")
return self.zone["backlight"]["wave_dir"]
def get_current_logo_effect(self):
"""
Get the device's current logo effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_logo_effect")
return self.zone["logo"]["effect"]
def get_current_logo_effect_colors(self):
"""
Get the device's current logo effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_logo_effect_colors")
return self.zone["logo"]["colors"]
def get_current_logo_effect_speed(self):
"""
Get the device's current logo effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_logo_effect_speed")
return self.zone["logo"]["speed"]
def get_current_logo_wave_dir(self):
"""
Get the device's current logo wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_logo_wave_dir")
return self.zone["logo"]["wave_dir"]
def get_current_scroll_effect(self):
"""
Get the device's current scroll effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_scroll_effect")
return self.zone["scroll"]["effect"]
def get_current_scroll_effect_colors(self):
"""
Get the device's current scroll effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_scroll_effect_colors")
return self.zone["scroll"]["colors"]
def get_current_scroll_effect_speed(self):
"""
Get the device's current scroll effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_scroll_effect_speed")
return self.zone["scroll"]["speed"]
def get_current_scroll_wave_dir(self):
"""
Get the device's current scroll wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_scroll_wave_dir")
return self.zone["scroll"]["wave_dir"]
def get_current_left_effect(self):
"""
Get the device's current left effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_left_effect")
return self.zone["left"]["effect"]
def get_current_left_effect_colors(self):
"""
Get the device's current left effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_left_effect_colors")
return self.zone["left"]["colors"]
def get_current_left_effect_speed(self):
"""
Get the device's current left effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_left_effect_speed")
return self.zone["left"]["speed"]
def get_current_left_wave_dir(self):
"""
Get the device's current left wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_left_wave_dir")
return self.zone["left"]["wave_dir"]
def get_current_right_effect(self):
"""
Get the device's current right effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_right_effect")
return self.zone["right"]["effect"]
def get_current_right_effect_colors(self):
"""
Get the device's current right effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_right_effect_colors")
return self.zone["right"]["colors"]
def get_current_right_effect_speed(self):
"""
Get the device's current right effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_right_effect_speed")
return self.zone["right"]["speed"]
def get_current_right_wave_dir(self):
"""
Get the device's current right wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_right_wave_dir")
return self.zone["right"]["wave_dir"]
def get_current_charging_effect(self):
"""
Get the device's current charging effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_charging_effect")
return self.zone["charging"]["effect"]
def get_current_charging_effect_colors(self):
"""
Get the device's current charging effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_charging_effect_colors")
return self.zone["charging"]["colors"]
def get_current_charging_effect_speed(self):
"""
Get the device's current charging effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_charging_effect_speed")
return self.zone["charging"]["speed"]
def get_current_charging_wave_dir(self):
"""
Get the device's current charging wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_charging_wave_dir")
return self.zone["charging"]["wave_dir"]
def get_current_fast_charging_effect(self):
"""
Get the device's current fast_charging effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_fast_charging_effect")
return self.zone["fast_charging"]["effect"]
def get_current_fast_charging_effect_colors(self):
"""
Get the device's current fast_charging effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_fast_charging_effect_colors")
return self.zone["fast_charging"]["colors"]
def get_current_fast_charging_effect_speed(self):
"""
Get the device's current fast_charging effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_fast_charging_effect_speed")
return self.zone["fast_charging"]["speed"]
def get_current_fast_charging_wave_dir(self):
"""
Get the device's current fast_charging wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_fast_charging_wave_dir")
return self.zone["fast_charging"]["wave_dir"]
def get_current_fully_charged_effect(self):
"""
Get the device's current fully_charged effect
:return: Effect
:rtype: string
"""
self.logger.debug("DBus call get_current_fully_charged_effect")
return self.zone["fully_charged"]["effect"]
def get_current_fully_charged_effect_colors(self):
"""
Get the device's current fully_charged effect's colors
:return: 3 colors
:rtype: list of byte
"""
self.logger.debug("DBus call get_current_fully_charged_effect_colors")
return self.zone["fully_charged"]["colors"]
def get_current_fully_charged_effect_speed(self):
"""
Get the device's current fully_charged effect's speed
:return: Speed
:rtype: int
"""
self.logger.debug("DBus call get_current_fully_charged_effect_speed")
return self.zone["fully_charged"]["speed"]
def get_current_fully_charged_wave_dir(self):
"""
Get the device's current fully_charged wave direction
:return: Direction
:rtype: int
"""
self.logger.debug("DBus call get_current_fully_charged_wave_dir")
return self.zone["fully_charged"]["wave_dir"]
@property
def effect_sync(self):
"""
Propagate the obsever call upwards, used for syncing effects
:return: Effects sync flag
:rtype: bool
"""
return self._effect_sync_propagate_up
@effect_sync.setter
def effect_sync(self, value):
"""
Setting to true will propagate observer events upwards
:param value: Effect sync
:type value: bool
"""
self._effect_sync_propagate_up = value
@property
def disable_notify(self):
"""
Disable notifications flag
:return: Flag
:rtype: bool
"""
return self._disable_notifications
@disable_notify.setter
def disable_notify(self, value):
"""
Set the disable notifications flag
:param value: Disable
:type value: bool
"""
self._disable_notifications = value
@property
def disable_persistence(self):
"""
Disable persistence flag
:return: Flag
:rtype: bool
"""
return self._disable_persistence
@disable_persistence.setter
def disable_persistence(self, value):
"""
Set the disable persistence flag
:param value: Disable
:type value: bool
"""
self._disable_persistence = value
def get_driver_path(self, driver_filename):
"""
Get the path to a driver file
:param driver_filename: Name of driver file
:type driver_filename: str
:return: Full path to driver
:rtype: str
"""
return os.path.join(self._device_path, driver_filename)
def get_serial(self):
"""
Get serial number for device
:return: String of the serial number
:rtype: str
"""
# TODO raise exception if serial can't be got and handle during device add
if self._serial is None:
serial_path = os.path.join(self._device_path, 'device_serial')
count = 0
serial = ''
while len(serial) == 0:
if count >= 5:
break
try:
with open(serial_path, 'r') as f:
serial = f.read().strip()
except (PermissionError, OSError) as err:
self.logger.warning('getting serial: {0}'.format(err))
serial = ''
except UnicodeDecodeError as err:
self.logger.warning('malformed serial: {0}'.format(err))
serial = ''
count += 1
if len(serial) == 0:
time.sleep(0.1)
self.logger.debug('getting serial: {0} count:{1}'.format(serial, count))
if serial == '' or serial == 'Default string' or serial == 'empty (NULL)' or serial == 'As printed in the D cover':
serial = 'UNKWN{0:012}'.format(random.randint(0, 4096))
self._serial = serial.replace(' ', '_')
return self._serial
def get_device_mode(self):
"""
Get device mode
:return: String of device mode and arg separated by colon, e.g. 0:0 or 3:0
:rtype: str
"""
device_mode_path = os.path.join(self._device_path, 'device_mode')
with open(device_mode_path, 'rb') as mode_file:
count = 0
mode = mode_file.read().strip()
while len(mode) == 0:
if count >= 3:
break
mode = mode_file.read().strip()
count += 1