.NET Core

D-Bus is a Linux message bus system. Many system daemons (like systemd, PulseAudio, bluez) and desktop services can be controlled via D-Bus. Some applications can be reached via the global system bus and others are on a per-user-login-session bus.

Higher-level bindings are available for various popular frameworks and languages. Tmds.DBus is a .NET implementation. The library is based on dbus-sharp/ndesk-dbus, which target Mono/.NET 2.0. Tmds.DBus leverages async/await (Task-based asynchronous pattern) introduced in .NET 4.5/C# 5.0. The library targets netstandard1.5 which means it runs on .NET 4.6.1+ and .NET Core 1.0+.

To use a D-Bus service, its functionality must be described as C# interfaces. Because this is a tedious and error-prone task, Tmds.DBus comes with a cli tool that does this for us. The tool queries the services and automatically generates the interface code. .NET Core 2.0 is needed as a development dependency to run the tool.

If you don't have .NET Core on your machine, you can find installation instructions at www.dot.net/core. Alternatively, on Fedora, you can install the DotNet SIG packages.

In this post, we will build a small application that writes a console message when a network interface changes state. To detect the state changes we use the NetworkManager daemon’s D-Bus service. We will perform the steps of code-generation and then enhance the generated code.

We start by using the dotnet cli to create a new console application:

$ dotnet new console -o netmon
$ cd netmon

Now we add references to Tmds.DBus and Tmds.DBus.Tool in netmon.csproj. We also set the LangVersion so we can use an async Main (C# 7.1).

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Tmds.DBus" Version="0.5.0" />
    <DotNetCliToolReference Include="Tmds.DBus.Tool" Version="0.5.0" />
  </ItemGroup>
</Project>

Now we restore to fetch these dependencies:

$ dotnet restore

Next, we use the list command to find out some information about the NetworkManager service. list services show the available services. Using list objects we can see the objects exposed by a service. The command prints the path of each object followed by the interfaces it implements.

$ dotnet dbus list services --bus system | grep NetworkManager
org.freedesktop.NetworkManager
$ dotnet dbus list objects --bus system --service org.freedesktop.NetworkManager | head -2
/org/freedesktop : org.freedesktop.DBus.ObjectManager
/org/freedesktop/NetworkManager : org.freedesktop.NetworkManager

The output of the commands show us the org.freedesktop.NetworkManager service is on the system bus and has an entry point object at /org/freedesktop/NetworkManager which implements org.freedesktop.NetworkManager.

Now we invoke the codegen command to generate C# interfaces for the NetworkManager service.

$ dotnet dbus codegen --bus system --service org.freedesktop.NetworkManager

This generates a NetworkManager.DBus.cs file in the local folder.

We update Program.cs to use an async Main and instantiate an INetworkManager proxy object. This proxy is created on Connection.System. This singleton makes it easy to share the same Connection throughout the application.

using System;
using Tmds.DBus;
using NetworkManager.DBus;
using System.Threading.Tasks;
namespace DBusExample
{
  class Program
  {
    static async Task Main(string[] args)
    {
      Console.WriteLine("Monitoring network state changes. Press Ctrl-C to stop.");
      var systemConnection = Connection.System;
      var networkManager = systemConnection.CreateProxy<INetworkManager>("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager");
      // TODO: watch state changes
      await Task.Delay(int.MaxValue);
    }
  }
}

When we look at the INetworkManager interface in NetworkManager.DBus.cs, we see it has a GetDevicesAsync method.

Task<ObjectPath[]> GetDevicesAsync();

This method is returning ObjectPath[]. These paths refer to other objects of the D-Bus service. We can use them with CreateProxy passing the IDevice type. But instead, we'll update the method to reflect it is returning IDevice objects.

Task<IDevice[]> GetDevicesAsync();

Now we can add the code to iterate over the devices and add a signal handler for the state change:

foreach (var device in await networkManager.GetDevicesAsync())
{
  var interfaceName = await device.GetInterfaceAsync();
  await device.WatchStateChangedAsync(
  change => Console.WriteLine($"{interfaceName}: {change.oldState} -> {change.newState}"));
}

When we run our program and change our network interfaces (e.g. turn on/off WiFi) notifications show up:

$ dotnet run
Press any key to close the application.
wlp4s0: 100 -> 20

If we look up the documentation of the StateChanged signal, we find the meaning of the magical constants: NMDeviceState.

We can model this enumeration in C#:

enum DeviceState : uint
{
  Unknown = 0,
  Unmanaged = 10,
  Unavailable = 20,
  Disconnected = 30,
  Prepare = 40,
  Config = 50,
  NeedAuth = 60,
  IpConfig = 70,
  IpCheck = 80,
  Secondaries = 90,
  Activated = 100,
  Deactivating = 110,
  Failed = 120
}

We add the enum to NetworkManager.DBus.cs and then update the signature of WatchStateChangedAsync so it uses DeviceState instead of uint.

Task<IDisposable> WatchStateChangedAsync(Action<(DeviceState newState, DeviceState oldState, uint reason)> action);

When we run our application again, we see more meaningful messages:

$ dotnet run
Press any key to close the application.
wlp4s0: Activated -> Unavailable

That finishes the example. We've covered the basic usage of Tmds.DBus and Tmds.DBus.Tool. To learn more about Tmds.DBus and D-Bus, check out the GitHub project and freedesktop.org website.

Last updated: February 6, 2024