Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // control charging of battery on apple M1
- // tested on macbook pro 2021 model
- // works on linux
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <errno.h>
- #include <syslog.h>
- enum charge_mode {
- CHARGE_AUTO,
- CHARGE_INHIBIT_CHARGE,
- CHARGE_FORCE_DISCHARGE,
- };
- static const char *chargemodes[] = {
- "auto",
- "inhibit-charge",
- "force-discharge",
- };
- #define CAPACITY_FILE \
- "/sys/class/power_supply/macsmc-battery/capacity"
- #define CHARGE_BEHAVIOR_FILE \
- "/sys/class/power_supply/macsmc-battery/charge_behaviour"
- #define LOWER_CHARGE 70
- #define UPPER_CHARGE 90
- static enum charge_mode last_mode = -1;
- static void set_charge_mode(enum charge_mode mode)
- {
- char *logname = "charge-ctl";
- FILE *cb;
- if (mode == last_mode)
- return;
- cb = fopen(CHARGE_BEHAVIOR_FILE, "w");
- if (!cb) {
- perror("fopen");
- exit(EXIT_FAILURE);
- }
- fprintf(cb, "%s", chargemodes[mode]);
- fclose(cb);
- last_mode = mode;
- openlog(logname, LOG_PID, LOG_USER);
- syslog(LOG_USER | LOG_INFO, chargemodes[mode]);
- }
- int main(int argc, char **argv)
- {
- int option, limit = UPPER_CHARGE;
- pid_t pid, sid;
- while ((option = getopt(argc, argv, "l:uh")) != -1) {
- switch (option) {
- case 'h':
- puts("help");
- puts("-l limit capacity");
- exit(EXIT_SUCCESS);
- case 'l':
- limit = atoi(optarg);
- printf("limit: %d\n", limit);
- break;
- default: /* '?' */
- puts("unknown option");
- exit(EXIT_FAILURE);
- }
- }
- pid = fork();
- if (pid < 0)
- exit(EXIT_FAILURE);
- if (pid > 0)
- exit(EXIT_SUCCESS);
- umask(0);
- sid = setsid();
- if (sid < 0)
- exit(EXIT_FAILURE);
- if ((chdir("/")) < 0)
- exit(EXIT_FAILURE);
- close(STDIN_FILENO);
- close(STDOUT_FILENO);
- close(STDERR_FILENO);
- while (1) {
- FILE *capfile;
- char cap[6];
- int icap;
- capfile = fopen(CAPACITY_FILE, "r");
- fgets(cap, 5, capfile);
- fclose(capfile);
- icap = atoi(cap);
- if (icap < LOWER_CHARGE)
- set_charge_mode(CHARGE_AUTO);
- else if (icap > limit)
- set_charge_mode(CHARGE_FORCE_DISCHARGE);
- else
- set_charge_mode(CHARGE_INHIBIT_CHARGE);
- sleep(30);
- }
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement