forked from ceva-dsp/sh2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsh2.c
More file actions
2622 lines (2138 loc) · 76.1 KB
/
sh2.c
File metadata and controls
2622 lines (2138 loc) · 76.1 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
/*
* Copyright 2015-2022 CEVA, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License and
* any applicable agreements you may have with CEVA, Inc.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file sh2.c
* @author David Wheeler
* @date 22 Sept 2015
* @brief API Definition for SH-2 Sensor Hub.
*
* The sh2 API provides functions for opening a session with
* the sensor hub and performing all supported operations with it.
* This includes enabling sensors and reading events as well as
* other housekeeping functions.
*
*/
//Suppress warning about fopen and strcpy safety under MSVC
#ifdef _MSC_VER
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
#endif
#include "sh2.h"
#include "sh2_err.h"
#include "shtp.h"
#include "sh2_util.h"
#include <string.h>
#include <stdio.h>
// ------------------------------------------------------------------------
// Private type definitions
#define CHAN_EXECUTABLE_DEVICE (1)
#define CHAN_SENSORHUB_CONTROL (2)
#define CHAN_SENSORHUB_INPUT (3)
#define CHAN_SENSORHUB_INPUT_WAKE (4)
#define CHAN_SENSORHUB_INPUT_GIRV (5)
// executable/device channel responses
#define EXECUTABLE_DEVICE_CMD_RESET (1)
#define EXECUTABLE_DEVICE_CMD_ON (2)
#define EXECUTABLE_DEVICE_CMD_SLEEP (3)
// executable/device channel responses
#define EXECUTABLE_DEVICE_RESP_RESET_COMPLETE (1)
// Tags for sensorhub app advertisements.
#define TAG_SH2_VERSION (0x80)
#define TAG_SH2_REPORT_LENGTHS (0x81)
// Max length of sensorhub version string.
#define MAX_VER_LEN (16)
// Max number of report ids supported
#define SH2_MAX_REPORT_IDS (64)
#if defined(_MSC_VER)
#define PACKED_STRUCT struct
#pragma pack(push, 1)
#elif defined(__GNUC__)
#define PACKED_STRUCT struct __attribute__((packed))
#else
#define PACKED_STRUCT __packed struct
#endif
#define ADVERT_TIMEOUT_US (200000)
// Command and Subcommand values
#define SH2_CMD_ERRORS 1
#define SH2_CMD_COUNTS 2
#define SH2_COUNTS_GET_COUNTS 0
#define SH2_COUNTS_CLEAR_COUNTS 1
#define SH2_CMD_TARE 3
#define SH2_TARE_TARE_NOW 0
#define SH2_TARE_PERSIST_TARE 1
#define SH2_TARE_SET_REORIENTATION 2
#define SH2_CMD_INITIALIZE 4
#define SH2_INIT_SYSTEM 1
#define SH2_INIT_UNSOLICITED 0x80
// #define SH2_CMD_FRS 5 /* Depreciated */
#define SH2_CMD_DCD 6
#define SH2_CMD_ME_CAL 7
#define SH2_CMD_DCD_SAVE 9
#define SH2_CMD_GET_OSC_TYPE 0x0A
#define SH2_CMD_CLEAR_DCD_AND_RESET 0x0B
#define SH2_CMD_CAL 0x0C
#define SH2_CAL_START 0
#define SH2_CAL_FINISH 1
#define SH2_CMD_BOOTLOADER 0x0D /* SH-2 Reference Manual 6.4.12 */
#define SH2_BL_MODE_REQ 0
#define SH2_BL_STATUS_REQ 1
#define SH2_CMD_INTERACTIVE_ZRO 0x0E /* SH-2 Reference Manual 6.4.13 */
#define SH2_CMD_WHEEL_REQ 0x0F
#define SH2_CMD_DR_CAL_SAVE 0x10
// SENSORHUB_COMMAND_REQ
#define SENSORHUB_COMMAND_REQ (0xF2)
#define COMMAND_PARAMS (9)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t seq;
uint8_t command;
uint8_t p[COMMAND_PARAMS];
} CommandReq_t;
// SENSORHUB_COMMAND_RESP
#define SENSORHUB_COMMAND_RESP (0xF1)
#define RESPONSE_VALUES (11)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t seq;
uint8_t command;
uint8_t commandSeq;
uint8_t respSeq;
uint8_t r[RESPONSE_VALUES];
} CommandResp_t;
// SENSORHUB_PROD_ID_REQ
#define SENSORHUB_PROD_ID_REQ (0xF9)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t reserved;
} ProdIdReq_t;
// SENSORHUB_PROD_ID_RESP
#define SENSORHUB_PROD_ID_RESP (0xF8)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t resetCause;
uint8_t swVerMajor;
uint8_t swVerMinor;
uint32_t swPartNumber;
uint32_t swBuildNumber;
uint16_t swVerPatch;
uint8_t reserved0;
uint8_t reserved1;
} ProdIdResp_t;
// Report definitions
// Bit fields for Feature Report flags
#define FEAT_CHANGE_SENSITIVITY_MODE_BIT 0
#define FEAT_CHANGE_SENSITIVITY_ENABLE_BIT 1
#define FEAT_WAKEUP_ENABLE_BIT 2
#define FEAT_ALWAYS_ON_ENABLE_BIT 3
#define FEAT_SNIFF_ENABLE_BIT 4
#define FEAT_CHANGE_SENSITIVITY_RELATIVE (1 << FEAT_CHANGE_SENSITIVITY_MODE_BIT)
#define FEAT_CHANGE_SENSITIVITY_ABSOLUTE (0 << FEAT_CHANGE_SENSITIVITY_MODE_BIT)
#define FEAT_CHANGE_SENSITIVITY_ENABLED (1 << FEAT_CHANGE_SENSITIVITY_ENABLE_BIT)
#define FEAT_CHANGE_SENSITIVITY_DISABLED (0 << FEAT_CHANGE_SENSITIVITY_ENABLE_BIT)
#define FEAT_WAKE_ENABLED (1 << FEAT_WAKEUP_ENABLE_BIT)
#define FEAT_WAKE_DISABLED (0 << FEAT_WAKEUP_ENABLE_BIT)
#define FEAT_ALWAYS_ON_ENABLED (1 << FEAT_ALWAYS_ON_ENABLE_BIT)
#define FEAT_ALWAYS_ON_DISABLED (0 << FEAT_ALWAYS_ON_ENABLE_BIT)
#define FEAT_SNIFF_ENABLED (1 << FEAT_SNIFF_ENABLE_BIT)
#define FEAT_SNIFF_DISABLED (0 << FEAT_SNIFF_ENABLE_BIT)
// GET_FEATURE_REQ
#define SENSORHUB_GET_FEATURE_REQ (0xFE)
typedef PACKED_STRUCT{
uint8_t reportId;
uint8_t featureReportId;
} GetFeatureReq_t;
// SENSORHUB_GET_FEATURE_RESP
#define SENSORHUB_GET_FEATURE_RESP (0xFC)
typedef PACKED_STRUCT{
uint8_t reportId;
uint8_t featureReportId; // sensor id
uint8_t flags; // FEAT_... values
uint16_t changeSensitivity;
uint32_t reportInterval_uS;
uint32_t batchInterval_uS;
uint32_t sensorSpecific;
} GetFeatureResp_t;
typedef struct sh2_s sh2_t;
typedef int (sh2_OpStart_t)(sh2_t *pSh2);
typedef void (sh2_OpRx_t)(sh2_t *pSh2, const uint8_t *payload, uint16_t len);
typedef void (sh2_OpReset_t)(sh2_t *pSh2);
typedef struct sh2_Op_s {
uint32_t timeout_us;
sh2_OpStart_t *start;
sh2_OpRx_t *rx;
sh2_OpReset_t *onReset;
} sh2_Op_t;
// Parameters and state information for the operation in progress
typedef union {
struct {
CommandReq_t req;
} sendCmd;
struct {
sh2_ProductIds_t *pProdIds;
uint8_t nextEntry;
uint8_t expectedEntries;
} getProdIds;
struct {
sh2_SensorConfig_t *pConfig;
sh2_SensorId_t sensorId;
} getSensorConfig;
struct {
const sh2_SensorConfig_t *pConfig;
sh2_SensorId_t sensorId;
} setSensorConfig;
struct {
uint16_t frsType;
uint32_t *pData;
uint16_t *pWords;
uint16_t nextOffset;
} getFrs;
struct {
uint16_t frsType;
uint32_t *pData;
uint16_t words;
uint16_t offset;
} setFrs;
struct {
uint8_t severity;
sh2_ErrorRecord_t *pErrors;
uint16_t *pNumErrors;
uint16_t errsRead;
} getErrors;
struct {
sh2_SensorId_t sensorId;
sh2_Counts_t *pCounts;
} getCounts;
struct {
uint8_t sensors;
} calConfig;
struct {
uint8_t *pSensors;
} getCalConfig;
struct {
sh2_SensorId_t sensorId;
} forceFlush;
struct {
sh2_OscType_t *pOscType;
} getOscType;
struct {
uint32_t interval_us;
} startCal;
struct {
sh2_CalStatus_t status;
} finishCal;
struct {
uint8_t wheelIndex;
uint32_t timestamp;
int16_t wheelData;
uint8_t dataType;
} wheelRequest;
} sh2_OpData_t;
// Max length of an FRS record, words.
#define MAX_FRS_WORDS (72)
struct sh2_s {
// Pointer to the SHTP HAL
sh2_Hal_t *pHal;
// associated SHTP instance
void *pShtp;
volatile bool resetComplete;
char version[MAX_VER_LEN+1];
// Multi-step operation support
const sh2_Op_t *pOp;
int opStatus;
sh2_OpData_t opData;
uint8_t lastCmdId;
uint8_t cmdSeq;
uint8_t nextCmdSeq;
// Event callback and it's cookie
sh2_EventCallback_t *eventCallback;
void * eventCookie;
// Sensor callback and it's cookie
sh2_SensorCallback_t *sensorCallback;
void * sensorCookie;
// Storage space for reading sensor metadata
uint32_t frsData[MAX_FRS_WORDS];
uint16_t frsDataLen;
// Stats
uint32_t execBadPayload;
uint32_t emptyPayloads;
uint32_t unknownReportIds;
};
#define SENSORHUB_BASE_TIMESTAMP_REF (0xFB)
typedef PACKED_STRUCT {
uint8_t reportId;
int32_t timebase;
} BaseTimestampRef_t;
#define SENSORHUB_TIMESTAMP_REBASE (0xFA)
typedef PACKED_STRUCT {
uint8_t reportId;
int32_t timebase;
} TimestampRebase_t;
// SENSORHUB_FORCE_SENSOR_FLUSH
#define SENSORHUB_FORCE_SENSOR_FLUSH (0xF0)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t sensorId;
} ForceFlushReq_t;
// SENSORHUB_FLUSH_COMPLETED
#define SENSORHUB_FLUSH_COMPLETED (0xEF)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t sensorId;
} ForceFlushResp_t;
typedef struct sh2_ReportLen_s {
uint8_t id;
uint8_t len;
} sh2_ReportLen_t;
// SENSORHUB_FRS_WRITE_REQ
#define SENSORHUB_FRS_WRITE_REQ (0xF7)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t reserved;
uint16_t length;
uint16_t frsType;
} FrsWriteReq_t;
// SENSORHUB_FRS_WRITE_DATA_REQ
#define SENSORHUB_FRS_WRITE_DATA_REQ (0xF6)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t reserved;
uint16_t offset;
uint32_t data0;
uint32_t data1;
} FrsWriteDataReq_t;
// FRS write status values
#define FRS_WRITE_STATUS_RECEIVED (0)
#define FRS_WRITE_STATUS_UNRECOGNIZED_FRS_TYPE (1)
#define FRS_WRITE_STATUS_BUSY (2)
#define FRS_WRITE_STATUS_WRITE_COMPLETED (3)
#define FRS_WRITE_STATUS_READY (4)
#define FRS_WRITE_STATUS_FAILED (5)
#define FRS_WRITE_STATUS_NOT_READY (6) // data received when not in write mode
#define FRS_WRITE_STATUS_INVALID_LENGTH (7)
#define FRS_WRITE_STATUS_RECORD_VALID (8)
#define FRS_WRITE_STATUS_INVALID_RECORD (9)
#define FRS_WRITE_STATUS_DEVICE_ERROR (10)
#define FRS_WRITE_STATUS_READ_ONLY (11)
// SENSORHUB_FRS_WRITE_RESP
#define SENSORHUB_FRS_WRITE_RESP (0xF5)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t status;
uint16_t wordOffset;
} FrsWriteResp_t;
// RESP_FRS_READ_REQ
#define SENSORHUB_FRS_READ_REQ (0xF4)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t reserved;
uint16_t readOffset;
uint16_t frsType;
uint16_t blockSize;
} FrsReadReq_t;
// Get Datalen portion of len_status field
#define FRS_READ_DATALEN(x) (((x) >> 4) & 0x0F)
// Get status portion of len_status field
#define FRS_READ_STATUS(x) ((x) & 0x0F)
// Status values
#define FRS_READ_STATUS_NO_ERROR 0
#define FRS_READ_STATUS_UNRECOGNIZED_FRS_TYPE 1
#define FRS_READ_STATUS_BUSY 2
#define FRS_READ_STATUS_READ_RECORD_COMPLETED 3
#define FRS_READ_STATUS_OFFSET_OUT_OF_RANGE 4
#define FRS_READ_STATUS_RECORD_EMPTY 5
#define FRS_READ_STATUS_READ_BLOCK_COMPLETED 6
#define FRS_READ_STATUS_READ_BLOCK_AND_RECORD_COMPLETED 7
#define FRS_READ_STATUS_DEVICE_ERROR 8
// SENSORHUB_FRS_READ_RESP
#define SENSORHUB_FRS_READ_RESP (0xF3)
typedef PACKED_STRUCT {
uint8_t reportId;
uint8_t len_status; // See FRS_READ... macros above
uint16_t wordOffset;
uint32_t data0;
uint32_t data1;
uint16_t frsType;
uint8_t reserved0;
uint8_t reserved1;
} FrsReadResp_t;
// ------------------------------------------------------------------------
// Private data
// SH2 state
sh2_t _sh2;
// SH2 Async Event Message
static sh2_AsyncEvent_t sh2AsyncEvent;
// Lengths of reports by report id.
static const sh2_ReportLen_t sh2ReportLens[] = {
// Sensor reports
{.id = SH2_ACCELEROMETER, .len = 10},
{.id = SH2_GYROSCOPE_CALIBRATED, .len = 10},
{.id = SH2_MAGNETIC_FIELD_CALIBRATED, .len = 10},
{.id = SH2_LINEAR_ACCELERATION, .len = 10},
{.id = SH2_ROTATION_VECTOR, .len = 14},
{.id = SH2_GRAVITY, .len = 10},
{.id = SH2_GYROSCOPE_UNCALIBRATED, .len = 16},
{.id = SH2_GAME_ROTATION_VECTOR, .len = 12},
{.id = SH2_GEOMAGNETIC_ROTATION_VECTOR, .len = 14},
{.id = SH2_PRESSURE, .len = 8},
{.id = SH2_AMBIENT_LIGHT, .len = 8},
{.id = SH2_HUMIDITY, .len = 6},
{.id = SH2_PROXIMITY, .len = 6},
{.id = SH2_TEMPERATURE, .len = 6},
{.id = SH2_MAGNETIC_FIELD_UNCALIBRATED, .len = 16},
{.id = SH2_TAP_DETECTOR, .len = 5},
{.id = SH2_STEP_COUNTER, .len = 12},
{.id = SH2_SIGNIFICANT_MOTION, .len = 6},
{.id = SH2_STABILITY_CLASSIFIER, .len = 6},
{.id = SH2_RAW_ACCELEROMETER, .len = 16},
{.id = SH2_RAW_GYROSCOPE, .len = 16},
{.id = SH2_RAW_MAGNETOMETER, .len = 16},
{.id = SH2_STEP_DETECTOR, .len = 8},
{.id = SH2_SHAKE_DETECTOR, .len = 6},
{.id = SH2_FLIP_DETECTOR, .len = 6},
{.id = SH2_PICKUP_DETECTOR, .len = 8},
{.id = SH2_STABILITY_DETECTOR, .len = 6},
{.id = SH2_PERSONAL_ACTIVITY_CLASSIFIER, .len = 16},
{.id = SH2_SLEEP_DETECTOR, .len = 6},
{.id = SH2_TILT_DETECTOR, .len = 6},
{.id = SH2_POCKET_DETECTOR, .len = 6},
{.id = SH2_CIRCLE_DETECTOR, .len = 6},
{.id = SH2_HEART_RATE_MONITOR, .len = 6},
{.id = SH2_ARVR_STABILIZED_RV, .len = 14},
{.id = SH2_ARVR_STABILIZED_GRV, .len = 12},
{.id = SH2_GYRO_INTEGRATED_RV, .len = 14},
{.id = SH2_IZRO_MOTION_REQUEST, .len = 6},
{.id = SH2_RAW_OPTICAL_FLOW, .len = 24},
{.id = SH2_DEAD_RECKONING_POSE, .len = 60},
{.id = SH2_WHEEL_ENCODER, .len = 12},
// Other response types
{.id = SENSORHUB_FLUSH_COMPLETED, .len = 2},
{.id = SENSORHUB_COMMAND_RESP, .len = 16},
{.id = SENSORHUB_FRS_READ_RESP, .len = 16},
{.id = SENSORHUB_FRS_WRITE_RESP, .len = 4},
{.id = SENSORHUB_PROD_ID_RESP, .len = 16},
{.id = SENSORHUB_TIMESTAMP_REBASE, .len = 5},
{.id = SENSORHUB_BASE_TIMESTAMP_REF, .len = 5},
{.id = SENSORHUB_GET_FEATURE_RESP, .len = 17},
};
// ------------------------------------------------------------------------
// Private functions
// SH-2 transaction phases
static int opStart(sh2_t *pSh2, const sh2_Op_t *pOp)
{
// return error if another operation already in progress
if (pSh2->pOp) return SH2_ERR_OP_IN_PROGRESS;
// Establish this operation as the new operation in progress
pSh2->pOp = pOp;
pSh2->opStatus = SH2_OK;
int rc = pOp->start(pSh2); // Call start method
if (rc != SH2_OK) {
// Unregister this operation
pSh2->opStatus = rc;
pSh2->pOp = 0;
}
return rc;
}
static void opRx(sh2_t *pSh2, const uint8_t *payload, uint16_t len)
{
if ((pSh2->pOp != 0) && // An operation is in progress
(pSh2->pOp->rx != 0)) { // and it has an rx method
pSh2->pOp->rx(pSh2, payload, len); // Call receive method
}
}
static int opCompleted(sh2_t *pSh2, int status)
{
// Record status
pSh2->opStatus = status;
// Signal that op is done.
pSh2->pOp = 0;
return SH2_OK;
}
static void opOnReset(sh2_t *pSh2)
{
if (pSh2->pOp != 0) {
if (pSh2->pOp->onReset != 0) {
// This operation has its own reset handler so use it.
pSh2->pOp->onReset(pSh2);
}
else {
// No reset handler : abort the operation with SH2_ERR code
opCompleted(pSh2, SH2_ERR);
}
}
}
static uint8_t getReportLen(uint8_t reportId)
{
for (unsigned n = 0; n < ARRAY_LEN(sh2ReportLens); n++) {
if (sh2ReportLens[n].id == reportId) {
return sh2ReportLens[n].len;
}
}
return 0;
}
static void sensorhubControlHdlr(void *cookie, uint8_t *payload, uint16_t len, uint32_t timestamp)
{
(void)timestamp; // unused.
sh2_t *pSh2 = (sh2_t *)cookie;
uint16_t cursor = 0;
uint32_t count = 0;
CommandResp_t * pResp = 0;
if (len == 0) {
pSh2->emptyPayloads++;
return;
}
while (cursor < len) {
// Get next report id
count++;
uint8_t reportId = payload[cursor];
// Determine report length
uint8_t reportLen = getReportLen(reportId);
if (reportLen == 0) {
// An unrecognized report id
pSh2->unknownReportIds++;
return;
}
else {
// Check for unsolicited initialize response
if (reportId == SENSORHUB_COMMAND_RESP) {
pResp = (CommandResp_t *)(payload+cursor);
if ((pResp->command == (SH2_CMD_INITIALIZE | SH2_INIT_UNSOLICITED)) &&
(pResp->r[1] == SH2_INIT_SYSTEM)) {
// This is an unsolicited INIT message.
// Ignore this. EXECUTABLE_DEVICE_RESP_RESET_COMPLETE makes it redundant.
}
} // Check for Get Feature Response
else if (reportId == SENSORHUB_GET_FEATURE_RESP) {
if (pSh2->eventCallback) {
GetFeatureResp_t * pGetFeatureResp;
pGetFeatureResp = (GetFeatureResp_t *)(payload + cursor);
sh2AsyncEvent.eventId = SH2_GET_FEATURE_RESP;
sh2AsyncEvent.sh2SensorConfigResp.sensorId = pGetFeatureResp->featureReportId;
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.changeSensitivityEnabled =
((pGetFeatureResp->flags & FEAT_CHANGE_SENSITIVITY_ENABLED) != 0);
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.changeSensitivityRelative =
((pGetFeatureResp->flags & FEAT_CHANGE_SENSITIVITY_RELATIVE) != 0);
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.wakeupEnabled =
((pGetFeatureResp->flags & FEAT_WAKE_ENABLED) != 0);
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.alwaysOnEnabled =
((pGetFeatureResp->flags & FEAT_ALWAYS_ON_ENABLED) != 0);
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.changeSensitivity =
pGetFeatureResp->changeSensitivity;
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.reportInterval_us =
pGetFeatureResp->reportInterval_uS;
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.batchInterval_us =
pGetFeatureResp->batchInterval_uS;
sh2AsyncEvent.sh2SensorConfigResp.sensorConfig.sensorSpecific =
pGetFeatureResp->sensorSpecific;
pSh2->eventCallback(pSh2->eventCookie, &sh2AsyncEvent);
}
}
// Hand off to operation in progress, if any
opRx(pSh2, payload+cursor, reportLen);
cursor += reportLen;
}
}
}
static int opProcess(sh2_t *pSh2, const sh2_Op_t *pOp)
{
int status = SH2_OK;
uint32_t start_us = 0;
start_us = pSh2->pHal->getTimeUs(pSh2->pHal);
status = opStart(pSh2, pOp);
if (status != SH2_OK) {
return status;
}
uint32_t now_us = start_us;
// While op not complete and not timed out.
while ((pSh2->pOp != 0) &&
((pOp->timeout_us == 0) ||
((now_us-start_us) < pOp->timeout_us))) {
if (pSh2->pShtp == 0) {
// Was SH2 interface closed unexpectedly?
pSh2->opStatus = SH2_ERR;
break;
}
// Service SHTP to poll the device.
shtp_service(pSh2->pShtp);
// Update the time
now_us = pSh2->pHal->getTimeUs(pSh2->pHal);
}
if (pSh2->pOp != 0) {
// Operation has timed out. Clean up.
pSh2->pOp = 0;
pSh2->opStatus = SH2_ERR_TIMEOUT;
}
return pSh2->opStatus;
}
// Produce 64-bit microsecond timestamp for a sensor event
static uint64_t touSTimestamp(uint32_t hostInt, int32_t referenceDelta, uint16_t delay)
{
static uint32_t lastHostInt = 0;
static uint32_t rollovers = 0;
uint64_t timestamp;
// Count times hostInt timestamps rolled over to produce upper bits
if (hostInt < lastHostInt) {
rollovers++;
}
lastHostInt = hostInt;
timestamp = ((uint64_t)rollovers << 32);
timestamp += hostInt + (referenceDelta + delay) * 100;
return timestamp;
}
static void sensorhubInputHdlr(sh2_t *pSh2, uint8_t *payload, uint16_t len, uint32_t timestamp)
{
sh2_SensorEvent_t event;
uint16_t cursor = 0;
int32_t referenceDelta = 0;
while (cursor < len) {
// Get next report id
uint8_t reportId = payload[cursor];
// Determine report length
uint8_t reportLen = getReportLen(reportId);
if (reportLen == 0) {
// An unrecognized report id
pSh2->unknownReportIds++;
return;
}
else {
if (reportId == SENSORHUB_BASE_TIMESTAMP_REF) {
const BaseTimestampRef_t *rpt = (const BaseTimestampRef_t *)(payload+cursor);
// store base timestamp reference
referenceDelta = -rpt->timebase;
}
else if (reportId == SENSORHUB_TIMESTAMP_REBASE) {
const TimestampRebase_t *rpt = (const TimestampRebase_t *)(payload+cursor);
referenceDelta += rpt->timebase;
}
else if (reportId == SENSORHUB_FLUSH_COMPLETED) {
// Route this as if it arrived on command channel.
opRx(pSh2, payload+cursor, reportLen);
}
else {
// Sensor event. Call callback
uint8_t *pReport = payload+cursor;
uint16_t delay = ((pReport[2] & 0xFC) << 6) + pReport[3];
event.timestamp_uS = touSTimestamp(timestamp, referenceDelta, delay);
event.delay_uS = (referenceDelta + delay) * 100;
event.reportId = reportId;
memcpy(event.report, pReport, reportLen);
event.len = reportLen;
if (pSh2->sensorCallback != 0) {
pSh2->sensorCallback(pSh2->sensorCookie, &event);
}
}
// Move to next report in the payload
cursor += reportLen;
}
}
}
static void sensorhubInputNormalHdlr(void *cookie, uint8_t *payload, uint16_t len, uint32_t timestamp)
{
sh2_t *pSh2 = (sh2_t *)cookie;
sensorhubInputHdlr(pSh2, payload, len, timestamp);
}
static void sensorhubInputWakeHdlr(void *cookie, uint8_t *payload, uint16_t len, uint32_t timestamp)
{
sh2_t *pSh2 = (sh2_t *)cookie;
sensorhubInputHdlr(pSh2, payload, len, timestamp);
}
static void sensorhubInputGyroRvHdlr(void *cookie, uint8_t *payload, uint16_t len, uint32_t timestamp)
{
sh2_t *pSh2 = (sh2_t *)cookie;
sh2_SensorEvent_t event;
uint16_t cursor = 0;
uint8_t reportId = SH2_GYRO_INTEGRATED_RV;
uint8_t reportLen = getReportLen(reportId);
while (cursor < len) {
event.timestamp_uS = timestamp;
event.reportId = reportId;
memcpy(event.report, payload+cursor, reportLen);
event.len = reportLen;
if (pSh2->sensorCallback != 0) {
pSh2->sensorCallback(pSh2->sensorCookie, &event);
}
cursor += reportLen;
}
}
static void executableDeviceHdlr(void *cookie, uint8_t *payload, uint16_t len, uint32_t timestamp)
{
(void)timestamp; // unused
sh2_t *pSh2 = (sh2_t *)cookie;
// Discard if length is bad
if (len != 1) {
pSh2->execBadPayload++;
return;
}
switch (payload[0]) {
case EXECUTABLE_DEVICE_RESP_RESET_COMPLETE:
// reset process is now done.
pSh2->resetComplete = true;
// Send reset event to SH2 operation processor.
// Some commands may handle themselves. Most will be aborted with SH2_ERR.
opOnReset(pSh2);
// Notify client that reset is complete.
sh2AsyncEvent.eventId = SH2_RESET;
if (pSh2->eventCallback) {
pSh2->eventCallback(pSh2->eventCookie, &sh2AsyncEvent);
}
break;
default:
pSh2->execBadPayload++;
break;
}
}
static int sendExecutable(sh2_t *pSh2, uint8_t cmd)
{
return shtp_send(pSh2->pShtp, CHAN_EXECUTABLE_DEVICE, &cmd, 1);
}
static int sendCtrl(sh2_t *pSh2, const uint8_t *data, uint16_t len)
{
return shtp_send(pSh2->pShtp, CHAN_SENSORHUB_CONTROL, data, len);
}
static int16_t toQ14(double x)
{
int16_t retval = (int16_t)(x * (1<<14));
return retval;
}
// ------------------------------------------------------------------------
// Get Product ID support
// Get Product ID Op handler
static int getProdIdStart(sh2_t *pSh2)
{
int rc = SH2_OK;
ProdIdReq_t req;
pSh2->opData.getProdIds.nextEntry = 0;
pSh2->opData.getProdIds.expectedEntries = 4; // Most products supply 4 product ids.
// When the first arrives, we'll know if
// we need to adjust this.
// Set up request to issue
memset(&req, 0, sizeof(req));
req.reportId = SENSORHUB_PROD_ID_REQ;
rc = sendCtrl(pSh2, (uint8_t *)&req, sizeof(req));
return rc;
}
static void getProdIdRx(sh2_t *pSh2, const uint8_t *payload, uint16_t len)
{
(void)len; // unused
ProdIdResp_t *resp = (ProdIdResp_t *)payload;
// skip this if it isn't the product id response.
if (resp->reportId != SENSORHUB_PROD_ID_RESP) return;
// Store this product id, if we can
sh2_ProductIds_t *pProdIds = pSh2->opData.getProdIds.pProdIds;
if (pProdIds) {
// Store the product id response
if (pSh2->opData.getProdIds.nextEntry < pSh2->opData.getProdIds.expectedEntries) {
sh2_ProductId_t *pProdId = &pProdIds->entry[pSh2->opData.getProdIds.nextEntry];
pProdId->resetCause = resp->resetCause;
pProdId->swVersionMajor = resp->swVerMajor;
pProdId->swVersionMinor = resp->swVerMinor;
pProdId->swPartNumber = resp->swPartNumber;
pProdId->swBuildNumber = resp->swBuildNumber;
pProdId->swVersionPatch = resp->swVerPatch;
pProdId->reserved0 = resp->reserved0;
pProdId->reserved1 = resp->reserved1;
if ((pProdId->swPartNumber == 10004095) ||
(pProdId->swPartNumber == 10004818) ||
(pProdId->swPartNumber == 10005028)) {
// FSP200 has 5 product id entries
pSh2->opData.getProdIds.expectedEntries = 5;
}
pSh2->opData.getProdIds.nextEntry++;
}
}
// Complete this operation if there is no storage for more product ids
if ((pSh2->opData.getProdIds.pProdIds == 0) ||
(pSh2->opData.getProdIds.nextEntry >= pSh2->opData.getProdIds.expectedEntries)) {
pSh2->opData.getProdIds.pProdIds->numEntries = pSh2->opData.getProdIds.nextEntry;
opCompleted(pSh2, SH2_OK);
}
return;
}
const sh2_Op_t getProdIdOp = {
.start = getProdIdStart,
.rx = getProdIdRx,
};
// ------------------------------------------------------------------------
// Set Sensor Config
static int getSensorConfigStart(sh2_t *pSh2)
{
int rc = SH2_OK;
GetFeatureReq_t req;
// set up request to issue
memset(&req, 0, sizeof(req));
req.reportId = SENSORHUB_GET_FEATURE_REQ;
req.featureReportId = pSh2->opData.getSensorConfig.sensorId;
rc = sendCtrl(pSh2, (uint8_t *)&req, sizeof(req));
return rc;
}
static void getSensorConfigRx(sh2_t *pSh2, const uint8_t *payload, uint16_t len)
{
(void)len; // unused
GetFeatureResp_t *resp = (GetFeatureResp_t *)payload;
sh2_SensorConfig_t *pConfig;
// skip this if it isn't the response we're waiting for.
if (resp->reportId != SENSORHUB_GET_FEATURE_RESP) return;
if (resp->featureReportId != pSh2->opData.getSensorConfig.sensorId) return;
// Copy out data
pConfig = pSh2->opData.getSensorConfig.pConfig;
pConfig->changeSensitivityEnabled = ((resp->flags & FEAT_CHANGE_SENSITIVITY_ENABLED) != 0);
pConfig->changeSensitivityRelative = ((resp->flags & FEAT_CHANGE_SENSITIVITY_RELATIVE) != 0);
pConfig->wakeupEnabled = ((resp->flags & FEAT_WAKE_ENABLED) != 0);
pConfig->alwaysOnEnabled = ((resp->flags & FEAT_ALWAYS_ON_ENABLED) != 0);
pConfig->sniffEnabled = ((resp->flags & FEAT_SNIFF_ENABLED) !=0);
pConfig->changeSensitivity = resp->changeSensitivity;
pConfig->reportInterval_us = resp->reportInterval_uS;
pConfig->batchInterval_us = resp->batchInterval_uS;
pConfig->sensorSpecific = resp->sensorSpecific;
// Complete this operation
opCompleted(pSh2, SH2_OK);
return;
}
const sh2_Op_t getSensorConfigOp = {
.start = getSensorConfigStart,
.rx = getSensorConfigRx,
};
// ------------------------------------------------------------------------
// Set Sensor Config
// SENSORHUB_SET_FEATURE_CMD
#define SENSORHUB_SET_FEATURE_CMD (0xFD)
typedef PACKED_STRUCT {
uint8_t reportId; // 0xFD
uint8_t featureReportId; // sensor id
uint8_t flags; // FEAT_... values
uint16_t changeSensitivity;
uint32_t reportInterval_uS;
uint32_t batchInterval_uS;
uint32_t sensorSpecific;
} SetFeatureReport_t;
static int setSensorConfigStart(sh2_t *pSh2)
{
SetFeatureReport_t req;
uint8_t flags = 0;
int rc;
sh2_SensorConfig_t *pConfig = pSh2->opData.getSensorConfig.pConfig;
if (pConfig->changeSensitivityEnabled) flags |= FEAT_CHANGE_SENSITIVITY_ENABLED;
if (pConfig->changeSensitivityRelative) flags |= FEAT_CHANGE_SENSITIVITY_RELATIVE;
if (pConfig->wakeupEnabled) flags |= FEAT_WAKE_ENABLED;
if (pConfig->alwaysOnEnabled) flags |= FEAT_ALWAYS_ON_ENABLED;
if (pConfig->sniffEnabled) flags |= FEAT_SNIFF_ENABLED;
memset(&req, 0, sizeof(req));
req.reportId = SENSORHUB_SET_FEATURE_CMD;
req.featureReportId = pSh2->opData.setSensorConfig.sensorId;
req.flags = flags;
req.changeSensitivity = pConfig->changeSensitivity;
req.reportInterval_uS = pConfig->reportInterval_us;
req.batchInterval_uS = pConfig->batchInterval_us;
req.sensorSpecific = pConfig->sensorSpecific;
rc = sendCtrl(pSh2, (uint8_t *)&req, sizeof(req));
opCompleted(pSh2, rc);
return rc;
}
const sh2_Op_t setSensorConfigOp = {