Created
April 13, 2023 00:42
-
-
Save cmrigney/3d293ff79beb1907a14f1f1f52743e1e to your computer and use it in GitHub Desktop.
Forwards LoRa messages via web server. Written in my version of Lox. Runs on Pi Pico.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Forwards LoRa messages via web server. Written in my version of Lox. Runs on Pi Pico. | |
| var pico = systemImport("pico"); | |
| var lora = systemImport("lora_radio"); | |
| pico.LEDPin.on(); | |
| fun error(msg) { | |
| logln(msg); | |
| pico.LEDPin.off(); | |
| pico.exit(); | |
| } | |
| if(!pico.isW()) { | |
| error("Only works on W"); | |
| } | |
| // AP setup | |
| pico.createAP("MYAP", "MYPASSWORD"); | |
| // LoRa setup | |
| var ResetPinNum = 20; | |
| var InterruptPinNum = 21; | |
| var radio = lora.RF95(ResetPinNum, InterruptPinNum); | |
| if (!radio.isDetected()) { | |
| error("Radio not detected"); | |
| } | |
| logln("Radio detected"); | |
| radio.setTxPower(20); | |
| var messageId = 1; | |
| var receivedMessages = Array(); | |
| // Http server setup | |
| var server = pico.HTTPServer(8080); | |
| server.use("/mem", fun (req, res) { | |
| res.json(.{ | |
| vm: getMemStats(), | |
| pico: pico.getPicoStats() | |
| }); | |
| }); | |
| server.use("/messages", fun (req, res) { | |
| res.json(.{ messages: receivedMessages }); | |
| }); | |
| server.use("/clear", fun (req, res) { | |
| if(req.method != "POST") { | |
| return res.json(.{ error: "Only POST allowed" }).status(405); | |
| } | |
| receivedMessages = Array(); | |
| res.json(.{ messages: receivedMessages }); | |
| }); | |
| server.use("/send", fun (req, res) { | |
| if(req.method != "POST") { | |
| return res.json(.{ error: "Only POST allowed" }).status(405); | |
| } | |
| var body = req.json(); | |
| if(body == nil or body.message.length() >= 220) { | |
| return res.json(.{ error: "Invalid body" }).status(400); | |
| } | |
| radio.waitForPacketSent(); | |
| radio.send(Buffer(body.message)); | |
| res.json(.{ | |
| _id: messageId, | |
| message: body.message, | |
| createdAt: clock(), | |
| }); | |
| messageId = messageId + 1; | |
| }); | |
| logln("Listening on port 8080"); | |
| server.listen(true); | |
| while(true) { | |
| if(radio.available()) { | |
| receivedMessages.push(.{ | |
| _id: messageId, | |
| message: radio.recv().asString(), | |
| createdAt: clock(), | |
| }); | |
| messageId = messageId + 1; | |
| } | |
| server.poll(); | |
| pico.sleep(0.1); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment