forked from trainman419/python-cec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cec.cpp
1191 lines (1092 loc) · 38.5 KB
/
cec.cpp
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
/* cec.cpp
*
* Copyright (C) 2013 Austin Hendrix <namniart@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This file provides the python cec module, which is a python wrapper
* around libcec
*
* Author: Austin Hendrix <namniart@gmail.com>
*/
// request the std format macros
#define __STDC_FORMAT_MACROS
#include <Python.h>
#include <stdlib.h>
#include <inttypes.h>
#include <libcec/cec.h>
#include <algorithm>
#include <list>
#include "device.h"
using namespace CEC;
// Basic design/usage:
//
// ( cec.add_callback(event, handler) )
// ???
//
// ( cec.remove_callback(event, handler) )
// ???
//
// ( cec.transmit( ??? ) )
// call ICECAdapter::Transmit()
//
// Events:
// - log message
// message.message[1024]
// message.level (bitfield)
// message.time (int64)
// - key press
// key.keycode (int/enum)
// key.duration (int)
// - command
// command.initiator (logical address)
// command.destination (logical address)
// command.ack
// command.eom
// command.opcode (enum)
// command.parameters
// command.opcode_set (flag for when opcode is set; should probably use
// this to set opcode to None)
// command.transmit_timeout
// - cec configuration changed (adapter/library config change)
// - alert
// - menu state changed
// this is potentially thorny; see libcec source and CEC spec
// ???
// - source activated
//
#define EVENT_LOG 0x0001
#define EVENT_KEYPRESS 0x0002
#define EVENT_COMMAND 0x0004
#define EVENT_CONFIG_CHANGE 0x0008
#define EVENT_ALERT 0x0010
#define EVENT_MENU_CHANGED 0x0020
#define EVENT_ACTIVATED 0x0040
#define EVENT_VALID 0x007F
#define EVENT_ALL 0x007F
//#define DEBUG 1
#ifdef DEBUG
# define debug(...) printf("CEC DEBUG: " __VA_ARGS__)
#else
# define debug(...)
#endif
// cec_adapter_descriptor and DetectAdapters were introduced in 2.1.0
#if CEC_LIB_VERSION_MAJOR >= 3 || (CEC_LIB_VERSION_MAJOR >= 2 && CEC_LIB_VERSION_MINOR >= 1)
#define CEC_ADAPTER_TYPE cec_adapter_descriptor
#define CEC_FIND_ADAPTERS DetectAdapters
#define HAVE_CEC_ADAPTER_DESCRIPTOR 1
#else
#define CEC_ADAPTER_TYPE cec_adapter
#define CEC_FIND_ADAPTERS FindAdapters
#define HAVE_CEC_ADAPTER_DESCRIPTOR 0
#endif
int parse_physical_addr(const char * addr) {
int a, b, c, d;
if( sscanf(addr, "%x.%x.%x.%x", &a, &b, &c, &d) == 4 ) {
if( a > 0xF || b > 0xF || c > 0xF || d > 0xF ) return -1;
if( a < 0 || b < 0 || c < 0 || d < 0 ) return -1;
return (a << 12) | (b << 8) | (c << 4) | d;
} else {
return -1;
}
}
#define RETURN_BOOL(arg) do { \
bool result; \
Py_BEGIN_ALLOW_THREADS \
result = (arg); \
Py_END_ALLOW_THREADS \
PyObject * ret = (result)?Py_True:Py_False; \
Py_INCREF(ret); \
return ret; \
} while(0)
void parse_test() {
assert(parse_physical_addr("0.0.0.0") == 0);
assert(parse_physical_addr("F.0.0.0") == 0xF000);
assert(parse_physical_addr("0.F.0.0") == 0x0F00);
assert(parse_physical_addr("0.0.F.0") == 0x00F0);
assert(parse_physical_addr("0.0.0.F") == 0x000F);
assert(parse_physical_addr("-1.0.0.0") == -1);
assert(parse_physical_addr("0.-1.0.0") == -1);
assert(parse_physical_addr("0.0.-1.0") == -1);
assert(parse_physical_addr("0.0.0.-1") == -1);
assert(parse_physical_addr("foo") == -1);
assert(parse_physical_addr("F.F.F.F") == 0xFFFF);
assert(parse_physical_addr("f.f.f.f") == 0xFFFF);
}
ICECAdapter * CEC_adapter;
PyObject * Device;
std::list<CEC_ADAPTER_TYPE> get_adapters() {
std::list<CEC_ADAPTER_TYPE> res;
// release the Global Interpreter lock
Py_BEGIN_ALLOW_THREADS
// get adapters
int cec_count = 10;
CEC_ADAPTER_TYPE * dev_list = (CEC_ADAPTER_TYPE*)malloc(
cec_count * sizeof(CEC_ADAPTER_TYPE));
int count = CEC_adapter->CEC_FIND_ADAPTERS(dev_list, cec_count);
if( count > cec_count ) {
cec_count = count;
dev_list = (CEC_ADAPTER_TYPE*)realloc(dev_list,
cec_count * sizeof(CEC_ADAPTER_TYPE));
count = CEC_adapter->CEC_FIND_ADAPTERS(dev_list, cec_count);
count = (std::min)(count, cec_count);
}
for( int i=0; i<count; i++ ) {
res.push_back(dev_list[i]);
}
free(dev_list);
// acquire the GIL before returning to code that uses python objects
Py_END_ALLOW_THREADS
return res;
}
static PyObject * list_adapters(PyObject * self, PyObject * args) {
PyObject * result = NULL;
if( PyArg_ParseTuple(args, ":list_adapters") ) {
std::list<CEC_ADAPTER_TYPE> dev_list = get_adapters();
// set up our result list
result = PyList_New(0);
// populate our result list
std::list<CEC_ADAPTER_TYPE>::const_iterator itr;
for( itr = dev_list.begin(); itr != dev_list.end(); itr++ ) {
#if HAVE_CEC_ADAPTER_DESCRIPTOR
PyList_Append(result, Py_BuildValue("s", itr->strComName));
/* Convert all of the fields
PyList_Append(result, Py_BuildValue("sshhhhii",
itr->strComName,
itr->strComPath,
itr->iVendorId,
itr->iProductId,
itr->iFirmwareVersion,
itr->iPhysicalAddress,
itr->iFirmwareBuildDate,
itr->adapterType
));
*/
#else
PyList_Append(result, Py_BuildValue("s", itr->comm));
/* Convert all of the fields
PyList_Append(result, Py_BuildValue("sshhhhii",
itr->comm,
itr->strComPath,
itr->iVendorId,
itr->iProductId,
itr->iFirmwareVersion,
itr->iPhysicalAddress,
itr->iFirmwareBuildDate,
itr->adapterType
));
*/
#endif
}
}
return result;
}
static PyObject * init(PyObject * self, PyObject * args) {
PyObject * result = NULL;
const char * dev = NULL;
if( PyArg_ParseTuple(args, "|s:init", &dev) ) {
if( !dev ) {
std::list<CEC_ADAPTER_TYPE> devs = get_adapters();
if( devs.size() > 0 ) {
#if HAVE_CEC_ADAPTER_DESCRIPTOR
dev = devs.front().strComName;
#else
dev = devs.front().comm;
#endif
} else {
PyErr_SetString(PyExc_Exception, "No default adapter found");
}
}
}
if( dev ) {
bool success = false;
Py_BEGIN_ALLOW_THREADS
success = CEC_adapter->Open(dev);
Py_END_ALLOW_THREADS
if( success ) {
Py_INCREF(Py_None);
result = Py_None;
} else {
CECDestroy(CEC_adapter);
CEC_adapter = NULL;
char errstr[1024];
snprintf(errstr, 1024, "CEC failed to open %s", dev);
PyErr_SetString(PyExc_IOError, errstr);
}
}
return result;
}
static PyObject * list_devices(PyObject * self, PyObject * args) {
PyObject * result = NULL;
if( PyArg_ParseTuple(args, ":list_devices") ) {
cec_logical_addresses devices;
Py_BEGIN_ALLOW_THREADS
devices = CEC_adapter->GetActiveDevices();
Py_END_ALLOW_THREADS
//result = PyList_New(0);
result = PyDict_New();
for( uint8_t i=0; i<32; i++ ) {
if( devices[i] ) {
PyObject * ii = Py_BuildValue("(b)", i);
PyObject * dev = PyObject_CallObject(Device, ii);
Py_DECREF(ii);
if( dev ) {
//PyList_Append(result, dev);
PyDict_SetItem(result, Py_BuildValue("b", i), dev);
} else {
Py_DECREF(result);
result = NULL;
break;
}
}
}
}
return result;
}
struct Callback {
public:
long int event;
PyObject * cb;
Callback(long int e, PyObject * c) : event(e), cb(c) {
}
};
typedef std::list<Callback> cb_list;
cb_list callbacks;
static PyObject * add_callback(PyObject * self, PyObject * args) {
PyObject * result = NULL;
PyObject * callback;
long int events = EVENT_ALL; // default to all events
if( PyArg_ParseTuple(args, "O|i:add_callback", &callback, &events) ) {
// check that event is one of the allowed events
if( events & ~(EVENT_VALID) ) {
PyErr_SetString(PyExc_TypeError, "Invalid event(s) for callback");
return NULL;
}
if( !PyCallable_Check(callback)) {
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
return NULL;
}
Py_INCREF(callback);
Callback new_cb(events, callback);
debug("Adding callback for event %ld\n", events);
callbacks.push_back(new_cb);
Py_INCREF(Py_None);
result = Py_None;
}
return result;
}
static PyObject * remove_callback(PyObject * self, PyObject * args) {
PyObject * callback;
long int events = EVENT_ALL; // default to all events
if( PyArg_ParseTuple(args, "O|i:remove_callback", &callback, &events) ) {
for( cb_list::iterator itr = callbacks.begin();
itr != callbacks.end();
++itr ) {
if( itr->cb == callback ) {
// clear out the given events for this callback
itr->event &= ~(events);
if( itr->event == 0 ) {
// if this callback has no events, remove it
itr = callbacks.erase(itr);
Py_DECREF(callback);
}
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject * make_bound_method_args(PyObject * self, PyObject * args) {
Py_ssize_t count = 0;
if( PyTuple_Check(args) ) {
count = PyTuple_Size(args);
}
PyObject * result = PyTuple_New(count+1);
if( result == NULL ) {
return NULL;
}
assert(self != NULL);
Py_INCREF(self);
PyTuple_SetItem(result, 0, self);
for( int i=0; i<count; i++ ) {
PyObject * arg = PyTuple_GetItem(args, i);
if( arg == NULL ) {
Py_DECREF(result);
return NULL;
}
Py_INCREF(arg);
PyTuple_SetItem(result, i+1, arg);
}
return result;
}
static PyObject * trigger_event(long int event, PyObject * args) {
assert(event & EVENT_ALL);
Py_INCREF(Py_None);
PyObject * result = Py_None;
//debug("Triggering event %ld\n", event);
int i=0;
for( cb_list::const_iterator itr = callbacks.begin();
itr != callbacks.end();
++itr ) {
//debug("Checking callback %d with events %ld\n", i, itr->event);
if( itr->event & event ) {
//debug("Calling callback %d\n", i);
PyObject * callback = itr->cb;
PyObject * arguments = args;
if( PyMethod_Check(itr->cb) ) {
callback = PyMethod_Function(itr->cb);
PyObject * self = PyMethod_Self(itr->cb);
if( self ) {
// bound method, prepend self/cls to argument tuple
arguments = make_bound_method_args(self, args);
}
}
// see also: PyObject_CallFunction(...) which can take C args
PyObject * temp = PyObject_CallObject(callback, arguments);
if( arguments != args ) {
Py_XDECREF(arguments);
}
if( temp ) {
debug("Callback succeeded\n");
Py_DECREF(temp);
} else {
debug("Callback failed\n");
Py_DECREF(Py_None);
return NULL;
}
}
i++;
}
return result;
}
static PyObject * transmit(PyObject * self, PyObject * args) {
unsigned char destination;
unsigned char opcode;
const char * params = NULL;
int param_count = 0;
if( PyArg_ParseTuple(args, "bb|s#:transmit", &destination, &opcode,
¶ms, ¶m_count) ) {
if( destination < 0 || destination > 15 ) {
PyErr_SetString(PyExc_ValueError, "Logical address must be between 0 and 15");
return NULL;
}
if( param_count > CEC_MAX_DATA_PACKET_SIZE ) {
char errstr[1024];
snprintf(errstr, 1024, "Too many parameters, maximum is %d",
CEC_MAX_DATA_PACKET_SIZE);
PyErr_SetString(PyExc_ValueError, errstr);
return NULL;
}
cec_command data;
bool success;
Py_BEGIN_ALLOW_THREADS
data.initiator = CEC_adapter->GetLogicalAddresses().primary;
data.destination = (cec_logical_address)destination;
data.opcode = (cec_opcode)opcode;
data.opcode_set = 1;
if( params ) {
for( int i=0; i<param_count; i++ ) {
data.PushBack(((uint8_t *)params)[i]);
}
}
success = CEC_adapter->Transmit(data);
Py_END_ALLOW_THREADS
RETURN_BOOL(success);
}
return NULL;
}
static PyObject * is_active_source(PyObject * self, PyObject * args) {
unsigned char addr;
if( PyArg_ParseTuple(args, "b:is_active_source", &addr) ) {
if( addr < 0 || addr > 15 ) {
PyErr_SetString(PyExc_ValueError, "Logical address must be between 0 and 15");
return NULL;
} else {
RETURN_BOOL(CEC_adapter->IsActiveSource((cec_logical_address)addr));
}
}
return NULL;
}
static PyObject * set_active_source(PyObject * self, PyObject * args) {
unsigned char devtype = (unsigned char)CEC_DEVICE_TYPE_RESERVED;
if( PyArg_ParseTuple(args, "|b:set_active_source", &devtype) ) {
if( devtype < 0 || devtype > 5 ) {
PyErr_SetString(PyExc_ValueError, "Device type must be between 0 and 5");
return NULL;
} else {
RETURN_BOOL(CEC_adapter->SetActiveSource((cec_device_type)devtype));
}
}
return NULL;
}
static PyObject * volume_up(PyObject * self, PyObject * args) {
if( PyArg_ParseTuple(args, ":volume_up") )
RETURN_BOOL(CEC_adapter->VolumeUp());
return NULL;
}
static PyObject * volume_down(PyObject * self, PyObject * args) {
if( PyArg_ParseTuple(args, ":volume_up") )
RETURN_BOOL(CEC_adapter->VolumeDown());
return NULL;
}
#if CEC_LIB_VERSION_MAJOR > 1
static PyObject * toggle_mute(PyObject * self, PyObject * args) {
if( PyArg_ParseTuple(args, ":toggle_mute") )
RETURN_BOOL(CEC_adapter->AudioToggleMute());
return NULL;
}
#endif
static PyObject * set_stream_path(PyObject * self, PyObject * args) {
PyObject * arg;
if( PyArg_ParseTuple(args, "O:set_stream_path", &arg) ) {
Py_INCREF(arg);
#if PY_MAJOR_VERSION >= 3
if(PyLong_Check(arg)) {
long arg_l = PyLong_AsLong(arg);
#else
if(PyInt_Check(arg)) {
long arg_l = PyInt_AsLong(arg);
#endif
Py_DECREF(arg);
if( arg_l < 0 || arg_l > 15 ) {
PyErr_SetString(PyExc_ValueError, "Logical address must be between 0 and 15");
return NULL;
} else {
RETURN_BOOL(CEC_adapter->SetStreamPath((cec_logical_address)arg_l));
}
#if PY_MAJOR_VERSION >= 3
} else if(PyUnicode_Check(arg)) {
const char * arg_s = PyUnicode_AsUTF8(arg);
#else
} else if(PyString_Check(arg)) {
char * arg_s = PyString_AsString(arg);
#endif
if( arg_s ) {
int pa = parse_physical_addr(arg_s);
Py_DECREF(arg);
if( pa < 0 ) {
PyErr_SetString(PyExc_ValueError, "Invalid physical address");
return NULL;
} else {
RETURN_BOOL(CEC_adapter->SetStreamPath((uint16_t)pa));
}
} else {
Py_DECREF(arg);
return NULL;
}
} else if(PyUnicode_Check(arg)) {
// Convert from Unicode to ASCII
PyObject* ascii_arg = PyUnicode_AsASCIIString(arg);
if (NULL == ascii_arg) {
// Means the string can't be converted to ASCII, the codec failed
PyErr_SetString(PyExc_ValueError,
"Could not convert address to ASCII");
return NULL;
}
// Get the actual bytes as a C string
char * arg_s = PyByteArray_AsString(ascii_arg);
if( arg_s ) {
int pa = parse_physical_addr(arg_s);
Py_DECREF(arg);
if( pa < 0 ) {
PyErr_SetString(PyExc_ValueError, "Invalid physical address");
return NULL;
} else {
RETURN_BOOL(CEC_adapter->SetStreamPath((uint16_t)pa));
}
} else {
Py_DECREF(arg);
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "parameter must be string or int");
return NULL;
}
}
return NULL;
}
PyObject * set_physical_addr(PyObject * self, PyObject * args) {
char * addr_s;
if( PyArg_ParseTuple(args, "s:set_physical_addr", &addr_s) ) {
int addr = parse_physical_addr(addr_s);
if( addr >= 0 ) {
RETURN_BOOL(CEC_adapter->SetPhysicalAddress((uint16_t)addr));
} else {
PyErr_SetString(PyExc_ValueError, "Invalid physical address");
return NULL;
}
}
return NULL;
}
PyObject * set_port(PyObject * self, PyObject * args) {
unsigned char dev, port;
if( PyArg_ParseTuple(args, "bb", &dev, &port) ) {
if( dev > 15 ) {
PyErr_SetString(PyExc_ValueError, "Invalid logical address");
return NULL;
}
if( port > 15 ) {
PyErr_SetString(PyExc_ValueError, "Invalid port");
return NULL;
}
RETURN_BOOL(CEC_adapter->SetHDMIPort((cec_logical_address)dev, port));
}
return NULL;
}
PyObject * can_persist_config(PyObject * self, PyObject * args) {
if( PyArg_ParseTuple(args, ":can_persist_config") ) {
RETURN_BOOL(CEC_adapter->CanPersistConfiguration());
}
return NULL;
}
PyObject * persist_config(PyObject * self, PyObject * args) {
if( PyArg_ParseTuple(args, ":persist_config") ) {
if( ! CEC_adapter->CanPersistConfiguration() ) {
PyErr_SetString(PyExc_NotImplementedError,
"Cannot persist configuration");
return NULL;
}
libcec_configuration config;
if( ! CEC_adapter->GetCurrentConfiguration(&config) ) {
PyErr_SetString(PyExc_IOError, "Could not get configuration");
return NULL;
}
RETURN_BOOL(CEC_adapter->PersistConfiguration(&config));
}
return NULL;
}
static PyMethodDef CecMethods[] = {
{"list_adapters", list_adapters, METH_VARARGS, "List available adapters"},
{"init", init, METH_VARARGS, "Open an adapter"},
{"list_devices", list_devices, METH_VARARGS, "List devices"},
{"add_callback", add_callback, METH_VARARGS, "Add a callback"},
{"remove_callback", remove_callback, METH_VARARGS, "Remove a callback"},
{"transmit", transmit, METH_VARARGS, "Transmit a raw CEC command"},
{"is_active_source", is_active_source, METH_VARARGS, "Check active source"},
{"set_active_source", set_active_source, METH_VARARGS, "Set active source"},
{"volume_up", volume_up, METH_VARARGS, "Volume Up"},
{"volume_down", volume_down, METH_VARARGS, "Volume Down"},
#if CEC_LIB_VERSION_MAJOR > 1
{"toggle_mute", toggle_mute, METH_VARARGS, "Toggle Mute"},
#endif
{"set_stream_path", set_stream_path, METH_VARARGS, "Set HDMI stream path"},
{"set_physical_addr", set_physical_addr, METH_VARARGS,
"Set HDMI physical address"},
{"can_persist_config", can_persist_config, METH_VARARGS,
"return true if the current adapter can persist the CEC configuration"},
{"persist_config", persist_config, METH_VARARGS,
"persist CEC configuration to adapter"},
{"set_port", set_port, METH_VARARGS, "Set upstream HDMI port"},
{NULL, NULL, 0, NULL}
};
libcec_configuration * CEC_config;
ICECCallbacks * CEC_callbacks;
#if CEC_LIB_VERSION_MAJOR >= 4
void log_cb(void * self, const cec_log_message* message) {
#else
int log_cb(void * self, const cec_log_message message) {
#endif
debug("got log callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
#if CEC_LIB_VERSION_MAJOR >= 4
int level = message->level;
long int time = message->time;
const char* msg = message->message;
#else
int level = message.level;
long int time = message.time;
const char* msg = message.message;
#endif
// decode message ignoring invalid characters
PyObject * umsg = PyUnicode_DecodeASCII(msg, strlen(msg), "ignore");
PyObject * args = Py_BuildValue("(iilO)", EVENT_LOG,
level,
time,
umsg);
if( args ) {
trigger_event(EVENT_LOG, args);
Py_DECREF(args);
}
Py_XDECREF(umsg);
PyGILState_Release(gstate);
#if CEC_LIB_VERSION_MAJOR >= 4
return;
#else
return 1;
#endif
}
#if CEC_LIB_VERSION_MAJOR >= 4
void keypress_cb(void * self, const cec_keypress* key) {
#else
int keypress_cb(void * self, const cec_keypress key) {
#endif
debug("got keypress callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
#if CEC_LIB_VERSION_MAJOR >= 4
cec_user_control_code keycode = key->keycode;
unsigned int duration = key->duration;
#else
cec_user_control_code keycode = key.keycode;
unsigned int duration = key.duration;
#endif
PyObject * args = Py_BuildValue("(iBI)", EVENT_KEYPRESS,
keycode,
duration);
if( args ) {
trigger_event(EVENT_KEYPRESS, args);
Py_DECREF(args);
}
PyGILState_Release(gstate);
#if CEC_LIB_VERSION_MAJOR >= 4
return;
#else
return 1;
#endif
}
static PyObject * convert_cmd(const cec_command* cmd) {
#if PY_MAJOR_VERSION >= 3
return Py_BuildValue("{sBsBsOsOsBsy#sOsi}",
#else
return Py_BuildValue("{sBsBsOsOsBss#sOsi}",
#endif
"initiator", cmd->initiator,
"destination", cmd->destination,
"ack", cmd->ack ? Py_True : Py_False,
"eom", cmd->eom ? Py_True : Py_False,
"opcode", cmd->opcode,
"parameters", cmd->parameters.data, cmd->parameters.size,
"opcode_set", cmd->opcode_set ? Py_True : Py_False,
"transmit_timeout", cmd->transmit_timeout);
}
#if CEC_LIB_VERSION_MAJOR >= 4
void command_cb(void * self, const cec_command* command) {
#else
int command_cb(void * self, const cec_command command) {
#endif
debug("got command callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
#if CEC_LIB_VERSION_MAJOR >= 4
const cec_command * cmd = command;
#else
const cec_command * cmd = &command;
#endif
PyObject * args = Py_BuildValue("(iO&)", EVENT_COMMAND, convert_cmd, cmd);
if( args ) {
trigger_event(EVENT_COMMAND, args);
Py_DECREF(args);
}
PyGILState_Release(gstate);
#if CEC_LIB_VERSION_MAJOR >= 4
return;
#else
return 1;
#endif
}
#if CEC_LIB_VERSION_MAJOR >= 4
void config_cb(void * self, const libcec_configuration*) {
#else
int config_cb(void * self, const libcec_configuration) {
#endif
debug("got config callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
// TODO: figure out how to pass these as parameters
// yeah... right.
// we'll probably have to come up with some functions for converting the
// libcec_configuration class into a python Object
// this will probably be _lots_ of work and should probably wait until
// a later release, or when it becomes necessary.
PyObject * args = Py_BuildValue("(i)", EVENT_CONFIG_CHANGE);
if( args ) {
// don't bother triggering an event until we can actually pass arguments
//trigger_event(EVENT_CONFIG_CHANGE, args);
Py_DECREF(args);
}
PyGILState_Release(gstate);
#if CEC_LIB_VERSION_MAJOR >= 4
return;
#else
return 1;
#endif
}
#if CEC_LIB_VERSION_MAJOR >= 4
void alert_cb(void * self, const libcec_alert alert, const libcec_parameter p) {
#else
int alert_cb(void * self, const libcec_alert alert, const libcec_parameter p) {
#endif
debug("got alert callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * param = Py_None;
if( p.paramType == CEC_PARAMETER_TYPE_STRING ) {
param = Py_BuildValue("s", p.paramData);
} else {
Py_INCREF(param);
}
PyObject * args = Py_BuildValue("(iiN)", EVENT_ALERT, alert, param);
if( args ) {
trigger_event(EVENT_ALERT, args);
Py_DECREF(args);
}
PyGILState_Release(gstate);
#if CEC_LIB_VERSION_MAJOR >= 4
return;
#else
return 1;
#endif
}
int menu_cb(void * self, const cec_menu_state menu) {
debug("got menu callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * args = Py_BuildValue("(ii)", EVENT_MENU_CHANGED, menu);
if( args ) {
trigger_event(EVENT_MENU_CHANGED, args);
Py_DECREF(args);
}
PyGILState_Release(gstate);
return 1;
}
void activated_cb(void * self, const cec_logical_address logical_address,
const uint8_t state) {
debug("got activated callback\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * active = (state == 1) ? Py_True : Py_False;
PyObject * args = Py_BuildValue("(iOi)", EVENT_ACTIVATED, active,
logical_address);
if( args ) {
trigger_event(EVENT_ACTIVATED, args);
Py_DECREF(args);
}
PyGILState_Release(gstate);
return;
}
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"cec",
NULL,
-1,
CecMethods,
NULL,
NULL,
NULL,
NULL
};
#endif
#if PY_MAJOR_VERSION >= 3
#define INITERROR return NULL
#else
#define INITERROR return
#endif
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit_cec(void) {
#else
PyMODINIT_FUNC initcec(void) {
#endif
// Make sure threads are enabled in the python interpreter
// this also acquires the global interpreter lock
PyEval_InitThreads();
// set up libcec
// libcec config
CEC_config = new libcec_configuration();
CEC_config->Clear();
snprintf(CEC_config->strDeviceName, 13, "python-cec");
// CEC_CLIENT_VERSION_CURRENT was introduced in 2.0.4
// just use 2.1.0 because the conditional is simpler
#if CEC_LIB_VERSION_MAJOR >= 3
CEC_config->clientVersion = LIBCEC_VERSION_CURRENT;
#elif CEC_LIB_VERSION_MAJOR >= 2 && CEC_LIB_VERSION_MINOR >= 1
CEC_config->clientVersion = CEC_CLIENT_VERSION_CURRENT;
#else
// fall back to 1.6.0 since it's the lowest common denominator shipped with
// Ubuntu
CEC_config->clientVersion = CEC_CLIENT_VERSION_1_6_0;
#endif
CEC_config->bActivateSource = 0;
CEC_config->deviceTypes.Add(CEC_DEVICE_TYPE_RECORDING_DEVICE);
// libcec callbacks
CEC_callbacks = new ICECCallbacks();
#if CEC_LIB_VERSION_MAJOR > 1 || ( CEC_LIB_VERSION_MAJOR == 1 && CEC_LIB_VERSION_MINOR >= 7 )
CEC_callbacks->Clear();
#endif
#if CEC_LIB_VERSION_MAJOR >= 4
CEC_callbacks->logMessage = log_cb;
CEC_callbacks->keyPress = keypress_cb;
CEC_callbacks->commandReceived = command_cb;
CEC_callbacks->configurationChanged = config_cb;
CEC_callbacks->alert = alert_cb;
CEC_callbacks->menuStateChanged = menu_cb;
CEC_callbacks->sourceActivated = activated_cb;
#else
CEC_callbacks->CBCecLogMessage = log_cb;
CEC_callbacks->CBCecKeyPress = keypress_cb;
CEC_callbacks->CBCecCommand = command_cb;
CEC_callbacks->CBCecConfigurationChanged = config_cb;
CEC_callbacks->CBCecAlert = alert_cb;
CEC_callbacks->CBCecMenuStateChanged = menu_cb;
CEC_callbacks->CBCecSourceActivated = activated_cb;
#endif
CEC_config->callbacks = CEC_callbacks;
CEC_adapter = (ICECAdapter*)CECInitialise(CEC_config);
if( !CEC_adapter ) {
PyErr_SetString(PyExc_IOError, "Failed to initialize libcec");
INITERROR;
}
#if CEC_LIB_VERSION_MAJOR > 1 || ( CEC_LIB_VERSION_MAJOR == 1 && CEC_LIB_VERSION_MINOR >= 8 )
CEC_adapter->InitVideoStandalone();
#endif
// set up python module
PyTypeObject * dev = DeviceTypeInit(CEC_adapter);
Device = (PyObject*)dev;
if(PyType_Ready(dev) < 0 ) INITERROR;
#if PY_MAJOR_VERSION >= 3
PyObject * m = PyModule_Create(&moduledef);
#else
PyObject * m = Py_InitModule("cec", CecMethods);
#endif
if( m == NULL ) INITERROR;
Py_INCREF(dev);
PyModule_AddObject(m, "Device", (PyObject*)dev);
// constants for event types
PyModule_AddIntMacro(m, EVENT_LOG);
PyModule_AddIntMacro(m, EVENT_KEYPRESS);
PyModule_AddIntMacro(m, EVENT_COMMAND);
PyModule_AddIntMacro(m, EVENT_CONFIG_CHANGE);
PyModule_AddIntMacro(m, EVENT_ALERT);
PyModule_AddIntMacro(m, EVENT_MENU_CHANGED);
PyModule_AddIntMacro(m, EVENT_ACTIVATED);
PyModule_AddIntMacro(m, EVENT_ALL);
// constants for alert types
PyModule_AddIntConstant(m, "CEC_ALERT_SERVICE_DEVICE",
CEC_ALERT_SERVICE_DEVICE);
PyModule_AddIntConstant(m, "CEC_ALERT_CONNECTION_LOST",
CEC_ALERT_CONNECTION_LOST);
PyModule_AddIntConstant(m, "CEC_ALERT_PERMISSION_ERROR",
CEC_ALERT_PERMISSION_ERROR);
PyModule_AddIntConstant(m, "CEC_ALERT_PORT_BUSY",
CEC_ALERT_PORT_BUSY);
PyModule_AddIntConstant(m, "CEC_ALERT_PHYSICAL_ADDRESS_ERROR",
CEC_ALERT_PHYSICAL_ADDRESS_ERROR);
PyModule_AddIntConstant(m, "CEC_ALERT_TV_POLL_FAILED",
CEC_ALERT_TV_POLL_FAILED);
// constants for menu events
PyModule_AddIntConstant(m, "CEC_MENU_STATE_ACTIVATED",
CEC_MENU_STATE_ACTIVATED);
PyModule_AddIntConstant(m, "CEC_MENU_STATE_DEACTIVATED",
CEC_MENU_STATE_DEACTIVATED);
// constants for device types
PyModule_AddIntConstant(m, "CEC_DEVICE_TYPE_TV",
CEC_DEVICE_TYPE_TV);
PyModule_AddIntConstant(m, "CEC_DEVICE_TYPE_RECORDING_DEVICE",
CEC_DEVICE_TYPE_RECORDING_DEVICE);
PyModule_AddIntConstant(m, "CEC_DEVICE_TYPE_RESERVED",
CEC_DEVICE_TYPE_RESERVED);
PyModule_AddIntConstant(m, "CEC_DEVICE_TYPE_TUNER",
CEC_DEVICE_TYPE_TUNER);
PyModule_AddIntConstant(m, "CEC_DEVICE_TYPE_PLAYBACK_DEVICE",
CEC_DEVICE_TYPE_PLAYBACK_DEVICE);
PyModule_AddIntConstant(m, "CEC_DEVICE_TYPE_AUDIO_SYSTEM",