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
|
//Copyright (C) Microsoft Corporation, All Rights Reserved.
//
//Abstract:
//
// This module contains the implementation of the pedometer sample driver
// hardware simulator.
//
//Environment:
//
// Windows User-Mode Driver Framework (UMDF)
#include "HardwareSimulator.h"
#include "HardwareSimulator.tmh"
#include "Device.h"
// Simulated pedometer data
// The simulation data represent the pedometer data for a user walking and running at different paces
// Since the simulator is designed to report a sample every second,
// each line in the table represents 1 second of data
const PedometerSample SimulatorData[] = {
// 1: Timestamp
// 2: IsFirstSample
// 3: Unknown step count
// 4: Unknown step duration in milliseconds
// 5: Walking step count
// 6: Walking step duration in milliseconds
// 7: Running step count
// 8: Running step duration in milliseconds
//
// | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
{ {}, TRUE, 0, 0, 0, 0, 0, 0 }, // the pedometer is reset
{ {}, FALSE, 0, 0, 0, 0, 0, 0 },
{ {}, FALSE, 0, 0, 1, 1000, 0, 0 }, // 3 seconds, The user starts walking
{ {}, FALSE, 0, 0, 3, 2000, 0, 0 },
{ {}, FALSE, 0, 0, 5, 3000, 0, 0 },
{ {}, FALSE, 0, 0, 7, 4000, 0, 0 },
{ {}, FALSE, 0, 0, 9, 5000, 0, 0 },
{ {}, FALSE, 0, 0, 12, 6000, 0, 0 }, // 8 seconds, the user starts accelerating the foot pace, the sensor hasn't detected a running pace yet
{ {}, FALSE, 0, 0, 12, 6000, 3, 1000 }, // 9 seconds, the sensors detects the user is running
{ {}, FALSE, 0, 0, 12, 6000, 6, 2000 },
{ {}, FALSE, 0, 0, 12, 6000, 10, 3000 },
{ {}, FALSE, 0, 0, 12, 6000, 14, 4000 },
{ {}, FALSE, 0, 0, 12, 6000, 18, 5000 },
{ {}, FALSE, 0, 0, 12, 6000, 22, 6000 },
{ {}, FALSE, 0, 0, 12, 6000, 25, 7000 }, // 15 seconds, the user starts decelerating
{ {}, FALSE, 0, 0, 12, 6000, 27, 8000 },
{ {}, FALSE, 0, 0, 12, 6000, 28, 9000 },
{ {}, FALSE, 0, 0, 13, 7000, 28, 9000 }, // 18 seconds, the user walks again
{ {}, FALSE, 0, 0, 14, 8000, 28, 9000 },
{ {}, FALSE, 0, 0, 15, 9000, 28, 9000 },
{ {}, FALSE, 0, 0, 16, 10000, 28, 9000 },
{ {}, FALSE, 0, 0, 16, 10000, 28, 9000 }, // 22 seconds, the user stops walking
{ {}, FALSE, 0, 0, 16, 10000, 28, 9000 },
{ {}, FALSE, 0, 0, 16, 10000, 28, 9000 },
};
HardwareSimulator::HardwareSimulator() :
m_HasReset(TRUE),
m_Index(0),
m_Lock(NULL),
m_State(SimulatorState_NotInitialized),
m_SimulatorInstance(NULL),
m_Timer(NULL),
m_HistoryIntervalInMs(0),
m_History({})
{
}
HardwareSimulator::~HardwareSimulator()
{
}
// This static routine performs simulator initialization. The routine creates a
// timer object that periodically updates the m_Index location
NTSTATUS
HardwareSimulator::Initialize(
_In_ WDFDEVICE Device, // WDF device representing the sensor
_Out_ WDFOBJECT *SimulatorInstance) // Instance of the WDF object for the simulator
{
PHardwareSimulator pSimulator = nullptr;
NTSTATUS Status = STATUS_SUCCESS;
WDF_OBJECT_ATTRIBUTES HardwareSimulatorAttributes = {};
SENSOR_FunctionEnter();
// Create WDFOBJECT for the hardware simulator
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&HardwareSimulatorAttributes, HardwareSimulator);
HardwareSimulatorAttributes.ParentObject = Device;
Status = WdfObjectCreate(&HardwareSimulatorAttributes, SimulatorInstance);
if (!NT_SUCCESS(Status))
{
TraceError("PED %!FUNC! WdfObjectCreate failed %!STATUS!", Status);
goto Exit;
}
pSimulator = GetHardwareSimulatorContextFromInstance(*SimulatorInstance);
if (nullptr == pSimulator)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
TraceError("PED %!FUNC! GetHardwareSimulatorContextFromInstance failed %!STATUS!", Status);
goto Exit;
}
pSimulator->InitializeInternal(*SimulatorInstance);
Exit:
SENSOR_FunctionExit(Status);
return Status;
}
// Internal routine to perform simulator initialization
NTSTATUS
HardwareSimulator::InitializeInternal(
_In_ WDFOBJECT SimulatorInstance) // Instance of the WDF object for the simulator
{
NTSTATUS Status = STATUS_SUCCESS;
WDF_OBJECT_ATTRIBUTES TimerAttributes = {};
WDF_TIMER_CONFIG TimerConfig = {};
SENSOR_FunctionEnter();
// Only initialize the simulator if it is in the "not initialized" state
if (SimulatorState_NotInitialized == m_State)
{
// Create sample Lock
Status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &m_Lock);
if (!NT_SUCCESS(Status))
{
m_Lock = NULL;
TraceError("PED %!FUNC! WdfWaitLockCreate for m_Lock failed %!STATUS!", Status);
goto Exit;
}
// Create a timer object for simulation updates
WDF_TIMER_CONFIG_INIT(&TimerConfig, HardwareSimulator::OnTimerExpire);
WDF_OBJECT_ATTRIBUTES_INIT(&TimerAttributes);
TimerAttributes.ParentObject = SimulatorInstance;
TimerAttributes.ExecutionLevel = WdfExecutionLevelPassive;
Status = WdfTimerCreate(&TimerConfig, &TimerAttributes, &m_Timer);
if (!NT_SUCCESS(Status))
{
m_Timer = NULL;
TraceError("PED %!FUNC! WdfTimerCreate failed %!STATUS!", Status);
goto Exit;
}
// Create history lock
Status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &m_HistoryLock);
if (!NT_SUCCESS(Status))
{
TraceError("PED %!FUNC! WdfWaitLockCreate failed %!STATUS!", Status);
goto Exit;
}
m_HistoryIntervalInMs = Pedometer_Default_HistoryInterval_Ms;
// Initialize history buffer
m_History.pData = reinterpret_cast<PPedometerSample>(malloc(sizeof(PedometerSample) * Pedometer_Default_MaxHistoryEntries));
if (nullptr == m_History.pData)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
TraceError("PED %!FUNC! Allocating circular buffer for history failed %!STATUS!", Status);
goto Exit;
}
m_History.FirstElemIndex = 0;
m_History.LastElemIndex = 0;
m_History.NumOfElems = 0;
m_History.BufferLength = Pedometer_Default_MaxHistoryEntries;
// Create an auto-reset event for signaling the busy read to stop
m_HistoryCancelReadEvt = CreateEvent(NULL, FALSE, FALSE, NULL);
if (NULL == m_HistoryCancelReadEvt)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
TraceError("PED %!FUNC! Failed to create an event %!STATUS!", Status);
goto Exit;
}
// Create timer object for keeping history
WDF_TIMER_CONFIG_INIT(&TimerConfig, HardwareSimulator::OnHistoryTimerExpire);
WDF_OBJECT_ATTRIBUTES_INIT(&TimerAttributes);
TimerAttributes.ParentObject = SimulatorInstance;
TimerAttributes.ExecutionLevel = WdfExecutionLevelPassive;
Status = WdfTimerCreate(&TimerConfig, &TimerAttributes, &m_HistoryTimer);
if (!NT_SUCCESS(Status))
{
TraceError("PED %!FUNC! WdfTimerCreate for history failed %!STATUS!", Status);
goto Exit;
}
// Set the simulator state to "initialized"
m_State = SimulatorState_Initialized;
m_SimulatorInstance = SimulatorInstance;
}
Exit:
if (!NT_SUCCESS(Status) && NULL != m_Lock)
{
WdfObjectDelete(m_Lock);
m_Lock = NULL;
}
SENSOR_FunctionExit(Status);
return Status;
}
// This routine perform a simulator cleanup
NTSTATUS
HardwareSimulator::Cleanup()
{
NTSTATUS status = STATUS_SUCCESS;
if (SimulatorState_Started == m_State)
{
Stop();
}
// Delete lock
if (NULL != m_Lock)
{
WdfObjectDelete(m_Lock);
m_Lock = NULL;
}
// Close handle to Read cancellation event
if (NULL != m_HistoryCancelReadEvt)
{
CloseHandle(m_HistoryCancelReadEvt);
m_HistoryCancelReadEvt = NULL;
}
m_History.FirstElemIndex = 0;
m_History.LastElemIndex = 0;
m_History.NumOfElems = 0;
m_History.BufferLength = 0;
// Delete history buffer
if (nullptr != m_History.pData)
{
free(m_History.pData);
m_History.pData = nullptr;
}
// Delete history lock
if (NULL != m_HistoryLock)
{
WdfObjectDelete(m_HistoryLock);
m_HistoryLock = NULL;
}
// Set the simulator state to "not initialized"
m_State = SimulatorState_NotInitialized;
return status;
}
// This routine starts the simulator
NTSTATUS
HardwareSimulator::Start()
{
NTSTATUS status = STATUS_SUCCESS;
SENSOR_FunctionEnter();
if (SimulatorState_Initialized == m_State)
{
WdfTimerStart(m_Timer, WDF_REL_TIMEOUT_IN_MS(SIMULATOR_HARDWARE_INTERVAL_MS));
m_State = SimulatorState_Started;
}
SENSOR_FunctionExit(status);
return status;
}
// This routine stops the simulator
NTSTATUS
HardwareSimulator::Stop()
{
NTSTATUS status = STATUS_SUCCESS;
SENSOR_FunctionEnter();
if (SimulatorState_Started == m_State)
{
WdfTimerStop(m_Timer, TRUE);
m_State = SimulatorState_Initialized;
}
SENSOR_FunctionExit(status);
return status;
}
// This callback is called when the simulator wait time has expired and the simulator
// is ready to switch to the next sample. The callback updates the sample index and
// schedules the next wake up time.
VOID
HardwareSimulator::OnTimerExpire(
_In_ WDFTIMER Timer) // WDF timer object
{
HardwareSimulator *pSimulator = nullptr;
NTSTATUS Status = STATUS_SUCCESS;
SENSOR_FunctionEnter();
pSimulator = GetHardwareSimulatorContextFromInstance(WdfTimerGetParentObject(Timer));
if (nullptr == pSimulator)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
TraceError("PED %!FUNC! GetHardwareSimulatorContextFromInstance failed %!STATUS!", Status);
}
if (NT_SUCCESS(Status))
{
// Increment the sample index, roll over if the index reach the end of the array
WdfWaitLockAcquire(pSimulator->m_Lock, NULL);
pSimulator->m_Index++;
pSimulator->m_Index = pSimulator->m_Index % ARRAYSIZE(SimulatorData);
if (FALSE != SimulatorData[pSimulator->m_Index].IsFirstAfterReset)
{
pSimulator->m_HasReset = TRUE;
}
WdfWaitLockRelease(pSimulator->m_Lock);
WdfTimerStart(pSimulator->m_Timer, WDF_REL_TIMEOUT_IN_MS(SIMULATOR_HARDWARE_INTERVAL_MS));
}
SENSOR_FunctionExit(Status);
}
// This routine returns the current sample from the driver at the current m_Index
// location
NTSTATUS
HardwareSimulator::GetSample(
_Out_ PedometerSample *Sample) // Pedometer sample
{
NTSTATUS Status = STATUS_SUCCESS;
SENSOR_FunctionEnter();
if (nullptr == Sample)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
TraceError("PED %!FUNC! Sample parameter is null");
}
if (NT_SUCCESS(Status))
{
WdfWaitLockAcquire(m_Lock, NULL);
*Sample = SimulatorData[m_Index];
// The IsFirstAfterReset value should only be true for the first sample after a pedometer reset.
// (Simulator specific) The below makes sure this requirement is respected when multiple calls to GetSample()
// happen in a shorter time than is required by the simulator to switch to the next sample (i.e. if multiple calls
// to GetSample() happen within the same second).
if (FALSE != m_HasReset)
{
Sample->IsFirstAfterReset = TRUE;
m_HasReset = FALSE;
}
else
{
Sample->IsFirstAfterReset = FALSE;
}
WdfWaitLockRelease(m_Lock);
GetSystemTimePreciseAsFileTime(&Sample->Timestamp);
}
SENSOR_FunctionExit(Status);
return Status;
}
// This routine resets the pedometer
NTSTATUS
HardwareSimulator::Reset()
{
NTSTATUS Status = STATUS_SUCCESS;
SENSOR_FunctionEnter();
WdfWaitLockAcquire(m_Lock, NULL);
m_Index = 0;
WdfWaitLockRelease(m_Lock);
SENSOR_FunctionExit(Status);
return Status;
}
// This routine is called by history retrieval thread to remove an entry from the history buffer.
// Note this function must be called under lock
_Requires_lock_held_(m_HistoryLock)
NTSTATUS
HardwareSimulator::RemoveDataElemFromHistoryBuffer(
_Out_ PPedometerSample pData // Pedometer data removed from the buffer
)
{
NTSTATUS Status = STATUS_SUCCESS;
if (0 == m_History.NumOfElems)
{
// buffer empty
Status = STATUS_NO_MORE_ENTRIES;
}
else
{
*pData = m_History.pData[m_History.FirstElemIndex];
m_History.FirstElemIndex++;
m_History.FirstElemIndex %= m_History.BufferLength;
m_History.NumOfElems--;
if (0 == m_History.NumOfElems)
{
// Buffer Empty. 'LastElemIndex' should be same as 'FirstElemIndex'
m_History.LastElemIndex = m_History.FirstElemIndex;
}
}
return Status;
}
// This routine is called by worker thread to add an entry to the history buffer.
// Note this function must be called under lock
_Requires_lock_held_(m_HistoryLock)
NTSTATUS
HardwareSimulator::AddDataElemToHistoryBuffer(
_In_ PPedometerSample pData // Pedometer data to be added to the buffer
)
{
NTSTATUS Status = STATUS_SUCCESS;
if (0 == m_History.NumOfElems)
{
// buffer empty
m_History.NumOfElems++;
}
else if (m_History.BufferLength > m_History.NumOfElems)
{
// buffer not full yet. Increment the index of the last element in the circular buffer
m_History.LastElemIndex++;
m_History.LastElemIndex %= m_History.BufferLength;
// Increment the num of elements
m_History.NumOfElems++;
}
else if (m_History.BufferLength == m_History.NumOfElems)
{
// buffer full. Over-write the oldest element in the circular buffer
m_History.FirstElemIndex++;
m_History.FirstElemIndex %= m_History.BufferLength;
m_History.LastElemIndex++;
m_History.LastElemIndex %= m_History.BufferLength;
}
m_History.pData[m_History.LastElemIndex] = *pData;
return Status;
}
// This callback is called when interval wait time has expired and driver is ready
// to collect new sample. The callback stores pedometer data in history buffer,
// and schedules next wake up time.
VOID
HardwareSimulator::OnHistoryTimerExpire(
_In_ WDFTIMER HistoryTimer // WDF timer object
)
{
PHardwareSimulator pSimulator = nullptr;
NTSTATUS Status = STATUS_SUCCESS;
PedometerSample Sample = {};
SENSOR_FunctionEnter();
pSimulator = GetHardwareSimulatorContextFromInstance(WdfTimerGetParentObject(HistoryTimer));
if (nullptr == pSimulator)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
TraceError("PED %!FUNC! GetHardwareSimulatorContextFromInstance failed %!STATUS!", Status);
goto Exit;
}
// Just use the current sample to store in the history buffer
Status = pSimulator->GetSample(&Sample);
if (!NT_SUCCESS(Status))
{
TraceError("PED %!FUNC! GetSample failed %!STATUS!", Status);
goto Exit;
}
WdfWaitLockAcquire(pSimulator->m_HistoryLock, NULL);
// Add data to the buffer
Status = pSimulator->AddDataElemToHistoryBuffer(&Sample);
if (!NT_SUCCESS(Status))
{
TraceError("PED %!FUNC! AddDataElemToHistoryBuffer Failed %!STATUS!", Status);
}
WdfWaitLockRelease(pSimulator->m_HistoryLock);
// Schedule next wake up time
if (FALSE != pSimulator->m_HistoryStarted)
{
WdfTimerStart(pSimulator->m_HistoryTimer, WDF_REL_TIMEOUT_IN_MS(pSimulator->m_HistoryIntervalInMs));
}
Exit:
SENSOR_FunctionExit(Status);
}
// This routine starts a timer that periodically records the samples to History
NTSTATUS
HardwareSimulator::StartHistory()
{
NTSTATUS Status = STATUS_SUCCESS;
WdfWaitLockAcquire(m_HistoryLock, NULL);
if (FALSE != m_HistoryStarted)
{
Status = STATUS_DEVICE_BUSY;
TraceError("PED %!FUNC! History Collection is already started %!STATUS!", Status);
goto Exit;
}
// Start keeping history
m_HistoryStarted = TRUE;
// Start timer
WdfTimerStart(m_HistoryTimer, WDF_REL_TIMEOUT_IN_MS(m_HistoryIntervalInMs));
Exit:
WdfWaitLockRelease(m_HistoryLock);
return Status;
}
// This routine stops the timer that is responsible for history collection.
NTSTATUS
HardwareSimulator::StopHistory()
{
WdfWaitLockAcquire(m_HistoryLock, NULL);
// Stop collecting history
m_HistoryStarted = FALSE;
// Stop timer
WdfTimerStop(m_HistoryTimer, TRUE);
WdfWaitLockRelease(m_HistoryLock);
return STATUS_SUCCESS;
}
// This routine clears the history collected thus far
NTSTATUS
HardwareSimulator::ClearHistory()
{
NTSTATUS Status = STATUS_SUCCESS;
WdfWaitLockAcquire(m_HistoryLock, NULL);
m_History.FirstElemIndex = 0;
m_History.LastElemIndex = 0;
m_History.NumOfElems = 0;
RtlZeroMemory(m_History.pData, (m_History.BufferLength*sizeof(PedometerSample)));
// Clearing History should reset the Pedometer
Status = Reset();
WdfWaitLockRelease(m_HistoryLock);
return Status;
}
// This routine reads the history collected so far up to a maximum of 'BufferSize' records.
// Once read, those samples will be removed from the History.
// All read samples will be removed from the History buffer
// Any unread samples will continue to persist int the History buffer
NTSTATUS
HardwareSimulator::ReadHistory(
_Inout_ PULONG SamplesCount,
_Out_writes_to_(*SamplesCount, *SamplesCount) PPedometerSample HistorySamplesBuffer
)
{
NTSTATUS Status = STATUS_SUCCESS;
ULONG SamplesCopied = 0;
// Make sure we have sufficient memory to fill in the samples
if (0 == *SamplesCount)
{
Status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
while (*SamplesCount > SamplesCopied)
{
PedometerSample Data = {};
// Check whether the Cancel event is signaled before looping through each time to retrieve an entry from the history buffer.
if (WAIT_OBJECT_0 == WaitForSingleObjectEx(m_HistoryCancelReadEvt, 0, FALSE))
{
TraceError("PED %!FUNC! Read canceled");
Status = STATUS_CANCELLED;
break;
}
WdfWaitLockAcquire(m_HistoryLock, NULL);
Status = RemoveDataElemFromHistoryBuffer(&Data);
WdfWaitLockRelease(m_HistoryLock);
if (!NT_SUCCESS(Status))
{
break;
}
HistorySamplesBuffer[SamplesCopied++] = Data;
}
if (STATUS_NO_MORE_ENTRIES == Status)
{
// Ignore STATUS_NO_MORE_ENTRIES if there were any entries that were copied
if (0 < SamplesCopied)
{
Status = STATUS_SUCCESS;
}
}
else if (*SamplesCount < SamplesCopied)
{
Status = STATUS_BUFFER_OVERFLOW;
}
Exit:
*SamplesCount = SamplesCopied;
return Status;
}
// This routine sets an event for the ReadHistory function to exit
// This is for illustration purpose only. For real HW, use an appropriate method to cancel the pending reads.
NTSTATUS
HardwareSimulator::SignalReadCancellation()
{
SetEvent(m_HistoryCancelReadEvt);
return STATUS_SUCCESS;
}
|