Subject: bug#24919: 24.5; battery.el not working in FreeBSD

From: Joakim Jalap <[email-masked]>
Date: Fri, 11 Nov 2016 18:58:39 +0100

Ignacio Torres <[email-masked]> writes:

> Running M-x battery in FreeBSD returns:
>
> Power disconnected, battery high (illegal% load, remaining time 0:00)
>
Here's a patch witch makes it return something else :)

Unfortunately I can't tets it on an actual laptop atm, but I /think/ it
might work.

-- Joakim

>From 8af54346db52ce1939632a60cac0cbd5c5f77063 Mon Sep 17 00:00:00 2001
From: Joakim Jalap <[email-masked]>
Date: Fri, 11 Nov 2016 18:00:22 +0100
Subject: [PATCH] Fix M-x battery on FreeBSD

	* lisp/battery.el (battery-bsd-apm): Fix to work with FreeBSD's apm(8)
---
 lisp/battery.el | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/lisp/battery.el b/lisp/battery.el
index e6e79b0..ddb0114 100644
--- a/lisp/battery.el
+++ b/lisp/battery.el
@@ -552,30 +552,40 @@ battery-bsd-apm
 %t Remaining battery charge time in the form `h:min'"
   (let* ((os-name (car (split-string
 			(shell-command-to-string "/usr/bin/uname"))))
-	 (apm-flag (if (equal os-name "OpenBSD") "P" "s"))
-	 (apm-cmd (concat "/usr/sbin/apm -ablm" apm-flag))
+         (os-freebsd (string= os-name "FreeBSD"))
+         (os-openbsd (string= os-name "OpenBSD"))
+         (battery-status-idx (if os-freebsd 1 0))
+         (percentage-idx (if os-freebsd 2 1))
+         (life-idx (if os-freebsd 4 2))
+         (line-status-idx (if os-freebsd 0 3))
+         (mode-idx (if os-freebsd 3 4))
+	 (apm-flags
+          (cond (os-freebsd "-ablts")
+                (os-openbsd "-ablmP")
+                (t "-ablms")))
+	 (apm-cmd (concat "/usr/sbin/apm " apm-flags))
 	 (apm-output (split-string (shell-command-to-string apm-cmd)))
 	 ;; Battery status
 	 (battery-status
-	  (let ((stat (string-to-number (nth 0 apm-output))))
+	  (let ((stat (string-to-number (nth battery-status-idx apm-output))))
 	    (cond ((eq stat 0) '("high" . ""))
 		  ((eq stat 1) '("low" . "-"))
 		  ((eq stat 2) '("critical" . "!"))
 		  ((eq stat 3) '("charging" . "+"))
 		  ((eq stat 4) '("absent" . nil)))))
 	 ;; Battery percentage
-	 (battery-percentage (nth 1 apm-output))
+	 (battery-percentage (nth percentage-idx apm-output))
 	 ;; Battery life
-	 (battery-life (nth 2 apm-output))
+	 (battery-life (nth life-idx apm-output))
 	 ;; AC status
 	 (line-status
-	  (let ((ac (string-to-number (nth 3 apm-output))))
+	  (let ((ac (string-to-number (nth line-status-idx apm-output))))
 	    (cond ((eq ac 0) "disconnected")
 		  ((eq ac 1) "connected")
 		  ((eq ac 2) "backup power"))))
 	 ;; Advanced power savings mode
 	 (apm-mode
-	  (let ((apm (string-to-number (nth 4 apm-output))))
+	  (let ((apm (string-to-number (nth mode-idx apm-output))))
 	    (if (string= os-name "OpenBSD")
 		(cond ((eq apm 0) "manual")
 		      ((eq apm 1) "automatic")
-- 
2.9.2