86 lines
2.8 KiB
TypeScript
86 lines
2.8 KiB
TypeScript
import * as http from "http";
|
|
import * as fs from "fs";
|
|
import * as path from "path";
|
|
import { ISensors } from "./io";
|
|
|
|
|
|
export default class HttpServer {
|
|
|
|
private httpServer: http.Server;
|
|
private port: number;
|
|
private root: string;
|
|
// public constructor(port: number, root: string, tune: (ch: string, adp?: number) => void, getChannels: ()=>string[], getSignal: (adapter:number)=>object) {
|
|
|
|
public constructor(port: number, root: string, getSensors: ()=>ISensors, setPower: (power: boolean) => void) {
|
|
this.port = port;
|
|
this.root = root;
|
|
this.httpServer = http.createServer((req, res) => {
|
|
let status: number = 404;
|
|
let body: any = "";
|
|
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
const pathname = path.normalize(url.pathname);
|
|
|
|
if (pathname.startsWith('/api/')) {
|
|
const query = pathname.split('/');
|
|
const api = query[2];
|
|
switch (req.method) {
|
|
case "GET":
|
|
switch (api) {
|
|
case "sensors":
|
|
body = JSON.stringify(getSensors());
|
|
status = 200;
|
|
break;
|
|
case "signal":
|
|
const adapter = parseInt(url.searchParams.get('adapter'));
|
|
// body = JSON.stringify(getSignal(adapter));
|
|
status = 200;
|
|
break;
|
|
|
|
}
|
|
break;
|
|
case "PUT":
|
|
switch (api) {
|
|
case "power":
|
|
const channel = decodeURIComponent(query[3]);
|
|
const adapter = parseInt(url.searchParams.get('adapter'));
|
|
// tune(channel, adapter);
|
|
status = 202;
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
}
|
|
else if (req.method === 'GET') {
|
|
const filePath = path.join(root, path.extname(pathname) === '' ? pathname + "/index.html" : pathname);
|
|
try {
|
|
body = fs.readFileSync(filePath);
|
|
status = 200;
|
|
}
|
|
catch (err) {
|
|
body = "Invalid File"
|
|
}
|
|
}
|
|
else {
|
|
body = "Invalid Request"
|
|
}
|
|
res.writeHead(status);
|
|
res.end(body);
|
|
|
|
});
|
|
}
|
|
public start() {
|
|
this.httpServer.listen(this.port, () => {
|
|
console.log(`Serving ${this.root} at http://localhost:${this.port}`);
|
|
});
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|