I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-stream module for most of the video-related code. However, when attempting to access the web socket, I encounter a type error related to app.ws(...
, specifically stating
Property 'ws' does not exist on type 'Application'
. I've made sure to import the typings for both express and express-ws.
I'm somewhat confused as to why this problem is occurring, especially since the same call works fine in JavaScript. Here's the code snippet - any help would be greatly appreciated!
import express from 'express';
import { Request, Response } from 'express';
import fs from 'fs';
import https from 'https';
import http from 'http';
import raspividStream from 'raspivid-stream';
import expressWs from 'express-ws';
const server: express.Application = express();
const httpPort: number = 8080;
const httpsPort: number = 8443;
const sslCredentials = {
key: fs.readFileSync('../ssl/localhost.key', 'utf8'),
cert: fs.readFileSync('../ssl/localhost.cert', 'utf8')
};
// CREATE SERVER
const httpServer = http.createServer(server);
const httpsServer = https.createServer(sslCredentials, server);
expressWs(server, httpsServer);
// ROUTES
server.get('*', (req: Request, res:Response) => {
if (!req.secure) {
return res.redirect(`https://${req.hostname}:${httpsPort}${req.originalUrl}`);
}
res.sendFile(__dirname + '/client/index.html');
});
// WEBSOCKET
server.ws('/video-stream', (ws) => {
console.log('Client connected');
ws.send(JSON.stringify({
action: 'init',
width: '960',
height: '540'
}));
var videoStream = raspividStream({ rotation: 180 });
videoStream.on('data', (data) => {
ws.send(data, { binary: true }, (error) => { if (error) console.error(error); });
});
ws.on('close', () => {
console.log('Client left');
videoStream.removeAllListeners('data');
});
});
// START SERVER
httpServer.listen(httpPort, () => {
console.log(`BabyCam (redirect) listening at http://localhost:${httpPort}/`);
});
httpsServer.listen(httpsPort, () => {
console.log(`BabyCam (SSL) listening at https://localhost:${httpsPort}/`);
});