7d67f142c273546792abe70fb0e830eda960716a
[profile/ivi/dlt-daemon.git] / src / winclientlib / winclientlib.cpp
1 /*******************************************************************************
2 **                                                                            **
3 **  SRC-MODULE: winclientLib.cpp                                              **
4 **                                                                            **
5 **  TARGET    : Windows                                                       **
6 **                                                                            **
7 **  PROJECT   : DLT                                                           **
8 **                                                                            **
9 **  AUTHOR    : Alexander Wenzel Alexander.AW.Wenzel@bmw.de                   **
10 **              Markus Klein                                                  **
11 **                                                                            **
12 **  PURPOSE   :                                                               **
13 **                                                                            **
14 **  REMARKS   :                                                               **
15 **                                                                            **
16 **  PLATFORM DEPENDANT [yes/no]: yes                                          **
17 **                                                                            **
18 **  TO BE CHANGED BY USER [yes/no]: no                                        **
19 **                                                                            **
20 *******************************************************************************/
21
22 /*******************************************************************************
23 **                      Author Identity                                       **
24 ********************************************************************************
25 **                                                                            **
26 ** Initials     Name                       Company                            **
27 ** --------     -------------------------  ---------------------------------- **
28 **  aw          Alexander Wenzel           BMW                                **
29 **  mk          Markus Klein               Fraunhofer ESK                     **
30 *******************************************************************************/
31
32 /*******************************************************************************
33 **                      Revision Control History                              **
34 *******************************************************************************/
35
36 /*
37  * $LastChangedRevision$
38  * $LastChangedDate$
39  * $LastChangedBy$
40  */
41
42 // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
43
44 // Disable C4995 and C4996 Warnings
45 #pragma warning(disable : 4995)
46 #pragma warning(disable : 4996)
47
48 #include "stdafx.h"
49
50 #include <winsock2.h>
51 #include <ws2tcpip.h>
52 #include <stdlib.h>
53 #include <stdio.h>
54 #include <windows.h>
55 #include <strsafe.h>
56 #include <io.h>
57
58 #include <string>
59 #include <iostream>
60
61 #include "winclientlib.h"
62 #include "dlt_client.h"
63
64 // Function prototypes
65 DWORD WINAPI MyThreadFunction( LPVOID lpParam );
66 void ErrorHandler(LPTSTR lpszFunction);
67
68 // Variables
69 static DWORD    dwThreadId;
70 static HANDLE   hThread;
71 static HANDLE   hEvent;
72
73 static DltClient windltclient;
74
75 #ifdef _MANAGED
76 #pragma managed(push, off)
77 #endif
78
79 BOOL APIENTRY DllMain( HMODULE hModule,
80                        DWORD  ul_reason_for_call,
81                        LPVOID lpReserved
82                      )
83 {
84     switch (ul_reason_for_call)
85     {
86     case DLL_PROCESS_ATTACH:
87     case DLL_THREAD_ATTACH:
88     case DLL_THREAD_DETACH:
89     case DLL_PROCESS_DETACH:
90     {
91         break;
92     }
93     }
94     return TRUE;
95 }
96
97 #ifdef _MANAGED
98 #pragma managed(pop)
99 #endif
100
101 using namespace std;
102
103 /*
104 Some helper functions
105 */
106
107 DWORD WINAPI MyThreadFunction( LPVOID lpParam )
108 {
109     // Enter Main Loop
110     dlt_client_main_loop(&windltclient, NULL, 0);
111
112     // Send event about thread termination
113     SetEvent(hEvent);
114
115     ExitThread(0);
116 }
117
118 void ErrorHandler(LPTSTR lpszFunction)
119 {
120     // Retrieve the system error message for the last-error code.
121     LPVOID lpMsgBuf;
122     LPVOID lpDisplayBuf;
123
124     DWORD dw = GetLastError();
125
126     FormatMessage(
127         FORMAT_MESSAGE_ALLOCATE_BUFFER |
128         FORMAT_MESSAGE_FROM_SYSTEM |
129         FORMAT_MESSAGE_IGNORE_INSERTS,
130         NULL,
131         dw,
132         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
133         (LPTSTR) &lpMsgBuf,
134         0, NULL );
135
136     // Display the error message.
137     lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
138                                       (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(TCHAR));
139     StringCchPrintf((LPTSTR)lpDisplayBuf,
140                     LocalSize(lpDisplayBuf) / sizeof(TCHAR),
141                     TEXT("%s failed with error %d: %s"),
142                     lpszFunction, dw, lpMsgBuf);
143
144     MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK);
145
146     // Free error-handling buffer allocations.
147     LocalFree(lpMsgBuf);
148     LocalFree(lpDisplayBuf);
149 }
150
151 /***
152 The interface functions
153 ****/
154
155 WWINCLIENTLIB_API void Dlt_RegisterMessageCallback(int (*registerd_callback) (DltMessage *message, void *data))
156 {
157     dlt_client_register_message_callback(registerd_callback);
158 }
159
160 WWINCLIENTLIB_API int Dlt_StartClient(char* server_address)
161 {
162     WSADATA wsaData;
163     int iResult;
164
165     if ((server_address==0) || (server_address[0]=='\0'))
166     {
167         return 0;
168     }
169
170     // Create event, used for thread termination
171     hEvent = CreateEvent(NULL,FALSE,FALSE,(LPCWSTR)"Test");
172
173     // Initialize Winsock
174     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
175     if (iResult)
176     {
177         printf("winclientlib: WSAStartup failed: %d\n", iResult);
178         return -1;
179     }
180
181     /* Initialize DLT Client */
182     if (dlt_client_init(&windltclient, 0)==-1)
183     {
184         ErrorHandler(TEXT("dlt_client_init()"));
185
186         Dlt_ExitClient();
187
188         return -1;
189     }
190
191     /* Setup parameters of DltClient */
192     windltclient.sock = -1;
193     windltclient.serial_mode = 0;         /* TCP connection:
194                                                                                      In Windows (with Visual C++),
195                                                                                      only TCP connection is allowed! */
196     windltclient.servIP = server_address; /* IP address */
197
198
199     /* Connect to TCP socket */
200     if (dlt_client_connect(&windltclient, 0)==-1)
201     {
202         ErrorHandler(TEXT("dlt_client_connect()"));
203
204         Dlt_ExitClient();
205
206         return -1;
207     }
208
209     // Create the thread to begin execution on its own.
210     hThread = CreateThread(
211                   NULL,                   // default security attributes
212                   0,                      // use default stack size
213                   MyThreadFunction,       // thread function name
214                   0,//(LPVOID)address,    // argument to thread function
215                   0,                      // use default creation flags
216                   &dwThreadId);           // returns the thread identifier
217
218     // Check the return value for success.
219     // If CreateThread fails, terminate execution.
220     // This will automatically clean up threads and memory.
221     if (hThread==0)
222     {
223         ErrorHandler(TEXT("CreateThread()"));
224
225         // Cleanup WSA
226         WSACleanup();
227
228         return -1;
229     }
230
231     return 0;
232 }
233
234 WWINCLIENTLIB_API int Dlt_InjectCall( char appID[4], char  contID[4], uint32_t serviceID, uint8_t *buf, uint32_t buf_len )
235 {
236     return dlt_client_send_inject_msg(&windltclient, appID, contID, serviceID, buf, buf_len);
237 }
238
239 WWINCLIENTLIB_API int Dlt_ExitClient()
240 {
241     printf("winclientlib: exiting ...\n");
242
243     // Terminate thread and close handles
244     if (windltclient.sock!=-1)
245     {
246         if (windltclient.serial_mode==1)
247         {
248             close(windltclient.sock);
249         }
250         else
251         {
252             closesocket(windltclient.sock);
253         }
254         windltclient.sock = -1;
255
256         WaitForSingleObject(hEvent,INFINITE);
257     }
258
259     CloseHandle(hEvent);
260     CloseHandle(hThread);
261
262     // Dlt Client Cleanup
263     if (dlt_client_cleanup(&windltclient,0)==-1)
264     {
265         printf("winclientlib: closing error.\n");
266     }
267     else
268     {
269         printf("winclientlib: closed.\n");
270     }
271
272     // Cleanup WSA
273     WSACleanup();
274
275     exit(0);
276 }