More features in the HTTP server (#16)

* Added more features to HTTP server

* Added a title to the multi-camera view page.
* Support naming cameras through a simple mapping using a text file.
* Updated some logging messages to be more verbose (and match those in pair.ts).
* Confirmed the charging status and battery level values reported back by DevStatusAck.
* Log camera status (charging, battery, Wifi strength) when connected.

* More updates to HTTP server

* Deal with Web Audio autoplay policy by starting camera on mute and adding a button to toggle the audio stream.
* Add a favicon so the server tan can be easily spotted.

The favicon file is a 48x48 32bpp ICO file, gzipped.

* Update README.md

* Describe flags and enable camera audio by default.

* Update audio button based on state change

* Update description of discovery_ip in bin.ts

* Update session start message in http_server.ts

* Update README.md

Update flags and note about --discovery_ip.
This commit is contained in:
Adriano Cunha
2024-04-30 16:18:10 +02:00
committed by GitHub
parent 66796267f2
commit 690c1b4146
8 changed files with 181 additions and 68 deletions
+15 -9
View File
@@ -24,12 +24,14 @@ configure a camera
Options:
--help Show help [boolean]
--version Show version number [boolean]
--debug [boolean] [default: false]
--debug Log debug messages [boolean] [default: false]
--ansi [boolean] [default: false]
--discovery_ip [default: "192.168.1.255"]
--discovery_ip Camera discovery IP address
[default: "192.168.1.255"]
--attempt_to_fix_packet_loss [default: false]
--ssid [string] [required]
--password [string] [required]
--ssid Wifi network for the camera to connect to
[string] [required]
--password Wifi network password [string] [required]
```
## Running
@@ -44,10 +46,12 @@ start http server
Options:
--help Show help [boolean]
--version Show version number [boolean]
--debug [boolean] [default: false]
--debug Log debug messages [boolean] [default: false]
--ansi [boolean] [default: false]
--audio [boolean] [default: false]
--discovery_ip [default: "192.168.1.255"]
--audio Also stream audio from camera
[boolean] [default: true]
--discovery_ip Camera discovery IP address
[default: "192.168.1.255"]
--attempt_to_fix_packet_loss [default: false]
--port HTTP Port to listen on [number] [default: 5000]
```
@@ -58,9 +62,11 @@ There's a basic UI which can display multiple cameras:
![](pics/web-ui.jpg?raw=true)
The server will send a broadcast packet every few seconds to discover all the cameras available; this means that it *must* run in the same broadcast domain (VLAN) as your cameras.
The server will send a broadcast packet every few seconds to discover all the cameras available; this means that it *must* run in the same broadcast domain (VLAN) as your cameras. For debugging purposes, you can send the packets to a specific camera by setting `--discovery_ip` to its IP address.
Clicking on the image will take you to a page that has audio streaming enabled.
Clicking on the image will take you to a page that has audio streaming. Click the button below the image to mute/unmute the audio.
To customize the camera names, edit the file `cameras.txt` and add the names of your cameras, one per line, in the format `CAMERA_ID=descriptive name` (you must restart the HTTP server for the changes to take effect).
## Protocol
+79 -27
View File
@@ -1,40 +1,72 @@
<html>
<h2>${id}</h2><a href="/camera/${id}"><img src="/camera/${id}"/></a><hr/>
<head>
<link rel="shortcut icon" href="/favicon.ico">
<title>${name}</title>
</head><body>
<h2>${name}</h2><a href="/camera/${id}"><img src="/camera/${id}"/></a><hr/>
<button onclick="toggle_audio()" id=audio disabled=true>Audio: disabled</button>
<script>
const alaw_to_s16_table = [
-5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752,
-2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016,
-20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160,
-27136, -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544,
-14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88,
-72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120,
-1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624,
-592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296,
8064, 7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264,
3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088,
28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080,
13568, 344, 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56,
40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952,
1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848,
];
const alaw_to_s16_table = [
-5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752,
-2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016,
-20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160,
-27136, -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544,
-14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88,
-72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120,
-1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624,
-592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296,
8064, 7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264,
3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088,
28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080,
13568, 344, 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56,
40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952,
1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848,
];
const alaw_to_s16 = (a_val) => {
return alaw_to_s16_table[a_val];
};
const alaw_to_s16 = (a_val) => {
return alaw_to_s16_table[a_val];
};
const audio_context = new AudioContext();
var audio_context;
const audio_button = document.getElementById('audio');
audio_button.disabled = !${audio};
update_audio_button();
function console_log(s) {
if (!${debug}) {
return;
}
let m = "";
for (let i = 0; i < arguments.length; i++) {
m += arguments[i];
}
console.log(m);
}
function setup_audio() {
audio_context = new AudioContext();
const gain_node = audio_context.createGain(); // Declare gain node
const channels =1;
const sample_rate = 8000;
const audioBuffer = audio_context.createBuffer(channels, 960, sample_rate); // 960??
//const audioBuffer = audio_context.createBuffer(channels, decoded.length, sample_rate);
gain_node.connect(audio_context.destination); // Connect gain node to speakers
audio_context.onstatechange = () => {
console_log("Audio state is now ", audio_context.state);
update_audio_button(audio_context.state == "running");
};
gain_node.connect(audio_context.destination); // Connect gain node to speakers
audio_context.resume();
const evtSource = new EventSource('/audio/${id}');
evtSource.onopen = (e) => {
console.log("evtsource open");
const evtSource = new EventSource("/audio/${id}");
if (${debug}) {
evtSource.onopen = (e) => {
console_log("evtsource open");
}
evtSource.onerror = (e) => {
console_log("evtsource error", e);
}
}
let endsAt = 0;
let startAt = 0;
@@ -55,8 +87,28 @@
source_node.start(startAt);
endsAt = now + audioBuffer.duration * 1000;
};
evtSource.onerror = (e) => {
console.log("evtsource error", e);
}
function update_audio_button(on) {
if (${audio}) {
audio_button.innerText = "Audio: " + (on ? "on \u{1F508}" : "off \u{1F507}");
}
}
function toggle_audio() {
if (audio_context == undefined) {
setup_audio();
return;
}
if (audio_context.state == "running") {
audio_context.suspend();
return;
}
if (audio_context.state == "suspended") {
audio_context.resume();
return;
}
console_log("Unknown audio stream status");
}
</script>
</html>
BIN
View File
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
# This is a simple name mapping for cameras, in the form
#
# CAMERA_ID=descriptive name
#
# Blank lines and lines starting with "#" are ignored.
#
# Any updates to this file require restarting the HTTP server.
# This file is meant to be updated manually, it is NOT updated dynamically.
FTYC811847AGFDZ=Office camera
+8 -7
View File
@@ -11,11 +11,11 @@ yargs(hideBin(process.argv))
"start http server",
(yargs) => {
return yargs
.option("debug", { default: false })
.option("debug", { describe: "Log debug messages", default: false })
.option("ansi", { default: false })
.option("audio", { default: false })
.option("audio", { describe: "Also stream audio from camera", default: true })
.boolean(["debug", "ansi", "audio"])
.option("discovery_ip", { default: "192.168.1.255" })
.option("discovery_ip", { describe: "Camera discovery IP address", default: "192.168.1.255" })
.option("attempt_to_fix_packet_loss", { default: false })
.option("port", { describe: "HTTP Port to listen on", default: 5000 })
.number(["port"])
@@ -31,13 +31,14 @@ yargs(hideBin(process.argv))
"configure a camera",
(yargs) => {
return yargs
.option("debug", { default: false })
.option("debug", { describe: "Log debug messages", default: false })
.option("ansi", { default: false })
.boolean(["debug", "ansi"])
.option("discovery_ip", { default: "192.168.1.255" })
.option("discovery_ip", { describe: "Camera discovery IP address", default: "192.168.1.255" })
.option("attempt_to_fix_packet_loss", { default: false })
.demandOption("ssid")
.demandOption("password")
.option("ssid", { describe: "Wifi network for the camera to connect to" })
.option("password", { describe: "Wifi network password" })
.demandOption(["ssid", "password"])
.string(["ssid", "password"]);
},
(argv) => {
+4 -4
View File
@@ -68,12 +68,12 @@ export const createResponseForControlCommand = (session: Session, dv: DataView):
if (cmd_id == ControlCommands.DevStatusAck) {
// ParseDevStatus -> offset relevant?
let charging = u32_swap(dv.add(0x28).readU32()) & 1; // 0x14000101 v 0x14000100
let power = u16_swap(dv.add(0x18).readU16()); // '3730' or '3765', milliVolts?
let charging = u32_swap(dv.add(0x28).readU32()) & 1 ? "" : "not "; // 0x14000101 v 0x14000100
let power = u16_swap(dv.add(0x18).readU16()); // '3730' or '3765', milliVolts
let dbm = dv.add(0x24).readU8() - 0x100; // 0xbf - 0x100 = -65dbm .. constant??
// > -50 = excellent, -50 to -60 good, -60 to -70 fair, <-70 weak
console.log(`charging? ${charging}, batlevel? ${power}, wifi dbm: ${dbm}`);
console.log(`Camera ${session.devName}: ${charging}charging, battery at ${power/1000}V, Wifi ${dbm} dBm`);
}
if (cmd_id == ControlCommands.WifiSettingsAck) {
@@ -93,7 +93,7 @@ export const createResponseForControlCommand = (session: Session, dv: DataView):
dns2: dv.add(0x10c).readString(0x10),
};
const buf = SendListWifi(session);
console.log(`Current wifi settings: ${JSON.stringify(wifiSettings, null, 2)}`);
console.log(`Current Wifi settings: ${JSON.stringify(wifiSettings, null, 2)}`);
return [buf];
}
+63 -19
View File
@@ -1,17 +1,35 @@
import { RemoteInfo } from "dgram";
import { readFileSync } from "node:fs";
import { readFileSync, existsSync } from "node:fs";
import http from "node:http";
import { opt } from "./options.js";
import { discoverDevices } from "./discovery.js";
import { DevSerial } from "./impl.js";
import { DevSerial, SendDevStatus } from "./impl.js";
import { Handlers, makeSession, Session, startVideoStream } from "./session.js";
let BOUNDARY = "a very good boundary line";
let responses: Record<string, http.ServerResponse[]> = {};
let audioResponses: Record<string, http.ServerResponse[]> = {};
let sessions: Record<string, Session> = {};
const BOUNDARY = "a very good boundary line";
const responses: Record<string, http.ServerResponse[]> = {};
const audioResponses: Record<string, http.ServerResponse[]> = {};
const sessions: Record<string, Session> = {};
// Text file containing the mapping of camera names.
const nameFile = "cameras.txt";
// Reads the simple mapping of camera names from the text file.
const cameraNames = Object.assign({},
...(existsSync(nameFile) ? readFileSync(nameFile, "utf8") : "").toString()
.replace(/\r\n/g, "\n").split("\n")
.filter(l => !l.startsWith("#"))
.filter(l => l.trim() != "")
.map(l => { let kv = l.split("="); return ({ [kv[0]]: kv[1] }); }));
// Returns the camera name (custom name, if it exists, otherwise its ID).
const cameraName = (id: string): string => cameraNames[id] || id;
// Page's favicon.
const favicon = readFileSync("cam.ico.gz");
// The HTTP server.
export const serveHttp = (opts: opt, port: number, with_audio: boolean) => {
const server = http.createServer((req, res) => {
if (req.url.startsWith("/ui/")) {
@@ -27,8 +45,12 @@ export const serveHttp = (opts: opt, port: number, with_audio: boolean) => {
res.end("Nothing online");
return;
}
const ui = readFileSync("asd.html").toString();
res.end(ui.replace(/\${id}/g, devId));
const ui = readFileSync("asd.html").toString()
.replace(/\${id}/g, devId)
.replace(/\${name}/g, cameraName(devId))
.replace(/\${audio}/g, with_audio.toString())
.replace(/\${debug}/g, opts.debug.toString());
res.end(ui);
return;
}
if (req.url.startsWith("/audio/")) {
@@ -46,22 +68,30 @@ export const serveHttp = (opts: opt, port: number, with_audio: boolean) => {
}
res.setHeader("Content-Type", `text/event-stream`);
audioResponses[devId].push(res);
console.log(`Audio stream requested for camera ${devId}`);
return;
}
if (req.url.startsWith("/favicon.ico")) {
res.setHeader("Content-Type", "image/x-icon");
res.setHeader("Content-Encoding", "gzip");
res.end(favicon);
return;
}
if (req.url.startsWith("/camera/")) {
let devId = req.url.split("/")[2];
console.log("requested for", devId);
console.log(`Video stream requested for camera ${devId}`);
let s = sessions[devId];
if (s === undefined) {
res.writeHead(400);
res.end("invalid ID");
res.end(`Camera ${devId} not discovered`);
return;
}
if (!s.connected) {
res.writeHead(400);
res.end("Nothing online");
res.end(`Camera ${devId} offline`);
return;
}
@@ -69,29 +99,43 @@ export const serveHttp = (opts: opt, port: number, with_audio: boolean) => {
responses[devId].push(res);
res.on("close", () => {
responses[devId] = responses[devId].filter((r) => r !== res);
console.log("Conn closed, kicked");
console.log(`Video stream closed for camera ${devId}`);
});
} else {
res.write(`<html>`);
res.write("<html>");
res.write("<head>");
res.write(`<link rel="shortcut icon" href="/favicon.ico">`);
res.write("<title>All cameras</title>");
res.write("</head>");
res.write("<body>");
res.write("<h1>All cameras</h1><hr/>");
Object.keys(sessions).forEach((id) =>
res.write(`<h2>${id}</h2><a href="/ui/${id}"><img src="/camera/${id}"/></a><hr/>`),
res.write(`<h2>${cameraName(id)}</h2><a href="/ui/${id}"><img src="/camera/${id}"/></a><hr/>`),
);
res.write(`</html>`);
res.write("</body>");
res.write("</html>");
res.end();
}
});
let devEv = discoverDevices(opts.debug, opts.discovery_ip);
const startSession = (s: Session) => {
s.send(SendDevStatus(s));
startVideoStream(s);
console.log(`Camera ${s.devName} is now ready to stream`);
}
devEv.on("discover", (rinfo: RemoteInfo, dev: DevSerial) => {
if (dev.devId in sessions) {
console.log(`ignoring ${dev.devId} - ${rinfo.address}`);
console.log(`Camera ${dev.devId} at ${rinfo.address} already discovered, ignoring`);
return;
}
console.log(`discovered ${dev.devId} - ${rinfo.address}`);
console.log(`Discovered camera ${dev.devId} at ${rinfo.address}`);
responses[dev.devId] = [];
audioResponses[dev.devId] = [];
const s = makeSession(Handlers, dev, rinfo, startVideoStream, opts);
const s = makeSession(Handlers, dev, rinfo, startSession, opts);
const header = Buffer.from(`--${BOUNDARY}\r\nContent-Type: image/jpeg\r\n\r\n`);
@@ -105,7 +149,7 @@ export const serveHttp = (opts: opt, port: number, with_audio: boolean) => {
});
s.eventEmitter.on("disconnect", () => {
console.log("deleting from sessions");
console.log(`Camera ${dev.devId} disconnected`);
delete sessions[dev.devId];
});
if (with_audio) {
+2 -2
View File
@@ -107,7 +107,7 @@ export const makeSession = (
};
session.eventEmitter.on("disconnect", () => {
console.log(`Disconnected from ${session.devName} - ${session.dst_ip}`);
console.log(`Disconnected from camera ${session.devName} at ${session.dst_ip}`);
session.dst_ip = "0.0.0.0";
session.connected = false;
session.timers.forEach((x) => clearInterval(x));
@@ -115,7 +115,7 @@ export const makeSession = (
});
session.eventEmitter.on("login", () => {
console.log(`Logged in - ${session.devName}`);
console.log(`Logging in to camera ${session.devName}`);
onLogin(session);
});
return session;