Skip to content

Commit f7d1320

Browse files
committed
Host server
1 parent 6aff418 commit f7d1320

15 files changed

+1384
-2
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.DS_Store

README.md

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,15 @@
1-
# InteractiveDanceFloor
2-
A modular interactive LED dance floor
1+
# Interactive LED Dance Floor
2+
3+
The goal is to create a touch reactive LED dance floor that is easy to setup, teardown and transport.
4+
5+
Follow the development on my [Hackaday project page](https://hackaday.io/project/189052-next-gen-interactive-dance-floor).
6+
7+
This is the successor to the original [Interactive Disco Dance Floor](https://github.com/jgillick/DiscoDanceFloorV1)
8+
9+
# Navigation
10+
11+
This monorepo is broken up into these areas:
12+
13+
- Hardware - KiCad and Fusion360 files for the circuit boards and physical structure.
14+
- Host - The host software that controls the individual dance floor tiles.
15+
- Firmware - The LED & touch sensor firmware running inside each dance floor tile and communicating with the host.

host/.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
dist/*
2+
node_modules

host/Dockerfile

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
FROM node:18-alpine
2+
3+
# Install ngrok
4+
USER root
5+
RUN wget https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-arm64.tgz
6+
RUN tar xvzf ngrok-v3-stable-linux-arm64.tgz -C /usr/local/bin
7+
8+
# Run node
9+
USER node
10+
WORKDIR /app
11+
12+
RUN ngrok config add-authtoken 28iWb7VdAva2WRNquDKPfPeAz0c_4tcN42AhrrERLxvi1YM69
13+
14+
COPY --chown=node . .
15+
RUN yarn install
16+
17+
CMD ["yarn", "dev"]

host/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Host Software
2+
3+
This is the software that connects to all the floor tiles and controls what they do.

host/docker-compose.yml

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
version: '3'
2+
services:
3+
node:
4+
build:
5+
context: .
6+
dockerfile: Dockerfile
7+
container_name: node-container
8+
volumes:
9+
- ./src:/home
10+
ports:
11+
- 3000:3000
12+
command: sh -c 'yarn install & yarn dev'
13+
links:
14+
- "redis"
15+
redis:
16+
image: redis:latest
17+
restart: always
18+
container_name: redis-container
19+
volumes:
20+
- ./store/redis:/data
21+
ports:
22+
- "6379:6379"
23+
command: redis-server --appendonly yes

host/package.json

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "Server",
3+
"version": "1.0.0",
4+
"main": "dist/index.js",
5+
"scripts": {
6+
"dev": "yarn ts-node-dev --respawn --transpile-only ./src/index.ts",
7+
"ngrok": "ngrok http --scheme=http --region=us --hostname=jngillick.ngrok.io 8080",
8+
"tunnel": "lt --port 3000 --subdomain=jgillick"
9+
},
10+
"license": "MIT",
11+
"dependencies": {
12+
"dotenv": "^16.0.3",
13+
"express": "^4.18.2",
14+
"express-ws": "^5.0.2",
15+
"ioredis": "^5.2.5",
16+
"morgan": "^1.10.0",
17+
"semver": "^7.3.8",
18+
"typescript": "^4.9.4",
19+
"uuid": "^9.0.0",
20+
"ws": "^8.12.0"
21+
},
22+
"devDependencies": {
23+
"@types/express-ws": "^3.0.1",
24+
"@types/node": "^18.11.18",
25+
"@types/ws": "^8.5.4",
26+
"ts-node-dev": "^2.0.0"
27+
}
28+
}

host/src/index.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import * as dotenv from "dotenv";
2+
dotenv.config();
3+
4+
import httpServer from "./server";
5+
6+
httpServer();

host/src/server/firmware_upgrade.ts

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { Request, Response } from "express";
2+
import { promises as fs } from "fs";
3+
import path from "path";
4+
import semver from "semver";
5+
6+
const FIRMWARE_PATH = `/static/firmware.bin`;
7+
const VERSION_OFFSET = 48;
8+
const VERSION_LEN = 5;
9+
10+
/**
11+
* Read the firmware version from the file
12+
*/
13+
async function getFirmwareVersion(): Promise<string> {
14+
const filepath = path.join(__dirname, FIRMWARE_PATH);
15+
const buffer = Buffer.alloc(VERSION_LEN);
16+
17+
let fd;
18+
let version = "";
19+
try {
20+
fd = await fs.open(filepath, "r");
21+
await fd.read(buffer, 0, VERSION_LEN, VERSION_OFFSET);
22+
version = buffer.toString("utf8");
23+
} catch (err) {
24+
console.error(err);
25+
}
26+
if (fd) {
27+
fd.close();
28+
}
29+
return version;
30+
}
31+
32+
/**
33+
* GET route that compares the version query string to the latest firmware file.
34+
* If the version query is less than the latest firmware, it redirects to the firmware file.
35+
* Otherwise it returns status 200.
36+
*/
37+
export const getFirmware = async (req: Request, res: Response) => {
38+
const versionParam = req.query.version;
39+
const appVersion = await getFirmwareVersion();
40+
41+
const response = {
42+
appVersion,
43+
updateAvailable: 0,
44+
firmwarePath: FIRMWARE_PATH,
45+
};
46+
47+
if (!versionParam) {
48+
res.status(400).send("ERROR: Version query param required");
49+
} else if (!semver.valid(versionParam)) {
50+
res.status(400).send("ERROR: Invalid version string");
51+
} else {
52+
const updateAvailable =
53+
appVersion &&
54+
semver.valid(appVersion) &&
55+
semver.gt(appVersion, versionParam);
56+
response.updateAvailable = updateAvailable ? 1 : 0;
57+
58+
res.status(200).send(response);
59+
}
60+
};

host/src/server/index.ts

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import express from "express";
2+
import morgan from "morgan";
3+
import path from "path";
4+
5+
import { getFirmware } from "./firmware_upgrade";
6+
import { initWebSockets } from "./websockets";
7+
8+
const PORT = process.env.PORT || 3000;
9+
const STATIC_DIR = path.join(__dirname, "../../static");
10+
11+
export default function httpServer() {
12+
const app = express();
13+
14+
// Logging
15+
app.use(morgan("tiny"));
16+
17+
// Static file serving
18+
app.use("/static", express.static(path.join(__dirname, STATIC_DIR)));
19+
20+
// Routes
21+
app.get("/firmware", getFirmware);
22+
23+
// WebSocket
24+
initWebSockets(app);
25+
26+
// Start server
27+
app.listen(PORT, () => {
28+
console.log(`🚀 Server at localhost:${PORT}`);
29+
});
30+
}

host/src/server/websockets.ts

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { Express } from "express";
2+
import expressWs from "express-ws";
3+
import { WebSocket } from "ws";
4+
5+
let state = 0;
6+
7+
export function initWebSockets(app: Express) {
8+
const webservice = expressWs(app);
9+
10+
webservice.app.ws("/", (ws) => {
11+
// New client
12+
ws.send(String(state), { binary: false });
13+
14+
ws.on("message", (data) => {
15+
const msg = data.toString();
16+
console.log(`Received: ${msg}`);
17+
18+
if (msg == "toggle") {
19+
const toggled = state ? 0 : 1;
20+
console.log({ previous: state, new: toggled });
21+
22+
state = toggled;
23+
24+
const clients = webservice.getWss().clients;
25+
clients.forEach((client) => {
26+
if (client.readyState === WebSocket.OPEN) {
27+
client.send(String(state), { binary: false });
28+
}
29+
});
30+
}
31+
});
32+
});
33+
console.log("🔌 WebSockets started");
34+
}

host/static/firmware.bin

872 KB
Binary file not shown.

host/tsconfig.json

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig to read more about this file */
4+
5+
/* Projects */
6+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16+
// "jsx": "preserve", /* Specify what JSX code is generated. */
17+
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26+
27+
/* Modules */
28+
"module": "commonjs", /* Specify what module code is generated. */
29+
"rootDir": "./src", /* Specify the root folder within your source files. */
30+
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
31+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
36+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38+
// "resolveJsonModule": true, /* Enable importing .json files. */
39+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
40+
41+
/* JavaScript Support */
42+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45+
46+
/* Emit */
47+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
48+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
49+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52+
"outDir": "./dist", /* Specify an output folder for all emitted files. */
53+
// "removeComments": true, /* Disable emitting comments. */
54+
// "noEmit": true, /* Disable emitting files from a compilation. */
55+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
56+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
57+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
58+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
59+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
61+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
62+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
63+
// "newLine": "crlf", /* Set the newline character for emitting files. */
64+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
65+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
66+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
67+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
68+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
69+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
70+
71+
/* Interop Constraints */
72+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
75+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
77+
78+
/* Type Checking */
79+
"strict": true, /* Enable all strict type-checking options. */
80+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
81+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
82+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
83+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
84+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
85+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
86+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
87+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
88+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
89+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
90+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
91+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
92+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
93+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
94+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
95+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98+
99+
/* Completeness */
100+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
102+
}
103+
}

host/websocket_test.html

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8" />
5+
<title>NodeJS WebSocket Server</title>
6+
</head>
7+
<body>
8+
<button id="btn">Uknown</button>
9+
<script>
10+
const ws = new WebSocket("ws://localhost:3000");
11+
const btn = document.getElementById("btn");
12+
13+
ws.addEventListener("open", () => {
14+
console.log("We are connected");
15+
});
16+
17+
btn.addEventListener("click", () => {
18+
ws.send("toggle");
19+
});
20+
21+
ws.addEventListener("message", function (event) {
22+
const state = event.data;
23+
btn.innerHTML = state === "1" ? "ON" : "OFF";
24+
});
25+
</script>
26+
</body>
27+
</html>

0 commit comments

Comments
 (0)