5a310ce7d91709f233551b6d180176a7e2a398f5
[profile/ivi/audiomanager.git] / AudioManagerDaemon / src / DBusWrapper.cpp
1 /**
2  * Copyright (C) 2011, BMW AG
3  *
4  * GeniviAudioMananger AudioManagerDaemon
5  *
6  * \file SocketHandler.cpp
7  *
8  * \date 20-Oct-2011 3:42:04 PM
9  * \author Christian Mueller (christian.ei.mueller@bmw.de)
10  *
11  * \section License
12  * GNU Lesser General Public License, version 2.1, with special exception (GENIVI clause)
13  * Copyright (C) 2011, BMW AG Christian Mueller  Christian.ei.mueller@bmw.de
14  *
15  * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation.
16  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License, version 2.1, for more details.
17  * You should have received a copy of the GNU Lesser General Public License, version 2.1, along with this program; if not, see <http://www.gnu.org/licenses/lgpl-2.1.html>.
18  * Note that the copyright holders assume that the GNU Lesser General Public License, version 2.1, may also be applicable to programs even in cases in which the program is not a library in the technical sense.
19  * Linking AudioManager statically or dynamically with other modules is making a combined work based on AudioManager. You may license such other modules under the GNU Lesser General Public License, version 2.1. If you do not want to license your linked modules under the GNU Lesser General Public License, version 2.1, you may use the program under the following exception.
20  * As a special exception, the copyright holders of AudioManager give you permission to combine AudioManager with software programs or libraries that are released under any license unless such a combination is not permitted by the license of such a software program or library. You may copy and distribute such a system following the terms of the GNU Lesser General Public License, version 2.1, including this special exception, for AudioManager and the licenses of the other code concerned.
21  * Note that people who make modified versions of AudioManager are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License, version 2.1, gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception.
22  *
23  */
24
25 #include <dbus/DBusWrapper.h>
26 #include <SocketHandler.h>
27 #include <config.h>
28 #include <fstream>
29 #include <sstream>
30 #include <string>
31 #include <cassert>
32 #include <cstdlib>
33 #include "DLTWrapper.h"
34
35 using namespace am;
36
37 #define ROOT_INTROSPECT_XML                                                                                             \
38 DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                                                               \
39 "<node>"                                                                                                                                \
40 "<interface name='org.AudioManager.freedesktop.DBus.Introspectable'>"   \
41 "<method name='Introspect'>"                                                                                    \
42 "       <arg name='xml_data' type='s' direction='out'/>"                                        \
43 "</method>"                                                                                                                     \
44 "</interface>"                                                                                                                  \
45
46 DBusWrapper* DBusWrapper::mReference = NULL;
47
48 DBusWrapper::DBusWrapper(SocketHandler* socketHandler) :
49         pDbusDispatchCallback(this, &DBusWrapper::dbusDispatchCallback), //
50         pDbusFireCallback(this, &DBusWrapper::dbusFireCallback), //
51         pDbusCheckCallback(this, &DBusWrapper::dbusCheckCallback), //
52         pDbusTimerCallback(this, &DBusWrapper::dbusTimerCallback), //
53         mDbusConnection(0), //
54         mDBusError(), //
55         mNodesList(), //
56         mListTimerhandlePointer(), //
57         mSocketHandler(socketHandler)
58 {
59     assert(mSocketHandler!=0);
60
61     dbus_error_init(&mDBusError);
62     logInfo("DBusWrapper::DBusWrapper Opening DBus connection");
63     mDbusConnection = dbus_bus_get(DBUS_BUS_SESSION, &mDBusError);
64     if (dbus_error_is_set(&mDBusError))
65     {
66         logError("DBusWrapper::DBusWrapper Error while getting the DBus");
67         dbus_error_free(&mDBusError);
68     }
69     if (NULL == mDbusConnection)
70     {
71         logError("DBusWrapper::DBusWrapper DBus Connection is null");
72     }
73
74     //then we need to adopt the dbus to our mainloop:
75     //first, we are old enought to live longer then the connection:
76     dbus_connection_set_exit_on_disconnect(mDbusConnection, FALSE);
77
78     //we do not need the manual dispatching, since it is not allowed to call from a different thread. So leave it uncommented:
79     //dbus_connection_set_dispatch_status_function
80
81     //add watch functions:
82     dbus_bool_t watch = dbus_connection_set_watch_functions(mDbusConnection, addWatch, removeWatch, toogleWatch, this, NULL);
83     if (!watch)
84     {
85         logError("DBusWrapper::DBusWrapper Registering of watch functions failed");
86     }
87
88     //add timer functions:
89     dbus_bool_t timer = dbus_connection_set_timeout_functions(mDbusConnection, addTimeout, removeTimeout, toggleTimeout, this, NULL);
90     if (!timer)
91     {
92         logError("DBusWrapper::DBusWrapper Registering of timer functions failed");
93     }
94
95     //register callback for Introspectio
96     mObjectPathVTable.message_function = DBusWrapper::cbRootIntrospection;
97     dbus_connection_register_object_path(mDbusConnection, DBUS_SERVICE_OBJECT_PATH, &mObjectPathVTable, this);
98     int ret = dbus_bus_request_name(mDbusConnection, DBUS_SERVICE_PREFIX, DBUS_NAME_FLAG_DO_NOT_QUEUE, &mDBusError);
99     if (dbus_error_is_set(&mDBusError))
100     {
101         logError("DBusWrapper::DBusWrapper Name Error",mDBusError.message);
102         dbus_error_free(&mDBusError);
103     }
104     if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret)
105     {
106         logError("DBusWrapper::DBusWrapper Wrapper is not the Primary Owner",ret);
107         exit(1);
108     }
109 }
110
111 DBusWrapper::~DBusWrapper()
112 {
113     //close the connection again
114     logInfo("DBusWrapper::~DBusWrapper Closing DBus connection");
115     dbus_connection_unref(mDbusConnection);
116
117     //clean up all timerhandles we created but did not delete before
118     std::vector<sh_timerHandle_t*>::iterator it = mListTimerhandlePointer.begin();
119     for (; it != mListTimerhandlePointer.end(); ++it)
120     {
121         delete *it;
122     }
123 }
124
125 void DBusWrapper::registerCallback(const DBusObjectPathVTable* vtable, const std::string& path, void* userdata)
126 {
127     logInfo("DBusWrapper::~registerCallback register callback:",path);
128
129     std::string completePath = std::string(DBUS_SERVICE_OBJECT_PATH) + "/" + path;
130     dbus_error_init(&mDBusError);
131     mDbusConnection = dbus_bus_get(DBUS_BUS_SESSION, &mDBusError);
132     dbus_connection_register_object_path(mDbusConnection, completePath.c_str(), vtable, userdata);
133     if (dbus_error_is_set(&mDBusError))
134     {
135         logError("DBusWrapper::registerCallack error: ",mDBusError.message);
136         dbus_error_free(&mDBusError);
137     }
138     mNodesList.push_back(path);
139 }
140
141 DBusHandlerResult DBusWrapper::cbRootIntrospection(DBusConnection *conn, DBusMessage *msg, void *reference)
142 {
143     logInfo("DBusWrapper::~cbRootIntrospection called:");
144
145     mReference = (DBusWrapper*) reference;
146     std::list<std::string> nodesList = mReference->mNodesList;
147     DBusMessage * reply;
148     DBusMessageIter args;
149     dbus_uint32_t serial = 0;
150     if (dbus_message_is_method_call(msg, DBUS_INTERFACE_INTROSPECTABLE, "Introspect"))
151     {
152         std::list<std::string>::iterator nodeIter = nodesList.begin();
153         const char *xml = ROOT_INTROSPECT_XML;
154         std::stringstream introspect;
155         introspect << std::string(xml);
156         for (; nodeIter != nodesList.end(); ++nodeIter)
157         {
158             introspect << "<node name='" << nodeIter->c_str() << "'/>";
159         }
160         introspect << "</node>";
161
162         reply = dbus_message_new_method_return(msg);
163         std::string s = introspect.str();
164         const char* string = s.c_str();
165
166         // add the arguments to the reply
167         dbus_message_iter_init_append(reply, &args);
168         if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string))
169         {
170             logError("DBusWrapper::~cbRootIntrospection DBUS Out Of Memory!");
171         }
172
173         // send the reply && flush the connection
174         if (!dbus_connection_send(conn, reply, &serial))
175         {
176             logError("DBusWrapper::~cbRootIntrospection DBUS Out Of Memory!");
177         }
178         dbus_connection_flush(conn);
179         // free the reply
180         dbus_message_unref(reply);
181
182         return DBUS_HANDLER_RESULT_HANDLED;
183     }
184     else
185     {
186         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
187     }
188 }
189
190 void DBusWrapper::dbusMainLoop()
191 {
192     logInfo("DBusWrapper::dbusMainLoop Entering MainLoop");
193
194     while (dbus_connection_read_write_dispatch(mDbusConnection, -1))
195     {
196
197     }
198 }
199
200 void DBusWrapper::getDBusConnection(DBusConnection *& connection) const
201 {
202     connection = mDbusConnection;
203 }
204
205 dbus_bool_t DBusWrapper::addWatch(DBusWatch *watch, void *userData)
206 {
207     mReference = (DBusWrapper*) userData;
208     assert(mReference!=0);
209     return mReference->addWatchDelegate(watch, userData);
210 }
211
212 dbus_bool_t DBusWrapper::addWatchDelegate(DBusWatch * watch, void* userData)
213 {
214     (void) userData;
215     int16_t event = 0;
216     sh_pollHandle_t handle = 0;
217     uint flags = dbus_watch_get_flags(watch);
218
219     /* no watch flags for disabled watches */
220     if (dbus_watch_get_enabled(watch))
221     {
222         if (flags & DBUS_WATCH_READABLE)
223             event |= POLLIN;
224         if (flags & DBUS_WATCH_WRITABLE)
225             event |= POLLOUT;
226     }
227
228     logInfo("DBusWrapper::addWatchDelegate entered new watch, fd=",dbus_watch_get_unix_fd(watch),"event flag=",event);
229     am_Error_e error = mSocketHandler->addFDPoll(dbus_watch_get_unix_fd(watch), event, NULL, &pDbusFireCallback, &pDbusCheckCallback, &pDbusDispatchCallback, watch, handle);
230
231     //if everything is alright, add the watch and the handle to our map so we know this relationship
232     if (error == E_OK && handle != 0)
233     {
234         mMapHandleWatch.insert(std::make_pair(watch, handle));
235         return true;
236     }
237     logError("DBusWrapper::addWatchDelegate entering watch failed");
238     return (true);
239 }
240
241 void DBusWrapper::removeWatch(DBusWatch *watch, void *userData)
242 {
243     mReference = (DBusWrapper*) userData;
244     assert(mReference!=0);
245     mReference->removeWatchDelegate(watch, userData);
246 }
247
248 void DBusWrapper::removeWatchDelegate(DBusWatch *watch, void *userData)
249 {
250     (void) userData;
251     std::map<DBusWatch*, sh_pollHandle_t>::iterator iterator = mMapHandleWatch.begin();
252     iterator = mMapHandleWatch.find(watch);
253     if (iterator != mMapHandleWatch.end())
254         mSocketHandler->removeFDPoll(iterator->second);
255     logInfo("DBusWrapper::removeWatch removed watch with handle",iterator->second);
256     mMapHandleWatch.erase(iterator);
257 }
258
259 void DBusWrapper::toogleWatch(DBusWatch *watch, void *userData)
260 {
261     mReference = (DBusWrapper*) userData;
262     assert(mReference!=0);
263     mReference->toogleWatchDelegate(watch, userData);
264 }
265
266 void DBusWrapper::toogleWatchDelegate(DBusWatch *watch, void *userData)
267 {
268     (void) userData;
269     int16_t event = 0;
270     dbus_watch_get_unix_fd(watch);
271     uint flags = dbus_watch_get_flags(watch);
272     /* no watch flags for disabled watches */
273     if (dbus_watch_get_enabled(watch))
274     {
275         if (flags & DBUS_WATCH_READABLE)
276             event |= POLLIN;
277         if (flags & DBUS_WATCH_WRITABLE)
278             event |= POLLOUT;
279     }
280     std::map<DBusWatch*, sh_pollHandle_t>::iterator iterator = mMapHandleWatch.begin();
281     iterator = mMapHandleWatch.find(watch);
282     if (iterator != mMapHandleWatch.end())
283         mSocketHandler->updateEventFlags(iterator->second, event);
284     logInfo("DBusWrapper::toogleWatchDelegate watch was toggeled");
285 }
286
287 dbus_bool_t DBusWrapper::addTimeout(DBusTimeout *timeout, void* userData)
288 {
289     mReference = (DBusWrapper*) userData;
290     assert(mReference!=0);
291     return mReference->addTimeoutDelegate(timeout, userData);
292 }
293
294 dbus_bool_t DBusWrapper::addTimeoutDelegate(DBusTimeout *timeout, void* userData)
295 {
296     if (!dbus_timeout_get_enabled(timeout))
297         return false;
298
299     //calculate the timeout in timeval
300     timespec pollTimeout;
301     int localTimeout = dbus_timeout_get_interval(timeout);
302     pollTimeout.tv_sec = localTimeout / 1000;
303     pollTimeout.tv_nsec = (localTimeout % 1000) * 1000000;
304
305     //prepare handle and callback. new is eval, but there is no other choice because we need the pointer!
306     sh_timerHandle_t* handle = new sh_timerHandle_t;
307     mListTimerhandlePointer.push_back(handle);
308     shTimerCallBack* buffer = &pDbusTimerCallback;
309
310     //add the timer to the pollLoop
311     mSocketHandler->addTimer(pollTimeout, buffer, *handle, timeout);
312
313     //save the handle with dbus context
314     dbus_timeout_set_data(timeout, handle, NULL);
315
316     //save timeout in Socket context
317     userData = timeout;
318     logInfo("DBusWrapper::addTimeoutDelegate a timeout was added");
319     return true;
320 }
321
322 void DBusWrapper::removeTimeout(DBusTimeout *timeout, void* userData)
323 {
324     mReference = (DBusWrapper*) userData;
325     assert(mReference!=0);
326     mReference->removeTimeoutDelegate(timeout, userData);
327 }
328
329 void DBusWrapper::removeTimeoutDelegate(DBusTimeout *timeout, void* userData)
330 {
331     (void) userData;
332     //get the pointer to the handle and remove the timer
333     sh_timerHandle_t* handle = (sh_timerHandle_t*) dbus_timeout_get_data(timeout);
334     mSocketHandler->removeTimer(*handle);
335
336     //now go throught the timerlist and remove the pointer, free memory
337     std::vector<sh_timerHandle_t*>::iterator it = mListTimerhandlePointer.begin();
338     for (; it != mListTimerhandlePointer.end(); ++it)
339     {
340         if (*it == handle)
341         {
342             mListTimerhandlePointer.erase(it);
343             break;
344         }
345     }
346     delete handle;
347     logInfo("DBusWrapper::removeTimeoutDelegate a timeout was removed");
348 }
349
350 void DBusWrapper::toggleTimeout(DBusTimeout *timeout, void* userData)
351 {
352     mReference = (DBusWrapper*) userData;
353     assert(mReference!=0);
354     mReference->toggleTimeoutDelegate(timeout, userData);
355 }
356
357 bool am::DBusWrapper::dbusDispatchCallback(const sh_pollHandle_t handle, void *userData)
358 {
359     (void) handle;
360     (void) userData;
361     bool returnVal = true;
362     dbus_connection_ref(mDbusConnection);
363     if (dbus_connection_dispatch(mDbusConnection) == DBUS_DISPATCH_COMPLETE)
364         returnVal = false;
365     dbus_connection_unref(mDbusConnection);
366 //    logInfo("DBusWrapper::dbusDispatchCallback was called");
367     return returnVal;
368 }
369
370 bool am::DBusWrapper::dbusCheckCallback(const sh_pollHandle_t handle, void *userData)
371 {
372     (void) handle;
373     (void) userData;
374     bool returnVal = false;
375     dbus_connection_ref(mDbusConnection);
376     if (dbus_connection_get_dispatch_status(mDbusConnection) == DBUS_DISPATCH_DATA_REMAINS)
377         returnVal = true;
378     dbus_connection_unref(mDbusConnection);
379 //    logInfo("DBusWrapper::dbusCheckCallback was called");
380     return returnVal;
381 }
382
383 void am::DBusWrapper::dbusFireCallback(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)
384 {
385     (void) handle;
386     (void) userData;
387     assert(userData!=NULL);
388     uint flags = 0;
389
390     if (pollfd.revents & POLLIN)
391         flags |= DBUS_WATCH_READABLE;
392     if (pollfd.revents & POLLOUT)
393         flags |= DBUS_WATCH_WRITABLE;
394     if (pollfd.revents & POLLHUP)
395         flags |= DBUS_WATCH_HANGUP;
396     if (pollfd.revents & POLLERR)
397         flags |= DBUS_WATCH_ERROR;
398
399     DBusWatch *watch = (DBusWatch*) userData;
400
401     dbus_connection_ref(mDbusConnection);
402     dbus_watch_handle(watch, flags);
403     dbus_connection_unref(mDbusConnection);
404 //    logInfo("DBusWrapper::dbusFireCallback was called");
405 }
406
407 void DBusWrapper::toggleTimeoutDelegate(DBusTimeout *timeout, void* userData)
408 {
409     (void) userData;
410     //get the pointer to the handle and remove the timer
411     sh_timerHandle_t* handle = (sh_timerHandle_t*) dbus_timeout_get_data(timeout);
412
413     //stop or restart?
414     if (dbus_timeout_get_enabled(timeout))
415     {
416         //calculate the timeout in timeval
417         timespec pollTimeout;
418         int localTimeout = dbus_timeout_get_interval(timeout);
419         pollTimeout.tv_sec = localTimeout / 1000;
420         pollTimeout.tv_nsec = (localTimeout % 1000) * 1000000;
421         mSocketHandler->restartTimer(*handle, pollTimeout);
422     }
423     else
424     {
425         mSocketHandler->stopTimer(*handle);
426     }logInfo("DBusWrapper::toggleTimeoutDelegate was called");
427 }
428
429 void DBusWrapper::dbusTimerCallback(sh_timerHandle_t handle, void *userData)
430 {
431     assert(userData!=NULL);
432     if (dbus_timeout_get_enabled((DBusTimeout*) userData))
433     {
434         timespec ts;
435         ts.tv_nsec = -1;
436         ts.tv_sec = -1;
437         mSocketHandler->restartTimer(handle, ts);
438     }
439     dbus_timeout_handle((DBusTimeout*) userData);
440     logInfo("DBusWrapper::dbusTimerCallback was called");
441 }
442