@kairotic/io 0.0.0-stage → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,76 @@
1
+ ;; oscout · Kairotic events and messages as OSC, through a relay's bridge (SuperCollider, Max, Pd, TouchOSC…)
2
+ ;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.
3
+ (let [;; ── the bridge: one socket per address, shared by every osc box of the page ──
4
+ ;; A page cannot send UDP: the relay started with --osc does it (npx @kairotic/relay --osc).
5
+ default-url "ws://localhost:8765/osc"
6
+ relay-url (fn [] (or (try (.getItem js/localStorage "kairotic-osc-relay") (catch :default _ nil)) default-url))
7
+ socket (fn [url]
8
+ (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))
9
+ s (aget all url)]
10
+ (if (and s (< (.. s -ws -readyState) 2))
11
+ s
12
+ (let [ws (js/WebSocket. url)
13
+ s #js {:ws ws :listeners #js [] :queue #js []}]
14
+ (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))
15
+ (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]
16
+ (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))
17
+ (aset all url s)
18
+ s))))
19
+ send! (fn [url m] (let [s (socket url) ws (.-ws s) j (js/JSON.stringify (clj->js m))]
20
+ (if (= 1 (.-readyState ws)) (.send ws j) (.push (.-queue s) j))))
21
+ num (fn [x] (if (number? x) x 0))
22
+ ;; ── an event as OSC: /kairotic/<type> with its values in a fixed order, for a SynthDef or a Max patch ──
23
+ event->osc (fn [e]
24
+ (case (:type e)
25
+ :note {:address "/kairotic/note" :types "iffi" :args [(num (:id e)) (num (:freq e)) (num (or (:amp e) (when (:gate e) 0.8))) (if (:gate e) 1 0)]}
26
+ :glide {:address "/kairotic/glide" :types "if" :args [(num (:id e)) (num (:freq e))]}
27
+ :cc {:address "/kairotic/cc" :types "iif" :args [(num (:ch e)) (num (:cc e)) (num (:value e))]}
28
+ :pressure {:address "/kairotic/pressure" :types "if" :args [(num (:id e)) (num (:value e))]}
29
+ :tilt {:address "/kairotic/tilt" :types "ff" :args [(:x e) (:y e)]}
30
+ :shake {:address "/kairotic/shake" :types "f" :args [(:value e)]}
31
+ (:button :axis) {:address (str "/kairotic/pad/" (if (:name e) (name (:name e)) (str (if (= :axis (:type e)) "a" "b") (or (:axis e) (:button e)))))
32
+ :args (if (some? (:gate e)) [(:value e) (if (:gate e) 1 0)] [(:value e)])}
33
+ :serial (cond (:values e) {:address "/kairotic/serial" :args (vec (:values e))}
34
+ (number? (:value e)) {:address (str "/kairotic/serial/" (:key e)) :args [(:value e)]}
35
+ :else {:address "/kairotic/serial" :types "s" :args [(str (:text e))]})
36
+ (:clock :start :stop :continue) {:address (str "/kairotic/" (name (:type e))) :args []}
37
+ nil))
38
+ ;; a list that starts with an address: (/synth/freq 440) → /synth/freq 440
39
+ address? (fn [x] (let [s (cond (string? x) x (keyword? x) (str (when (namespace x) (str (namespace x) "/")) (name x)) (symbol? x) (str x))]
40
+ (when (and s (= "/" (subs s 0 1))) s)))
41
+ clean (fn [x] (cond (keyword? x) (name x) (or (number? x) (string? x) (boolean? x)) x :else (str x)))]
42
+ {;; ── about ──
43
+ :class "oscout"
44
+ :license "MPL-2.0"
45
+ :doc "OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \"ws://…\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶."
46
+ :usage "oscout [target]"
47
+ :io [1 0]
48
+ :size [96 30]
49
+ :args [[:target nil]]
50
+ :help {:inlets ["an event map, a list (address args…), or [:relay \"ws://…/osc\"]"]
51
+ :outlets []
52
+ :example "(box :b1 \"msg /kairotic/hello 1 2.5\" 40 30)\n(box :b2 \"oscout\" 40 80)\n(connect :b1 0 :b2 0)"
53
+ :try "Run npx @kairotic/relay --osc on this machine and click the message: SuperCollider (sclang, port 57120) receives /kairotic/hello 1 2.5."
54
+ :see ["oscin" "midiout"]}
55
+
56
+ ;; ── logic ──
57
+ :receive (fn [{:keys [value args]}]
58
+ (cond
59
+ (and (vector? value) (= :relay (first value)) (string? (second value)))
60
+ {:effects [[:relay (second value)]] :show {:label "relay set"}}
61
+ (and (map? value) (not= :osc (:src value)))
62
+ (if-let [m (event->osc value)]
63
+ {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}}
64
+ {})
65
+ (and (sequential? value) (address? (first value)))
66
+ (let [m {:address (address? (first value)) :args (mapv clean (rest value))}]
67
+ {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}})
68
+ :else {}))
69
+ ;; with or without ▶: OSC is a message, not a sound
70
+ :tasks {:osc (fn [m _] (send! (relay-url) m) (js/Promise.resolve true))
71
+ :relay (fn [url _] (try (.setItem js/localStorage "kairotic-osc-relay" url) (catch :default _ nil)) (js/Promise.resolve url))}
72
+
73
+ ;; ── view ──
74
+ :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str "oscout" (when (:target args) (str " " (name (:target args))))))})
75
+ :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]
76
+ [:text {:x 8 :y 19 :size 11} :$label]]})
@@ -0,0 +1,95 @@
1
+ ;; serial · a board on a serial port (an Arduino, an ESP32…): its lines of text as values and events
2
+ ;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.
3
+ (let [number-of (fn [s] (when (re-matches #"[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?" s) (js/parseFloat s)))
4
+ ;; a line: "512 300 1" (or with commas) → values; "pot:512 light=300" → one event per key; else text
5
+ line-events (fn [line]
6
+ (let [line (.trim line) ev (fn [m] (merge {:src :serial :type :serial} m))
7
+ words (remove empty? (.split line (js/RegExp. "[\\s,;]+")))]
8
+ (cond
9
+ (empty? line) []
10
+ (every? number-of words) [(ev {:values (mapv number-of words)})]
11
+ (every? #(re-matches #"[^:=]+[:=][^:=]+" %) words)
12
+ (vec (for [w words :let [[k v] (.split w (js/RegExp. "[:=]"))]]
13
+ (ev (if-let [n (number-of v)] {:key k :value n} {:key k :text v}))))
14
+ :else [(ev {:text line})])))
15
+ ;; text comes in pieces that do not respect lines: what follows the last newline waits for the next
16
+ chunk (fn [buf text]
17
+ (let [lines (.split (str buf text) (js/RegExp. "\\r?\\n"))
18
+ rest-buf (last lines)]
19
+ [(if (> (count rest-buf) 512) "" rest-buf) (vec (mapcat line-events (butlast lines)))]))]
20
+ {;; ── about ──
21
+ :class "serial"
22
+ :license "MPL-2.0"
23
+ :doc "A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\"512 300 1\", or with commas) go out as a list on the left; key:value pairs (\"pot:512 light=300\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \"pot\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \"open\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari."
24
+ :usage "serial [baud]"
25
+ :io [1 2]
26
+ :size [96 30]
27
+ :args [[:baud 115200]]
28
+ :help {:inlets [":open (asks for the port), :close, or a line to send to the board"]
29
+ :outlets ["the numbers of a line (a list), or [key value] for each key:value" "every line, as events"]
30
+ :example "(box :b1 \"msg :open\" 40 30)\n(box :b2 \"serial 9600\" 40 70)\n(box :b3 \"print\" 40 120)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)"
31
+ :try "Press ▶, click open and choose the board's port: what it prints arrives as numbers."
32
+ :see ["motion" "gamepad" "oscout"]}
33
+
34
+ ;; ── logic ──
35
+ :receive (fn [{:keys [inlet value state args]}]
36
+ (let [buf (or (:buf state) "")]
37
+ (cond
38
+ (and (= inlet :audio) (:error value)) {:state state :effects [[:print (:error value)]] :show {:label "no port"}}
39
+ (and (= inlet :audio) (:status value)) {:state state :show {:label (:status value)}}
40
+ (and (= inlet :audio) (string? (:text value)))
41
+ (let [[b2 es] (chunk buf (:text value))]
42
+ (cond-> {:state (assoc state :buf b2)
43
+ :out (vec (mapcat (fn [e] [(cond (:values e) [0 (:values e)]
44
+ (contains? e :value) [0 [(:key e) (:value e)]]
45
+ :else [0 (or (:text e) "")])
46
+ [1 e]])
47
+ es))
48
+ }
49
+ (seq es) (assoc :show {:label (let [e (last es)] (cond (:values e) (str (:values e)) (:key e) (str (:key e) " " (or (:value e) (:text e))) :else (:text e)))})))
50
+ (#{:open} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}
51
+ (#{:close} value) {:effects [[:close true]]}
52
+ (string? value) {:effects [[:write value]]}
53
+ (sequential? value) {:effects [[:write (apply str (interpose " " (map #(if (keyword? %) (name %) (str %)) value)))]]}
54
+ :else {})))
55
+
56
+ ;; ── view ──
57
+ :derive (fn [{:keys [shown]}] {:label (or (:label shown) "serial")})
58
+ :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]
59
+ [:text {:x 8 :y 19 :size 11} :$label]]
60
+
61
+ ;; ── outside: the port, while ▶ runs ──
62
+ :audio {:create (fn [_ b _] {:id (:id b) :port (atom nil) :writer (atom nil) :reader (atom nil) :alive (atom true) :inlets [] :outlets []})
63
+ :effects {:open (fn [node baud _]
64
+ (let [report (fn [v] (when @(:alive node) (api/report! (:id node) v nil)))]
65
+ (if-not (.-serial js/navigator)
66
+ (report {:error "serial: this browser has no Web Serial (Chrome, Edge or Firefox 151+)"})
67
+ (-> (.requestPort (.-serial js/navigator))
68
+ (.then (fn [port] (.then (.open port #js {:baudRate baud}) (fn [_] port))))
69
+ (.then (fn [port]
70
+ (reset! (:port node) port)
71
+ (reset! (:writer node) (.getWriter (.-writable port)))
72
+ (report {:status (str "open · " baud)})
73
+ (let [dec (js/TextDecoderStream.)
74
+ _ (.catch (.pipeTo (.-readable port) (.-writable dec)) (fn [_] nil))
75
+ reader (.getReader (.-readable dec))]
76
+ (reset! (:reader node) reader)
77
+ ((fn step []
78
+ (-> (.read reader)
79
+ (.then (fn [r] (if (.-done r)
80
+ (report {:status "closed"})
81
+ (do (report {:text (.-value r)}) (step)))))
82
+ (.catch (fn [_] (report {:status "closed"})))))))))
83
+ (.catch (fn [e] (report {:error (str "serial: " (.-message e))})))))))
84
+ :write (fn [node line _]
85
+ (when-let [w @(:writer node)] (.write w (.encode (js/TextEncoder.) (str line "\n")))))
86
+ :close (fn [node _ _]
87
+ (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))
88
+ (when-let [w @(:writer node)] (.releaseLock w))
89
+ (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50))
90
+ (reset! (:port node) nil) (reset! (:writer node) nil))}
91
+ :dispose (fn [node]
92
+ (reset! (:alive node) false)
93
+ (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))
94
+ (when-let [w @(:writer node)] (try (.releaseLock w) (catch :default _ nil)))
95
+ (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50)))}})