UNPKG

@komponent/unifi-protect-lib

Version:

Node library for connecting to Ubiquiti Unifi Protect controllers and listen for events

101 lines (78 loc) 2.78 kB
# unifi-protect-lib A Node library for connection to Unifi Protect controllers and listen for events. ## Notice > A lot of this code has been taken from the excellent https://github.com/hjdhjd/homebridge-unifi-protect repository. > However, since that code is geared towards Homebridge, I have created this library with a subset of those functions, in addition to some refactoring to make it easier to use in standalone apps. > Please note that this library is not feature complete, it only contains functionality for connecting to, and listening to events from a controller. ## Getting started ```typescript import { UnifiApiClient, UnifiCameraHandler, UnifiImageHandler, ConsoleLogger, } from "@komponent/unifi-protect-lib"; let retries = 0; const start = async () => { try { const apiClient = new UnifiApiClient( ConsoleLogger, // You can use your own logger if you want, just implement the Logger interface process.env.CLOUD_KEY_HOST, process.env.CLOUD_KEY_USER, process.env.CLOUD_KEY_PASSWORD ); const onDoorbellEvent = async (camera: ProtectCameraConfig) => { const snapshot = await imageHandler.getSnapshot({ camera: camera, }); if (snapshot) { // TODO: Do your own thing } }; const onMotionEvent = async (camera: ProtectCameraConfig) => { const snapshot = await imageHandler.getSnapshot({ camera: camera, }); if (snapshot) { // TODO: Do your own thing } }; const imageHandler = new UnifiImageHandler(ConsoleLogger, apiClient); const cameraHandler = new UnifiCameraHandler(ConsoleLogger, apiClient, { refreshInterval: 5, onDoorbellEvent: onDoorbellEvent, onMotionEvent: onMotionEvent, }); await apiClient.init(); // Print current status apiClient.status(); const eventListener = await apiClient.listen(); // Run on each camera websocket update eventListener?.on("message", (data: Buffer) => cameraHandler.handleUpdate(data) ); // Restart on close eventListener?.on("close", () => { if (retries < 5) { start(); retries = 0; } else { console.error("Too many retries. Closing Websocket for good"); } }); } catch (error) { console.error(error); } }; (async () => { await start(); })(); ``` ## Development Run the following commands at the root of this repository. ``` npm i npm link ``` Now you can start developing the plugin. To include the source in a local project, navigate to the root folder of your project and run `npm link @komponent/unifi-protect-lib`. You will now reference the local version of the when using `import { x } from "@komponent/unifi-protect-lib"` in your files.