stevensonmt

stevensonmt

How to interact with D-Bus from an Elixir app?

Anyone have experience interacting with DBus from within an elixir app? I’m trying to think of the best way to make the app’s internal state available to other services and setting a DBus property seems like one way to do so. I just can’t find much information about doing so from within elixir/erlang.

Marked As Solved

cblavier

cblavier

We use dbus from elixir on our Elixir Nerves project (running on raspberry pi3).
We use it to control different omxplayer processes.

No special library involved, we have a DBusServer genserver managing the state of our daemon. We use the Elixir Port API to monitor its state

We start the daemon like this:

def start_daemon do
  cmd = "dbus-daemon --session --nofork --print-pid --print-address"
  port = Port.open({:spawn, cmd}, [:binary])

  receive do
    {^port, {:data, output}} -> {:ok, port, output}
  after
    @start_timeout -> :error
  end
end

we parse the command output with this code to extract its pid

defp parse_command_output(output) do
  pid_match = Regex.named_captures(~r/^(?<pid>\d+)$/m, output)
  address_match = Regex.named_captures(~r/^(?<address>unix:(path|abstract).*)$/m, output)
  pid = pid_match["pid"]
  address = address_match["address"]

  cond do
    pid && address -> {:ok, %{bus_pid: pid, bus_address: address}}
    address -> :pid_not_found
    true -> :error
  end
end

and interact with it like this

System.cmd(
  "dbus-send",
  [
    "--session",
    "--print-reply=literal",
    "--dest=#{dest}",
    object_name,
    action,
    message
  ],
  env: [
    {"DBUS_SESSION_BUS_ADDRESS", bus_address},
    {"DBUS_SESSION_BUS_PID", bus_pid}
  ]
)

Also Liked

stevensonmt

stevensonmt

Plan to update this thread with a more thorough breakdown when I wrap up the project but I just wanted to mention that in order to get the functionality out of dbus that I really wanted I had to break down and use Rustler to wrap dbus-rs bindings. The interaction can then be handled with busctl from scripts or from within the app using the dbus-rs calls. I’m sure there are other ways but this is the only workable solution I could find.

To anyone interested, I wanted to use the zbus crate instead of dbus-rs because the documentation on that crate is so good, but zbus is async first, so much that even the blocking API requires use of async. Async functions with Rustler were a layer of complexity beyond my current capacity.

tj0

tj0

BTW, regarding the comment from @cblavier , it looks like that they are starting their own dbus session on Nerves and then interacting with dbus-send. I think this is probably because they bring the system up from scratch.

If you are planning to run on Ubuntu for example, you can just use the already existing
DBUS_SESSION_BUS_ADDRESS in your environment.

Anyway, I’m not really sure what you’re trying to build, so just remember that if the session/user dbus environmental variable already exists, that is the one you probably want.

tj0

tj0

I haven’t done this in Erlang/Elixir, but I got smacked real bad once because there’s a difference between the system and session dbus.

Here are some notes in case you are unfamiliar.

There are two different dbus types. There is a “system” dbus which usually runs under /run/dbus/system_bus_socket (or some close by location) as user dbus and is typically not the source of problems.

However, there is generally confusion when a program doesn’t work. That’s becaues the [system] dbus is running, but the program can’t find [user] dbus.

The user dbus runs as your regular user account and does not have a well-known location to listen. Usually, programs needing the user-dbus will read the location from environmental variable DBUS_SESSION_BUS_ADDRESS.

Note you might think that launching your program with dbus-launch is a good idea because it will then easily find dbus. This thinking will get you in a world of hurt because now there will be three separate dbus interfaces running, none of which speak to the other.

Good luck in your quest. :crossed_fingers:

tj0

tj0

Yes, all the names are pretty random. I used emacs dbus interface to query and figure out what is happening on dbus. Also, a copious use of dbus-monitor to understand what events are being published.

For cli, I’ve used busctl:

$ busctl --user
NAME                                       PID PROCESS         USER    CONNECTION    UNIT SESSION DESCRIPTION
....
org.a11y.Bus                              1764 at-spi-bus-laun tj :1.9          -    -       -          
org.flatpak.Authenticator.Oci                - -               -       (activatable) -    -       -          
org.freedesktop.DBus                      1269 dbus-daemon     tj -             -    -       -          
org.freedesktop.Flatpak                   2433 flatpak-session tj :1.17         -    -       -          
org.freedesktop.Notifications             1822 dunst           tj :1.14         -    -       -          
org.freedesktop.network-manager-applet    1718 nm-applet       tj :1.10         c2   -       -          
org.freedesktop.portal.Flatpak               - -               -       (activatable) -    -       -          
org.gnome.keyring.PrivatePrompter            - -               -       (activatable) -    -       -          
org.gnome.keyring.SystemPrompter             - -               -       (activatable) -    -       -          
org.gtk.GLib.PACRunner                       - -               -       (activatable) -    -       -          
org.mozilla.firefox.ZGVmYXVsdC1yZWxlYXNl 17451 xdg-dbus-proxy  tj :1.820        c2   -       -          
org.mpris.MediaPlayer2.mpv                5750 mpv             tj :1.968        -    -       -          
org.mpris.MediaPlayer2.playerctld         1749 playerctld      tj :1.7          -    -       -          

Also, check out linux - A list of available D-Bus services - Unix & Linux Stack Exchange

There’s a few examples in python there also for interaction. Also qdbus and qdbusviewer as QT-based dbus tools. I’ve never used any of them as I couldn’t figure out the correct packages for my distro.

dimitarvp

dimitarvp

Well if you send more info I can try my hand at it.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement