commit a3fca5bf05423e227ec3e327196210bde92506aa
parent e0bd7aec1ee35ad6ef8e30e18cd997b4f18f65ea
Author: Daniel Barlow <dan@telent.net>
Date: Sun, 26 May 2024 15:37:08 +0100
devout: add functions to read sysfs attributes
Diffstat:
2 files changed, 53 insertions(+), 2 deletions(-)
diff --git a/pkgs/devout/devout.fnl b/pkgs/devout/devout.fnl
@@ -1,3 +1,4 @@
+(local { : dirname } (require :anoia))
(local ll (require :lualinux))
(local {
: AF_LOCAL
@@ -145,6 +146,25 @@
:_tbl #(do fds) ;exposed for tests
}))
+(fn read-if-exists [pathname]
+ (match (ll.open pathname 0 0)
+ fd (let [s (ll.read fd 4096)
+ s1 (string.gsub s "[ \n]*(.-)[ \n]*" "%1")]
+ (ll.close fd)
+ s1)
+ nil nil))
+
+(fn sysfs [fspath]
+ {
+ :attr (fn [_ path name]
+ (read-if-exists (.. fspath "/" path "/" name)))
+ :attrs (fn [self path name]
+ (when path
+ (or (self:attr path name)
+ (self:attrs (dirname path) name))))
+ })
+
+
(fn run []
(let [[sockname nl-groups] arg
s (check-errno (unix-socket sockname))
@@ -170,4 +190,4 @@
(ll.poll pollfds 5000)
(loop:feed (unpack-pollfds pollfds))))))
-{ : database : run : event-loop : parse-event }
+{ : database : run : event-loop : parse-event : sysfs }
diff --git a/pkgs/devout/test.fnl b/pkgs/devout/test.fnl
@@ -1,4 +1,4 @@
-(local { : database : event-loop : parse-event } (require :devout))
+(local { : database : event-loop : parse-event : sysfs } (require :devout))
(local { : view } (require :fennel))
(local ll (require :lualinux))
(import-macros { : expect : expect= } :anoia.assert)
@@ -207,4 +207,35 @@ MINOR=17")
))
+;; tests for sysfs attrs
+
+(example
+ "read attributes from sysfs"
+ (let [sysfs (sysfs "./fixtures/sys")]
+ ;; finds attr at path
+ (expect=
+ (sysfs:attr "devices/pci0000:00/0000:00:14.0/usb1/1-2" "idVendor")
+ "1199")
+ ;; finds attr in ancestor directory
+ (expect=
+ (sysfs:attrs
+ "devices/pci0000:00/0000:00:14.0/usb1/1-7/1-7:1.0/bluetooth/hci0"
+ "idVendor")
+ "8087")
+ ;; nil if no attr
+ (expect=
+ (sysfs:attrs
+ "devices/pci0000:00/0000:00:14.0/usb1/1-7/1-7:1.0/bluetooth/hci0"
+ "idOfWizard")
+ nil)
+ ;; closer ancestor wins against more distant one
+ (expect=
+ (sysfs:attrs
+ "devices/pci0000:00/0000:00:14.0/usb1/1-7/1-7:1.0/bluetooth/hci0"
+ "modalias")
+ "usb:v8087p0A2Bd0001dcE0dsc01dp01icE0isc01ip01in00")))
+
+
+
+
(if failed (os.exit 1) (print "OK"))