summaryrefslogtreecommitdiff
path: root/wpd/WpdBasicHardwareDriver/RS232Target.cpp
blob: bedfecd2827203303d426ac483c6f43ef229faea (plain)
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
#include "stdafx.h"

#include "RS232Target.tmh"

RS232Target::RS232Target() :
    m_cRef(1), m_pBaseDriver(NULL)
{
}

RS232Target::~RS232Target()
{
    Delete();
}

ULONG __stdcall RS232Target::AddRef()
{
    InterlockedIncrement((long*) &m_cRef);
    return m_cRef;
}

ULONG __stdcall RS232Target::Release()
{
    ULONG ulRefCount = m_cRef - 1;

    if (InterlockedDecrement((long*) &m_cRef) == 0)
    {
        delete this;
        return 0;
    }
    return ulRefCount;
}

HRESULT __stdcall RS232Target::QueryInterface(
    REFIID riid,
    void** ppv)
{
    HRESULT hr = S_OK;

    if(riid == IID_IUnknown)
    {
        *ppv = static_cast<IUnknown*>(this);
        AddRef();
    }
    if(riid == __uuidof(IRequestCallbackRequestCompletion))
    {
        *ppv = static_cast<IRequestCallbackRequestCompletion*>(this);
        AddRef();
    }
    else
    {
        *ppv = NULL;
        hr = E_NOINTERFACE;
    }
    return hr;
}



/**
 * This method is called to initialize the RS232 I/O Target
 */
HRESULT RS232Target::Create(_In_ WpdBaseDriver* pBaseDriver,
                            _In_ IWDFDevice*    pDevice, 
                                 HANDLE         hRS232Port)
{
    CComPtr<IWDFFileHandleTargetFactory> pFileHandleTargetFactory;

    HRESULT hr = S_OK;

    if (pDevice == NULL)
    {
        hr = E_POINTER;
        CHECK_HR(hr, "NULL parameter received for IWDFDevice");
        return hr;
    }

    m_pWDFDevice = pDevice;
    m_pBaseDriver = pBaseDriver;

    hr = m_pWDFDevice->QueryInterface(IID_PPV_ARGS(&pFileHandleTargetFactory));
    CHECK_HR(hr, "QI of IID_IWDFFileHandleTargetFactory failed");

    if (hr == S_OK)
    {
        hr = pFileHandleTargetFactory->CreateFileHandleTarget(hRS232Port, &m_pFileTarget);
        CHECK_HR(hr, "Failed to create an I/O Target for the port file handle");
    }

    if (hr == S_OK)
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_FLAG_DEVICE, 
                    "%!FUNC! Created win32 I/O target %p for handle %p", m_pFileTarget, hRS232Port);
    }

    return hr;
}

/**
 * This method is called to remove the RS232 I/O Target object
 * and do any cleanup
 */
void RS232Target::Delete()
{
    if (m_pFileTarget)
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_FLAG_DEVICE, 
                    "%!FUNC! Deleted win32 I/O target %p", m_pFileTarget);
        m_pFileTarget = NULL;
    }

    if (m_pWDFDevice)
    {
        m_pWDFDevice = NULL;
    }

    if (m_pBaseDriver)
    {
        m_pBaseDriver = NULL;
    }
}

/**
 * This method is called to start the RS232 I/O Target after it 
 * it has been created
 */
HRESULT RS232Target::Start()
{
    CComPtr<IWDFIoTargetStateManagement> pStateMgmt;

    HRESULT hr                      = S_OK;

    if (m_pFileTarget)
    {
        hr = m_pFileTarget->QueryInterface(IID_PPV_ARGS(&pStateMgmt));
        CHECK_HR(hr, "Failed to QI IWDFIoTargetStateManagement from the I/O target");

        if (hr == S_OK)
        {
            hr = pStateMgmt->Start();
            CHECK_HR(hr, "Failed to start the I/O target");
        }

        if (hr == S_OK && IsReady())
        {
            TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_FLAG_DEVICE, "%!FUNC! I/O target ready.  Sending read request");    
            hr = SendReadRequest();  
            CHECK_HR(hr, "SendReadRequest failed");
        }
    }
    return hr;
}

/**
 * This method is called to stop the RS232 I/O Target 
 * if it is currently running
 */
