-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (91 loc) · 2.74 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import https from "@small-tech/https"
import express from "express"
import os from "os"
import * as socketIo from "socket.io"
import five from "johnny-five"
const app = express()
const hostname = "localhost"
const localIP = os
.networkInterfaces()
.en0.find((a) => a.family === "IPv4").address
// Set up socket server
const server = https.createServer(app)
const io = new socketIo.Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
transport: ["websocket"],
},
})
// 1. Socket Map
// We'll keep track of connected sockets as "subscribers"
const subscribers = new Map()
const subscribe = (id, socket) => {
if (subscribers.has(id)) {
console.log(
`Client with ID ${id} already connected. Disconnecting older client.`
)
unsubscribe(id)
}
subscribers.set(id, socket)
console.log(`Connected to ${id}.`)
}
const unsubscribe = (id) => {
subscribers.delete(id)
console.log(`Disconnected from ${id}.`)
}
// 2. Arduino
// Set up arduino light state and button listeners
const board = new five.Board({ repl: false })
board.on("ready", function () {
// Arduino ready to go
console.log("Board ready")
// Set up button on pin 7 and led on pin 3
const button = new five.Button(7)
const led = new five.Led(3)
// Led State
let isLedOn = false
// Notify all subscribers when Led changes
function emitLedStatus() {
console.log(`Led: ${isLedOn ? "On" : "Off"}`)
subscribers.forEach((socket) => socket.emit("status", { isLedOn }))
}
// Turn the Led on or off and update the state
function toggleLed() {
if (isLedOn) {
led.off()
isLedOn = false
} else {
led.on()
isLedOn = true
}
emitLedStatus()
}
// Listen for button presses to toggle the Led
button.on("press", () => {
toggleLed()
})
// Runs when each client connects to the socket server
io.on("connection", (socket) => {
console.log("Connection")
const { id = "DefaultSocket" } = socket.handshake.query
// Add subscriber for each new connection
subscribe(id, socket)
// Listener for "toggle" event from Framer
socket.on("toggle", () => {
toggleLed()
})
// Clean up when client disconnects
socket.on("disconnect", () => {
unsubscribe(id)
})
})
})
// Start up server and log addresses for local and network
const startServer = (port = 3000) => {
server.listen(port, "0.0.0.0", () => {
console.log(`Listening at https://${hostname}:${port}`)
if (localIP) console.log(`On Network at http://${localIP}:${port}`)
})
}
startServer()