DBUS通信C/C++/Python/Nodejs编译调试整理
本系列文章由ex_net(张建波)编写,转载请注明出处。
http://blog.csdn.net/ex_net/article/details/70231753
作者:张建波 邮箱: 281451020@qq.com 欢迎来电交流!
一、C/C++的DBUS调试
操作系统环境准备
(1)Ubuntu 系统(14/16/17均可)
https://www.ubuntu.com/download/desktop
(2)Eclipse 开发工具
很多大神推荐用make 编译,可能由于我比较笨,不习惯命令行的缘故,因此无论干什么都要搞个IDE工具。
(3)从百度上寻找DBUS代码。。。。为了方便感兴趣的朋友,同时又懒得去寻找了,我就直接把代码贴这里了。
#define DBUS_API_SUBJECT_TO_CHANGE#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* Connect to the DBUS bus and send a broadcast signal
*/
void sendsignal(char *sigvalue)
{
DBusMessage *msg;
DBusMessageIter args;
DBusConnection *conn;
DBusError err;
int ret;
dbus_uint32_t serial = 0;
printf("Sending signal with value %s\n", sigvalue);
// initialise the error value
dbus_error_init(&err);
// connect to the DBUS system bus, and check for errors
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
exit(1);
}
// register our name on the bus, and check for errors
ret = dbus_bus_request_name(conn, "test.signal.source", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Name Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret)
{
exit(1);
}
// create a signal & check for errors
msg = dbus_message_new_signal("/", // object name of the signal
"test.method.caller", // interface name of the signal
"Test"); // name of the signal
if (NULL == msg)
{
fprintf(stderr, "Message Null\n");
exit(1);
}
// append arguments onto signal
dbus_message_iter_init_append(msg, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue))
{
fprintf(stderr, "Out Of Memory!\n");
exit(1);
}
// send the message and flush the connection
if (!dbus_connection_send(conn, msg, &serial))
{
fprintf(stderr, "Out Of Memory!\n");
exit(1);
}
dbus_connection_flush(conn);
printf("Signal Sent\n");
// free the message and close the connection
dbus_message_unref(msg);
//dbus_connection_close(conn);
}
/**
* Call a method on a remote object
*/
void query(char *param)
{
DBusMessage *msg;
DBusMessageIter args;
DBusConnection *conn;
DBusError err;
DBusPendingCall *pending;
int ret;
bool stat;
dbus_uint32_t level;
printf("Calling remote method with %s\n", param);
// initialiset the errors
dbus_error_init(&err);
// connect to the system bus and check for errors
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
exit(1);
}
// request our name on the bus
ret = dbus_bus_request_name(conn, "test.method.caller", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Name Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret)
{
exit(1);
}
// create a new method call and check for errors
msg = dbus_message_new_method_call("test.method.server", // target for the method call
"/test/method/Object", // object to call on
"test.method.Type", // interface to call on
"Method"); // method name
if (NULL == msg)
{
fprintf(stderr, "Message Null\n");
exit(1);
}
// append arguments
dbus_message_iter_init_append(msg, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, ¶m))
{
fprintf(stderr, "Out Of Memory!\n");
exit(1);
}
// send message and get a handle for a reply
if (!dbus_connection_send_with_reply(conn, msg, &pending, -1))
{ // -1 is default timeout
fprintf(stderr, "Out Of Memory!\n");
exit(1);
}
if (NULL == pending)
{
fprintf(stderr, "Pending Call Null\n");
exit(1);
}
dbus_connection_flush(conn);
printf("Request Sent\n");
// free message
dbus_message_unref(msg);
// block until we recieve a reply
dbus_pending_call_block(pending);
// get the reply message
msg = dbus_pending_call_steal_reply(pending);
if (NULL == msg)
{
fprintf(stderr, "Reply Null\n");
exit(1);
}
// free the pending message handle
dbus_pending_call_unref(pending);
// read the parameters
if (!dbus_message_iter_init(msg, &args))
fprintf(stderr, "Message has no arguments!\n");
else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args))
fprintf(stderr, "Argument is not boolean!\n");
else
dbus_message_iter_get_basic(&args, &stat);
if (!dbus_message_iter_next(&args))
fprintf(stderr, "Message has too few arguments!\n");
else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
fprintf(stderr, "Argument is not int!\n");
else
dbus_message_iter_get_basic(&args, &level);
printf("Got Reply: %d, %d\n", stat, level);
// free reply and close connection
dbus_message_unref(msg);
//dbus_connection_close(conn);
}
void reply_to_method_call(DBusMessage *msg, DBusConnection *conn)
{
DBusMessage *reply;
DBusMessageIter args;
dbus_bool_t stat = TRUE;
dbus_uint32_t level = 21614;
dbus_uint32_t serial = 0;
char *param = "";
// read the arguments
if (!dbus_message_iter_init(msg, &args))
fprintf(stderr, "Message has no arguments!\n");
else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
fprintf(stderr, "Argument is not string!\n");
else
dbus_message_iter_get_basic(&args, ¶m);
printf("Method called with %s\n", param);
// create a reply from the message
reply = dbus_message_new_method_return(msg);
// add the arguments to the reply
dbus_message_iter_init_append(reply, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &stat))
{
fprintf(stderr, "Out Of Memory! append stat.\n");
exit(1);
}
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level))
{
fprintf(stderr, "Out Of Memory! append level.\n");
exit(1);
}
// send the reply && flush the connection
if (!dbus_connection_send(conn, reply, &serial))
{
fprintf(stderr, "Out Of Memory! send reply.\n");
exit(1);
}
dbus_connection_flush(conn);
// free the reply
dbus_message_unref(reply);
}
void reply_to_method_call_introspect(DBusMessage *msg, DBusConnection *conn)
{
DBusMessage *reply;
DBusMessageIter args;
//dbus_bool_t stat = TRUE;
//dbus_uint32_t level = 21614;
dbus_uint32_t serial = 0;
char *param = "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\""
" \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">"
"<!-- GDBus 2.34.1 -->"
"<node>"
" <interface name=\"org.freedesktop.DBus.Introspectable\">"
" <method name=\"Introspect\">"
" <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>"
" </method>"
" </interface>"
" <interface name=\"test.method.caller\">"
" <method name=\"Method\">"
" <arg type=\"s\" name=\"msg\" direction=\"in\"/>"
" <arg type=\"b\" name=\"stat\" direction=\"out\"/>"
" <arg type=\"u\" name=\"level\" direction=\"out\"/>"
" </method>"
" <signal name=\"Test\">"
" <arg type=\"s\" name=\"interface\"/>"
" </signal>"
" </interface>"
"</node>";
/*
// read the arguments
if (!dbus_message_iter_init(msg, &args))
fprintf(stderr, "Message has no arguments!\n");
else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
fprintf(stderr, "Argument is not string!\n");
else
dbus_message_iter_get_basic(&args, ¶m);
printf("Method called with %s\n", param); */
// create a reply from the message
reply = dbus_message_new_method_return(msg);
// add the arguments to the reply
dbus_message_iter_init_append(reply, &args);
if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, ¶m))
{
fprintf(stderr, "Out Of Memory! append stat.\n");
exit(1);
}
// send the reply && flush the connection
if (!dbus_connection_send(conn, reply, &serial))
{
fprintf(stderr, "Out Of Memory! send reply.\n");
exit(1);
}
dbus_connection_flush(conn);
// free the reply
dbus_message_unref(reply);
}
/**
* Server that exposes a method call and waits for it to be called
*/
void listen()
{
DBusMessage *msg;
DBusMessage *reply;
DBusMessageIter args;
DBusConnection *conn;
DBusError err;
int ret;
char *param;
printf("Listening for method calls\n");
// initialise the error
dbus_error_init(&err);
// connect to the bus and check for errors
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
fprintf(stderr, "Connection Null\n");
exit(1);
}
// request our name on the bus and check for errors
ret = dbus_bus_request_name(conn, "test.method.server", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Name Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret)
{
fprintf(stderr, "Not Primary Owner (%d)\n", ret);
exit(1);
}
// loop, testing for new messages
while (true)
{
// non blocking read of the next available message
dbus_connection_read_write(conn, 0);
msg = dbus_connection_pop_message(conn);
// loop again if we haven't got a message
if (NULL == msg)
{
sleep(1);
continue;
}
// check this is a method call for the right interface & method
if (dbus_message_is_method_call(msg, "test.method.Type", "Method"))
reply_to_method_call(msg, conn);
// try Introspect
if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Introspectable", "Introspect"))
reply_to_method_call_introspect(msg, conn);
// free the message
dbus_message_unref(msg);
}
// close the connection
dbus_connection_close(conn);
}
/**
* Listens for signals on the bus
*/
void receive()
{
DBusMessage *msg;
DBusMessageIter args;
DBusConnection *conn;
DBusError err;
int ret;
char *sigvalue;
printf("Listening for signals\n");
// initialise the errors
dbus_error_init(&err);
// connect to the bus and check for errors
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Connection Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (NULL == conn)
{
exit(1);
}
// request our name on the bus and check for errors
ret = dbus_bus_request_name(conn, "test.signal.sink", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Name Error (%s)\n", err.message);
dbus_error_free(&err);
}
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret)
{
exit(1);
}
// add a rule for which messages we want to see
dbus_bus_add_match(conn, "type='signal',interface='test.signal.Type'", &err); // see signals from the given interface
dbus_connection_flush(conn);
if (dbus_error_is_set(&err))
{
fprintf(stderr, "Match Error (%s)\n", err.message);
exit(1);
}
printf("Match rule sent\n");
// loop listening for signals being emmitted
while (true)
{
// non blocking read of the next available message
dbus_connection_read_write(conn, 0);
msg = dbus_connection_pop_message(conn);
// loop again if we haven't read a message
if (NULL == msg)
{
sleep(1);
continue;
}
// check if the message is a signal from the correct interface and with the correct name
if (dbus_message_is_signal(msg, "test.signal.Type", "Test"))
{
// read the parameters
if (!dbus_message_iter_init(msg, &args))
fprintf(stderr, "Message Has No Parameters\n");
else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
fprintf(stderr, "Argument is not string!\n");
else
dbus_message_iter_get_basic(&args, &sigvalue);
printf("Got Signal with value %s\n", sigvalue);
}
// free the message
dbus_message_unref(msg);
}
// close the connection
dbus_connection_close(conn);
}
int main(int argc, char **argv)
{
if (2 > argc)
{
printf("Syntax: dbus-example [send|receive|listen|query] [<param>]\n");
return 1;
}
char *param = "no param";
if (3 >= argc && NULL != argv[2])
param = argv[2];
if (0 == strcmp(argv[1], "send"))
sendsignal(param);
else if (0 == strcmp(argv[1], "receive"))
receive();
else if (0 == strcmp(argv[1], "listen"))
listen();
else if (0 == strcmp(argv[1], "query"))
query(param);
else
{
printf("Syntax: dbus-example [send|receive|listen|query] [<param>]\n");
return 1;
}
return 0;
}
安装dbus支持库
apt-get install libdbus-1-dev
apt-get install libglib2.0-dev
在Eclisp里新建一个C++项目,将上面的代码复制进去,由于这个代码的引用是
#include <dbus/dbus.h>然而我们实际的dbus.h是在/usr/include/dbus-1.0下,所以要手工设置Eclisp,才能编译。参考下面的3个图片
由于我们采用了C++编译器,所以需要在代码里加上string.h头文件引用.
(4)点击Eclisp 的Build吧!正常情况下,就编译成功了
(5)准备“服务说明文件”
vi /usr/share/dbus-1/system-services/test.method.server.service
[D-BUS Service]Name=test.method.serverExec=/bin/false
(6)准确“权限文件”
vi /etc/dbus-1/system.d/dbus-example.conf
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"><busconfig> <!-- This configuration file specifies the required security policies for the dbus-example to work. --> <!-- Only root or user ops can own the dbus-example service --> <policy user="oo"> <allow own="test.method.server"/> <allow own="test.method.caller"/> <allow own="test.signal.source"/> <allow own="test.signal.sink"/> </policy> <policy user="root"> <allow own="test.method.server"/> <allow own="test.method.caller"/> <allow own="test.signal.source"/> <allow own="test.signal.sink"/> </policy> <!-- Allow anyone to invoke methods on dbus-example server --> <policy context="default"> <allow own="test.method.server"/> <allow own="test.method.caller"/> <allow own="test.signal.source"/> <allow own="test.signal.sink"/> <allow send_destination="test.method.server"/> <allow receive_sender="test.method.caller"/> </policy> </busconfig>
测试流程:先启动
./dbus-example listen
然后再启动发送和接收,你就可以看到消息了
./dbus-example send "hello"
二、用Python来接收测试
安装python
然后安装
apt-get install python-dbus
apt-get install python-gobject
敲入下面的代码,保存s.py后,python s.py执行
#!/usr/bin/env pythonimport dbusimport dbus.decoratorsimport dbus.glibimport gobjectbus = dbus.SystemBus()def catchall_hello_signals_handler(hello_string): print hello_string bus.add_signal_receiver(catchall_hello_signals_handler, dbus_interface = "test.method.caller", signal_name = "Test")loop = gobject.MainLoop()loop.run()运行后效果见下图
用刚刚C的代码发送消息,用python 接收
三、用nodejs接收
wget https://nodejs.org/dist/v6.10.2/node-v6.10.2-linux-x64.tar.xz
解压
tar -xvf node-v6.10.2-linux-x64.tar.xz
移到通用的软件安装目录 /opt/
sudo mv node-v6.10.2-linux-x64 /opt/
安装 npm 和 node 命令到系统命令
sudo ln -s /opt/node-v6.10.2-linux-x64/bin/node /usr/local/bin/node
sudo ln -s /opt/node-v6.10.2-linux-x64/bin/npm /usr/local/bin/npm
验证:
node -v
npm -v
mkdir node-dbus 目录
npm init
vi signal.js
代码如下:
var DBus = require('dbus');var bus = DBus.getBus('system');//bus.getInterface('nodejs.dbus.ExampleService', '/nodejs/dbus/ExampleService', 'nodejs.dbus.ExampleService.Interface1', function(err, iface) {bus.getInterface('test.method.server', '/', 'test.method.caller', function (err, iface) { if (err) return console.log(err) console.log('ok') iface.on('Test', function (count) { console.log(count); });});
安装dbus支持库
npm install dbus
正常情况下,稍等几分钟就编译完成了
运行后,截图如下:
至此!手工了。 一个C++程序DBUS发送【信号】,另外的python和nodejs 程序同步收到!
结束语
本次试验历经一个星期,特别感谢李书、吴海阳二位的鼎力帮助,才得到了这个完美的实验结果。
参考网址:
https://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html
https://www.npmjs.com/package/node-dbus
https://cgit.freedesktop.org/dbus/dbus-python/tree/examples
http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers/keplersr2