HRESULT RS232Target::Stop()
{
    CComPtr<IWDFIoTargetStateManagement> pStateMgmt;

    HRESULT hr = S_OK;

    // Stop the target only if it is started. 
    if (m_pFileTarget && (WdfIoTargetStarted == GetState()))
    {
        hr = m_pFileTarget->QueryInterface(IID_PPV_ARGS(&pStateMgmt));
        CHECK_HR(hr, "Failed to QI IWDFIoTargetStateManagement from the I/O target");

        if (hr == S_OK)
        {
            // Stop the target, and cancel sent I/O
            hr = pStateMgmt->Stop(WdfIoTargetCancelSentIo);
            CHECK_HR(hr, "Failed to stop the I/O target");
        }

        if (hr == S_OK)
        {
            TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_FLAG_DEVICE, "%!FUNC! S_OK");
        }
    }
    return hr;
}

/**
 * This method is called to return the current state of the RS232 I/O Target
 */
WDF_IO_TARGET_STATE RS232Target::GetState()
{
    CComPtr<IWDFIoTargetStateManagement> pStateMgmt;

    WDF_IO_TARGET_STATE State = WdfIoTargetStateUndefined;
    HRESULT             hr    = S_OK;

    if (m_pFileTarget)
    {
        hr = m_pFileTarget->QueryInterface(IID_PPV_ARGS(&pStateMgmt));
        CHECK_HR(hr, "Failed to QI IWDFIoTargetStateManagement from the I/O target");
        
        if (hr == S_OK)
        {
            State = pStateMgmt->GetState();
        }
    }
    return State;
}


/**
 * This method returns TRUE is the target is ready to receive requests
 */
BOOL RS232Target::IsReady()
{
    if (WdfIoTargetStarted == GetState())
    {
        return TRUE;
    }
    return FALSE;
}


/**
 * This method is called to dispatch an asynchronous read request to the RS232 I/O Target
 * with a completion callback
 */
HRESULT RS232Target::SendReadRequest()
{
    CComPtr<IWDFDriver>                        pWdfDriver;
    CComPtr<IWDFFile>                          pWdfFile;
    CComPtr<IWDFMemory>                        pWdfBuffer;
    CComPtr<IWDFIoRequest>                     pWdfReadRequest;
    CComPtr<IRequestCallbackRequestCompletion> pCompletionCallback;

    HRESULT  hr          = S_OK;

    if (m_pWDFDevice == NULL || m_pFileTarget == NULL)
    {
        hr = HRESULT_FROM_WIN32(ERROR_NOT_READY);
        CHECK_HR(hr, "Device is not ready to receive read requests");
        return hr;
    }

    m_pWDFDevice->GetDriver(&pWdfDriver);

    ZeroMemory((void*)m_pReadBuffer, sizeof(m_pReadBuffer));

    // Create the WDF memory buffer
    hr = pWdfDriver->CreatePreallocatedWdfMemory(m_pReadBuffer, 
                                                 sizeof(m_pReadBuffer), 
                                                 NULL, // no object event callback
                                                 NULL, // driver object as parent
                                                 &pWdfBuffer); 
    CHECK_HR(hr, "Failed to create the pre-allocaed WDF memory");
 
    if (hr == S_OK)
    {
        hr = m_pWDFDevice->CreateRequest(NULL, // no object event callback
                                         m_pWDFDevice, // device object as parent
                                         &pWdfReadRequest);

        CHECK_HR(hr, "Failed to create a WDF request");    
    }

    if (hr == S_OK)
    {
        // Format the read request
        m_pFileTarget->GetTargetFile(&pWdfFile);

        hr = m_pFileTarget->FormatRequestForRead(pWdfReadRequest,
                                                  pWdfFile,
                                                  pWdfBuffer,
                                                  NULL,  // no memory offset
                                                  NULL); // no device offset  

        CHECK_HR(hr, "Failed to format the WDF request for read");    
    }

    if (hr == S_OK)
    {
        this->QueryInterface(IID_PPV_ARGS(&pCompletionCallback));

        // Set the completion callback
        pWdfReadRequest->SetCompletionCallback(pCompletionCallback, NULL);

        hr = pWdfReadRequest->Send(m_pFileTarget, 0, 0);
        CHECK_HR(hr, "Failed to send the read request");
    }

    if (FAILED(hr))
    {
        // Cleanup on failure
        if (pWdfReadRequest)
        {
            pWdfReadRequest->DeleteWdfObject();
        }
    }

    return hr;
}


/**
 * This method is called to dispatch an asynchronous write request to the RS232 I/O Target
 * with a completion callback
 */
