Repository navigation
Expand file tree
/
Copy pathmagic_mapper.py
More file actions
1060 lines (895 loc) · 37.9 KB
/
Copy pathmagic_mapper.py
File metadata and controls
1060 lines (895 loc) · 37.9 KB
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
import os
import re
import sys
import time
import traceback
import struct
import subprocess
import json
import fcntl
# We need the socket library for send_tcp_command(), but this isn't always installed in WebOS
try:
import socket
SOCKET_AVAILABLE = True
except ImportError:
SOCKET_AVAILABLE = False
# We need select to read more than one input device (the IR receiver), it may be missing too
try:
import select
SELECT_AVAILABLE = True
except ImportError:
SELECT_AVAILABLE = False
VERSION = "1.1.0"
# Default settings. Don't edit these here, override them in the "magic_mapper_settings"
# section of magic_mapper_config.json instead (see the Settings section of the README)
BLOCK_MOUSE = False # block_mouse: disable the mouse, requires EXCLUSIVE_MODE
EXCLUSIVE_MODE = True # exclusive_mode: prevent bound codes from the input device from being seen by WebOS
INPUT_DEVICE_NAME = 'LGE M-RCU - Builtin [0]' # input_device_name: the exact Name= shown in /proc/bus/input/devices
IR_INPUT_ENABLED = False # ir_input_enabled: also read button presses from the IR receiver
IR_INPUT_DEVICE_NAME = 'LGE RCU' # ir_input_device_name: the exact Name= of the IR receiver in /proc/bus/input/devices
IR_EXCLUSIVE_MODE = True # ir_exclusive_mode: grab the IR device so mapped IR buttons don't also do their normal action
OUTPUT_DEVICE_NAME = 'LGE M-RCU - Builtin [2]' # output_device_name: unbound codes get resent to this device in exclusive mode
# If OUTPUT_DEVICE_NAME isn't found, another 'LGE M-RCU - Builtin [N]' device is picked automatically
INPUT_DEVICE_NAME_SET = False # True when input_device_name was set in the config
OUTPUT_DEVICE_NAME_SET = False # True when output_device_name was set in the config
# On webOS 10+, keys resent through Builtin [2] make Back exit the app instead of closing menus,
# so Builtin [1] is preferred there unless output_device_name is set
WEBOS_10_OUTPUT_DEVICE_NAME = 'LGE M-RCU - Builtin [1]'
WEBOS_MAJOR_VERSION = 0 # set in main()
BUTTONS = {
398: "red",
399: "green",
400: "yellow",
401: "blue",
402: "ch_up",
403: "ch_down",
115: "vol_up",
114: "vol_down",
207: "play",
119: "pause",
128: "stop",
167: "record",
168: "rewind",
208: "fastforward",
2: "1",
3: "2",
4: "3",
5: "4",
6: "5",
7: "6",
8: "7",
9: "8",
10: "9",
11: "0",
1038: "prime",
1107: "sling",
1037: "netflix",
1042: "disney",
1043: "lg_channels",
1044: "rakuten",
1086: "alexa",
1117: "google",
362: "guide",
428: "voice",
771: "channels",
787: "channels_alt", # seen on an LG IR remote
994: "...",
799: "...alt", # seen on an LG IR remote, button with three dots surrounded by a rectangle
1083: "search",
217: "search_alt", # seen on an LG IR remote
174: "exit", # seen on an LG IR remote, appears to exit apps
829: "sap",
1116: "tv",
358: "info",
773: "home",
28: "ok",
412: "back",
1123: "home_hub",
1124: "accessibility",
139: "settings",
103: "up",
108: "down",
105: "left",
106: "right",
}
MOUSE_WHEEL = {
1: "wheel_up",
-1: "wheel_down"
}
EVIOCGRAB = 1074021776 # Don't mess with this
def cycle_energy_mode(inputs):
"""cycle energy modes between min med max off"""
modes = ["max", "med", "min", "off"]
if inputs.get("reverse_order"):
modes.reverse()
current_mode = get_picture_settings()["settings"]["energySaving"]
if current_mode in modes:
next_mode = modes.index(current_mode) + 1
else: # It's probably in auto mode so just start at the first mode
next_mode = 0
if next_mode >= len(modes):
next_mode = 0
inputs["mode"] = modes[next_mode]
set_energy_mode(inputs)
def toggle_eye_comfort(inputs):
"""Toggle the eye comfort mode aka reduce blue light"""
current_mode = get_picture_settings()["settings"]["eyeComfortMode"]
print("current eye comfort mode: current_mode %s" % current_mode)
if current_mode == "off":
new_mode = "on"
else:
new_mode = "off"
endpoint = "luna://com.webos.settingsservice/setSystemSettings"
payload = {"category": "picture", "settings": {"eyeComfortMode": new_mode}}
luna_send(endpoint, payload)
if inputs.get("notifications"):
show_message("Reduce blue light mode: %s" % new_mode)
def screen_off(inputs):
"""Turns the screen off, but not the TV itself.
Press any button but power and vol to turn it back on.
"""
endpoint = "luna://com.webos.service.tvpower/power/turnOffScreen"
payload = {}
luna_send(endpoint, payload)
def set_energy_mode(inputs):
"""Sets the energy savings mode
Inputs:
- mode (string, default: none)
- Valid values: min med max off auto screen_off
Note screen_off may not work on some models, best to use the screen_off function instead
"""
mode = inputs["mode"]
endpoint = "luna://com.webos.settingsservice/setSystemSettings"
payload = {"category": "picture", "settings": {"energySaving": mode}}
luna_send(endpoint, payload)
if inputs.get("notifications"):
show_message("Energy mode: %s" % mode)
def increase_oled_light(inputs):
"""Increase the oled light value
Inputs:
increment (10) - the value to raise the light level on each press
disable_energy_savings (True) - If energy savings is on, disable it
"""
increment_oled_light(inputs, direction="up")
def reduce_oled_light(inputs):
"""Decrease the oled light value
Inputs:
increment (10) - the value to lower the light level on each press
disable_energy_savings (True) - If energy savings is on, disable it
"""
increment_oled_light(inputs, direction="down")
def set_oled_backlight(inputs):
backlight = inputs["backlight"]
endpoint = "luna://com.webos.settingsservice/setSystemSettings"
payload = {"category": "picture", "settings": {"backlight": backlight}}
luna_send(endpoint, payload)
if inputs.get("notifications"):
show_message("OLED Backlight: %s" % backlight)
def launch_app(inputs):
"""Launch an app by app_id
Inputs:
app_id - Use list_apps.py to get the app_id
params (optional) - dict of launch params passed to the app.
For the browser (com.webos.app.browser) use {"target": "https://..."}
to open a specific URL.
"""
app_id = inputs["app_id"]
endpoint = "luna://com.webos.service.applicationmanager/launch"
payload = {"id": app_id}
params = inputs.get("params")
if params:
payload["params"] = params
luna_send(endpoint, payload)
def send_ir_command(inputs):
"""Send an IR command to a configured device
This relies on you using the device connection manager to setup your IR device (ie a soundbar)
Once setup you can use this function to have the remote send IR commands
"""
tv_input = inputs["tv_input"] # "OPTICAL", other inputs untested
keycode = inputs["keycode"] # "IR_KEY_VOLUP" "IR_KEY_POWER"
device_type = inputs["device_type"] # "audio"
endpoint = "luna://com.webos.service.irdbmanager/sendIrCommand"
payload = {
"keyCode": keycode,
"buttonState": "single",
"connectedInput": tv_input,
"deviceType": device_type,
}
luna_send(endpoint, payload)
def curl(inputs):
"""Execute the system curl binary with the provided inputs
Note this script has to work on Python 2.7 and 3.x, and very
few Python libraries are included in WebOS, so we'll just
keep it simple and use the system curl binary vs urllib.
"""
url = inputs.get("url")
if not url:
print("ERROR: curl function called but url not supplied")
return
method = inputs.get("method", "GET").upper()
command_string = "curl -vs -X %s" % method
command = command_string.split()
headers = inputs.get("headers")
if headers:
if type(headers) == list:
for header in headers:
command.append("-H")
command.append(header)
else:
if type(headers) != str: # Python 2.7 on the C9 returns unicode instead of str
headers = str(headers)
command.append("-H")
command.append(headers)
data = inputs.get("data")
if data:
command.append("-d")
command.append(data)
command.append(url)
print("Running curl command: %s" % " ".join(command))
try:
output = subprocess.check_output(command)
except subprocess.CalledProcessError as error:
print("WARNING: curl command failed")
print(error)
return
return output
def press_button(inputs):
"""Simulate a button press on the remote
This is useful to simulate the play and pause buttons for remotes that don't have these buttons
Inputs: button_name (str)
"""
button = inputs["button"]
keycode = get_keycode(button)
if not keycode:
return
output_device_path = resolve_output_device()
print("Simulating keystroke with button '%s' (keycode %s). Output device: %s" % (button, keycode, output_device_path))
send_keystroke(output_device_path, keycode)
def send_cec_button(inputs):
"""This sends an HDMI-CEC button press to the current input device
Consider this experimental, little is known about how this works (from my perspective as the developer)
Inputs:
code (integer, default: none) - The code to send. Only code known at present is 18882561 which is "Home".
"""
code = inputs["code"]
if WEBOS_MAJOR_VERSION < 5:
endpoint = "luna://com.webos.service.tv.keymanager/createKeyEvent"
code_key = "code"
else:
endpoint = "luna://com.webos.service.eim/cec/sendKeyEvent"
code_key = "key"
payload = {code_key: code, "device": "remoteControl", "id": "magic_mapper", "type": "keyDown"}
luna_send(endpoint, payload)
payload["type"] = "keyUp"
luna_send(endpoint, payload)
def set_dynamic_tone_mapping(inputs):
"""Set a specific value for Dynamic Tone Mapping
Inputs:
- value (string, default: none)
- Valid values: "off", "on", "HGIG"
"""
value = inputs["value"]
# values are case sensitive
if value.upper() == "HGIG":
value = "HGIG"
else:
value = value.lower()
endpoint = "luna://com.webos.settingsservice/setSystemSettings"
payload = {"category": "picture", "settings": {"hdrDynamicToneMapping": value}}
luna_send(endpoint, payload)
def disabled(inputs):
print("Key was disabled")
def send_tcp_command(inputs):
"""Send a TCP command to a specified IP address and port.
Inputs:
ip (str): The IP address of the target device.
port (int): The port number of the target device.
command (str): The command string to send.
timeout (float, optional): Socket timeout in seconds. Default is 5.
"""
if not SOCKET_AVAILABLE:
print("ERROR: socket library is not available, cannot use send_tcp_command()")
return
ip = inputs.get("ip")
port = inputs.get("port")
command = inputs.get("command")
timeout = inputs.get("timeout", 5.0)
if not ip or not port or command is None: # command can be an empty string
print("ERROR: send_tcp_command called with missing ip, port, or command")
return
try:
# Ensure command is a string and ends with a newline for many TCP services
if not command.endswith("\r\n"):
command += "\r\n"
# Convert command to bytes
command_bytes = command.encode('utf-8')
print("Sending TCP command '%s' to %s:%s" % (command, ip, port))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((ip, port))
sock.sendall(command_bytes)
# Optionally, receive a response
# response = sock.recv(1024)
# print("Received response: %s" % response.decode('utf-8'))
sock.close()
print("TCP command sent successfully.")
except socket.error as e:
print("ERROR: Could not send TCP command to %s:%s - %s" % (ip, port, e))
except Exception as e:
print("ERROR: An unexpected error occurred in send_tcp_command: %s" % e)
def toggle_piccap(inputs):
piccap_service = "luna://org.webosbrew.piccap.service"
status = luna_send("%s/status" % piccap_service, {})
status = json.loads(status)
if status.get("isRunning"):
action = "stopped"
endpoint = "%s/stop" % piccap_service
else:
action = "started"
endpoint = "%s/start" % piccap_service
luna_send(endpoint, {})
print("PicCap service %s" % action)
def toggle_bluetooth(inputs):
"""Toggle the WebOS bluetooth service on or off.
Disabling bluetooth turns the Magic Remote into an IR-only remote (only the
IR functions keep working), but stops unwanted bluetooth connection requests.
This starts/stops the same webos-bluetooth-service that the webOS Bluetooth
Disabler app controls; magic_mapper already runs as root so it can call the
init system directly instead of going through the Homebrew Channel service.
Inputs:
notifications (bool, default: False) - show a toast with the new state
"""
init_system = get_init_system()
if not init_system:
print("ERROR: could not determine init system, cannot toggle bluetooth")
if inputs.get("notifications"):
show_message("Bluetooth toggle failed")
return
active = bluetooth_is_active(init_system)
if active:
new_state = "off"
if init_system == "systemd":
command = ["systemctl", "stop", "webos-bluetooth-service.service"]
else:
command = ["stop", "webos-bluetooth-service"]
else:
new_state = "on"
if init_system == "systemd":
command = ["systemctl", "start", "webos-bluetooth-service.service"]
else:
command = ["start", "webos-bluetooth-service"]
print("Bluetooth service is %s, turning it %s" % (
"active" if active else "inactive", new_state))
try:
subprocess.check_call(command)
except (subprocess.CalledProcessError, OSError) as error:
print("WARNING: failed to toggle bluetooth: %s" % error)
if inputs.get("notifications"):
show_message("Bluetooth toggle failed")
return
print("Bluetooth turned %s" % new_state)
if inputs.get("notifications"):
show_message("Bluetooth: %s" % new_state)
###################################
# Private Functions
# The fuctions below here should not be called by magic_mapper_config.json
####################################
# The functions above that magic_mapper_config.json is allowed to call.
# If you add a new function for the config, add it here too.
CONFIG_FUNCTIONS = (
"cycle_energy_mode",
"toggle_eye_comfort",
"screen_off",
"set_energy_mode",
"increase_oled_light",
"reduce_oled_light",
"set_oled_backlight",
"launch_app",
"send_ir_command",
"curl",
"press_button",
"send_cec_button",
"set_dynamic_tone_mapping",
"disabled",
"send_tcp_command",
"toggle_piccap",
"toggle_bluetooth",
)
def get_button_map():
"""Read the json config file"""
config_path = os.path.join(os.path.dirname(__file__), "magic_mapper_config.json")
with open(config_path) as config_file:
button_map = json.load(config_file)
settings = button_map.pop("magic_mapper_settings", {})
apply_settings(settings)
return validate_button_map(button_map)
def validate_button_map(button_map):
"""Check every button mapping at startup and drop the invalid ones so the rest still work"""
valid_map = {}
for button, actions in button_map.items():
if actions == "disabled":
valid_map[button] = actions
continue
if isinstance(actions, dict):
action_list = [actions]
elif isinstance(actions, list):
action_list = actions
else:
print("ERROR: config for button '%s' must be a dict, a list of dicts, or \"disabled\", ignoring it" % button)
continue
problems = []
for action in action_list:
if not isinstance(action, dict):
problems.append("each entry must be a dict")
elif action.get("function") not in CONFIG_FUNCTIONS:
problems.append("unknown function '%s'" % action.get("function"))
elif not isinstance(action.get("inputs", {}), dict):
problems.append("inputs for '%s' must be a dict" % action["function"])
if not action_list:
problems.append("the list of actions is empty")
if problems:
print("ERROR: config for button '%s' is invalid (%s), ignoring it" % (button, "; ".join(problems)))
continue
valid_map[button] = actions
return valid_map
def apply_settings(settings):
"""Override the default settings with the magic_mapper_settings section of the config"""
global BLOCK_MOUSE, EXCLUSIVE_MODE, INPUT_DEVICE_NAME, INPUT_DEVICE_NAME_SET, OUTPUT_DEVICE_NAME, OUTPUT_DEVICE_NAME_SET
global IR_INPUT_ENABLED, IR_INPUT_DEVICE_NAME, IR_EXCLUSIVE_MODE
for key in settings:
if key not in ["block_mouse", "exclusive_mode", "input_device_name", "output_device_name",
"ir_input_enabled", "ir_input_device_name", "ir_exclusive_mode"]:
print("WARNING: unknown setting '%s' in magic_mapper_settings" % key)
if "block_mouse" in settings:
BLOCK_MOUSE = str_to_bool(settings["block_mouse"])
if "exclusive_mode" in settings:
EXCLUSIVE_MODE = str_to_bool(settings["exclusive_mode"])
if "input_device_name" in settings:
INPUT_DEVICE_NAME = settings["input_device_name"]
INPUT_DEVICE_NAME_SET = True
if "output_device_name" in settings:
OUTPUT_DEVICE_NAME = settings["output_device_name"]
OUTPUT_DEVICE_NAME_SET = True
if "ir_input_enabled" in settings:
IR_INPUT_ENABLED = str_to_bool(settings["ir_input_enabled"])
if "ir_input_device_name" in settings:
IR_INPUT_DEVICE_NAME = settings["ir_input_device_name"]
if "ir_exclusive_mode" in settings:
IR_EXCLUSIVE_MODE = str_to_bool(settings["ir_exclusive_mode"])
if BLOCK_MOUSE and not EXCLUSIVE_MODE:
print("WARNING: block_mouse has no effect unless exclusive_mode is true")
if "ir_exclusive_mode" in settings and IR_EXCLUSIVE_MODE and not IR_INPUT_ENABLED:
print("WARNING: ir_exclusive_mode has no effect unless ir_input_enabled is true")
def fire_event_one(action):
"""Execute the function configured for the button"""
func_name = action["function"]
print("func_name: %s" % func_name)
if func_name not in CONFIG_FUNCTIONS:
print("ERROR: function '%s' can't be called from magic_mapper_config.json" % func_name)
return
inputs = action.get("inputs", {})
globals()[func_name](inputs)
def fire_events(actions):
"""Execute the function(s) configured for the button"""
for action in actions:
fire_event_one(action)
def luna_send(endpoint, payload):
# Execute luna send and return the output
#
# webOS 10.x (Rockhopper) regression: `luna-send -n 1` is a silent no-op --
# it neither prints a response nor actually delivers the message, so every
# bound button would appear to do nothing. Verified A/B on an OLED65C4PUA
# (webOS 10.3.1): an identical launch call fires with `-t 1` and does nothing
# with `-n 1`. `-t 1` delivers exactly once (it means "time 1 iteration"),
# but the response payload comes back on STDERR behind a
# "timingServiceResponse" line, so the callers that json.loads() this need it
# recovered from there.
#
# Gated on version so pre-10 devices keep the exact original code path.
if WEBOS_MAJOR_VERSION >= 10:
command = ["/usr/bin/luna-send", "-t", "1", endpoint, json.dumps(payload)]
print("running command: %s" % command)
proc = subprocess.run(command, capture_output=True)
for line in proc.stderr.decode("utf-8", "replace").splitlines():
if "timingServiceResponse" in line and "{" in line:
return line[line.find("{"):]
return proc.stdout.decode("utf-8", "replace")
command = ["/usr/bin/luna-send", "-n", "1"]
command.append(endpoint)
command.append(json.dumps(payload))
print("running command: %s" % command)
output = subprocess.check_output(command)
return output
def increment_oled_light(inputs, direction):
"""Increment the oled backlight up or down"""
increment = inputs.get("increment", 10)
current_settings = get_picture_settings()["settings"]
disable_energy_savings = str_to_bool(inputs.get("disable_energy_savings", True))
if disable_energy_savings:
if current_settings["energySaving"] != "off":
set_energy_mode({"mode": "off"})
current_value = int(current_settings["backlight"])
if direction == "up":
new_value = current_value + increment
if new_value > 100:
new_value = 100
elif direction == "down":
new_value = current_value - increment
if new_value < 0:
new_value = 0
inputs["backlight"] = new_value
set_oled_backlight(inputs)
def get_picture_settings():
# Return the current settings
endpoint = "luna://com.webos.settingsservice/getSystemSettings"
payload = {"category": "picture"}
output = luna_send(endpoint, payload)
settings = json.loads(output)
return settings
def show_message(message):
"""Shows a "toast" message"""
endpoint = "luna://com.webos.notification/createToast"
payload = {"message": message}
luna_send(endpoint, payload)
def get_keycode(button):
"""Returns the keycode associated with the button name"""
keys = [k for k, v in BUTTONS.items() if v == button]
if keys:
return keys[0]
print('ERROR: Button "%s" not found!' % button)
return None
def send_keystroke(device, keycode):
"""Send a keystroke to the input device
We use this to simulate button presses like play/pause since those require special handling
Use the press_button function for magic_mapper_config.json
};
"""
send_input_event(device, keycode, 1, 1)
send_input_event(device, 0, 0, 0)
send_input_event(device, keycode, 0, 1)
send_input_event(device, 0, 0, 0)
def send_input_event(device, keycode, value, event_type):
"""Low level function to write to the input device file
Don't call this from magic_mapper_config.json
"""
input_format = "llHHI"
out_file = os.open(device, os.O_RDWR)
now = time.time()
tv_sec = int(now)
tv_usec = int((now - tv_sec) * 1000000)
data = [tv_sec, tv_usec, event_type, keycode, value]
# print("writing: %s" % data)
event = struct.pack(input_format, *data)
os.write(out_file, event)
os.close(out_file)
def str_to_bool(value):
"""Convert a config value to bool. Accepts bools and strings."""
if isinstance(value, bool):
return value
if str(value).lower() in ["yes", "true"]:
return True
return False
def get_webos_version():
"""Return webos version"""
try:
with open("/etc/starfish-release") as f:
release = f.read()
version = release.split()[2]
major_version = version.split(".")[0]
return int(major_version)
except (OSError, IOError, IndexError, ValueError) as e:
print("WARNING: could not determine the WebOS version, assuming an old version: %s" % e)
return 0
def get_init_system():
"""Detect whether the TV uses systemd or upstart.
On systemd TVs /sbin/init is a symlink to systemd. Upstart TVs have a plain
/sbin/init, so look for upstart's initctl instead.
Returns "systemd", "upstart", or None if unknown.
"""
if "systemd" in os.path.realpath("/sbin/init"):
return "systemd"
if os.path.exists("/sbin/initctl"):
return "upstart"
print("WARNING: could not determine the init system")
return None
def bluetooth_is_active(init_system):
"""Return True if the webos-bluetooth-service is currently running."""
if init_system == "systemd":
# `systemctl is-active` prints "active" and exits 0 when running, or
# prints "inactive"/"failed" and exits non-zero when not.
try:
output = subprocess.check_output(
["systemctl", "is-active", "webos-bluetooth-service.service"])
except subprocess.CalledProcessError as error:
output = error.output or b""
except OSError as error:
print("WARNING: could not query bluetooth status: %s" % error)
return False
return output.decode("utf-8", "replace").strip() == "active"
# upstart: `status webos-bluetooth-service` prints "... start/running"
# when up and "... stop/waiting" when down.
try:
output = subprocess.check_output(["status", "webos-bluetooth-service"])
except (subprocess.CalledProcessError, OSError) as error:
print("WARNING: could not query bluetooth status: %s" % error)
return False
return "start/running" in output.decode("utf-8", "replace")
def open_source_device(device_name, grab):
"""Resolve, open, and (optionally) grab an input device.
Returns a dict describing the source, or None if it could not be opened.
The device is opened unbuffered (os.open/os.read): a buffered file would
pull several events into Python's buffer where select() can't see them,
delaying key ups until the next press.
"""
path = resolve_input_device_by_name(device_name)
if not path:
print("WARNING: could not resolve input device '%s'" % device_name)
return None
try:
fd = os.open(path, os.O_RDONLY)
except (IOError, OSError) as error:
print("WARNING: could not open input device '%s' (%s): %s" % (device_name, path, error))
return None
grabbed = False
if grab:
try:
fcntl.ioctl(fd, EVIOCGRAB, 1)
grabbed = True
print("Exclusive mode: grabbed input device '%s' (%s)" % (device_name, path))
except (IOError, OSError) as error:
print("WARNING: could not grab '%s' (%s): %s" % (device_name, path, error))
print("Opened input device '%s' (%s)" % (device_name, path))
return {"name": device_name, "path": path, "fd": fd, "grabbed": grabbed}
def open_output_device():
"""Open the device unmapped events are resent to in exclusive mode, or return None"""
output_device_path = resolve_output_device()
if output_device_path is None:
return None
try:
output_device = os.open(output_device_path, os.O_WRONLY)
except (IOError, OSError) as error:
print("WARNING: could not open output device %s: %s" % (output_device_path, error))
return None
print("Keys will be resent to: %s" % output_device_path)
return output_device
def resend_event(output, event):
"""Resend an unmapped event to the output device, reopening the device once if the write fails"""
if output["fd"] is not None:
try:
os.write(output["fd"], event)
return
except (IOError, OSError) as error:
print("WARNING: could not resend event to the output device, reopening it: %s" % error)
try:
os.close(output["fd"])
except (IOError, OSError):
pass
output["fd"] = open_output_device()
if output["fd"] is None:
print("ERROR: no output device, dropping event")
return
try:
os.write(output["fd"], event)
except (IOError, OSError) as error:
print("ERROR: could not resend event to the output device, dropping it: %s" % error)
def input_loop(button_map):
# Read from the input device(s)
# https://stackoverflow.com/a/16682549/866057
input_format = "llHHi"
event_size = struct.calcsize(input_format)
buttons_waiting = {}
# (device name, grab) for every device we read: the remote over bluetooth,
# and if ir_input_enabled is true the IR receiver, which gets the remote's
# presses while bluetooth is off
wanted = [(INPUT_DEVICE_NAME, EXCLUSIVE_MODE)]
if IR_INPUT_ENABLED:
if not SELECT_AVAILABLE:
print("WARNING: the select library isn't available, IR input is disabled")
elif IR_INPUT_DEVICE_NAME == INPUT_DEVICE_NAME:
print("ir_input_device_name is the same as input_device_name, not reading it twice")
else:
wanted.append((IR_INPUT_DEVICE_NAME, IR_EXCLUSIVE_MODE))
output = {"fd": None}
if [name for name, grab in wanted if grab]:
print("Exclusive mode is enabled, taking over input device(s)")
output["fd"] = open_output_device()
if output["fd"] is None:
# Carry on without exclusive mode rather than exiting, so the buttons still work
print("ERROR: could not find output device, check output_device_name in magic_mapper_config.json. Continuing without exclusive mode")
wanted = [(name, False) for name, grab in wanted]
else:
print("EXCLUSIVE_MODE is disabled, will not override default button behavior")
sources = {} # fd -> source dict from open_source_device()
for name, grab in wanted:
source = open_source_device(name, grab)
if source:
sources[source["fd"]] = source
if not sources:
print("ERROR: could not find input device, check input_device_name in magic_mapper_config.json")
sys.exit(1)
first_loop = 2
while True:
if first_loop == 1:
print("First loop complete, Magic Mapper is running")
first_loop = 0
elif first_loop == 2:
print("Input loop started, waiting for button presses on %d device(s)" % len(sources))
first_loop = 1
if SELECT_AVAILABLE:
readable = select.select(list(sources), [], [])[0]
else:
readable = list(sources) # only one device without select, a blocking read is fine
for fd in readable:
source = sources[fd]
try:
event = os.read(fd, event_size)
except (IOError, OSError) as error:
event = None
print("WARNING: could not read input device '%s': %s" % (source["name"], error))
if not event:
# Exit so start_magic_mapper restarts us and reopens the devices
print("ERROR: lost input device '%s', exiting" % source["name"])
sys.exit(1)
handle_event(event, input_format, source, button_map, buttons_waiting, output)
def handle_event(event, input_format, source, button_map, buttons_waiting, output):
"""Process a single input event read from one of the source devices."""
(tv_sec, tv_usec, event_type, code, value) = struct.unpack(input_format, event)
now = time.time()
key = None
if event_type == 1:
key = BUTTONS.get(code)
elif event_type == 2:
code = value # up/down
key = MOUSE_WHEEL.get(code)
value = 0
buttons_waiting[(source["name"], code)] = now
actions = button_map.get(key)
if actions == "disabled":
print("Button %s is disabled" % key)
return
current_app = None
if actions:
if type(actions) is not list:
actions = [actions]
endpoint = "luna://com.webos.applicationManager/getForegroundAppInfo"
try:
current_app = json.loads(luna_send(endpoint, {})).get('appId')
except Exception:
print("ERROR: could not get the foreground app, only mappings without an appId will be used")
traceback.print_exc()
filtered_actions = []
found_match = False
for action in actions:
appId = action.get('appId')
if appId is None:
filtered_actions += [action]
if appId == current_app:
filtered_actions += [action]
found_match = True
if appId == '!' and not found_match:
filtered_actions += [action]
actions = filtered_actions
if not actions:
# In exclusive mode we resend unhandled events so others can read them.
# Only grabbed devices need this, ungrabbed devices already deliver their events normally.
if source["grabbed"] and not (BLOCK_MOUSE and code == 1198):
resend_event(output, event)
if key and value == 1:
print("Button %s not configured in magic_mapper_config.json (device: %s, code: %s)" % (key, source["name"], code))
elif value == 1:
print("Button code %s ignored (device: %s)" % (code, source["name"]))
return
wait_key = (source["name"], code)
# Button Down
if value == 1:
print("%s button down (device: %s)" % (key, source["name"]))
if wait_key in buttons_waiting and now - buttons_waiting[wait_key] < 1.0:
print("WARNING: Got code %s DOWN while waiting for UP" % code)
buttons_waiting[wait_key] = now
# Button Up
if value == 0:
if wait_key not in buttons_waiting:
print("WARNING: Got code %s UP with no DOWN" % code)
elif now - buttons_waiting[wait_key] > 1.0:
print("Ignoring long press of %s" % key)
# Tell the user that the long press was blocked because of magic mapper; to avoid any confusion.
try:
luna_send("luna://com.webos.notification/createToast", {"sourceId":"magic mapper","message":"long press for %s is disabled due to magic mapper" % key})
except Exception:
traceback.print_exc()
else:
print("%s button up (device: %s)" % (key, source["name"]))
print("firing event(s) for code: %s button: %s" % (code, key))
# Don't let one failing action kill the script
try:
fire_events(actions)
except Exception:
print("ERROR: action for button %s failed" % key)
traceback.print_exc()
if wait_key in buttons_waiting:
del buttons_waiting[wait_key]
def read_input_devices():
"""
Parse /proc/bus/input/devices into a list of (name, event_path) tuples
"""
try:
with open("/proc/bus/input/devices", "r") as f:
data = f.read()
except Exception as e:
print("ERROR: cannot read /proc/bus/input/devices: %s" % e)
return []
devices = []
# Split before each I: line; each block describes one device.
# The pattern must consume the newline: re.split ignores zero-width matches before python 3.7
blocks = re.split(r"\n\s*(?=I:)", data.strip())
for block in blocks:
# Look for N: Name="..."
m_name = re.search(r'^N:\s+Name="([^"]+)"', block, flags=re.M)
if not m_name:
continue
# Look for H: Handlers=... and pick the first 'eventX'
event_path = None
m_handlers = re.search(r'^H:\s+Handlers=([^\n]+)', block, flags=re.M)
if m_handlers:
for h in m_handlers.group(1).split():
if h.startswith("event") and h[5:].isdigit():
event_path = "/dev/input/" + h
break
devices.append((m_name.group(1), event_path))
return devices
def resolve_input_device_by_name(device_name, quiet=False):
"""
Find the input device path by looking for the device_name in /proc/bus/input/devices
quiet=True skips the warning when the device isn't found
"""
print("Resolving input device path for device named '%s'" % device_name)
devices = read_input_devices()
for name, event_path in devices: