Git Product home page Git Product logo

dbus-native's Introduction

node-dbus

Greenkeeper badge D-bus protocol client and server for node.js

Build Status

Installation

npm install dbus-native

or

git clone https://github.com/sidorares/node-dbus # clone the repo
cd node-dbus
npm install # install dependencies
sudo cp examples/com.github.sidorares.dbus.Example.conf /etc/dbus-1/system.d/ # if you want to test examples/service.js

Usage

Short example using desktop notifications service

var dbus = require('dbus-native');
var sessionBus = dbus.sessionBus();
sessionBus.getService('org.freedesktop.Notifications').getInterface(
    '/org/freedesktop/Notifications',
    'org.freedesktop.Notifications', function(err, notifications) {

    // dbus signals are EventEmitter events
    notifications.on('ActionInvoked', function() {
        console.log('ActionInvoked', arguments);
    });
    notifications.on('NotificationClosed', function() {
        console.log('NotificationClosed', arguments);
    });
    notifications.Notify('exampl', 0, '', 'summary 3', 'new message text', ['xxx yyy', 'test2', 'test3', 'test4'], [],  5, function(err, id) {
       //setTimeout(function() { n.CloseNotification(id, console.log); }, 4000);
    });
});

API

Low level messaging: bus connection

connection = dbus.createClient(options)

options:

  • socket - unix socket path
  • port - TCP port
  • host - TCP host
  • busAddress - encoded bus address. Default is DBUS_SESSION_BUS_ADDRESS environment variable. See http://dbus.freedesktop.org/doc/dbus-specification.html#addresses
  • authMethods - array of authentication methods, which are attempted in the order provided (default:['EXTERNAL', 'DBUS_COOKIE_SHA1', 'ANONYMOUS'])
  • ayBuffer - boolean (default:true): if true 'ay' dbus fields are returned as buffers
  • ReturnLongjs - boolean (default:false): if true 64 bit dbus fields (x/t) are read out as Long.js objects, otherwise they are converted to numbers (which should be good up to 53 bits)
  • ( TODO: add/document option to use adress from X11 session )

connection has only one method, message(msg)

message fields:

  • type - methodCall, methodReturn, error or signal
  • path - object path
  • interface
  • destination
  • sender
  • member
  • serial
  • signature
  • body
  • errorName
  • replySerial

connection signals:

  • connect - emitted after successful authentication
  • message
  • error

example:

var dbus = require('dbus-native');
var conn = dbus.createConnection();
conn.message({
    path:'/org/freedesktop/DBus',
    destination: 'org.freedesktop.DBus',
    'interface': 'org.freedesktop.DBus',
    member: 'Hello',
    type: dbus.messageType.methodCall
});
conn.on('message', function(msg) { console.log(msg); });

Note on INT64 'x' and UINT64 't'

Long.js is used for 64 Bit support. https://github.com/dcodeIO/long.js The following javascript types can be marshalled into 64 bit dbus fields:

  • typeof 'number' up to 53bits
  • typeof 'string' (consisting of decimal digits with no separators or '0x' prefixed hexadecimal) up to full 64bit range
  • Long.js objects (or object with compatible properties)

By default 64 bit dbus fields are unmarshalled into a 'number' (with precision loss beyond 53 bits). Use {ReturnLongjs:true} option to return the actual Long.js object and preserve the entire 64 bits.

Links

dbus-native's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dbus-native's Issues

Marshalling error

This seems to be the root of my problem, and it sure looks to me like an error (or undocumented limitation?) in the marshalling function:

marshall = require('./marshall.js');

// OK
marshall(   's', [
            'abc'
], 0);


// OK
marshall(   'v', [
            [ 's', 'abc' ]
],0);


// OK
marshall(   'a{ss}', [
            [ [ 'abc', 'def' ] ]
], 0);


// Fail: Invalid struct data
marshall(   'v', [
            [ 'a{ss}', [ [ 'abc', 'def' ] ] ]
], 0);

If it helps, here's the actual message I need to send: it's an "sv", where the v is an "a{sv}" with one member. I can do it in python, but not node.

"\22\0\0\0IPv4.Configuration\0\5a{sv}\0\0\0\31\0\0\0\0\0\0\0\6\0\0\0Method\0\1s\0\0\0\4\0\0\0dhcp\0"

problem if call bus.connection.end(); too early

if i create sessionBus start use it and without delay call bus.connection.end();
i have errors like

 Uncaught Error: read ECONNRESET
  at errnoException (net.js:901:11)
  at Pipe.onread (net.js:556:19)

 Uncaught Error: read ECONNRESET
  at errnoException (net.js:901:11)
  at Pipe.onread (net.js:556:19)

Error when get a service from org.freedesktop.PolicyKit1

When I use dbus-native to get a service from org.freedesktop.PolicyKit1,but I get failed.
Here is my code:

var dbus = require('dbus-native');

action_id = 'org.freedesktop.policykit.exec';
details = {};
flags = 1;
cancellation = '';

var sessionBus = dbus.sessionBus();
sessionBus.getService('org.freedesktop.PolicyKit1').getInterface(
    '/org/freedesktop/PolicyKit1/Authority',
    'org.freedesktop.PolicyKit1.Authority', function(err, notifications) {
        if(err){
                console.log('err'+err);
        }
        console.log(JSON.stringify(notifications));
         notifications.CheckAuthorization(('unix-process', {'pid':process.getpid, 'start-time':0}), action_id, details, flags, cancellation_id, function(err, id) {
        console.log('wpp');
    });
});

And here is my error:

screenshot from 2015-04-15 11 46 56

Export Introspection of D-Bus Service.

How can I provide introspection data of my D-Bus Service?
When I used dbus Python module, introspection was provided automatically.
Can I do same by using this module, or I must to do it yourself?
This issue isn't significant but it's a little bit of convenience.

How to use dbus.Byte in python like in dbus-native

Hi,
Can you give me some way to use dbus-native as I can use "dbus.Byte" and " dbus.ByteArray " in python?
Some data I can use "dbus.ByteArray" in python to communicate with application like NetworkManager,
but failed in dbus-native.
Here is a link to dbus.ByteArray:
http://dbus.freedesktop.org/doc/dbus-python/api/dbus.ByteArray-class.html
And here is my python code:

import dbus
con = {
    '802-11-wireless':{
        'ssid':dbus.ByteArray('homewifi'),
    },
    'connection':{
        'type':'802-11-wireless',
        'uuid':'7371bb78-c1f7-42a3-a9db-5b9566e8ca07',
        'id':'My_need_wifi'
    },
    'ipv4':{'method':'auto'},
    'ipv6':{'method':'auto'}
}
bus = dbus.SystemBus()
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
settings.AddConnection(con)

