summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/smart-relay.rtk48
-rwxr-xr-xsrc/smart-relay.sh5
2 files changed, 53 insertions, 0 deletions
diff --git a/src/smart-relay.rtk b/src/smart-relay.rtk
new file mode 100644
index 0000000..270780a
--- /dev/null
+++ b/src/smart-relay.rtk
@@ -0,0 +1,48 @@
1(module smart-relay racket/base
2 (require mqtt-client)
3 (provide main)
4
5 (define (make-send-to-dev data)
6 (lambda (dev)
7 (with-output-to-file dev
8 #:exists 'truncate
9 #:mode 'binary
10 (lambda ()
11 (write-bytes data)))))
12
13 (define send-message-on
14 (make-send-to-dev (bytes #xA0 #x01 #x01 #xA2)))
15 (define send-message-off
16 (make-send-to-dev (bytes #xA0 #x01 #x00 #xA1)))
17
18 (define (make-toggle-relay dev)
19 (let ((turn-on? #t))
20 (lambda ()
21 (displayln (format "Relay on ~a toggled" dev))
22 (if turn-on?
23 (send-message-on dev)
24 (send-message-off dev))
25 (set! turn-on? (not turn-on?)))))
26
27 (define (main #:host [host "localhost"]
28 #:username [username #f]
29 #:password [password #f]
30 #:client-name [client-name "smart-relay"]
31 #:topic-name [topic-name "hsp/bobma/smart-relay"]
32 #:relay-dev [relay-dev "/dev/ttyUSB0"])
33 (define toggle-relay (make-toggle-relay relay-dev))
34 (mqtt/with-client (host client-name)
35 (mqtt/with-connection (#:keep-alive-interval 20
36 #:clean-session #t
37 #:username username
38 #:password password)
39
40 (mqtt/subscribe topic-name)
41 (let loop ()
42 (mqtt/with-message-recv (topic payload)
43 (displayln (format "Message \"~a\" recieved on topic \"~a\"" payload topic))
44 (cond
45 ((string=? (bytes->string/utf-8 payload)
46 "toggle")
47 (toggle-relay))))
48 (loop))))))
diff --git a/src/smart-relay.sh b/src/smart-relay.sh
new file mode 100755
index 0000000..af5fa26
--- /dev/null
+++ b/src/smart-relay.sh
@@ -0,0 +1,5 @@
1#!/bin/sh
2
3raco pkg install mqtt-client
4racket -e "(begin (require (file \"smart-relay.rtk\")) (main $@))"
5