No notification with my program started with systemd

167 Views Asked by At

I develop a small program in Python3 to test the level of my battery and send a notification when it exceeds a threshold.

This my code:

#!/usr/bin/env python3

import configparser, signal
from subprocess import run
from sys import exit
from time import sleep
from gi.repository import Gio

CHARGE_NOW = "/sys/class/power_supply/BAT0/charge_now"
CHARGE_FULL = "/sys/class/power_supply/BAT0/charge_full"

#####
## Load configuration file
configfile = "./check_battery.conf"
try:
    cfg = configparser.ConfigParser()
    cfg.read(configfile)
except FileNotFoundError:
    print("No found configuration file")
    exit(1)
except:
    print("Error to load configuration file")
    exit(1)

def notification(text):
    Application=Gio.Application.new ("check.battery", Gio.ApplicationFlags.FLAGS_NONE);
    Application.register ();
    Notification=Gio.Notification.new ("BATTERY");
    Notification.set_body (text);
    Icon=Gio.ThemedIcon.new ("dialog-information");
    Notification.set_icon (Icon);
    Application.send_notification (None, Notification);

def readSysFile(file_path):
    with open(file_path, "r") as fp:
        return fp.read()

def readPercBat():
    return int(100 * int(readSysFile(CHARGE_NOW)) / int(readSysFile(CHARGE_FULL)))

def mainloop():
    delay = int(cfg['BAT']['refresh'])
    perc_to_warning = int(cfg['BAT']['perc_to_warning'])
    perc_to_shutdown = int(cfg['BAT']['perc_to_shutdown'])
    while True:
        if readPercBat() <= perc_to_warning \
        and readPercBat() > perc_to_shutdown:
            notification("Battery is low")
            perc_to_warning = readPercBat() - int(cfg['BAT']['step_after_warning'])
        elif readPercBat() <= perc_to_shutdown:
            notification("Shutdown now")
            run(["shutdown", "now"])
        sleep(int(cfg['BAT']['refresh']))

def quit(signal, frame):
    exit(0)
signal.signal(signal.SIGINT, quit)
signal.signal(signal.SIGTERM, quit)


if __name__ == "__main__":
    mainloop()


# vim: ft=python ts=8 et sw=4 sts=4

When I run in local, it's OK. I created a script .service for systemd to start it when I logged in my session.

This my script .service:

[Unit]
Description=Test l état de la batterie et ouvre une fenêtre quand elle est trop basse
After=graphical.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/check_battery.py
ExecReload=/usr/bin/kill -HUP $MAINPID
PIDFile=/var/run/check_battery.pid
Restart=on-failure
User=romain

[Install]
WantedBy=graphical.target


# vim: ft=systemd

It's okay, I can start without a problem. As soon as he sends a notification, it doesn't display and I have those errors:

g_dbus_connection_signal_subscribe: assertion 'G_IS1_DBUS_CONNECTION (connection)' failed
g_dbus_connection_call_internal: assertion 'G_IS_DBUS_CONNECTION (connection)' failed

I don't know how to solve my problem, an idea?

0

There are 0 best solutions below