Is there any way I can use like dbus.Byte or dbus.ByteArray in dbus-native like in python-dbus ?
Thanks.

Invalid struct data with 'av' marshalling

When i try to update my lan connection via dbus call to network manager i get an invalid struct data error.
My guess would be that i somehow use the 'av' part for address-data incorrectly.
In the network-manager connection settings specification ( https://developer.gnome.org/NetworkManager/stable/ref-settings.html ) address-data is an 'array of vardict' . I'm not even sure if i translated that correctly into an 'a{sv}' here.

Here is some example code for my problem:

    var dbus = require('dbus-native');
    var _bus = dbus.systemBus();

    updateConnection();

    /**
     * updates an existing network connection
     */
    function updateConnection() {

      connection = [
        ["connection",[
          ["id",["s","Ethernet connection 1"]],
          ["uuid",["s","e341b3bc-3ddd-4fd3-bddd-8b71162f5c33"]],
          ["type",["s","802-3-ethernet"]]
        ]],
        ["ipv4",[
          ["address-data",["av",
            [
              ["sv",[["address"],["s","192.168.1.1"]]],
              ["sv",[["prefix"],["u",24]]]
            ]
          ]],
          ["method",["s","manual"]]
        ]],
        ["802-3-ethernet",[
          ["duplex",["s","full"]]
        ]],
        ["ipv6",[
          ["method",["s","auto"]]
        ]]
      ]

      path = '/org/freedesktop/NetworkManager/Settings/18';

      _bus.getService('org.freedesktop.NetworkManager').getInterface(
        path,
        'org.freedesktop.NetworkManager.Settings.Connection', function(err, Connection) {
          if (err){
            console.log(err);
          }

          Connection.Update(connection, function(err,one){
            console.log(err,one);
          });
        }
      );
    }

Are square brackets valid in signatures?

In the marshall/unmarshall test I see one line that contains brackets.  Is that a valid signature? Reason I'm asking was my validation for signatures was raising an error on this line.

 ['g', ['xxxtt[t]s{u}uuiibb']]

Should it be

 ['g', ['xxxtt(t)s{u}uuiibb']]

I couldn't find square brackets in the dbus spec.

Get properties in a dict

Hi,
When I get a dict,how do I get value in it?
Like in this picture,
how can I get value of Interface or Udi?
2015-04-01 16 14 35

What about to delete all console.log from release version

for example
dbus-native/lib/stdifaces.js:24: console.log('STDINTARFACES MATHD CALL', msg);

very hard to run tests or run some console scripts with this
i always need to delete them in local copies
also output to console slow down execution of code

How to run examples?

I've got some dbus objects I've implemented in python and wanted to see if I can use them from node which I'm new to. I've install dbus-native and cloned the git tree. I thought I'd start by looking at the examples but I'm not sure how to run them as I get the follow results:

node server2.js

events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:769:11)
at Object.afterWrite (net.js:593:19)

What am I doing wrong? I'm running on RHEL6 with node 0.8.14.

Works on ubuntu, does not work on debian

Hi all

I'm trying the following script to listen for freshly started ssh servers on the local network. It works fine when run on by ubuntu (12.04) but fails on debian (wheezy): Dbus replies with REJECTED EXTERNAL DBUS_COOKIE_SHA1 ANONYMOUS
If I run it as root, it works fine.

I've compared configs and they are equal (on ubuntu there is an additional line that I've added with no success).
The other difference I've seen is that ubuntu is running dbus 1.4, while wheezy is running 1.6

Any hints?

var dbus = require('dbus-native');
var systemBus = dbus.systemBus();

systemBus.getService('org.freedesktop.Avahi').getInterface('/', 'org.freedesktop.Avahi.Server', function (err, avahi) {
    avahi.ServiceBrowserNew(-1, 0, "_ssh._tcp", "local", 0, function (err, browser_path) {
        systemBus.getService('org.freedesktop.Avahi').getInterface(browser_path, 'org.freedesktop.Avahi.ServiceBrowser', function (err, service_browser) {
            service_browser.on("ItemNew", function (_, _1, name, type, domain) {
                console.log("ItemNew", arguments);
                avahi.ServiceResolverNew(-1, 0, name, type, domain, 0, 0, function (err, resolver_path) {
                    systemBus.getService('org.freedesktop.Avahi').getInterface(resolver_path, 'org.freedesktop.Avahi.ServiceResolver', function (err, service_resolver) {
                        service_resolver.on("Found", function () {
                            console.log("Found", arguments);
                            service_resolver.Free();
                        })
                    });
                });
            });
            service_browser.on("ItemRemove", function () {
                console.log("ItemRemove", arguments)
            });
        });
    });
});

Monitoring NetworkManager 1.0

I am trying to switch from the libdbus based node-dbus over to dbus-native and am having some problems with getting signals from NetworManager. If I run dbus-monitor with the parameters in this script I see all the messages come across. My script runs and connects to the system bus but I get no signals emitted.

var bus = require('dbus-native').systemBus();
var signame = 'StateChanged';
bus.addMatch('type=\'signal\',member=\'' + signame + '\'',
             function(err, value) {
                 if (err) throw new Error(err);                                      
});                                                        
var signalFullName = bus.mangle('/org/freedesktop/NetworkManager',
                                'org.freedesktop.NetworkManager',
                                signame);

bus.signals.on(signalFullName, function(messageBody) {                  
    console.log(messageBody);
});

Getting a string property fails

This worked in the previous version I had installed (0.0.13), but seems broken on git HEAD:

var dbus = require('dbus-native');
var sessionBus = dbus.sessionBus();
sessionBus.getService('org.PulseAudio1').getInterface(
    '/org/pulseaudio/server_lookup1',
    'org.PulseAudio.ServerLookup1',
    function(err, lookup) {
        if(err) throw err;
        lookup.Address(function(err, addr) {
            console.log("Address returned", arguments);
        });
    }
);

Prints:

Address returned { '0': null, '1': undefined }

Using dbus-monitor, I can see the call being made and returning correctly, so I think it's just not being processed properly by the message parsing code:

