From 92db1fdac315a471bfd7a619a7f4efb1684df25e Mon Sep 17 00:00:00 2001 From: jdlugosz963 Date: Sat, 27 Jul 2024 20:43:21 +0200 Subject: Initial commit. --- src/smart-relay.rtk | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ src/smart-relay.sh | 5 +++++ 2 files changed, 53 insertions(+) create mode 100644 src/smart-relay.rtk create mode 100755 src/smart-relay.sh (limited to 'src') 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 @@ +(module smart-relay racket/base + (require mqtt-client) + (provide main) + + (define (make-send-to-dev data) + (lambda (dev) + (with-output-to-file dev + #:exists 'truncate + #:mode 'binary + (lambda () + (write-bytes data))))) + + (define send-message-on + (make-send-to-dev (bytes #xA0 #x01 #x01 #xA2))) + (define send-message-off + (make-send-to-dev (bytes #xA0 #x01 #x00 #xA1))) + + (define (make-toggle-relay dev) + (let ((turn-on? #t)) + (lambda () + (displayln (format "Relay on ~a toggled" dev)) + (if turn-on? + (send-message-on dev) + (send-message-off dev)) + (set! turn-on? (not turn-on?))))) + + (define (main #:host [host "localhost"] + #:username [username #f] + #:password [password #f] + #:client-name [client-name "smart-relay"] + #:topic-name [topic-name "hsp/bobma/smart-relay"] + #:relay-dev [relay-dev "/dev/ttyUSB0"]) + (define toggle-relay (make-toggle-relay relay-dev)) + (mqtt/with-client (host client-name) + (mqtt/with-connection (#:keep-alive-interval 20 + #:clean-session #t + #:username username + #:password password) + + (mqtt/subscribe topic-name) + (let loop () + (mqtt/with-message-recv (topic payload) + (displayln (format "Message \"~a\" recieved on topic \"~a\"" payload topic)) + (cond + ((string=? (bytes->string/utf-8 payload) + "toggle") + (toggle-relay)))) + (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 @@ +#!/bin/sh + +raco pkg install mqtt-client +racket -e "(begin (require (file \"smart-relay.rtk\")) (main $@))" + -- cgit v1.2.3