]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/ac-power.c
relicense to LGPLv2.1 (with exceptions)
[thirdparty/systemd.git] / src / ac-power.c
CommitLineData
3d20ed6d
LP
1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
3d20ed6d
LP
11 (at your option) any later version.
12
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
5430f7f2 16 Lesser General Public License for more details.
3d20ed6d 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
3d20ed6d
LP
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
22#include <stdlib.h>
23#include <stdbool.h>
24#include <errno.h>
25#include <string.h>
26#include <libudev.h>
27
28#include "util.h"
3d20ed6d 29
06cdd248 30static int on_ac_power(void) {
3d20ed6d
LP
31 int r;
32
33 struct udev *udev;
34 struct udev_enumerate *e = NULL;
35 struct udev_list_entry *item = NULL, *first = NULL;
36 bool found_offline = false, found_online = false;
37
38 if (!(udev = udev_new())) {
39 r = -ENOMEM;
40 goto finish;
41 }
42
43 if (!(e = udev_enumerate_new(udev))) {
44 r = -ENOMEM;
45 goto finish;
46 }
47
48 if (udev_enumerate_add_match_subsystem(e, "power_supply") < 0) {
49 r = -EIO;
50 goto finish;
51 }
52
53 if (udev_enumerate_scan_devices(e) < 0) {
54 r = -EIO;
55 goto finish;
56 }
57
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;
62
63 if (!(d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item)))) {
64 r = -ENOMEM;
65 goto finish;
66 }
67
68 if (!(type = udev_device_get_sysattr_value(d, "type")))
69 goto next;
70
71 if (!streq(type, "Mains"))
72 goto next;
73
74 if (!(online = udev_device_get_sysattr_value(d, "online")))
75 goto next;
76
77 if (streq(online, "1")) {
78 found_online = true;
79 break;
80 } else if (streq(online, "0"))
81 found_offline = true;
82
83 next:
84 udev_device_unref(d);
85 }
86
87 r = found_online || !found_offline;
88
89finish:
90 if (e)
91 udev_enumerate_unref(e);
92
93 if (udev)
94 udev_unref(udev);
95
96 return r;
97}
06cdd248
LP
98
99int main(int argc, char *argv[]) {
100 int r;
101
102 /* This is mostly intended to be used for scripts which want
103 * to detect whether AC power is plugged in or not. */
104
105 if ((r = on_ac_power()) < 0) {
106 log_error("Failed to read AC status: %s", strerror(-r));
107 return EXIT_FAILURE;
108 }
109
110 return r == 0;
111}