HRESULT RS232Target::SendWriteRequest(
    _In_reads_(cbBufferSize) BYTE*           pBuffer,
                             size_t          cbBufferSize)
{
    CComPtr<IWDFDriver>                        pWdfDriver;
    CComPtr<IWDFFile>                          pWdfFile;
    CComPtr<IWDFMemory>                        pWdfBuffer;
    CComPtr<IWDFIoRequest>                     pWdfWriteRequest;
    CComPtr<IRequestCallbackRequestCompletion> pCompletionCallback;

    HRESULT  hr = S_OK;

    if (pBuffer == NULL)
    {
        hr = E_POINTER;
        CHECK_HR(hr, "A NULL buffer parameter was received");
        return hr;
    }

    if (m_pWDFDevice == NULL || m_pFileTarget == NULL)
    {
        hr = HRESULT_FROM_WIN32(ERROR_NOT_READY);
        CHECK_HR(hr, "Device is not ready to receive write requests");
    }

    m_pWDFDevice->GetDriver(&pWdfDriver);
    m_pFileTarget->GetTargetFile(&pWdfFile);

    // Create the WDF memory buffer
    hr = pWdfDriver->CreatePreallocatedWdfMemory(pBuffer, 
                                                 cbBufferSize, 
                                                 NULL, // no object event callback
                                                 NULL, // driver object as parent
                                                 &pWdfBuffer); 
    CHECK_HR(hr, "Failed to create a pre-allocaed Wdf memory buffer from the input buffer of size %d", static_cast<DWORD>(cbBufferSize));
 
    if (hr == S_OK)
    {
        hr = m_pWDFDevice->CreateRequest(NULL, // no object event callback
                                         m_pWDFDevice, // device object as parent
                                         &pWdfWriteRequest);

        CHECK_HR(hr, "Failed to create a WDF request");    
    }

    if (hr == S_OK)
    {
        hr = m_pFileTarget->FormatRequestForWrite(pWdfWriteRequest,
                                                  pWdfFile,
                                                  pWdfBuffer,
                                                  NULL,  // no memory offset
                                                  NULL); // no device offset  

        CHECK_HR(hr, "Failed to format the WDF request for write");    
    }

    if (hr == S_OK)
    {
        this->QueryInterface(IID_PPV_ARGS(&pCompletionCallback));

        // Set the completion callback
        pWdfWriteRequest->SetCompletionCallback(pCompletionCallback, NULL);

        hr = pWdfWriteRequest->Send(m_pFileTarget, 0, 0);
        CHECK_HR(hr, "Failed to send the write request");
    }
    
    if (FAILED(hr))
    {
        // Cleanup on failure
        if (pWdfWriteRequest)
        {
            pWdfWriteRequest->DeleteWdfObject();
        }
    }

    return hr;
}


/**
 * This callback method is called by UMDF on the completion of the asynchronous reads and writes
 */
void RS232Target::OnCompletion(
    _In_ IWDFIoRequest*                 pWdfRequest,
    _In_ IWDFIoTarget*                  pIoTarget,
    _In_ IWDFRequestCompletionParams*   pParams,
    _In_ PVOID                          pContext)
{
    UNREFERENCED_PARAMETER(pIoTarget);
    UNREFERENCED_PARAMETER(pContext);
    UNREFERENCED_PARAMETER(pParams);

    CComPtr<IWDFRequestCompletionParams>   pCompletionParams;
    HRESULT hr = S_OK;

    // Get the request completion status
    pWdfRequest->GetCompletionParams(&pCompletionParams);

    HRESULT hrStatus = pCompletionParams->GetCompletionStatus();
    WDF_REQUEST_TYPE RequestType = pCompletionParams->GetCompletedRequestType();

    if (RequestType == WdfRequestRead)
    {
        TraceEvents(TRACE_LEVEL_VERBOSE, TRACE_FLAG_DEVICE, "%!FUNC! Read Status %!HRESULT!", hrStatus);

        // Retrieve the data from the completed read request if successful
        if (SUCCEEDED(hrStatus) && m_pBaseDriver)
        {
            m_pBaseDriver->ProcessReadData(m_pReadBuffer, sizeof(m_pReadBuffer));
        }

        // Send another read request if the target is not stopped or removed
        if (IsReady())
        {
            hr = SendReadRequest();  
            CHECK_HR(hr, "SendReadRequest failed");
        }


    } 
    else if (RequestType == WdfRequestWrite)
    {
        TraceEvents(TRACE_LEVEL_VERBOSE, TRACE_FLAG_DEVICE, "%!FUNC! Write Status %!HRESULT!", hrStatus);
    }

    // Clean up the existing request
    pWdfRequest->DeleteWdfObject();
}