method call sender=:1.201 -> dest=org.freedesktop.DBus serial=1 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hello
method call sender=:1.201 -> dest=org.PulseAudio1 serial=2 path=/org/pulseaudio/server_lookup1; interface=org.freedesktop.DBus.Introspectable; member=Introspect
method return sender=:1.10 -> dest=:1.201 reply_serial=2
    string "<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node> <!-- If you are looking for documentation make sure to check out
            http://pulseaudio.org/wiki/DBusInterface -->
<interface name="org.PulseAudio.ServerLookup1">
    <property name="Address" type="s" access="read"/>
</interface>
<interface name="org.freedesktop.DBus.Introspectable">
    <method name="Introspect">
    <arg name="data" type="s" direction="out"/>
    </method>
</interface>
<interface name="org.freedesktop.DBus.Properties">
    <method name="Get">
    <arg name="interface_name" type="s" direction="in"/>
    <arg name="property_name" type="s" direction="in"/>
    <arg name="value" type="v" direction="out"/>
    </method>
    <method name="Set">
    <arg name="interface_name" type="s" direction="in"/>
    <arg name="property_name" type="s" direction="in"/>
    <arg name="value" type="v" direction="in"/>
    </method>
    <method name="GetAll">
    <arg name="interface_name" type="s" direction="in"/>
    <arg name="props" type="a{sv}" direction="out"/>
    </method>
</interface>
</node>
"
method call sender=:1.201 -> dest=org.PulseAudio1 serial=3 path=/org/pulseaudio/server_lookup1; interface=org.freedesktop.DBus.Properties; member=Get
    string "org.PulseAudio.ServerLookup1"
    string "Address"
method return sender=:1.10 -> dest=:1.201 reply_serial=3
    variant       string "unix:path=/run/user/1000/pulse/dbus-socket"

(the last line contains the actual Address property)

Difficult to reproduce crash

Hi,

I have implemented a small interface towards the linux network manager with the help of dbus-native but have crashes every once in a while.

I'm still in the process of debugging the issue, however the crash is as follows:

~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/lib/xml2js.js:216
          throw ex;
                ^
TypeError: Cannot read property 'length' of undefined
    at ~/repo/node_modules/node-network-manager/node_modules/dbus-native/lib/introspect.js:18:31
    at Parser.<anonymous> (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/lib/xml2js.js:199:18)
    at Parser.emit (events.js:95:17)
    at Object.saxParser.onclosetag (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/lib/xml2js.js:183:24)
    at emit (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/node_modules/sax/lib/sax.js:615:33)
    at emitNode (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/node_modules/sax/lib/sax.js:620:3)
    at closeTag (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/node_modules/sax/lib/sax.js:861:5)
    at Object.write (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/node_modules/sax/lib/sax.js:1294:29)
    at Parser.exports.Parser.Parser.parseString (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/lib/xml2js.js:211:31)
    at Parser.parseString (~/repo/node_modules/node-network-manager/node_modules/dbus-native/node_modules/xml2js/lib/xml2js.js:6:61)
    at Object.<anonymous> (~/repo/node_modules/node-network-manager/node_modules/dbus-native/lib/introspect.js:12:14)

I'm currently using version 0.1.0

The reason the crash is on line 18 in introspect.js is that I added (thats the
only modification I have made since starting to debug this):

console.log(JSON.stringify(result));

on line 17, which is where the crash happens in the original code.

What that extra debugging statement showed was that it crashes when result is an empty object:

{}

So what happens is that the property 'interface' is undefined on the result
object (since it is empty) which causes ifaces.length to throw an exception.
I'm guessing it is related to some DBus-object dissapearing during runtime, but
this is all the data I have atm.

Connecting to dbus-daemon on OS X

I'm trying to connect to dbus-daemon on OS X, but I keep getting this error. I'm confused because I don't want the node client to start a server, I want it to connect to the dbus-daemon, so it shouldn't complain that the address is in use. In this instance, I launched dbus-daemon from the command line and told it to listen on a TCP socket. I get the same response.

$ node server.js 
version mismatch between local (0.4.2) and global (undefined) Locomotive module
Starting podtique config server with content dir: /Users/rmann/Desktop/TAHReencoded
createStream opts: {}
Address: tcp:host=localhost,port=64359,guid=9954de09c00a3376525c6a8e5500b6f3
connect deprecated multipart: use parser (multiparty, busboy, formidable) npm module instead node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:56:20
connect deprecated limit: Restrict request size at location of read node_modules/express/node_modules/connect/lib/middleware/multipart.js:86:15
connect deprecated methodOverride: use method-override npm module instead config/initializers/30_middleware.js:16:20
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1129:14)
    at listen (net.js:1155:10)
    at net.js:1253:9
    at dns.js:85:18
    at process._tickCallback (node.js:355:11)
    at Function.Module.runMain (module.js:503:11)
    at startup (node.js:129:16)
    at node.js:814:3

Unable to use UDisks devices

For some reason, the following code works:

var udisksService = dbus
    .systemBus()
    .getService("org.freedesktop.UDisks");

udisksService.getInterface("/org/freedesktop/UDisks", "org.freedesktop.UDisks", function(err, udisks)
    {
        udisks.EnumerateDevices(function(err, res)
        {
                      console.log(res)
        })
    });

However, this does not:

var udisksService = dbus
    .systemBus()
    .getService("org.freedesktop.UDisks");
udisksService.getInterface("/org/freedesktop/UDisks/devices/sdb", "org.freedesktop.UDisks.Device", function(err, device)
{
});

It crashes with:
TypeError: Cannot call method 'toString' of undefined

Or to be more precise, "parser.parseString(xml, function (err, result) {" (line 13 on introspect.js), meaning that xml is empty (undefined) - meaning that Introspect returns nothing.

However, when calling the same function with another DBus client (e.g. d-feet debugger or another dbus module for node) it works fine.

What could be wrong?

Dict of string, variant -> hash map

The dbus type a{sv} (array of string -> variant pairs) is considered a dictionary, so it usually gets translated to a JS object by DBus clients.
In this Dbus implementation, it remains an array of pairs (also arrays).

invoke callback hangs if connection is not closed

Method call over system bus hangs if callback doesn't close connection, for example:
var dbus = require('dbus-native');
var bus = dbus.systemBus();
bus.invoke({
path: '/org/freedesktop/systemd1',
destination: 'org.freedesktop.systemd1',
'interface': 'org.freedesktop.systemd1.Manager',
member: 'ListUnits',
signature: '',
body: [],
type: dbus.messageType.methodCall
}, function (err, res) {
console.log(res);
});
This code prints method call result and then hangs until I send SIGINT to the process.
However If I close connection with bus.connection.end() right after console.log call, everything just works. Is this expected behavior? Neither docs nor examples mention this issue, so maybe it some misconfiguration on the host side?

Fails to call UDisks2 GetManagedObjects.

Using npm version [email protected]

the following fails with:

buffer.js:156
function Buffer(subject, encoding, offset) {
^
RangeError: Maximum call stack size exceeded

source code:

var dbus = require('dbus-native');

var bus = dbus.systemBus();
var conn = bus.connection;
conn.message({
path:'/org/freedesktop/UDisks2',
destination: 'org.freedesktop.UDisks2',
'interface': 'org.freedesktop.DBus.ObjectManager',
member: 'GetManagedObjects',
type: dbus.messageType.methodCall
});
conn.on('message', function(msg) { console.log(msg); });

Does not work with UDisk2

Expected this to work (I'm using Ubuntu 14.04) but I'm getting an undefined object for interface:

  var dbus = require('dbus-native');
  var bus = dbus.systemBus();
  var service = bus.getService('org.freedesktop.UDisks2');
  service.getInterface('/org/freedesktop/UDisks2', 'org.freedesktop.UDisks2', function(err, ud) {
    if(err) throw err;
    // TypeError: Cannot call method 'on' of undefined
    ud.on('DeviceAdded', function(deviceObjectPath) {
      console.log('DeviceAdded', deviceObjectPath);
    });
  });

Any idea?

Memory leak from bus.invoke

I've isolated a memory leak to the use of bus.invoke. I wrote a minimal script to invoke a DBUS method repeatedly and used memwatch to discover leaks. Faking the invoke with a timeout to trigger the callback removed the leak. So, it's definitely somewhere in the loop between invoking and processing the response.

I haven't been able to track it down further than that. Unfortunately, I'm in a cross-compiled node deployment and remote debugging with node-inspector and webkit-devtools-agent isn't working.

I'm running [email protected] and [email protected].

Any help would be appreciated. If I figure it out, I'll post something.

Special case introspected properties signals.

I found listening to an introspected object's 'PropertiesChanged' signal failed using the interface.on('') method. This is happening because those signals come from a different interface. If we special case them it is much easier to get access to these signals in our code.

diff --git a/lib/introspect.js b/lib/introspect.js
index efab01a..269a428 100644
--- a/lib/introspect.js
+++ b/lib/introspect.js
@@ -34,7 +34,19 @@ module.exports = function(obj, callback) {
                       return sigHandlers[index];
                   }

+                  function getSignalFullName(objName, ifName, signame) {
+                      if (signame == 'PropertiesChanged' ||
+                          signame == 'PropertyFlagsChanged') {
+                          ifName = 'org.freedesktop.DBus.Properties';
+                      };
+                      return bus.mangle(obj.name, ifName, signame);
+                  }
+
                   function getMatchRule(objName, ifName, signame) {
+                      if (signame == 'PropertiesChanged' ||                                  
+                          signame == 'PropertyFlagsChanged') {              
+                          ifName = 'org.freedesktop.DBus.Properties';        
+                      };
                       return "type='signal',path='" + objName + "',interface='" + ifName + "',member='" + signame + "'";
                   }

@@ -44,7 +56,7 @@ module.exports = function(obj, callback) {
                           // An example is "type='signal',sender='org.freedesktop.DBus', interface='org.freedesktop.DBus',member='Foo', path='/bar/foo',destination=':452345.34'" ...
                           //var match = "type='signal',sender='"+obj.service.name+ ...

-                          var signalFullName = bus.mangle(obj.name, ifName, signame);
+                          var signalFullName = getSignalFullName(obj.name, ifName, signame);

                           if (!bus.signals.listeners(signalFullName).length) {
                               // This is the first time, so call addMatch
@@ -64,7 +76,7 @@ module.exports = function(obj, callback) {

                   currentIface.removeListener = (function(ifName) {
                       return function(signame, callback) {
-                          var signalFullName = bus.mangle(obj.name, ifName, signame);
+                          var signalFullName = getSignalFullName(obj.name, ifName, signame);
                           bus.signals.removeListener(signalFullName, getSigHandler(callback));

                           if (!bus.signals.listeners(signalFullName).length) {

What do you think about this solution, and should we do the same for GetProperties, SetProperties, and ListProperties methods?

dbus-send in node.js

A newbie question.

I am trying to use node.js to communicate with omxplayer.

In shell the commands are like this:

export DBUS_SESSION_BUS_ADDRESS=`cat /tmp/omxplayerdbus.$USER`
export DBUS_SESSION_BUS_PID=`cat /tmp/omxplayerdbus.$USER.pid`

# read play back status
dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.PlaybackStatus

# read movie position
dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Position

# read movie duration
dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Duration

# action: pause
dbus-send --print-reply=literal --session --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Action int32:16

# action: seek to $pos
dbus-send --print-reply=literal --session --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.SetPosition objpath:/not/used int64:$pos

I am trying to do these in node.js.
I found this question http://stackoverflow.com/questions/26085289/nodejs-dbus-not-working so I guess the code should be like this (example for reading the position):

var fs = require('fs');
var dbus = require('dbus-native');

var bus = dbus.sessionBus({
        busAddress: fs.readFileSync('/tmp/omxplayerdbus.root', 'ascii').trim()
});

bus.invoke({
        path: "/org/mpris/MediaPlayer2",
        interface: "org.freedesktop.DBus.Properties",
        member: "Get",
        destination: "org.mpris.MediaPlayer2.omxplayer",
        signature: "ss",
        body: [
                "org.mpris.MediaPlayer2.omxplayer",
                "Position"
        ]
}, function(err, position) {
        console.log(err, position);
});

console.log('ok');

Well... it runs... it prints 'ok'. But did it send the message? How do I read the position back?

I understand this is probably a stupid question, but I can't figure it out.
Thanks!

Getting Systembus signals without destination

I seem to not get any signal messages from the systembus that have a null destination.

I receive all messages that have a destination of the new address of the DBUS connection, But i do not receive any message's that have a global destination.

i'm using the following code to get all messages:

var sysBus = dbus.systemBus();
console.log('got sys bus');
//sysBus.connection.on('message', console.log);
//sysBus.connection.on('RoomTemperature', console.log);
//sysBus.connection.on('data',console.log);
sysBus.connection.on('message', function(msg) {
console.log('got message');
console.log('type = ' + msg.type);

});

but i'm only getting the signals from the DBus daemon with the nameing stuff.

Am i missing something or is this a bug in the software?

A example from the dbus-monitor from the message i'm trying to capture:

signal sender=:1.37 -> dest=(null destination) serial=9 path=/; interface=com.tclcode.otmonitor; member=ControlSetpoint
double 6

abstract-socket dependency?

Is there any way to avoid the abstract-socket dependency? I'm trying to use this on OS X, and it doesn't support abstract sockets.

How to get the mount-point of a plugged in usb device?

First of all: Thank you so much for providing the dbus module for node.js. It's definitly what I was searching for! I also found one of your examples, which detects, if a usb device has been plugged in.

What I have so far:

var dbus = require('dbus-native');

var bus = dbus.systemBus();
udservice = bus.getService('org.freedesktop.UDisks');
udservice.getInterface(
    '/org/freedesktop/UDisks',
    'org.freedesktop.UDisks', 
    function(err, ud) {
        ud.on('DeviceAdded', function(deviceObjectPath) {
                console.log('DeviceAdded', deviceObjectPath);
        });
        ud.on('DeviceRemoved', function(deviceObjectPath) {
                console.log('DeviceRemoved', deviceObjectPath);
        });
        }
);

Now I'm looking for a way to get the mounting point (or name) of the device. Right now I'm getting the device object path.
Is this possible?

Problem accessing system bus

I am unable to open the system bus for access. When I try, I get the following error:
/home/jgriglack/Projects/ikabit/build/rootfs/share/ikabit-equipment-service/node_modules/dbus-native/lib/handshake.js:95
if (err) throw err;
^
Error: EISDIR, read
It appears that it is unable to find a certificate.

Here is part of the code:

time_dbus.js

DBUS_TIME_INTERFACE = 'org.freedesktop.DBus.Properties';
DBUS_TIME_DESTINATION = 'org.freedesktop.timedate1';
DBUS_TIME_PATH = '/com/freedesktop/timedate1';
DBUS_TIME_INTROSPECT = 'org.freedesktop.DBus.Introspectable';
DBUS_TIME_PROPERTIES = 'org.freedesktop.DBus.Properties';

var _ = require('underscore');
var equipment_dbus = require('./equipment_dbus');
var Q = require('q');

//var bus = equipment_dbus.bus;

var dbus = require('dbus-native');

function time_dbus_bus()
{
    return dbus.systemBus();
}

var bus = time_dbus_bus();


/**
 * initialize will initialize the nameList and typeList variables used
 * for validating the names to Set and for sending the correct type to
 * the Set dbus function.
 */
function initialize()
{
    initializeSignals();
    bus.getService(DBUS_TIME_DESTINATION).getInterface(DBUS_TIME_PATH,
        DBUS_TIME_INTROSPECT, function(err, iface) 
    {
        if (err) 
        {
            console.log("bus.getInterface ", err);
        }
        else
        {
            var responseCallback = function(err,result)
            {
                if (err != null)
                {
                    console.log("Error! ", err);
                }

                if (result != null)
                {
                    var tmp = result.match(/property type=.*"/g);
                    var type = [];
                    var name = [];
                    for (var i = 0; i < tmp.length; i++)
                    {
                        var typeStart = tmp[i].lastIndexOf("type=")+6;
                        typeList[i] = tmp[i].substring(typeStart, typeStart+1);
                        var nameStart = tmp[i].lastIndexOf("name=")+6;
                        var nameEnd = tmp[i].lastIndexOf("access")-2;
                        nameList[i] = tmp[i].substring(nameStart, nameEnd);
                    }
                }
            }

            iface.Introspect(responseCallback);
        }
    });
}

exports.initialize = initialize;

/**
 * @brief Set the system clock
 * @param timeValue  the time value
 */
function setTime(timeValue)
{
    var deferred = Q.defer();
    bus.getService(DBUS_TIME_DESTINATION).getInterface(DBUS_TIME_PATH,
        DBUS_TIME_INTERFACE, function(err, iface)
    {
        if (err)
        {
            deferred.reject(err);
        }
        else
        {
            iface.SetTime(timeValue, 0, 0, function(err, result)
            {
                if (err)
                {
                    deferred.reject(err);
                }
                else
                {
                    deferred.resolve(result);
                }
            });
        }
    });
    return deferred.promise;
}

exports.setTime = setTime;

time.js

var time_dbus = require('../dbus/time_dbus');
var defs = require('../definitions');
var statusEnum = defs.statusEnum;

require('shelljs/global');

//logging setup from
//http://brilliantbritz.com/setting-up-winston-logger-in-nodejs/
var winston = require('winston');

var logger = new (winston.Logger)({
 transports: [
     new (winston.transports.Console)({ level: 'error',
                                        colorize: true}),
 ]
});

module.exports = function (app)
{

/**
 * @brief get the time
 *
 * @name GET /v1/time
 */
    app.get('/v1/time', function(request, response)
    {
        function truncateDecimals (num, digits) 
        {
            var numS = num.toString();
            var decPos = numS.indexOf('.');
            var substrLength = decPos == -1 ? numS.length : 1 + decPos + digits;
            var trimmedResult = numS.substr(0, substrLength);
            var finalResult = isNaN(trimmedResult) ? 0 : trimmedResult;

            return parseFloat(finalResult);
        }

        /* The javascript Date.now() function returns a time in
         * milliseconds, so we divide by 1000 to get seconds
         */
        var timeVal = truncateDecimals((Date.now() / 1000), 0);

        response.send(statusEnum.STATUS_OK, 
                      JSON.stringify({"UTCSeconds":timeVal}));
    });

/**
 * @brief set the time
 * 
 * request body json format:
 * 
 * { "UTCSeconds": <int>, "Timezone":"America/New_York" }
 * where the UTCSeconds is the UTC Epoch seconds
 *           Timezone is one of the valid timezones in 
 *               /usr/share/zoneinfo/zone.tab
 * @name POST /v1/time
 */
    app.post('/v1/time', function(request, response) 
    {
        var setCount = 0;
        var timeRequest = request.body;
        var status = {};

        if (timeRequest.hasOwnProperty("UTCSeconds"))
        {
            // timedated wants the time in nanoseconds
            var timeValue = timeRequest.UTCSeconds * 1000000;

            if (timeValue > 0)
            {
            time_dbus.setTime(timeValue)
            .then(function(result)
            {
            setCount++;
            })
            .catch( function(err)
            {
                console.log("time interface ", err);
            });
            }
        }

        response.send(statusEnum.STATUS_OK, 
                      JSON.stringify(status));
    });

}

Error: write EPIPE on Ubuntu Quantal

The creation of session bus fails for some reason on Ubuntu Quantal:

> var dbus = require("dbus-native");
undefined
> var sessionBus = dbus.sessionBus();
undefined
> 
events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: write EPIPE
    at errnoException (net.js:770:11)
    at Object.afterWrite (net.js:594:19)

I'm using version 0.0.8 from npm and I have the socat package installed.

Use dbus-native to call NetworkManager

I've meet some problem when I try to use dbus-native with nodejs to call to NetworkManager and let NetworkManager connect to a SSID(WIFI).
I use the connection is :

con = [ //a
  ['802-11-wireless', [
    ['mode', ['s','infrastructure']],
    ['security', ['s','802-11-wireless-security']],
    ['ssid', ['y',stringToArrayOfBytes('TP-LINK_10DC')]]
  ]],
  ['802-11-wireless-security', [
    ['auth-alg', ['s','open']], 
    ['key-mgmt', ['s','wpa-psk']],
    ['psk', ['s','0123456789']]
  ]],
  ['connection',[
    ['id', ['s','TP-LINK_10DC']],
    ['type', ['s','802-11-wireless']],
    ['uuid', ['s',uuid.v1().toString()]]
  ]],
    ['ipv4', [
        ['method', ['s','auto']]
    ]],
    ['ipv6', [
    ['method', ['s','auto']]
        ]]
]

and my code is:

var dbus = require('dbus-native');
var systemBus = dbus.systemBus();
var uuid = require('uuid');

var stringToArrayOfBytes = function (str) {
  var bytes = [];
  for (var i = 0; i < str.length; ++i) {
      bytes.push(str.charCodeAt(i));
  }
  return bytes;
};
con = [ //a
  ['802-11-wireless', [
    ['mode', ['s','infrastructure']],
    ['security', ['s','802-11-wireless-security']],
    ['ssid', ['ai',stringToArrayOfBytes('TP-LINK_10DC')]]
  ]],
  ['802-11-wireless-security', [
    ['auth-alg', ['s','open']], 
    ['key-mgmt', ['s','wpa-psk']],
    ['psk', ['s','0123456789']]
  ]],
  ['connection',[
    ['id', ['s','TP-LINK_10DC']],
    ['type', ['s','802-11-wireless']],
    ['uuid', ['s',uuid.v1().toString()]]
  ]],
 ['ipv4', [
 ['method', ['s','auto']]
 ]],
 ['ipv6', [
    ['method', ['s','auto']]
        ]]
]
systemBus.getService('org.freedesktop.NetworkManager').getInterface(
 '/org/freedesktop/NetworkManager',
 'org.freedesktop.NetworkManager', function(err, Device) {
// console.log(Device);
 Device.AddAndActivateConnection(con,'/org/freedesktop/NetworkManager/Devices/0','/',function(err,id){
 console.log(id);
 });

});

In my code,SSID is the name of WIFI,and psk is my password.ID is also the name of WIFI.But id can use the form of string,ssid should use the form of bytes.
What can I do to help me Connect to a SSID?
Thanks.

API break between 0.1.1 and 0.1.2

I recently upgraded from dbus-native 0.1.1 to 0.1.2 and now get crashes that
appear to be because of a change in API.

Bisecting the issue I found that my code stopped working with commit
f21eab6

I deviced the following small test to illustrate the difference:

'use strict';
var assert = require('assert');
var dbus = require('dbus-native');

var sysbus = dbus.systemBus();
var service = sysbus.getService('org.freedesktop.NetworkManager');

service.getInterface('/org/freedesktop/NetworkManager', 'org.freedesktop.DBus.Properties', function(err, propIface) {
    assert.ifError(err);
    propIface.GetAll('org.freedesktop.NetworkManager', function(err, props) {
        assert.ifError(err);
        console.log(require('util').inspect(props, { depth: null }));
    });
});

With version 0.1.1 I get the following output:

[ [ 'Devices',
    [ [ '/org/freedesktop/NetworkManager/Devices/0',
        '/org/freedesktop/NetworkManager/Devices/1',
        '/org/freedesktop/NetworkManager/Devices/2',
        '/org/freedesktop/NetworkManager/Devices/4',
        '/org/freedesktop/NetworkManager/Devices/6',
        '/org/freedesktop/NetworkManager/Devices/7' ] ] ],
  [ 'NetworkingEnabled', [ true ] ],
  [ 'WirelessEnabled', [ true ] ],
  [ 'WirelessHardwareEnabled', [ true ] ],
  [ 'WwanEnabled', [ true ] ],
  [ 'WwanHardwareEnabled', [ true ] ],
  [ 'WimaxEnabled', [ true ] ],
  [ 'WimaxHardwareEnabled', [ true ] ],
  [ 'ActiveConnections',
    [ [ '/org/freedesktop/NetworkManager/ActiveConnection/23',
        '/org/freedesktop/NetworkManager/ActiveConnection/3',
        '/org/freedesktop/NetworkManager/ActiveConnection/2',
        '/org/freedesktop/NetworkManager/ActiveConnection/1',
        '/org/freedesktop/NetworkManager/ActiveConnection/0' ] ] ],
  [ 'PrimaryConnection',
    [ '/org/freedesktop/NetworkManager/ActiveConnection/1' ] ],
  [ 'ActivatingConnection', [ '/' ] ],
  [ 'Startup', [ false ] ],
  [ 'Version', [ '0.9.10.0' ] ],
  [ 'State', [ 70 ] ],
  [ 'Connectivity', [ 4 ] ] ]

While with version 0.1.2 I get the following:

[ [ 'Devices',
    [ [ { type: 'a', child: [ { type: 'o', child: [] } ] } ],
      [ [ '/org/freedesktop/NetworkManager/Devices/0',
          '/org/freedesktop/NetworkManager/Devices/1',
          '/org/freedesktop/NetworkManager/Devices/2',
          '/org/freedesktop/NetworkManager/Devices/4',
          '/org/freedesktop/NetworkManager/Devices/6',
          '/org/freedesktop/NetworkManager/Devices/7' ] ] ] ],
  [ 'NetworkingEnabled',
    [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'WirelessEnabled',
    [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'WirelessHardwareEnabled',
    [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'WwanEnabled', [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'WwanHardwareEnabled',
    [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'WimaxEnabled', [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'WimaxHardwareEnabled',
    [ [ { type: 'b', child: [] } ], [ true ] ] ],
  [ 'ActiveConnections',
    [ [ { type: 'a', child: [ { type: 'o', child: [] } ] } ],
      [ [ '/org/freedesktop/NetworkManager/ActiveConnection/23',
          '/org/freedesktop/NetworkManager/ActiveConnection/3',
          '/org/freedesktop/NetworkManager/ActiveConnection/2',
          '/org/freedesktop/NetworkManager/ActiveConnection/1',
          '/org/freedesktop/NetworkManager/ActiveConnection/0' ] ] ] ],
  [ 'PrimaryConnection',
    [ [ { type: 'o', child: [] } ],
      [ '/org/freedesktop/NetworkManager/ActiveConnection/1' ] ] ],
  [ 'ActivatingConnection',
    [ [ { type: 'o', child: [] } ], [ '/' ] ] ],
  [ 'Startup', [ [ { type: 'b', child: [] } ], [ false ] ] ],
  [ 'Version', [ [ { type: 's', child: [] } ], [ '0.9.10.0' ] ] ],
  [ 'State', [ [ { type: 'u', child: [] } ], [ 70 ] ] ],
  [ 'Connectivity', [ [ { type: 'u', child: [] } ], [ 4 ] ] ] ]

Obiously this is a breaking change, my question is if this is an intentional
API break or if I should consider it a bug?

If it is an intentional break I think we should add some documentation
detailing the new API.

Reading "Metadata" property from VLC

I have a problem with reading the "Metadata" property from VLC. I created a gist for easy reproduction of the bug:
https://gist.github.com/snaselj/5481155

The problem is probably somewhere in unmarshalling and is somehow related to (but not caused by) this patch:
1ae6ea5

With the patch, my gist script throws an exception. Without it, it display a result but not unmarshalled correctly.

Thanks.

Crash when connecting to non existing unix socket

Hi,
I am trying to find a way to handle errors when trying to connect to unix abstract socket that was not open yet. The error I am getting is

events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:901:11)
at Object.afterWrite (net.js:718:19)

Tried try{}/catch{} block but it doesn't work. I see, there is error listener on stream but for some reason it doesn't work. For now the only way to catch it is to add uncaughtException handler to nodejs process. Maybe you can provide better way. Thanks.

The code to reproduce:

var dbus = require('dbus-native');
var bus;
setInterval(function(){console.log("Still running.");}, 1000);

setTimeout(function(){
bus = dbus.createClient({
busAddress : 'unix:abstract=testconnection',
path : '/com/TestConnection'
});
bus.connection.on('error', function (err) {
console.log(err);
});
}, 1000);

D-Feet throws an exception when Introspecting

I am trying to create a d-bus service using example/service/server2.js as a guide. It mostly works, but I found when I use D-Feet to Introspect the service, it throws a DBus exception “GDBus.Error:org.freedesktop.DBus.Error.UnknownService: Uh oh oh (36)” I thought this might be an issue with my code, so I tried running ‘node ./server2.js’ right from the example/service directory and got the same exception from D-Feet.

After some debugging I found that this exception is thrown in bus.js inside the message event handler this.connection.on(‘message’, .... What appears to be happening is D-Feet is invoking the Introspect method with msg.path set to “/“, and this path is not found in the list of exportedObjects. It looks like D-Feet invokes the Introspect method multiple times at each level of the msg.path hierarchy. I.E. the first Introspect method has msg.path set to ‘/‘, the next has msg.path set to ‘/com’, then ‘/com/github’, ‘/com/github/sidorares’ and finally ‘/com/github/sidorares/1’. I found that if I move the call to stdDbusIfaces(msg, self) before the check to see if the msg.path is in the self.exportedObjects[] list, then D-Feet introspection works perfectly:

diff --git a/lib/bus.js b/lib/bus.js
index cc8f482..a0a31fe 100644
--- a/lib/bus.js
+++ b/lib/bus.js
@@ -118,13 +118,13 @@ module.exports = function bus(conn, opts) {
            self.signals.emit(self.mangle(msg), msg.body, msg.signature);
        } else { // methodCall

+           if (stdDbusIfaces(msg, self))
+               return;
+
            // exported interfaces handlers
            var obj, iface, impl;
            if (obj = self.exportedObjects[msg.path]) {

-               if (stdDbusIfaces(msg, self))
-                   return;
-
                if (iface = obj[msg['interface']]) {
                    // now we are ready to serve msg.member
                    impl = iface[1];

From looking at the stdifaces.js code, I don't think this will cause much of a problem--but of course you would know better than I. Let me know what you think.

Implement dbus-send command

I'm a newbie here and I would like to use your d-bus library. I wanted to implement the following call with node-dbus, but I couldn't get it to a successful run:

dbus-send --print-reply --type=method_call --bus='unix:path=/var/run/dbus/my_bus_socket' --dest='de.my.Device' '/de/my/Device/alarm' de.my.common.Alarm.get_alarm_state

Could you give me a hint on how to do it?

Thanks in advance!

Exception when calling undefined service

Stack trace:

/home/pi/app/node_modules/dbus-native/lib/bus.js:268
                callback(null, obj.as(ifaceName));
                                   ^
TypeError: Cannot call method 'as' of undefined
    at /home/pi/app/node_modules/dbus-native/lib/bus.js:268:36
    at /home/pi/app/node_modules/dbus-native/lib/bus.js:259:26
    at Object.<anonymous> (/home/pi/app/node_modules/dbus-native/lib/introspect.js:10:23)
    at EventEmitter.<anonymous> (/home/pi/app/node_modules/dbus-native/lib/bus.js:114:26)
    at EventEmitter.emit (events.js:95:17)
    at /home/pi/app/node_modules/dbus-native/lib/message.js:60:22
    at /home/pi/app/node_modules/dbus-native/lib/unmarshall.js:107:17
    at Object.<anonymous> (/home/pi/app/node_modules/dbus-native/lib/unmarshall.js:205:29)
    at Object.self.tap (/home/pi/app/node_modules/dbus-native/node_modules/binary/index.js:191:12)
    at Object.<anonymous> (/home/pi/app/node_modules/dbus-native/lib/unmarshall.js:196:38)

Code:

var bus = dbus.systemBus();
bus.getService('org.freedesktop.login1').getInterface(
    '/org/freedesktop/login1',
    'org.freedesktop.login1.Manager',
    function(err, manager){...}
);

This is from a call to org.freedesktop.login1.Manager which is not available on Raspbian. Uncommenting line 268 make it work as expected but I'm not sure whether on Arch where logind is available it will work or not.

I notice that the error handler in my callback is always fired correctly but the app crashes afterwards.

I notice that on line 267 the statement didn't call return and many places where similar statement is made there are no return. Is this expected?

Set properties with dbus-native

Is there some ways for me to use your dbus-native to set a Property in dbus?
And what's the signature of boolean?
I want to set the property WirelessEnabled in org.freedesktop.NetworkManager,I want to set it to false or ture.
Like the code:

var sysbus = require('dbus-native').systemBus();    
sysbus.invoke({
    path: '/org/freedesktop/NetworkManager',
    destination: 'org.freedesktop.NetworkManager',
    'interface': 'org.freedesktop.NetworkManager',
    member: 'SetPropertry',
    signature: '',     //what do I write here to set boolean?
    body: [
        'WirelessEnabled', [
            '',     //Boolean?
            [  //  Boolean?

            ]
        ]
    ],
    type: dbus.messageType.methodCall    //What do I write here?
}, function (err, res) {
    // etc...
});

What can I do?
Thanks

How to stop listening to signals

I am binding an event handler as followed

var screenSaver;
sessionBus.getService('org.gnome.ScreenSaver').getInterface(
    '/org/gnome/ScreenSaver',
    'org.gnome.ScreenSaver',
    function(err, _screenSaver) {
        screenSaver = _screenSaver;

        screenSaver.on('ActiveChanged', screenSaverActiveChange);
    }
);

Now after some time I want to unbind the screenSaverActiveChange event handler, so I tried,

screenSaver.removeListener('ActiveChanged', screenSaverActiveChange);

But it says,

removeListener not implemented for dbus signals

Now, what is the correct way to unbind this event handler? Is there any other way I can implement the similar thing?

start is not defined

I'm testing latest master 391b4d9 and i'm getting this

Uncaught Exception ReferenceError: start is not defined
    at DBusBuffer.readArray (/var/webide/node_modules/dbus-native/lib/dbuffer.js:148:30)
    at DBusBuffer.readTree (/var/webide/node_modules/dbus-native/lib/dbuffer.js:84:17)
    at DBusBuffer.readArray (/var/webide/node_modules/dbus-native/lib/dbuffer.js:159:22)
    at DBusBuffer.readTree (/var/webide/node_modules/dbus-native/lib/dbuffer.js:84:17)
    at DBusBuffer.readStruct (/var/webide/node_modules/dbus-native/lib/dbuffer.js:115:22)
    at DBusBuffer.read (/var/webide/node_modules/dbus-native/lib/dbuffer.js:96:15)
    at Socket.<anonymous> (/var/webide/node_modules/dbus-native/lib/message.js:49:40)

Profiling node-dbus

Hi Andrey,

I am trying to profile node-dbus by creating a v8.log and running the mocha test through node-tick-processor. I've got the output no problem, but trying to glean information out of the produced log is proving difficult.

Would you be able to help me understand where node-dbus is spending most of it's time?

Statistical profiling result from v8.log, (132 ticks, 0 unaccounted, 0 excluded).

[Shared libraries]:
ticks total nonlib name
82 62.1% 0.0% /usr/lib64/libv8.so.3.14.5
24 18.2% 0.0% /usr/bin/node
16 12.1% 0.0% /usr/lib64/libc-2.20.so
1 0.8% 0.0% /usr/lib64/libpthread-2.20.so

[JavaScript]:
ticks total nonlib name
1 0.8% 11.1% Stub: FastNewContextStub
1 0.8% 11.1% Stub: BinaryOpStub_SHR_Alloc_SMI
1 0.8% 11.1% RegExp: ^(/?|)([\s\S]?)((?:.{1,2}|[^\/]+?|)(.[^.\/]|))(?:[/]*)$
1 0.8% 11.1% LazyCompile: ~unmarshall /home/username/node-dbus/lib/message.js:61
1 0.8% 11.1% LazyCompile: ~toString native v8natives.js:223
1 0.8% 11.1% LazyCompile: test /home/username/node-dbus/test/unmarshall-basic.js:8
1 0.8% 11.1% LazyCompile: APPLY_PREPARE native runtime.js:438
1 0.8% 11.1% LazyCompile: *writeSimple /home/username/node-dbus/lib/marshall.js:107
1 0.8% 11.1% LazyCompile: *append _linklist.js:63

.... rest of file....

Documentation issues

I'm having trouble making use of this package; for example, how do I call a method and pass in arguments?

For example:

# method void org.freedesktop.NetworkManager.Enable(bool enable)
rrix@hobbes:~ ()
$ qdbus --system org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.NetworkManager.Enable true
Error: org.freedesktop.NetworkManager.AlreadyEnabledOrDisabled
Already enabled
var dbus = require('dbus-native');

var bus = dbus.systemBus();
bus.invoke({ 
  destination:  'org.freedesktop.NetworkManager',
  path:         '/org/freedesktop/NetworkManager',
  interface:    'org.freedesktop.NetworkManager',
  member:       'Enable',
  signature:    'b',
  body:         [true]
}, function() {
  console.log(arguments);
});

Simply exits without error or output. What would the syntax for a call like this look like? Can API.txt be expanded upon?

Trouble finding my service

I realize this problem might be due to my lack of familiarity with dbus, but I'm running into this:

error: The name com.latencyzero.podtique was not provided by any .service files

Here's my code:

var sessionBus = dbus.sessionBus();
var service = sessionBus.getService('com.latencyzero.podtique');
service.getInterface('/com/latencyzero/podtique',
                        'com.latencyzero.podtique',
                        function(err, notifications)
                        {
                            if (err)
                            {
                                console.log("dbus error: " + err);
                            }
                            else
                            {
                                notifications.on('RadioStatus', function()
                                {
                                    console.log('RadioStatus', arguments);
                                });
                            }
                        });

I don't have any .service files. My C++ code seems to be able to construct and send a message without error like this:

const char* kDestination                =   "com.latencyzero.podtique";
const char* kPath                       =   "/com/latencyzero/podtique";
const char* kInterface                  =   "com.latencyzero.podtique";
const char* kMethodRadioStatus          =   "RadioStatus";

DBus::Message msg(kDestination,
                    kPath,
                    kInterface,
                    kMethodRadioStatus);
msg.setNoReply(true);
msg.append(inOn);

bool success = send(msg);
if (!success)
{
    LogDebug("Unable to send message");
    return false;
}

return true;

(the C++ code is just a wrapper around the standard libdbus API dbus_message_new_method_call() and dbus_message_append_args() and dbus_connection_send().

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.