summaryrefslogtreecommitdiff
path: root/src/winclientlib/winclientlib.cpp
blob: 7d67f142c273546792abe70fb0e830eda960716a (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
/*******************************************************************************
**                                                                            **
**  SRC-MODULE: winclientLib.cpp                                              **
**                                                                            **
**  TARGET    : Windows                                                       **
**                                                                            **
**  PROJECT   : DLT                                                           **
**                                                                            **
**  AUTHOR    : Alexander Wenzel Alexander.AW.Wenzel@bmw.de                   **
**              Markus Klein                                                  **
**                                                                            **
**  PURPOSE   :                                                               **
**                                                                            **
**  REMARKS   :                                                               **
**                                                                            **
**  PLATFORM DEPENDANT [yes/no]: yes                                          **
**                                                                            **
**  TO BE CHANGED BY USER [yes/no]: no                                        **
**                                                                            **
*******************************************************************************/

/*******************************************************************************
**                      Author Identity                                       **
********************************************************************************
**                                                                            **
** Initials     Name                       Company                            **
** --------     -------------------------  ---------------------------------- **
**  aw          Alexander Wenzel           BMW                                **
**  mk          Markus Klein               Fraunhofer ESK                     **
*******************************************************************************/

/*******************************************************************************
**                      Revision Control History                              **
*******************************************************************************/

/*
 * $LastChangedRevision$
 * $LastChangedDate$
 * $LastChangedBy$
 */

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib

// Disable C4995 and C4996 Warnings
#pragma warning(disable : 4995)
#pragma warning(disable : 4996)

#include "stdafx.h"

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <strsafe.h>
#include <io.h>

#include <string>
#include <iostream>

#include "winclientlib.h"
#include "dlt_client.h"

// Function prototypes
DWORD WINAPI MyThreadFunction( LPVOID lpParam );
void ErrorHandler(LPTSTR lpszFunction);

// Variables
static DWORD	dwThreadId;
static HANDLE   hThread;
static HANDLE 	hEvent;

static DltClient windltclient;

#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
    {
        break;
    }
    }
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

using namespace std;

/*
Some helper functions
*/

DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
    // Enter Main Loop
    dlt_client_main_loop(&windltclient, NULL, 0);

    // Send event about thread termination
    SetEvent(hEvent);

    ExitThread(0);
}

void ErrorHandler(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code.
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;

    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message.
    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
                                      (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
                    LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                    TEXT("%s failed with error %d: %s"),
                    lpszFunction, dw, lpMsgBuf);

    MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK);

    // Free error-handling buffer allocations.
    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

/***
The interface functions
****/

WWINCLIENTLIB_API void Dlt_RegisterMessageCallback(int (*registerd_callback) (DltMessage *message, void *data))
{
    dlt_client_register_message_callback(registerd_callback);
}

WWINCLIENTLIB_API int Dlt_StartClient(char* server_address)
{
    WSADATA wsaData;
    int iResult;

    if ((server_address==0) || (server_address[0]=='\0'))
    {
        return 0;
    }

    // Create event, used for thread termination
    hEvent = CreateEvent(NULL,FALSE,FALSE,(LPCWSTR)"Test");

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult)
    {
        printf("winclientlib: WSAStartup failed: %d\n", iResult);
        return -1;
    }

    /* Initialize DLT Client */
    if (dlt_client_init(&windltclient, 0)==-1)
    {
        ErrorHandler(TEXT("dlt_client_init()"));

        Dlt_ExitClient();

        return -1;
    }

    /* Setup parameters of DltClient */
    windltclient.sock = -1;
    windltclient.serial_mode = 0;         /* TCP connection:
										     In Windows (with Visual C++),
										     only TCP connection is allowed! */
    windltclient.servIP = server_address; /* IP address */


    /* Connect to TCP socket */
    if (dlt_client_connect(&windltclient, 0)==-1)
    {
        ErrorHandler(TEXT("dlt_client_connect()"));

        Dlt_ExitClient();

        return -1;
    }

    // Create the thread to begin execution on its own.
    hThread = CreateThread(
                  NULL,                   // default security attributes
                  0,                      // use default stack size
                  MyThreadFunction,       // thread function name
                  0,//(LPVOID)address,    // argument to thread function
                  0,                      // use default creation flags
                  &dwThreadId);           // returns the thread identifier

    // Check the return value for success.
    // If CreateThread fails, terminate execution.
    // This will automatically clean up threads and memory.
    if (hThread==0)
    {
        ErrorHandler(TEXT("CreateThread()"));

        // Cleanup WSA
        WSACleanup();

        return -1;
    }

    return 0;
}

WWINCLIENTLIB_API int Dlt_InjectCall( char appID[4], char  contID[4], uint32_t serviceID, uint8_t *buf, uint32_t buf_len )
{
    return dlt_client_send_inject_msg(&windltclient, appID, contID, serviceID, buf, buf_len);
}

WWINCLIENTLIB_API int Dlt_ExitClient()
{
    printf("winclientlib: exiting ...\n");

    // Terminate thread and close handles
    if (windltclient.sock!=-1)
    {
        if (windltclient.serial_mode==1)
        {
            close(windltclient.sock);
        }
        else
        {
            closesocket(windltclient.sock);
        }
        windltclient.sock = -1;

        WaitForSingleObject(hEvent,INFINITE);
    }

    CloseHandle(hEvent);
    CloseHandle(hThread);

    // Dlt Client Cleanup
    if (dlt_client_cleanup(&windltclient,0)==-1)
    {
        printf("winclientlib: closing error.\n");
    }
    else
    {
        printf("winclientlib: closed.\n");
    }

    // Cleanup WSA
    WSACleanup();

    exit(0);
}