1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
30 static int on_ac_power(void) {
34 struct udev_enumerate *e = NULL;
35 struct udev_list_entry *item = NULL, *first = NULL;
36 bool found_offline = false, found_online = false;
38 if (!(udev = udev_new())) {
43 if (!(e = udev_enumerate_new(udev))) {
48 if (udev_enumerate_add_match_subsystem(e, "power_supply") < 0) {
53 if (udev_enumerate_scan_devices(e) < 0) {
58 first = udev_enumerate_get_list_entry(e);
59 udev_list_entry_foreach(item, first) {
60 struct udev_device *d;
61 const char *type, *online;
63 if (!(d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item)))) {
68 if (!(type = udev_device_get_sysattr_value(d, "type")))
71 if (!streq(type, "Mains"))
74 if (!(online = udev_device_get_sysattr_value(d, "online")))
77 if (streq(online, "1")) {
80 } else if (streq(online, "0"))
87 r = found_online || !found_offline;
91 udev_enumerate_unref(e);
99 int main(int argc, char *argv[]) {
102 /* This is mostly intended to be used for scripts which want
103 * to detect whether AC power is plugged in or not. */
105 if ((r = on_ac_power()) < 0) {
106 log_error("Failed to read AC status: %s", strerror(-r));