GDBus 通信机制介绍及Demo版本

基于GDBus框架的进程间通信详解 首先简单介绍一下什么是GDBus。GDBus是一种基于d-bus技术的进程间通信框架,其中最核心的部分就是“Bus”,个人理解,它就是一个进程间通信的“桥梁”,不同的进程之间进行接收或者传递消息,都需要通过这个"Bus"总线。进程间通信的消息都会先发送到"Bus"总线上,然后再分发到目标进程上,"Bus"总线会根据收到消息的类型不同,采取不同的处理,主要处理可以分为两类:函数调用、信号广播。为了方便起见,我们假设有两个进程需要进行通信,一个Client进程,一个Server进程。... 阅读详情
AI摘要

本文详细介绍了DBus通信的概念,包括会话模式和总线模式的区别,并提供了具体的XML文档示例来说明如何定义DBus接口。进一步阐述了如何在Client和Server端实现DBus同步和异步接口调用,并通过C语言实现了一个简单的DBus服务和客户端示例。

一、DBus通信概念

DBus通信是IPC通信机制的一种方式,它有两种模式,分别为:session(会话模式)、system(总线模式)。

总线模式:采用总线模式时,系统需要维护一个DBus Daemon,每个DBus的请求通过DBus Daemon转发。这种模式Server只需要维护一个与DBus Daemon的链接,结构清晰,可以通过广播的方式发送消息到各个Client。

会话模式:这种模式一般称之为点对点的星型结构,Client与Server之间是直接的Peer2Peer的连接,少了DBus Daemon的中转,因此性能较好。

注意:在使用DBus通信前,需要保证系统安装了GIO_LIBS库,如果Linux环境还没有安装GIO_LIBS,请使用以下命令进行安装:

yum install libgnomeui-devel

二、DBus Demo介绍

DBus的通信机制是Server-Client模式,Server需要提供一个XML(eg: com.Yanlin.Gdbus.Example.xml)文档给Client端去说明DBus Server提供的interface name、signal name及它的arg name、 type、 direction、method name及它的arg name、 type、 direction。

com.Yanlin.Gdbus.Example.xml

<node>
  <interface name="com.Yanlin.Gdbus.Example">

    <signal name="MySignal1">
      <arg name="Value" type="s"/>
    </signal>

    <signal name="MySignal2">
      <arg name="Value" type="(is)"/>
    </signal>

    <method name="MyMethod1">
      <arg name="InArg"  direction="in"  type="s"/>
      <arg name="OutArg" direction="out" type="s"/>
    </method>

    <method name="MyMethod2">
      <arg name="InArg"  direction="in"  type="(ii)"/>
      <arg name="OutArg" direction="out" type="(si)"/>
    </method>

  </interface>
</node>

Client端需要用这个XML文档去产生两个文件-generated.h and -generated.c 另外,Server还需要提供一个header文档(eg: dbusCommon.h)去说明GDBus type、DBus name、object path。

dbusCommon.h

#ifndef YANLIN_GDBUS_EXAMPLE_H
#define YANLIN_GDBUS_EXAMPLE_H

#include <gio/gio.h> /* Bus define */

#define YANLIN_GDBUS_EXAMPLE_BUS         G_BUS_TYPE_SESSION
#define YANLIN_GDBUS_EXAMPLE_BUS_NAME    "com.yanlin.Gdbus.Example"
#define YANLIN_GDBUS_EXAMPLE_OBJECT_PATH "/com/yanlin/Gdbus/Example"

#endif
  • 程序架构大致会按照这样一个思路:
    Server、Client端会首先依赖XML产生的-generated.h and -generated.c两个文件封装相应的接口而产生两个静态库文件(在这里静态或者动态库都是一样)。然后编写两个应用测试程序去测试静态库导出的DBus同步、异步接口。

*Synchronize interface in the terminal of client.

gboolean
cyanlin_gdbus_example_call_my_method1_sync (
    CYanlinGdbusExample *proxy,
    const gchar *arg_InArg,
    gchar **out_OutArg,
    GCancellable *cancellable,
    GError **error)

gboolean
cyanlin_gdbus_example_call_my_method2_sync (
    CYanlinGdbusExample *proxy,
    GVariant *arg_InArg,
    GVariant **out_OutArg,
    GCancellable *cancellable,
    GError **error)

*Asynchronize interface in the terminal of client.

void
cyanlin_gdbus_example_call_my_method1 (
    CYanlinGdbusExample *proxy,
    const gchar *arg_InArg,
    GCancellable *cancellable,
    GAsyncReadyCallback callback,
    gpointer user_data)
gboolean
cyanlin_gdbus_example_call_my_method1_finish (
    CYanlinGdbusExample *proxy,
    gchar **out_OutArg,
    GAsyncResult *res,
    GError **error)

void
cyanlin_gdbus_example_call_my_method2 (
    CYanlinGdbusExample *proxy,
    GVariant *arg_InArg,
    GCancellable *cancellable,
    GAsyncReadyCallback callback,
    gpointer user_data)
gboolean
cyanlin_gdbus_example_call_my_method2_finish (
    CYanlinGdbusExample *proxy,
    GVariant **out_OutArg,
    GAsyncResult *res,
    GError **error)
DBus connect in the Client-side
  • critical interface
    1. g_main_loop_new(NULL, FALSE);
    2. g_bus_get_sync(YANLIN_GDBUS_EXAMPLE_BUS, NULL, &pConnError);
    3. cyanlin_gdbus_example_proxy_new_sync(pConnection,
      G_DBUS_PROXY_FLAGS_NONE,
      YANLIN_GDBUS_EXAMPLE_BUS_NAME,
      YANLIN_GDBUS_EXAMPLE_OBJECT_PATH,
      NULL,
      &pProxyError);
bool InitDBusCommunication(void)
{
    bool bRet = TRUE;
    GError *pConnError = NULL;
    GError *pProxyError = NULL;

    g_type_init();  /** initial for usage of "g" types */

    g_print("InitDBusCommunication: Client started.\n");

    do{
        bRet = TRUE;
        pLoop = g_main_loop_new(NULL, FALSE);   /** create main loop, but do not start it.*/

        /** First step: get a connection */
        pConnection = g_bus_get_sync(YANLIN_GDBUS_EXAMPLE_BUS, NULL, &pConnError);

        if (NULL == pConnError){
            /** Second step: try to get a connection to the given bus.*/
            pProxy = cyanlin_gdbus_example_proxy_new_sync(pConnection,
                                        G_DBUS_PROXY_FLAGS_NONE,
                                        YANLIN_GDBUS_EXAMPLE_BUS_NAME,
                                        YANLIN_GDBUS_EXAMPLE_OBJECT_PATH,
                                        NULL,
                                        &pProxyError);
            if (0 == pProxy){
                g_print("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message);
                g_error_free(pProxyError);
                bRet = FALSE;
            }


        }
        else{
            g_print("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message);
            g_error_free(pConnError);
            bRet = FALSE;
        }
    }while(FALSE == bRet);

    if (TRUE == bRet){
        /** Third step: Attach to dbus signals */
        registerClientSignalHandler(pProxy);
    }

    thread_create();
}
DBus register in the Server-side
  • critical interface
    1. g_main_loop_new(NULL, FALSE);
    2. g_bus_own_name(YANLIN_GDBUS_EXAMPLE_BUS,
      YANLIN_GDBUS_EXAMPLE_BUS_NAME,
      G_BUS_NAME_OWNER_FLAGS_NONE,
      &bus_acquired_cb,
      &name_acquired_cb,
      &name_lost_cb,
      NULL,
      NULL);
bool InitDBusCommunicationServer(void)
{
    bool bRet = TRUE;

    /** init for usage of "g" types */
    g_type_init();

    g_print("InitDBusCommunicationServer: Server started.\n");

    /** create main loop, but do not start it. */
    pLoop = g_main_loop_new(NULL, FALSE);

    /** first step: connect to dbus */
    (void)g_bus_own_name(YANLIN_GDBUS_EXAMPLE_BUS,
                        YANLIN_GDBUS_EXAMPLE_BUS_NAME,
                        G_BUS_NAME_OWNER_FLAGS_NONE,
                        &bus_acquired_cb,
                        &name_acquired_cb,
                        &name_lost_cb,
                        NULL,
                        NULL);
    /** emit my signal1 every 1 second to trigger example communication */
    g_timeout_add(1000, (GSourceFunc)Emit_My_signal1, NULL);

    /** emit my signal2 every2 second to trigger example communication */
    g_timeout_add(2000, (GSourceFunc)Emit_My_Signal2, NULL);

    thread_create();

    return bRet;    
}

详细代码:

  • libClient.c
/**
    Header files
*/

/**
    Own header
*/
#include "dbusCommon.h"
#include "libclient.h"

/**
    Generated headers
*/
#include "Example-generated.h"

/**
    System header
*/
#include <gio/gio.h>    /** GIO for dbus*/
#include <glib-2.0/glib.h>  /** GLIB for main loop*/  
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

/**
    instance init
*/
static GMainLoop *pLoop = NULL;
static GDBusConnection *pConnection = NULL;
static CYanlinGdbusExample *pProxy = NULL;
static gulong g_RetSignalHandler[RET_SIGNAL_HANDLE_SIZE];
static S_SIGNAL_CALLBACK g_signal_callback;
static S_METHOD_CALLBACK g_method_callback;

static gboolean My_Signal_1_Handler(CYanlinGdbusExample *object, const gchar *arg, gpointer userdata)
{
    if (NULL != g_signal_callback.callback1){
        g_signal_callback.callback1(arg);
    }

    return TRUE;
}

static gboolean My_Signal_2_Handler(CYanlinGdbusExample *object,  GVariant *arg, gpointer userdata)
{
    /** get the value from GVariant */
    gint int_arg = 0;
    gchar *char_arg = NULL;

    g_variant_get(arg, "(is)", &int_arg, &char_arg);

    if (NULL != g_signal_callback.callback2){
        g_signal_callback.callback2(int_arg, char_arg);
    }
    g_free(char_arg);

    return TRUE;
}

static void cb_OwnerNameChangedNotify(GObject *object, GParamSpec *pspec, gpointer userdata)
{
    gchar *pname_owner = NULL;
    pname_owner = g_dbus_proxy_get_name_owner((GDBusProxy*)object);

    if (NULL != pname_owner){
        g_print("DBus service is ready!\n");
        g_free(pname_owner);
    }
    else{
        g_print("DBus service is NOT ready!\n");
        g_free(pname_owner);
    }
}
bool registerClientSignalHandler(CYanlinGdbusExample *pProxy)
{
    g_print("registerClientSignalHandler call.\n");
    g_RetSignalHandler[0] = g_signal_connect(pProxy, "notify::g-name-owner", G_CALLBACK(cb_OwnerNameChangedNotify), NULL);
    g_RetSignalHandler[1] = g_signal_connect(pProxy, "my-signal1", G_CALLBACK(My_Signal_1_Handler), NULL);
    g_RetSignalHandler[2] = g_signal_connect(pProxy, "my-signal2", G_CALLBACK(My_Signal_2_Handler), NULL);
    return TRUE;
}

void registerSignalCallback(S_SIGNAL_CALLBACK *callback)
{
    if (NULL != callback){
        memcpy(&g_signal_callback, callback, sizeof(S_SIGNAL_CALLBACK));
    }
    else{
            g_print("registerSignalCallback: parameter point is NULL");
    }
}

void registerMethodCallback(S_METHOD_CALLBACK *callback)
{
    if (NULL != callback){
        memcpy(&g_method_callback, callback, sizeof(S_SIGNAL_CALLBACK));
    }
    else{
            g_print("registerMethodCallback: parameter point is NULL");
    }
}

static void MethodCallback_1(GObject* source_object, GAsyncResult* res, gpointer userdata)
{
    g_print("client MethodCallback_1 call.\n");

    gchar* out_arg = NULL;
    GError* pError = NULL;

    cyanlin_gdbus_example_call_my_method1_finish(pProxy, &out_arg, res, &pError);

    if(NULL == pError){
        if(NULL != g_method_callback.callback1){
            g_method_callback.callback1(out_arg, pError);
            g_free(out_arg);
        }
    }
    else{
        g_error_free(pError);
    }
}
void myMethodAsync_1(const char* in_arg)
{
    g_print("client myMethodAsync_1 call, in_arg = %s.\n", in_arg);

    cyanlin_gdbus_example_call_my_method1(pProxy, in_arg, NULL, MethodCallback_1, NULL);
    return;
}

void myMethod_1(const gchar *in_arg, gchar** out_arg, GError** pError)
{
    cyanlin_gdbus_example_call_my_method1_sync(pProxy, in_arg, out_arg, NULL, pError);

    if (*pError == NULL){
        g_print("client myMethod_1 call, in_arg = %s out_arg = %s.\n", in_arg, *out_arg);
            g_free(*out_arg);
    }
    else{
            g_print("client myMethod_1: Failed to call method. Reason: %s.\n", (*pError)->message);
            g_error_free(*pError);
    }

    return; 
}

static void MethodCallback_2(GObject* source_object, GAsyncResult* res, gpointer user_data)
{
    g_print("client MethodCallback_2 call.\n");

    GVariant *out_arg = NULL;
    GError *pError = NULL;
    gchar *out_arg1 = NULL;
    gint out_arg2 = 0;

    cyanlin_gdbus_example_call_my_method2_finish(pProxy, &out_arg, res, &pError);
    if (NULL == pError){
        /** get the result from the output paramter */
        g_variant_get(out_arg, "(si)", &out_arg1, &out_arg2);
        if(NULL != g_method_callback.callback2){
            g_method_callback.callback2(out_arg1, out_arg2, pError);
            g_free(out_arg1);
        }
    }
    else{
        g_error_free(pError);
    }

}
void myMethodAsync_2(const gint in_arg1, const gint in_arg2)
{
    g_print("client myMethodAsync_2 call, in_arg1 = %d, in_arg2 = %d.\n", in_arg1, in_arg2);

    GVariant *in_arg = g_variant_new("(ii)", in_arg1, in_arg2);
    cyanlin_gdbus_example_call_my_method2(pProxy, in_arg, NULL, MethodCallback_2, NULL);

    return;
}

void myMethod_2(const gint in_arg1, const gint in_arg2, gchar **out_arg1, gint *out_arg2, GError** pError)
{
    GVariant *in_arg = NULL;
    GVariant *out_arg = NULL;
    GError *Error = NULL;

    /** generate the input parameters */
    in_arg = g_variant_new("(ii)", in_arg1, in_arg2);

    /** call the server's dbus methods */
    cyanlin_gdbus_example_call_my_method2_sync(pProxy, in_arg, &out_arg, NULL, pError);
    if(NULL == *pError){
        /** get the result from the output parameter */
        g_variant_get(out_arg, "(si)", out_arg1, out_arg2);
        g_print("client myMethod_2 call, in_arg1 = %d, in_arg2 = %d, out_arg1 = %s, out_arg2 = %d.\n", in_arg1, in_arg2, *out_arg1, *out_arg2);
            g_free(*pError);
    }
    else{
            g_print("client myMethod_2: Failed to call method. Reason: %s.\n", (*pError)->message);
            g_error_free(*pError);
    }

    return; 
}

void *run(void* arg)
{
    g_print("run call in the client.\n");
    /** start the main event loop which manages all available sources of events */
    g_main_loop_run(pLoop);

    return ((void*)0);
}

int thread_create(void)
{
    int err;
    pthread_t thr;

    err = pthread_create(&thr, NULL, run, NULL);

    if(0 != err){
            g_print("Can't create thread: %s\n", strerror(err));
    }
    else{       
            g_print("New thread created: %s\n", strerror(err));
    }

    return err;
}

bool ExampleDBusServiceIsReady(void)
{
    gchar *owner_name = NULL;
    owner_name = g_dbus_proxy_get_name_owner((GDBusProxy*)pProxy);
    if(NULL != owner_name)
    {
        g_print("Owner Name: %s\n", owner_name);        
        g_free(owner_name);
        return true;
    }
    else
    {   
        g_print("Owner Name is NULL.");     
        return false;
    }
}

bool InitDBusCommunication(void)
{
    bool bRet = TRUE;
    GError *pConnError = NULL;
    GError *pProxyError = NULL;

    g_type_init();  /** initial for usage of "g" types */

    g_print("InitDBusCommunication: Client started.\n");

    do{
        bRet = TRUE;
        pLoop = g_main_loop_new(NULL, FALSE);   /** create main loop, but do not start it.*/

        /** First step: get a connection */
        pConnection = g_bus_get_sync(YANLIN_GDBUS_EXAMPLE_BUS, NULL, &pConnError);

        if (NULL == pConnError){
            /** Second step: try to get a connection to the given bus.*/
            pProxy = cyanlin_gdbus_example_proxy_new_sync(pConnection,
                                        G_DBUS_PROXY_FLAGS_NONE,
                                        YANLIN_GDBUS_EXAMPLE_BUS_NAME,
                                        YANLIN_GDBUS_EXAMPLE_OBJECT_PATH,
                                        NULL,
                                        &pProxyError);
            if (0 == pProxy){
                g_print("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message);
                g_error_free(pProxyError);
                bRet = FALSE;
            }


        }
        else{
            g_print("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message);
            g_error_free(pConnError);
            bRet = FALSE;
        }
    }while(FALSE == bRet);

    if (TRUE == bRet){
        /** Third step: Attach to dbus signals */
        registerClientSignalHandler(pProxy);
    }

    thread_create();
}

bool DeInitDBusCommunication(void)
{
    bool bRet = FALSE;

    if(0 != pLoop){
        g_main_loop_quit(pLoop);
        g_main_loop_unref(pLoop);
        bRet = TRUE;
    }

    return bRet;
}
  • libServer.c
/**
    Header files
*/

/** 
    Own header
*/
#include "dbusCommon.h"
#include "libServer.h"

/** 
    System header
*/
#include <gio/gio.h>   // GIO for dbus
#include <glib-2.0/glib.h>   // GLIB for main loop
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

/**
    Generated headers
*/
#include "Example-generated.h"

/**
    Instance init
*/
static GMainLoop         *pLoop     = NULL;
static CYanlinGdbusExample *pSkeleton = NULL;
static int callNum = 0;

/**
    Normal functions
*/
static gboolean Emit_My_signal1(gconstpointer p)
{
    g_print("Emit_My_Signal1() is called.\n");

    gchar buf[20];
    memset(buf, 0, 20);
    callNum++;
    sprintf(buf, "Server Signal1(%d)", callNum);

    cyanlin_gdbus_example_emit_my_signal1(pSkeleton, buf);

    return TRUE;
}

static gboolean Emit_My_Signal2(gconstpointer p)
{
    g_print("Emit_My_Signal2() is called.\n");

    callNum++;
    GVariant *payload = g_variant_new("(is)", callNum, "Server Signal2");

    cyanlin_gdbus_example_emit_my_signal2(pSkeleton, payload);

    return TRUE;
}

static gboolean My_Method1(CYanlinGdbusExample     *object,
                               GDBusMethodInvocation *invocation,
                               const gchar           *in_arg,
                               gpointer               user_data)
{
    g_print("Server MyMethod1 call. Parameter: %s.\n", in_arg);

    in_arg = "Server My_Method1 to output.";

    cyanlin_gdbus_example_complete_my_method1(object, invocation, in_arg);

    return TRUE;
}

static gboolean My_Method2(CYanlinGdbusExample     *object,
                               GDBusMethodInvocation *invocation,
                               GVariant           *in_arg,
                               gpointer               user_data)
{
  gint in_arg1 = 0;
  gint in_arg2 = 0;
  gint out_arg2 = 0;
  gchar *out_arg1 = "Server MyMethod2 to output.";
  GVariant *out_arg = NULL;

  /** Get the input parameters */
  g_variant_get(in_arg, "(ii)", &in_arg1, &in_arg2);

  g_print("Server MyMethod2 call. Parameter: in_arg1 = %d , in_arg2 = %d.\n", in_arg1, in_arg2);

  /** Generate the output parameters */
  out_arg2 = in_arg1 + in_arg2;
  out_arg = g_variant_new("(si)", out_arg1, out_arg2);

  cyanlin_gdbus_example_complete_my_method2(object, invocation, out_arg);

  return TRUE;

}

static void bus_acquired_cb(GDBusConnection *connection,
                                const gchar     *bus_name,
                                gpointer         user_data)
{
    GError *pError = NULL;

    /** Second step: Try to get a connection to the given bus. */
    pSkeleton = cyanlin_gdbus_example_skeleton_new();

    /** Third step: Attach to dbus signals. */
    (void) g_signal_connect(pSkeleton, "handle-my-method1", G_CALLBACK(My_Method1), NULL);
    (void) g_signal_connect(pSkeleton, "handle-my-method2", G_CALLBACK(My_Method2), NULL);

    /** Fourth step: Export interface skeleton. */
    (void) g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton),
                                              connection,
                                              YANLIN_GDBUS_EXAMPLE_OBJECT_PATH,
                                              &pError);
    if(pError != NULL){
        g_print("Error: Failed to export object. Reason: %s.\n", pError->message);
        g_error_free(pError);
        g_main_loop_quit(pLoop);
    }
}

static void name_acquired_cb(GDBusConnection *connection,
                                     const gchar     *bus_name,
                                     gpointer         user_data)
{
    g_print("name_acquired_cb call, Acquired bus name: %s.\n", YANLIN_GDBUS_EXAMPLE_BUS_NAME);
}

static void name_lost_cb(GDBusConnection *connection,
                             const gchar     *bus_name,
                             gpointer         user_data)
{
    if(connection == NULL)
    {
        g_print("name_lost_cb call, Error: Failed to connect to dbus.\n");
    }
    else
    {
        g_print("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", YANLIN_GDBUS_EXAMPLE_BUS_NAME);
    }

    g_main_loop_quit(pLoop);
}

void* run(void* para)
{
    g_print("run call in the server.\n");
        /** Start the Main Event Loop which manages all available sources of events */
    g_main_loop_run( pLoop );

    return ((void*)0);
}

int thread_create(void)
{
    int err;
    pthread_t thr;

    err = pthread_create(&thr, NULL, run, NULL);

    if (err != 0)
    {
        g_print("Can't create thread: %s\n", strerror(err));
    }
    else
    {
        g_print("New thread created: %s\n", strerror(err));
    }

    return err;
}


bool InitDBusCommunicationServer(void)
{
    bool bRet = TRUE;

    /** init for usage of "g" types */
    g_type_init();

    g_print("InitDBusCommunicationServer: Server started.\n");

    /** create main loop, but do not start it. */
    pLoop = g_main_loop_new(NULL, FALSE);

    /** first step: connect to dbus */
    (void)g_bus_own_name(YANLIN_GDBUS_EXAMPLE_BUS,
                        YANLIN_GDBUS_EXAMPLE_BUS_NAME,
                        G_BUS_NAME_OWNER_FLAGS_NONE,
                        &bus_acquired_cb,
                        &name_acquired_cb,
                        &name_lost_cb,
                        NULL,
                        NULL);
    /** emit my signal1 every 1 second to trigger example communication */
    g_timeout_add(1000, (GSourceFunc)Emit_My_signal1, NULL);

    /** emit my signal2 every2 second to trigger example communication */
    g_timeout_add(2000, (GSourceFunc)Emit_My_Signal2, NULL);

    thread_create();

    return bRet;    
}

bool DeinitDBusCommunicationServer(void)
{
    bool bRet = FALSE;
    if(0 != pLoop){
        g_main_loop_quit(pLoop);
        g_main_loop_unref(pLoop);
        bRet = TRUE;
    }

    return bRet;

}
  • CltExample.c
/**
    Header files
*/

#include "libclient.h"

/**
    Callback function
*/

void SignalCallback_1(const gchar* arg)
{
    g_print("Signal_1_Callback: Paramater value: %s.\n", arg);

    return;
}

void SignalCallback_2(const gint int_arg, const gchar* str_arg)
{
    g_print("Signal_2_Callback: Int value: %d, String value: %s\n", int_arg, str_arg);

    return;
}

void MethodCallback1(const gchar* arg, const GError* error)
{
    if (error == NULL)
    {
            g_print("Method1Callback: return value: %s.\n", arg);
    }
    else
    {
            g_print("Method1Callback: error message: %s.\n", error->message);
    }

    return;
}

void MethodCallback2(const gchar* out_arg1, const gint out_arg2, GError* error)
{
    if (error == NULL)
    {
            g_print("Method2Callback: return value: (%s, %d).\n", out_arg1, out_arg2);
    }
    else
    {
            g_print("Method2Callback: error message: %s.\n", error->message);
    }

    return;
}


int main(void)
{
    S_SIGNAL_CALLBACK signal_callback;
    S_METHOD_CALLBACK method_callback;

    signal_callback.callback1 = SignalCallback_1;
    signal_callback.callback2 = SignalCallback_2;

    registerSignalCallback(&signal_callback);

    method_callback.callback1 = MethodCallback1;
    method_callback.callback2 = MethodCallback2;

    registerMethodCallback(&method_callback);

    InitDBusCommunication();

    while(!ExampleDBusServiceIsReady());
#if 1
    const gchar *syncMehtod1Arg = "method1 synchronize call.";
    gchar *syncMethod1Out = NULL;
    GError *syncMethodError = NULL;

    myMethod_1(syncMehtod1Arg, &syncMethod1Out, &syncMethodError);
#endif
    gchar *asyncMethod1arg = "method1 asynchronize call.";
#if 1
    myMethodAsync_1(asyncMethod1arg);

    GError *syncMethod2Error = NULL;
    gint syncMethod2Arg1 = 12;
    gint syncMethod2Arg2 = 34;
    gchar *syncMethod2Out1 = NULL;
    gint syncMethod2Out2 = 0;

    myMethod_2(syncMethod2Arg1, syncMethod2Arg2, &syncMethod2Out1, &syncMethod2Out2, &syncMethod2Error);


    gint asyncMethod2Arg1 = 10;
    gint asyncMethod2Arg2 = 21;
    myMethodAsync_2(asyncMethod2Arg1, asyncMethod2Arg2);
#endif
    sleep(100);

    return 0;
}
  • SvrExample.c
#include "libServer.h"

int main(void)
{
    InitDBusCommunicationServer();

    sleep(100);

    return 0;
}
  • CMake file
# At least this cmake version is needed
CMAKE_MINIMUM_REQUIRED (VERSION 2.6)

# Define a project name for the SW package
PROJECT (YanLinDbusExample)

# version
SET(YanLinDbusExample_VERSION_MAJOR 1)
SET(YanLinDbusExample_VERSION_MINOR 0)

# XML file name
SET(XML_FILE_LIST com.Yanlin.Gdbus.Example.xml)
# generated file name
SET(XML_GEN_FILE_LIST Example-generated)

# check if the length of one of the above two lists is same as one of the other one
LIST(LENGTH XML_FILE_LIST XML_FILE_LIST_LEN)
LIST(LENGTH XML_GEN_FILE_LIST NAME_LIST_LEN)
MATH(EXPR XML_FILE_LIST_LEN "${XML_FILE_LIST_LEN}-1")
MATH(EXPR NAME_LIST_LEN "${NAME_LIST_LEN}-1")

IF(${XML_FILE_LIST_LEN} EQUAL ${NAME_LIST_LEN})
# generate files from XML
    FOREACH(INDEX RANGE 0 ${XML_FILE_LIST_LEN})
        LIST(GET XML_FILE_LIST ${INDEX} XML)
        LIST(GET XML_GEN_FILE_LIST ${INDEX} NAME_TMP)
        EXECUTE_PROCESS(COMMAND gdbus-codegen --interface com.Yanlin. --c-namespace CYanlin --generate-c-code ${PROJECT_BINARY_DIR}/${NAME_TMP} ${PROJECT_SOURCE_DIR}/${XML})
    ENDFOREACH(INDEX)
ELSE (${XML_FILE_LIST_LEN} EQUAL ${NAME_LIST_LEN})
    MESSAGE(FATAL_ERROR "The length (${XML_FILE_LIST_LEN}) of xml files list does not equal to the length(${NAME_LIST_LEN}) of the generated files name list")
ENDIF(${XML_FILE_LIST_LEN} EQUAL ${NAME_LIST_LEN})

# The library has to be dynamically linked to the header
INCLUDE_DIRECTORIES(/usr/include/glib-2.0)
INCLUDE_DIRECTORIES(/usr/lib/glib-2.0/include)
INCLUDE_DIRECTORIES(/usr/include/gio-unix-2.0)
INCLUDE_DIRECTORIES(/usr/lib/x86_64-linux-gnu/glib-2.0/include/)

INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/)
INCLUDE_DIRECTORIES(${PROJECT_BINARY_DIR}/)

link_directories(${PROJECT_BINARY_DIR}/)

set(SRCclient libClient.c ${PROJECT_BINARY_DIR}/Example-generated.c )
add_library(ExampleClientlib SHARED ${SRCclient})

#set(SRCclient libClient.c ${PROJECT_BINARY_DIR}/Example-generated.c )
#add_library(ExampleClientlib STATIC ${SRCclient})

set(SRCserver  libServer.c ${PROJECT_BINARY_DIR}/Example-generated.c)
add_library(ExampleServerlib STATIC ${SRCserver})

add_executable(SvrExample SvrExample.c)
target_link_libraries(SvrExample ${PROJECT_BINARY_DIR}/libExampleServerlib.a pthread gio-2.0 gobject-2.0 gmodule-2.0 gthread-2.0 rt glib-2.0)

add_executable(TCltExample CltExample.c)
target_link_libraries(TCltExample ${PROJECT_BINARY_DIR}/libExampleClientlib.so pthread gio-2.0 gobject-2.0 gmodule-2.0 gthread-2.0 rt glib-2.0)
  • libclient.h
#ifndef __LIB_CLIENT__
#define __LIB_CLIENT__

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
#include <glib-2.0/glib.h>

#include "Example-generated.h"

#define RET_SIGNAL_HANDLE_SIZE 3

typedef void (*SIGNAL1CALLBACK)(const gchar*);
typedef void (*SIGNAL2CALLBACK)(const gint, const gchar*);
typedef struct signalcallback
{
    SIGNAL1CALLBACK callback1;  
    SIGNAL2CALLBACK callback2;
}S_SIGNAL_CALLBACK;

typedef void (*METHOD1CALLBACK)(const gchar*, const GError*);
typedef void (*METHOD2CALLBACK)(const gchar*, const gint, GError*);
typedef struct methodcallback
{
    METHOD1CALLBACK callback1;  
    METHOD2CALLBACK callback2;
}S_METHOD_CALLBACK;



static gboolean My_Signal_1_Handler(CYanlinGdbusExample *object, const gchar *arg, gpointer userdata);
static gboolean My_Signal_2_Handler(CYanlinGdbusExample *object,  GVariant *arg, gpointer userdata);
static void cb_OwnerNameChangedNotify(GObject *object, GParamSpec *pspec, gpointer userdata);
bool registerClientSignalHandler(CYanlinGdbusExample *pProxy);
void registerSignalCallback(S_SIGNAL_CALLBACK *callback);
void registerMethodCallback(S_METHOD_CALLBACK *callback);
static void MethodCallback_1(GObject* source_object, GAsyncResult* res, gpointer userdata);
void myMethodAsync_1(const char* in_arg);
void myMethod_1(const gchar *in_arg, gchar** out_arg, GError** pError);
static void MethodCallback_2(GObject* source_object, GAsyncResult* res, gpointer user_data);
void myMethodAsync_2(const gint in_arg1, const gint in_arg2);
void myMethod_2(const gint in_arg1, const gint in_arg2, gchar **out_arg1, gint *out_arg2, GError** pError);
void *run(void* arg);
int thread_create(void);
bool ExampleDBusServiceIsReady(void);
bool InitDBusCommunication(void);
bool DeInitDBusCommunication(void);
#endif
  • libServer.h
#ifndef __SERVER_H__
#define __SERVER_H__

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>

#include "Example-generated.h"
/** thread function's definition */

static gboolean Emit_My_signal1(gconstpointer p);
static gboolean Emit_My_Signal2(gconstpointer p);
static gboolean My_Method1(CYanlinGdbusExample* object, GDBusMethodInvocation* invocation, const gchar* in_arg, gpointer user_data);
static gboolean My_Method2(CYanlinGdbusExample* object, GDBusMethodInvocation* invocation, GVariant* in_arg, gpointer user_data);
static void bus_acquired_cb(GDBusConnection* connection, const gchar* bus_name, gpointer user_data);
static void name_acquired_cb(GDBusConnection* connection, const gchar* bus_name, gpointer user_data);
static void name_lost_cb(GDBusConnection* connection, const gchar* bus_name, gpointer user_data);
void* run(void*);
int thread_create(void);
bool InitDBusCommunicationServer(void);
bool DeinitDBusCommunicationServer(void);
#endif
目录树:

├── build
├── CltExample.c
├── CMakeLists.txt
├── com.Yanlin.Gdbus.Example.xml
├── dbusCommon.h
├── libClient.c
├── libclient.h
├── libServer.c
├── libServer.h
└── SvrExample.c

精通GDBus:Linux IPC的现代C接口 GDBus是一个高级库,用于与D-Bus总线进行交互,D-Bus是一种用于Linux和UNIX系统的进程间通信机制。GDBus提供了创建D-Bus客户端和服务端的必要工具,支持异步调用、信号发送和接收、以及D-Bus方法的调用。GDBus作为GLib的一部分,提供了一个现代化的D-Bus IPC接口,允许C语言程序员轻松实现跨进程通信。其集成的异步操作支持、简化的API以及与GObject系统的兼容性,使其成为Linux环境下进行IPC的优选方案。 阅读详情

相关推荐

gdbus服务端客户端使用详解 - 服务端

本文介绍如何在linux系统使用gdbus进行进程,分为服务端和客户端。总体上是比较简单的,奈何gdbus的帮助文档实在太简单,网络上的资料也比较少。希望本文对需要使用gdbus的开发人员有帮助。 第一步,是编写interface和相应函数的xml文件(D-Bus introspection XML file),供之后借助gdbus-codegen来创建服务端和客户端相应的代码。比如:

kentonwu的博客 8139

一种IPC通信机制Gdbus详解

常规进程间通信有管道,消息队列,共享内存,以及socket等,每个都有优劣,这次我们介绍一种高阶的进程间通信方式DBus。DBus通信是IPC通信机制的一种方式,本身是建立在socket机制之上,它支持远程函数调用和信号传递。session(会话模式)、system(总线模式)**总线模式(system bus):**采用总线模式时,系统需要维护一个DBus Daemon,每个DBus的请求通过DBus Daemon转发。

凡人叶枫的博客 4229

别再死磕libbluetooth了!用DBUS和gdbus玩转BlueZ 5.54(附君正X2000实战代码)

本文详细介绍了从传统libbluetooth转向DBUS接口的BlueZ 5开发范式迁移,重点解析了DBUS架构的优势及在君正X2000平台上的实战应用。通过gdbus工具链和BLE串口服务实例,展示了现代蓝牙开发的高效方法,帮助开发者解决兼容性和权限问题,提升开发效率。

weixin_30561177的博客 414

DBus应用的俩种形态及实现

介绍一下基于DBus设计的应用程序的俩种形态及如何使用GDbus来实现。基于DBus的应用程序可以是使用DBus Daemon的总线型结构,每个DBus的请求通过DBus Daemon转发;或者是点对点的星型结构,Client与Server之间是直接的Peer2Peer的连接。这俩种结构各有优缺点:总线型的结构比较清晰,Server需要维护的连接较少,实际上只有一个与DBus Daemon相连的连

认真你就输了 8401

从Python示例到C代码:手把手拆解BlueZ 5的BLE串口服务Demo

本文详细介绍了如何将BlueZ 5的Python示例代码转换为C语言实现,重点解析了BLE串口服务的开发过程。通过DBus接口的跨语言映射原理和实战案例,帮助开发者掌握BlueZ开发的核心技术,降低Linux蓝牙协议栈的开发门槛。

weixin_30772105的博客 494

bluez inquiry 流程梳理--从代码层面理解bluez架构

从代码层面更好的去梳理bluez架构

badogyang的博客 2315

Glib学习(28) gdbus最简单的例子

官方文档:https://developer.gnome.org/gio/stable/ DBus的通信机制是Server-Client模式,Server需要提供一个XML(eg: cn.RTplay.Gdbus.Example.xml)文档给Client端去说明DBus Server提供的interface name、signal name及它的arg name、 type、 direction、method name及它的arg name、 type、 direction。 本例程代码:https:

andylauren的专栏 5957

gdbus-example:GDBUS 示例

gdbus-示例 GDBUS 示例 ./configure make && make install gdbus_server:服务器守护进程 gdbus_client:客户端程序

GDBus进程通信程序框架:跨平台进程通信的得力助手

这个代码实现了进程间通信的基本框架,厉害之处在于它可以方便地应用于不同平台间的进程通信。无论是 Linux X86、Linux ARM 还是 Android 平台,它都能大显身手。基于这套代码,开发系统守护进程以及进程间通信程序变得轻而易举。而且,经过大量测试并应用于量产项目,可靠性和稳定性那是杠杠的。

zWLzTRxDJb的博客 1548

gdbus 最简单可用demo源码

gdbus 最简单可用demo源码

Yolov5实现道路裂缝检测

Yolov5实现道路裂缝检测 参考代码链接 Github代码链接 基于Pytorch的Yolov5道路裂缝检测程序运行说明。大家可以结合我的说明和原文说明使用,有问题欢迎询问。 文章目录Yolov5实现道路裂缝检测环境要求测试训练自己的数据集1.创建dataset.yaml文件2.创建标签文件3.组织文件路径4.选择模型5.开始训练 环境要求 Python 3.8或之后的版本 还要安装requirements.txt文件中所有依赖包,包括1.7及以上版本的torch $ pip install -r req

qq_26751379的博客 2万+

gdbus 例子收集

gdbus 例子收集。

abc 394

CARLA 0.9.15从零开始:环境搭建与基础场景实战指南

本文是CARLA 0.9.15从零开始的完整环境搭建与基础运行教程。详细介绍了在Linux系统下配置Python环境、下载安装CARLA核心软件包、启动服务器以及运行第一个基础场景的步骤。重点演示了如何通过Python客户端脚本生成随机车流,并手动控制EGO车辆在仿真城市中行驶,为自动驾驶算法开发构建了坚实的仿真测试基础。

weixin_29053383的博客 777

GDBus实战:Linux进程间通信中的服务端导出与客户端代理开发

在Linux桌面环境中,进程间通信(IPC)是连接不同应用模块的基石。D-Bus作为系统与应用的通信总线,凭借其结构化消息和事件通知能力,成为桌面生态中事实上的标准。GDBus作为GLib/GIO为D-Bus提供的高层C API,屏蔽了连接认证、消息编解码等底层细节,让开发者可以专注于业务逻辑。其核心机制围绕GDBusConnection、接口XML和GDBusProxy展开:服务端通过注册总线名和导出对象暴露能力,客户端借助代理完成同步或异步方法调用,并通过信号订阅感知状态变化。这种“指令加事件”的通信模

weixin_32705179的博客 284

脑机接口(BCI)从原理到开发实战 07|运动想象BCI实战:基于BCI Competition IV 2a数据集

本文基于BCI Competition IV 2a数据集,详细介绍运动想象脑机接口系统的全流程实现。首先概述了该数据集的实验范式、参数特点和优势,然后指导环境准备与数据下载。通过代码示例展示了数据加载、事件标记提取和信号可视化方法。重点构建了完整的预处理流水线,包括通道选择、重参考、带通滤波(8-30Hz)和ICA去伪迹等关键步骤。文章旨在帮助读者将零散的BCI知识整合为完整的实战项目,掌握从原始脑电数据到运动意图解码的核心技术。

小明的博客 845

问题解答:如何不通过修改底层数据库表的方式,给数据库对应的数据结构,增添新的字段?

现在需要将这张表里的内容读取到 ABAP 内表里,并且针对每个行项目,增加一个新的列字段,我随便举个例子,这个列字段名称叫 LENGTH,值为 OBJ_NAME 字段的长度,使用。最笨的办法就是下面这样定义一个新的类型,这个类型的每个字段名称,都来自数据库表 TADIR 的同名字段,在末尾再增添自定义字段 length.其实我们是做 ALV 输出,只需要 ABAP 内表变量的类型,包含 TADIR 数据库表的全部字段,再加上新的 LENGTH 字段即可。这相当于多了一个中间层,没办法直接被 ALV 处理。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 477

《GDBus C 语言开发实战:从一份 XML 到一个能跑的服务》(三部曲 02 · 实战)

GDBus(C语言)开发需建立三大认知:通信经dbus-daemon中转,Skeleton(服务端骨架)与Proxy(客户端代理)为高层接口,区分GObject信号与D-Bus信号。流程为:①定义XML接口契约;②用gdbus-codegen生成代码;③服务端实现Skeleton回调,注册方法/信号/属性;④客户端通过Proxy调用方法或监听信号。关键点:接口统一源于XML,生成代码勿手动修改;方法调用与信号广播由GDBus库自动处理,开发者只需关注业务逻辑。

m0_56811551的博客 116

锂电池剩余使用寿命预测(RUL) | 基于Stacked-LSTM-Autoencoder的锂电池寿命多变量多步预测(Tensorflow)

锂电池剩余使用寿命预测(RUL) | 基于Stacked-LSTM-Autoencoder的锂电池寿命多变量多步预测(Tensorflow)

前程算法屋的博客 851

IPC进程间通信 D-Bus(Desktop Bus)快速入门(以libdbus-glib库为例)

文章目录一、D-Bus简介1、D-Bus简介2、不同IPC通信方式比较3、D-Bus特性二、D-Bus架构2、D-Bus接口层3、D-Bus总线层测试demo4、D-Bus封装层三、D-Bus术语1、D-Bus术语简介2、总线(Bus)3、地址(Address)4、连接名(Bus Name) 一、D-Bus简介 1、D-Bus简介 D-Bus是Desktop Bus的缩写,是针对桌面环境优化的IPC(InterProcess Communication)机制,用于进程间的通信或进程与内核的通信。 D-Bus

Dontla的博客 4265

QGIS004:【05矢量属性表】-保留字段、删除字段、添加唯一值索引字段、添加字段到属性表、添加自增量字段、添加XY字段到图层、文本型转浮点型、重构字段、重命名字段

摘要:QGIS矢量属性表工具箱包括保留字段、删除字段、添加唯一值索引字段、添加字段到属性表、添加自增量字段、添加XY字段到图层、文本型转浮点型、重构字段、重命名字段等选项,本文介绍各选项的基本操作。

qq_31762031的博客 2311

Win11此电脑怎么放在桌面上?Win11此电脑如何显示在电脑桌面上?

相信用习惯Win10的用户都喜欢电脑电脑桌面上的此电脑,但是很多用户更新完Win11正式版以后,发现桌面只有回收站和Microsoft Edge图标,没有此电脑。那么,Win11此电脑要如何显示呢?下面小编为大家简单介绍一下操作方法!5、桌面图标设置窗口,点击勾选计算机,然后点击确定,桌面就可以显示此电脑图标了。1、桌面空白处,点击右键,在打开的菜单项中,选择显示设置;4、个性化 - 主题,相关设置下,点击桌面图标设置;3、右侧点击主题(安装、创建、管理);2、设置窗口,左侧点击个性化;

shengyin714959的博客 13万+

D-Bus编译与应用实战:Linux系统级进程通信核心指南

D-Bus是Linux系统中实现跨进程、跨服务通信的基础协议,其本质是一套运行时消息总线契约,而非通用网络协议。它基于XML接口定义(IDL)、GVariant序列化和总线守护进程(dbus-daemon)协同工作,支撑GNOME/KDE桌面、systemd服务管理及硬件抽象层(如UPower、NetworkManager)的实时交互。技术价值在于提供标准化的‘推送式’事件通知机制,替代低效轮询,保障状态变更的瞬时性与可靠性。典型应用场景包括系统托盘工具开发、嵌入式服务集成、容器内IPC桥接及跨设备协同网关

weixin_31856057的博客 212

多模型机器学习生存预测分析:AUC比较、生存分层与SHAP解释

本文研究了多种机器学习模型在心力衰竭患者生存预测中的应用。通过比较逻辑回归、随机森林、XGBoost、LightGBM和梯度提升机五种模型的AUC表现,选择最优预测模型。基于最优模型的预测概率对患者进行风险分层,并使用Kaplan-Meier生存分析和log-rank检验验证分层的有效性。最后采用SHAP方法解释模型决策过程,识别关键预测因素。研究提供了从模型构建、评估到解释的完整技术流程,为临床预后预测提供了可复现的分析框架。

AI的内部世界的博客 157

进程间通信——信号

1、进程的独立与协作 进程在操作系统中运行时,每一个进程都是高度独立和封闭的!但是有些程序问题需要多个进程来协作完成。这时候就出现了一个矛盾。 进程高度独立且封闭,要达成进程的协作,就不得不让进程之间能够进行交流。如何解决? (1)、打破进程的独立性和封闭性;这样做带来的后果和风险是:i>缺乏安全性;ii>进程间的耦合度增加。由此可知该解决方案是完全不可行的...

weixin_34345753的博客 149

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Bluez目录结构分析

bluez目录结构分析

gacmy的专栏 1592

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

什么是 unix environment?

unix 环境的概述 环境是一个相对大范围的概念,unix 环境对该概念的作用范围进行了限定,尽管如此这个概念涉及的东西仍然十分庞大。 从内核到系统调用到 shell 与系统库,这些都是环境的一部分。应用程序依赖于这些环境来完成创建、执行、销毁的全过程。这一过程的每一部分都相当复杂,具体的细节可以根据个人兴趣进行深入研究,但总体的架构却需要尽早的建立。 登入 unix 系统后的控制环境 登入 unix 系统时,系统通过读取系统数据文件 /etc/passwd (密码文件)来为我们准备登入的环境。通过校验

龙瑜的博客 811

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

上一篇: Linux 指令---mount(挂载命令)
下一篇: GLib中的数据类型及操作
yanlinembed
博客等级 码龄12年 42粉丝 32原创
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值