/
hybrisadaptor.cpp
1614 lines (1407 loc) · 53.7 KB
/
hybrisadaptor.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
/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd
**
**
** $QT_BEGIN_LICENSE:LGPL$
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "hybrisadaptor.h"
#include "deviceadaptor.h"
#include <QDebug>
#include <QCoreApplication>
#include <QTimer>
#ifndef USE_BINDER
#include <hardware/hardware.h>
#endif
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <signal.h>
#ifdef USE_BINDER
#define SENSOR_BINDER_SERVICE_DEVICE "/dev/hwbinder"
#define SENSOR_BINDER_SERVICE_IFACE_1_0 "android.hardware.sensors@1.0::ISensors"
#define SENSOR_BINDER_SERVICE_NAME_1_0 SENSOR_BINDER_SERVICE_IFACE_1_0 "/default"
#define SENSOR_BINDER_SERVICE_IFACE_2_0 "android.hardware.sensors@2.0::ISensors"
#define SENSOR_BINDER_SERVICE_NAME_2_0 SENSOR_BINDER_SERVICE_IFACE_2_0 "/default"
#define SENSOR_BINDER_SERVICE_CALLBACK_IFACE_2_0 "android.hardware.sensors@2.0::ISensorsCallback"
#define SENSOR_BINDER_SERVICE_IFACE_2_1 "android.hardware.sensors@2.1::ISensors"
#define SENSOR_BINDER_SERVICE_NAME_2_1 SENSOR_BINDER_SERVICE_IFACE_2_1 "/default"
#define SENSOR_BINDER_SERVICE_CALLBACK_IFACE_2_1 "android.hardware.sensors@2.1::ISensorsCallback"
#define MAX_RECEIVE_BUFFER_EVENT_COUNT 128
static const GBinderClientIfaceInfo sensors_2_client_ifaces[] = {
{SENSOR_BINDER_SERVICE_IFACE_2_1, INJECT_SENSOR_DATA_2_1 },
{SENSOR_BINDER_SERVICE_IFACE_2_0, CONFIG_DIRECT_REPORT },
};
G_STATIC_ASSERT
(G_N_ELEMENTS(sensors_2_client_ifaces) == SENSOR_INTERFACE_2_1);
const char* const sensors_2_callback_ifaces[] = {
SENSOR_BINDER_SERVICE_CALLBACK_IFACE_2_1,
SENSOR_BINDER_SERVICE_CALLBACK_IFACE_2_0,
NULL
};
#endif
namespace {
/* Maximum number of events to transmit over event pipe in one go.
* Also defines maximum number of events to ask from android hal/service.
*/
const size_t maxEvents = 64;
}
/* ========================================================================= *
* UTILITIES
* ========================================================================= */
static char const *
sensorTypeName(int type)
{
switch (type) {
case SENSOR_TYPE_META_DATA: return "META_DATA";
case SENSOR_TYPE_ACCELEROMETER: return "ACCELEROMETER";
case SENSOR_TYPE_GEOMAGNETIC_FIELD: return "GEOMAGNETIC_FIELD";
case SENSOR_TYPE_ORIENTATION: return "ORIENTATION";
case SENSOR_TYPE_GYROSCOPE: return "GYROSCOPE";
case SENSOR_TYPE_LIGHT: return "LIGHT";
case SENSOR_TYPE_PRESSURE: return "PRESSURE";
case SENSOR_TYPE_TEMPERATURE: return "TEMPERATURE";
case SENSOR_TYPE_PROXIMITY: return "PROXIMITY";
case SENSOR_TYPE_GRAVITY: return "GRAVITY";
case SENSOR_TYPE_LINEAR_ACCELERATION: return "LINEAR_ACCELERATION";
case SENSOR_TYPE_ROTATION_VECTOR: return "ROTATION_VECTOR";
case SENSOR_TYPE_RELATIVE_HUMIDITY: return "RELATIVE_HUMIDITY";
case SENSOR_TYPE_AMBIENT_TEMPERATURE: return "AMBIENT_TEMPERATURE";
case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: return "MAGNETIC_FIELD_UNCALIBRATED";
case SENSOR_TYPE_GAME_ROTATION_VECTOR: return "GAME_ROTATION_VECTOR";
case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: return "GYROSCOPE_UNCALIBRATED";
case SENSOR_TYPE_SIGNIFICANT_MOTION: return "SIGNIFICANT_MOTION";
case SENSOR_TYPE_STEP_DETECTOR: return "STEP_DETECTOR";
case SENSOR_TYPE_STEP_COUNTER: return "STEP_COUNTER";
case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR: return "GEOMAGNETIC_ROTATION_VECTOR";
case SENSOR_TYPE_HEART_RATE: return "HEART_RATE";
case SENSOR_TYPE_TILT_DETECTOR: return "TILT_DETECTOR";
case SENSOR_TYPE_WAKE_GESTURE: return "WAKE_GESTURE";
case SENSOR_TYPE_GLANCE_GESTURE: return "GLANCE_GESTURE";
case SENSOR_TYPE_PICK_UP_GESTURE: return "PICK_UP_GESTURE";
case SENSOR_TYPE_WRIST_TILT_GESTURE: return "WRIST_TILT_GESTURE";
}
static char buf[32];
snprintf(buf, sizeof buf, "type%d", type);
return buf;
}
static void ObtainTemporaryWakeLock()
{
static bool triedToOpen = false;
static int wakeLockFd = -1;
if (!triedToOpen) {
triedToOpen = true;
wakeLockFd = ::open("/sys/power/wake_lock", O_RDWR);
if (wakeLockFd == -1) {
sensordLogW() << "wake locks not available:" << ::strerror(errno);
}
}
if (wakeLockFd != -1) {
sensordLogD() << "wake lock to guard sensor data io";
static const char m[] = "sensorfwd_pass_data 1000000000\n";
if (::write(wakeLockFd, m, sizeof m - 1) == -1) {
sensordLogW() << "wake locking failed:" << ::strerror(errno);
::close(wakeLockFd), wakeLockFd = -1;
}
}
}
/* ========================================================================= *
* HybrisSensorState
* ========================================================================= */
HybrisSensorState::HybrisSensorState()
: m_minDelay_us(0)
, m_maxDelay_us(0)
, m_delay_us(-1)
, m_active(-1)
{
memset(&m_fallbackEvent, 0, sizeof m_fallbackEvent);
}
HybrisSensorState::~HybrisSensorState()
{
}
/* ========================================================================= *
* HybrisManager
* ========================================================================= */
/* hybrisManager object is created on demand - which ought to happen
* well after QCoreApplication object has already been instantiated.
* Cleanup actions are executed on QCoreApplication::aboutToQuit signal.
* Destructor gets called after exit from main() and should be as
* close to nop as possible.
*/
Q_GLOBAL_STATIC(HybrisManager, hybrisManager)
HybrisManager::HybrisManager(QObject *parent)
: QObject(parent)
, m_initialized(false)
, m_registeredAdaptors()
#ifdef USE_BINDER
, m_client(NULL)
, m_deathId(0)
, m_pollTransactId(0)
, m_remote(NULL)
, m_serviceManager(NULL)
, m_sensorInterfaceEnum(SENSOR_INTERFACE_COUNT)
, m_sensorCallback(NULL)
#else
, m_halModule(NULL)
, m_halDevice(NULL)
#endif
, m_sensorArray(NULL)
, m_eventReaderTid(0)
, m_sensorCount(0)
, m_sensorState(NULL)
, m_indexOfType()
, m_indexOfHandle()
, m_eventPipeReadFd(-1)
, m_eventPipeWriteFd(-1)
, m_eventPipeNotifier(nullptr)
{
/* Arrange it so that sensors get stopped on exit from mainloop
*/
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit,
this, &HybrisManager::cleanup);
#ifdef USE_BINDER
startConnect();
#else
int err;
/* Open android sensor plugin */
err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,
(hw_module_t const**)&m_halModule);
if (err != 0) {
m_halModule = 0;
sensordLogW() << "hw_get_module() failed" << strerror(-err);
return ;
}
/* Open android sensor device */
err = sensors_open_1(&m_halModule->common, &m_halDevice);
if (err != 0) {
m_halDevice = 0;
sensordLogW() << "sensors_open() failed:" << strerror(-err);
return;
}
/* Get static sensor information */
m_sensorCount = m_halModule->get_sensors_list(m_halModule, &m_sensorArray);
initManager();
#endif
}
#ifdef USE_BINDER
bool HybrisManager::typeRequiresWakeup(int type)
{
// Sensors which are wake-up sensors by default
switch (type) {
case SENSOR_TYPE_PROXIMITY:
case SENSOR_TYPE_SIGNIFICANT_MOTION:
case SENSOR_TYPE_TILT_DETECTOR:
case SENSOR_TYPE_WAKE_GESTURE:
case SENSOR_TYPE_GLANCE_GESTURE:
case SENSOR_TYPE_PICK_UP_GESTURE:
case SENSOR_TYPE_WRIST_TILT_GESTURE:
case SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT:
return true;
default:
return false;
}
}
#endif
void HybrisManager::initManager()
{
/* Initialize sensor data forwarding pipe */
initEventPipe();
/* Reserve space for sensor state data */
m_sensorState = new HybrisSensorState[m_sensorCount];
/* Select and initialize sensors to be used */
for (int i = 0 ; i < m_sensorCount ; i++) {
/* Always do handle -> index mapping */
m_indexOfHandle.insert(m_sensorArray[i].handle, i);
bool use = true;
// Assumption: The primary sensor variants that we want to
// use are listed before the secondary ones that we want
// to ignore -> Use the 1st entry found for each sensor type.
if (m_indexOfType.contains(m_sensorArray[i].type)) {
use = false;
}
// some devices have compass and compass raw,
// ignore compass raw. compass has range 360
if (m_sensorArray[i].type == SENSOR_TYPE_ORIENTATION &&
m_sensorArray[i].maxRange != 360) {
use = false;
}
#ifdef USE_BINDER
// Pick wake-up variant for the types which are wake-up sensors by default
if (typeRequiresWakeup(m_sensorArray[i].type)) {
if ((m_sensorArray[i].flags & SENSOR_FLAG_WAKE_UP) == 0) {
sensordLogD() << "Ignoring non-wake-up sensor of type " << m_sensorArray[i].type << sensorTypeName(m_sensorArray[i].type);
use = false;
}
} else {
// All other sensors shall use non-wake-up sensor variant
if ((m_sensorArray[i].flags & SENSOR_FLAG_WAKE_UP) != 0) {
sensordLogD() << "Ignoring wake-up sensor of type " << m_sensorArray[i].type << sensorTypeName(m_sensorArray[i].type);
use = false;
}
}
#endif
sensordLogD() << Q_FUNC_INFO
<< (use ? "SELECT" : "IGNORE")
<< "type:" << m_sensorArray[i].type << sensorTypeName(m_sensorArray[i].type)
#ifdef USE_BINDER
<< "name:" << (m_sensorArray[i].name.data.str ?: "n/a");
#else
<< "name:" << (m_sensorArray[i].name ?: "n/a");
#endif
if (use) {
// min/max delay in hal is specified in [us]
int minDelay_us = m_sensorArray[i].minDelay;
int maxDelay_us = -1; // Assume: not defined by hal
#ifdef USE_BINDER
maxDelay_us = m_sensorArray[i].maxDelay;
#else
#ifdef SENSORS_DEVICE_API_VERSION_1_3
if (m_halDevice->common.version >= SENSORS_DEVICE_API_VERSION_1_3)
maxDelay_us = m_sensorArray[i].maxDelay;
#endif
#endif
/* If HAL does not define maximum delay, we need to invent
* something that a) allows sensorfwd logic to see a range
* instead of a point, b) is unlikely to be wrong enough to
* cause problems...
*
* For now use: minDelay * 2, but at least 1000 ms.
*/
if (maxDelay_us < 0 && minDelay_us > 0) {
maxDelay_us = (minDelay_us < 500000) ? 1000000 : (minDelay_us * 2);
sensordLogD("hal does not specify maxDelay, fallback: %d us",
maxDelay_us);
}
// Positive minDelay means delay /can/ be set - but depending
// on sensor hal implementation it can also mean that some
// delay /must/ be set or the sensor does not start reporting
// despite being enabled -> as an protection agains clients
// failing to explicitly set delays / using delays that would
// get rejected by upper levels of sensorfwd logic -> setup
// 200 ms delay (capped to reported min/max range).
if (minDelay_us >= 0) {
if (maxDelay_us < minDelay_us)
maxDelay_us = minDelay_us;
int delay_us = minDelay_us ? 200000 : 0;
if (delay_us < minDelay_us)
delay_us = minDelay_us;
else if (delay_us > maxDelay_us)
delay_us = maxDelay_us;
m_sensorState[i].m_minDelay_us = minDelay_us;
m_sensorState[i].m_maxDelay_us = maxDelay_us;
setDelay(m_sensorArray[i].handle, delay_us, true);
sensordLogD("delay = %d [%d, %d]",
m_sensorState[i].m_delay_us,
m_sensorState[i].m_minDelay_us,
m_sensorState[i].m_maxDelay_us);
}
m_indexOfType.insert(m_sensorArray[i].type, i);
/* Set sane fallback values for select sensors in case the
* hal does not report initial values. */
sensors_event_t *eve = &m_sensorState[i].m_fallbackEvent;
#ifndef USE_BINDER
eve->version = sizeof *eve;
#endif
eve->sensor = m_sensorArray[i].handle;
eve->type = m_sensorArray[i].type;
switch (m_sensorArray[i].type) {
case SENSOR_TYPE_LIGHT:
// Roughly indoor lightning
#ifdef USE_BINDER
eve->u.scalar = 400;
#else
eve->light = 400;
#endif
break;
case SENSOR_TYPE_PROXIMITY:
// Not-covered
#ifdef USE_BINDER
eve->u.scalar = m_sensorArray[i].maxRange;
#else
eve->distance = m_sensorArray[i].maxRange;
#endif
break;
default:
eve->sensor = 0;
eve->type = 0;
break;
}
}
/* Make sure all sensors are initially in stopped state */
setActive(m_sensorArray[i].handle, false);
}
#ifdef USE_BINDER
if (m_sensorInterfaceEnum == SENSOR_INTERFACE_1_0) {
pollEvents();
} else {
#endif
int err;
/* Start android sensor event reader */
err = pthread_create(&m_eventReaderTid, 0, eventReaderThread, this);
if (err) {
m_eventReaderTid = 0;
sensordLogC() << "Failed to start event reader thread";
return;
}
sensordLogD() << "Event reader thread started";
#ifdef USE_BINDER
}
#else
m_initialized = true;
#endif
}
HybrisManager::~HybrisManager()
{
/* This is exectuted after exiting main() function.
* No actions that need core application, binder ipc,
* android hal libraries, etc should be made.
*/
}
void HybrisManager::cleanup()
{
/* Stop any sensors that are active
*/
sensordLogD() << "stop all sensors";
foreach (HybrisAdaptor *adaptor, m_registeredAdaptors.values()) {
adaptor->stopSensor();
}
/* Stop reacting to async events
*/
#ifdef USE_BINDER
gbinder_remote_object_remove_handler(m_remote, m_deathId);
m_deathId = 0;
if (m_pollTransactId) {
gbinder_client_cancel(m_client, m_pollTransactId);
m_pollTransactId = 0;
// The above code just marks down pending POLL transaction as
// to be cancelled later on when handler thread gets woken up.
//
// If we are exiting right after cleanup(), that is never going
// to happen and gbinder_ipc_exit() cleanup code blocks sensorfwd
// exit indefinitely.
//
// As a workaround: make a dummy POLL transaction, for which a
// reply is sent immediately, which then wakes up the handler
// thread, the cancellation gets processed and exit is unblocked.
GBinderLocalRequest *req = gbinder_client_new_request2(m_client, POLL);
int32_t status = 0;
gbinder_local_request_append_int32(req, 0);
GBinderRemoteReply *reply = gbinder_client_transact_sync_reply(m_client, POLL, req, &status);
gbinder_remote_reply_unref(reply);
gbinder_local_request_unref(req);
}
gbinder_local_object_unref(m_sensorCallback);
m_sensorCallback = NULL;
#endif
if (m_eventReaderTid) {
sensordLogD() << "Canceling event reader thread";
int err = pthread_cancel(m_eventReaderTid);
if (err) {
sensordLogC() << "Failed to cancel event reader thread";
} else {
sensordLogD() << "Waiting for event reader thread to exit";
void *ret = 0;
struct timespec tmo = { 0, 0};
clock_gettime(CLOCK_REALTIME, &tmo);
tmo.tv_sec += 3;
err = pthread_timedjoin_np(m_eventReaderTid, &ret, &tmo);
if (err) {
sensordLogC() << "Event reader thread did not exit";
} else {
sensordLogD() << "Event reader thread terminated";
m_eventReaderTid = 0;
}
}
if (m_eventReaderTid) {
/* The reader thread is stuck.
* Continuing would be likely to release resourse
* still in active use and lead to segfaulting.
* Resort to doing a quick and dirty exit. */
_exit(EXIT_FAILURE);
}
}
/* Release remaining dynamic resources
*/
#ifdef USE_BINDER
gbinder_fmq_unref(m_wakeLockQueue);
m_wakeLockQueue = NULL;
gbinder_fmq_unref(m_eventQueue);
m_eventQueue = NULL;
gbinder_client_unref(m_client);
m_client = NULL;
gbinder_servicemanager_unref(m_serviceManager);
m_serviceManager = NULL;
m_remote = NULL; // auto-release
for (int i = 0 ; i < m_sensorCount ; i++) {
g_free((void*)m_sensorArray[i].name.data.str);
g_free((void*)m_sensorArray[i].vendor.data.str);
g_free((void*)m_sensorArray[i].typeAsString.data.str);
g_free((void*)m_sensorArray[i].requiredPermission.data.str);
}
delete[] m_sensorArray;
m_sensorArray = NULL;
#else
if (m_halDevice) {
sensordLogD() << "close sensor device";
int errorCode = sensors_close_1(m_halDevice);
if (errorCode != 0) {
sensordLogW() << "sensors_close() failed:" << strerror(-errorCode);
}
m_halDevice = NULL;
}
#endif
delete[] m_sensorState;
m_sensorState = NULL;
m_sensorCount = 0;
m_initialized = false;
/* Close sensor data transfer pipe */
cleanupEventPipe();
}
HybrisManager *HybrisManager::instance()
{
HybrisManager *priv = hybrisManager();
return priv;
}
#ifdef USE_BINDER
GBinderLocalReply *HybrisManager::sensorCallbackHandler(
GBinderLocalObject* obj,
GBinderRemoteRequest* req,
guint code,
guint flags,
int* status,
void* user_data)
{
(void)flags;
(void)obj;
(void)user_data;
sensordLogD() << "sensorCallbackHandler";
const char *iface = gbinder_remote_request_interface(req);
if (iface && (!strcmp(iface, SENSOR_BINDER_SERVICE_IFACE_2_0) ||
!strcmp(iface, SENSOR_BINDER_SERVICE_IFACE_2_1)
)) {
switch (code) {
case DYNAMIC_SENSORS_CONNECTED_2_0:
case DYNAMIC_SENSORS_CONNECTED_2_1:
sensordLogD() << "Dynamic sensor connected";
break;
case DYNAMIC_SENSORS_DISCONNECTED_2_0:
sensordLogD() << "Dynamic sensor disconnected";
break;
default:
sensordLogW() << "Unknown code (" << code << ")";
break;
}
*status = GBINDER_STATUS_OK;
sensordLogD() << "sensorCallbackHandler valid sensor interface";
}
return NULL;
}
void HybrisManager::getSensorList()
{
sensordLogD() << "Get sensor list";
GBinderReader reader;
GBinderRemoteReply *reply;
int status;
if (m_sensorInterfaceEnum == SENSOR_INTERFACE_2_1) {
reply = gbinder_client_transact_sync_reply(m_client, GET_SENSORS_LIST_2_1, NULL, &status);
} else {
reply = gbinder_client_transact_sync_reply(m_client, GET_SENSORS_LIST, NULL, &status);
}
if (status != GBINDER_STATUS_OK) {
sensordLogW() << "Unable to get sensor list: status " << status;
cleanup();
sleep(1);
startConnect();
return;
}
gbinder_remote_reply_init_reader(reply, &reader);
gbinder_reader_read_int32(&reader, &status);
gsize count = 0;
gsize vecSize = 0;
sensor_t *vec = (sensor_t *)gbinder_reader_read_hidl_vec(&reader, &count, &vecSize);
m_sensorCount = count;
m_sensorArray = new sensor_t[m_sensorCount];
for (int i = 0 ; i < m_sensorCount ; i++) {
memcpy(&m_sensorArray[i], &vec[i], sizeof(sensor_t));
// Read strings
GBinderBuffer *buffer = gbinder_reader_read_buffer(&reader);
m_sensorArray[i].name.data.str = g_strdup((const gchar *)buffer->data);
m_sensorArray[i].name.len = buffer->size;
m_sensorArray[i].name.owns_buffer = true;
gbinder_buffer_free(buffer);
buffer = gbinder_reader_read_buffer(&reader);
m_sensorArray[i].vendor.data.str = g_strdup((const gchar *)buffer->data);
m_sensorArray[i].vendor.len = buffer->size;
m_sensorArray[i].vendor.owns_buffer = true;
gbinder_buffer_free(buffer);
buffer = gbinder_reader_read_buffer(&reader);
m_sensorArray[i].typeAsString.data.str = g_strdup((const gchar *)buffer->data);
m_sensorArray[i].typeAsString.len = buffer->size;
m_sensorArray[i].typeAsString.owns_buffer = true;
gbinder_buffer_free(buffer);
buffer = gbinder_reader_read_buffer(&reader);
m_sensorArray[i].requiredPermission.data.str = g_strdup((const gchar *)buffer->data);
m_sensorArray[i].requiredPermission.len = buffer->size;
m_sensorArray[i].requiredPermission.owns_buffer = true;
gbinder_buffer_free(buffer);
}
gbinder_remote_reply_unref(reply);
initManager();
m_initialized = true;
sensordLogW() << "Hybris sensor manager initialized";
}
void HybrisManager::binderDied(GBinderRemoteObject *, void *user_data)
{
HybrisManager *conn =
static_cast<HybrisManager *>(user_data);
sensordLogW() << "Sensor service died! Trying to reconnect.";
conn->cleanup();
conn->startConnect();
}
void HybrisManager::startConnect()
{
if (!m_serviceManager) {
m_serviceManager = gbinder_servicemanager_new(SENSOR_BINDER_SERVICE_DEVICE);
}
if (gbinder_servicemanager_wait(m_serviceManager, -1)) {
finishConnect();
} else {
sensordLogW() << "Could not get service manager for sensor service";
cleanup();
}
}
void HybrisManager::finishConnect()
{
int initializeCode;
m_remote = gbinder_servicemanager_get_service_sync(m_serviceManager,
SENSOR_BINDER_SERVICE_NAME_2_1, NULL);
if (m_remote) {
sensordLogD() << "Connected to sensor 2.1 service";
m_sensorInterfaceEnum = SENSOR_INTERFACE_2_1;
initializeCode = INITIALIZE_2_1;
} else {
m_remote = gbinder_servicemanager_get_service_sync(m_serviceManager,
SENSOR_BINDER_SERVICE_NAME_2_0, NULL);
if (m_remote) {
sensordLogD() << "Connected to sensor 2.0 service";
m_sensorInterfaceEnum = SENSOR_INTERFACE_2_0;
initializeCode = INITIALIZE_2_0;
}
}
if (m_remote) {
sensordLogD() << "Initialize sensor service";
m_deathId = gbinder_remote_object_add_death_handler(m_remote, binderDied, this);
m_client = gbinder_client_new2(m_remote, sensors_2_client_ifaces, G_N_ELEMENTS(sensors_2_client_ifaces));
if (!m_client) {
sensordLogD() << "Could not create client for sensor service. Trying to reconnect.";
} else {
GBinderRemoteReply *reply;
GBinderLocalRequest *req = gbinder_client_new_request2(m_client, initializeCode);
int32_t status;
GBinderWriter writer;
gbinder_local_request_init_writer(req, &writer);
m_sensorCallback = gbinder_servicemanager_new_local_object2(
m_serviceManager,
sensors_2_callback_ifaces,
sensorCallbackHandler,
this);
m_eventQueue = gbinder_fmq_new(sizeof(sensors_event_t), 128,
GBINDER_FMQ_TYPE_SYNC_READ_WRITE, GBINDER_FMQ_FLAG_CONFIGURE_EVENT_FLAG, -1, 0);
gbinder_writer_append_fmq_descriptor(&writer, m_eventQueue);
m_wakeLockQueue = gbinder_fmq_new(sizeof(guint32), 128,
GBINDER_FMQ_TYPE_SYNC_READ_WRITE, GBINDER_FMQ_FLAG_CONFIGURE_EVENT_FLAG, -1, 0);
gbinder_writer_append_fmq_descriptor(&writer, m_wakeLockQueue);
gbinder_writer_append_local_object(&writer, m_sensorCallback);
reply = gbinder_client_transact_sync_reply(m_client, initializeCode, req, &status);
gbinder_local_request_unref(req);
if (status != GBINDER_STATUS_OK) {
sensordLogW() << "Initialize failed with status" << status << ". Trying to reconnect.";
gbinder_remote_reply_unref(reply);
} else {
int error;
GBinderReader reader;
gbinder_remote_reply_init_reader(reply, &reader);
gbinder_reader_read_int32(&reader, &status);
gbinder_reader_read_int32(&reader, &error);
gbinder_remote_reply_unref(reply);
if (!error) {
getSensorList();
return;
} else {
sensordLogW() << "Initialize failed with error" << error << ". Trying to reconnect.";
}
}
}
} else {
m_remote = gbinder_servicemanager_get_service_sync(m_serviceManager,
SENSOR_BINDER_SERVICE_NAME_1_0, NULL);
if (!m_remote) {
sensordLogD() << "Could not find remote object for sensor service. Trying to reconnect";
} else {
m_sensorInterfaceEnum = SENSOR_INTERFACE_1_0;
sensordLogD() << "Connected to sensor 1.0 service";
m_deathId = gbinder_remote_object_add_death_handler(m_remote, binderDied,
this);
m_client = gbinder_client_new(m_remote, SENSOR_BINDER_SERVICE_IFACE_1_0);
if (!m_client) {
sensordLogD() << "Could not create client for sensor service. Trying to reconnect.";
} else {
// Sometimes sensor service has lingering connetion from
// previous client which causes sensor service to restart
// and we need to test with poll if remote is really working.
GBinderRemoteReply *reply;
GBinderLocalRequest *req = gbinder_client_new_request2(m_client, POLL);
int32_t status;
// Empty poll to test if remote is working
req = gbinder_local_request_append_int32(req, 0);
reply = gbinder_client_transact_sync_reply(m_client, POLL, req, &status);
gbinder_local_request_unref(req);
gbinder_remote_reply_unref(reply);
if (status != GBINDER_STATUS_OK) {
sensordLogW() << "Poll failed with status" << status << ". Trying to reconnect.";
} else {
getSensorList();
return;
}
}
}
}
// On failure cleanup and wait before reconnecting
cleanup();
sleep(1);
startConnect();
}
#endif //USE_BINDER
int HybrisManager::handleForType(int sensorType) const
{
int index = indexForType(sensorType);
return (index < 0) ? -1 : m_sensorArray[index].handle;
}
sensors_event_t *HybrisManager::eventForHandle(int handle) const
{
sensors_event_t *event = 0;
int index = indexForHandle(handle);
if (index != -1) {
event = &m_sensorState[index].m_fallbackEvent;
}
return event;
}
int HybrisManager::indexForHandle(int handle) const
{
int index = m_indexOfHandle.value(handle, -1);
if (index == -1)
sensordLogW("HYBRIS CTL invalid sensor handle: %d", handle);
return index;
}
int HybrisManager::indexForType(int sensorType) const
{
int index = m_indexOfType.value(sensorType, -1);
if (index == -1)
sensordLogW("HYBRIS CTL invalid sensor type: %d", sensorType);
return index;
}
void HybrisManager::startReader(HybrisAdaptor *adaptor)
{
if (m_registeredAdaptors.values().contains(adaptor)) {
sensordLogD() << "activating " << adaptor->name() << adaptor->m_sensorHandle;
if (!setActive(adaptor->m_sensorHandle, true)) {
sensordLogW() <<Q_FUNC_INFO<< "failed";
adaptor->setValid(false);
}
}
}
void HybrisManager::stopReader(HybrisAdaptor *adaptor)
{
if (m_registeredAdaptors.values().contains(adaptor)) {
sensordLogD() << "deactivating " << adaptor->name();
if (!setActive(adaptor->m_sensorHandle, false)) {
sensordLogW() <<Q_FUNC_INFO<< "failed";
}
}
}
void HybrisManager::processSample(const sensors_event_t& data)
{
foreach (HybrisAdaptor *adaptor, m_registeredAdaptors.values(data.type)) {
if (adaptor->isRunning()) {
adaptor->processSample(data);
}
}
}
void HybrisManager::registerAdaptor(HybrisAdaptor *adaptor)
{
if (!m_registeredAdaptors.values().contains(adaptor) && adaptor->isValid()) {
m_registeredAdaptors.insert(adaptor->m_sensorType, adaptor);
}
}
float HybrisManager::scaleSensorValue(const float value, const int type) const
{
float outValue;
switch (type) {
case SENSOR_TYPE_ACCELEROMETER:
case SENSOR_TYPE_GRAVITY:
case SENSOR_TYPE_LINEAR_ACCELERATION:
//sensorfw wants milli-G'
outValue = value * GRAVITY_RECIPROCAL_THOUSANDS;
break;
case SENSOR_TYPE_MAGNETIC_FIELD:
case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
// uT to nT
outValue = value * 1000;
break;
case SENSOR_TYPE_GYROSCOPE:
case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
// From rad/s to mdeg/s
outValue = value * RADIANS_TO_DEGREES * 1000;
break;
case SENSOR_TYPE_PRESSURE:
// From hPa to Pa
outValue = value * 100;
break;
default:
outValue = value;
break;
}
return outValue;
}
float HybrisManager::getMaxRange(int handle) const
{
float range = 0;
int index = indexForHandle(handle);
if (index != -1) {
const struct sensor_t *sensor = &m_sensorArray[index];
range = scaleSensorValue(sensor->maxRange, sensor->type);
sensordLogT("HYBRIS CTL getMaxRange(%d=%s) -> %g",
sensor->handle, sensorTypeName(sensor->type), range);
}
return range;
}
float HybrisManager::getResolution(int handle) const
{
float resolution = 0;
int index = indexForHandle(handle);
if (index != -1) {
const struct sensor_t *sensor = &m_sensorArray[index];
resolution = scaleSensorValue(sensor->resolution, sensor->type);
sensordLogT("HYBRIS CTL getResolution(%d=%s) -> %g",
sensor->handle, sensorTypeName(sensor->type), resolution);
}
return resolution;
}
int HybrisManager::getMinDelay(int handle) const
{
int delay_us = 0;
int index = indexForHandle(handle);
if (index != -1) {
const struct sensor_t *sensor = &m_sensorArray[index];
HybrisSensorState *state = &m_sensorState[index];
delay_us = state->m_minDelay_us;
sensordLogT("HYBRIS CTL getMinDelay(%d=%s) -> %d",
sensor->handle, sensorTypeName(sensor->type), delay_us);
}
return delay_us;
}
int HybrisManager::getMaxDelay(int handle) const
{
int delay_us = 0;
int index = indexForHandle(handle);
if (index != -1) {
const struct sensor_t *sensor = &m_sensorArray[index];
HybrisSensorState *state = &m_sensorState[index];
delay_us = state->m_maxDelay_us;
sensordLogT("HYBRIS CTL getMaxDelay(%d=%s) -> %d",
sensor->handle, sensorTypeName(sensor->type), delay_us);
}
return delay_us;
}
int HybrisManager::getDelay(int handle) const
{
int delay_us = 0;
int index = indexForHandle(handle);
if (index != -1) {
const struct sensor_t *sensor = &m_sensorArray[index];
HybrisSensorState *state = &m_sensorState[index];
delay_us = state->m_delay_us;
sensordLogT("HYBRIS CTL getDelay(%d=%s) -> %d",
sensor->handle, sensorTypeName(sensor->type), delay_us);
}
return delay_us;
}
bool HybrisManager::setDelay(int handle, int delay_us, bool force)
{
bool success = false;
int index = indexForHandle(handle);
if (index != -1) {
const struct sensor_t *sensor = &m_sensorArray[index];
HybrisSensorState *state = &m_sensorState[index];
if (!force && state->m_delay_us == delay_us) {
sensordLogT("HYBRIS CTL setDelay(%d=%s, %d) -> no-change",
sensor->handle, sensorTypeName(sensor->type), delay_us);
success = true;
} else {
int64_t delay_ns = delay_us * 1000LL;
#ifdef USE_BINDER
int error;
GBinderLocalRequest *req = gbinder_client_new_request2(m_client, BATCH);
GBinderRemoteReply *reply;
GBinderReader reader;
GBinderWriter writer;
int32_t status;
gbinder_local_request_init_writer(req, &writer);
gbinder_writer_append_int32(&writer, sensor->handle);
gbinder_writer_append_int64(&writer, delay_ns);
gbinder_writer_append_int64(&writer, 0);
reply = gbinder_client_transact_sync_reply(m_client, BATCH, req, &status);
gbinder_local_request_unref(req);