This commit is contained in:
Evert Prants 2023-09-16 22:45:26 +03:00
commit 11e1d1b468
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
17 changed files with 5782 additions and 0 deletions

25
.eslintrc.js Normal file
View File

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

35
.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

73
README.md Normal file
View File

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ pnpm install
```
## Running the app
```bash
# development
$ pnpm run start
# watch mode
$ pnpm run start:dev
# production mode
$ pnpm run start:prod
```
## Test
```bash
# unit tests
$ pnpm run test
# e2e tests
$ pnpm run test:e2e
# test coverage
$ pnpm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

8
nest-cli.json Normal file
View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

73
package.json Normal file
View File

@ -0,0 +1,73 @@
{
"name": "homeweather",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/cache-manager": "^2.1.0",
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/schedule": "^3.0.3",
"cache-manager": "^5.2.3",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"usb": "^2.10.0"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^5.59.11",
"@typescript-eslint/parser": "^5.59.11",
"eslint": "^8.42.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.5.0",
"prettier": "^2.8.8",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

5163
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

15
src/app.controller.ts Normal file
View File

@ -0,0 +1,15 @@
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import { CacheInterceptor, CacheTTL } from '@nestjs/cache-manager';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@UseInterceptors(CacheInterceptor)
@CacheTTL(60000)
getWeather() {
return this.appService.getWeather();
}
}

11
src/app.module.ts Normal file
View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CacheModule } from '@nestjs/cache-manager';
@Module({
imports: [CacheModule.register()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

16
src/app.service.ts Normal file
View File

@ -0,0 +1,16 @@
import { Injectable, OnApplicationShutdown } from '@nestjs/common';
import WS1080 from './module/ws1080';
@Injectable()
export class AppService implements OnApplicationShutdown {
public station?: WS1080;
async getWeather() {
if (!this.station) this.station = WS1080.fromDevice();
return this.station.read();
}
onApplicationShutdown() {
this.station?.close();
}
}

8
src/main.ts Normal file
View File

@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();

271
src/module/ws1080.ts Normal file
View File

@ -0,0 +1,271 @@
import { getDeviceList, Device, Interface, InEndpoint } from 'usb';
const MAX_RAIN_JUMP = 10;
const WIND_DIRS = [
'N',
'NNE',
'NE',
'ENE',
'E',
'ESE',
'SE',
'SSE',
'S',
'SSW',
'SW',
'WSW',
'W',
'WNW',
'NW',
'NNW',
];
/**
* Model Dreamlink WH1080/WS1080
*
* This is a Node.js port of
* https://github.com/shaneHowearth/Dream-Link-WH1080-Weather-Station
*
* If running Ubuntu and getting permissions errors,
* follow the advice given here http://ubuntuforums.org/showthread.php?t=901891
*
* I found the GROUPS portion was REQUIRED on one machine, set it to an appropriate group for
* your system.
*
* `/etc/udev/rules.d/41-weather-device.rules`
*
* `SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device",SYSFS{idVendor}=="1941" , SYSFS{idProduct}=="8021", MODE="0666", GROUPS="shane"`
*
* OTOH my second machine requires these rules:
* `SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device",ATTR{idVendor}=="1941" , ATTR{idProduct}=="8021", MODE="0666", OWNER="shane"`
*
* Run `sudo udevadm control --reload-rules && sudo udevadm trigger` to reload the rules.
*
* Then remove your device from your machine and plug it back in again
*/
class WS1080 {
private previousRain = 0;
constructor(private device: Device, private dInterface: Interface) {}
/**
* Open USB device.
* @param vendor Vendor ID
* @param product Product ID
* @returns USB device and interface
*/
static fromDevice(vendor = 0x1941, product = 0x8021) {
const devices = getDeviceList();
const device = devices.find(
(dev) =>
dev.deviceDescriptor.idVendor === vendor &&
dev.deviceDescriptor.idProduct === product,
);
if (!device) {
throw new Error('Device not found');
}
device.open();
const iface = device.interface(0);
// If we don't detach the kernel driver we get I/O errors
if (iface.isKernelDriverActive()) {
iface.detachKernelDriver();
}
iface.claim();
device.timeout = 500;
return new WS1080(device, iface);
}
/**
* Read a block of data from the specified device, starting at the given offset.
* @param device USB
* @param iface USB Interface
* @param offset Byte offset
* @returns Buffer
*/
static async readBlock(device: Device, iface: Interface, offset: number) {
const least_significant_bit = offset & 0xff;
const most_significant_bit = (offset >> 8) & 0xff;
// Construct a binary message
const buffer = Buffer.from([
0xa1,
most_significant_bit,
least_significant_bit,
32,
0xa1,
most_significant_bit,
least_significant_bit,
32,
]);
// Send the binary message to the device via control transfer
await new Promise<number | Buffer | undefined>((resolve, reject) =>
device.controlTransfer(0x21, 0x09, 0x200, 0, buffer, (err, buf) =>
err ? reject(err) : resolve(buf),
),
);
// Read the response from the IN endpoint
return new Promise<Buffer | undefined>((resolve, reject) => {
const endpoint = iface.endpoints.find(
(endpoint) => endpoint.address === 0x81,
) as InEndpoint;
if (!endpoint) return reject('Correct IN endpoint was not found');
endpoint.transfer(32, (err, buf) => (err ? reject(err) : resolve(buf)));
});
}
/**
* Using the supplied temperature and humidity calculate the dew point
* From Wikipedia: The dew point is the temperature at which the water vapor
* in a sample of air at constant barometric pressure condenses into liquid
* water at the same rate at which it evaporates. At temperatures below
* the dew point, water will leave the air. The condensed water is called dew
* when it forms on a solid surface. The condensed water is called either fog
* or a cloud, depending on its altitude, when it forms in the air.
* @param temperature - Temperature
* @param humidity - Humidity
* @returns dew point
*/
static dewPoint(temperature: number, humidity: number) {
humidity /= 100.0;
const gamma =
(17.271 * temperature) / (237.7 + temperature) + Math.log(humidity);
return (237.7 * gamma) / (17.271 - gamma);
}
/**
* Return wind chill temp based on temperature & wind speed.
*
* Using the supplied temperature and wind speed calculate the wind chill
* factor.
*
* From Wikipedia: Wind-chill or windchill, (popularly wind chill factor) is
* the perceived decrease in air temperature felt by the body on exposed skin
* due to the flow of air.
*
* @param temperature Temperature
* @param wind Wind speed
* @returns Wind chill temperature
*/
static windChill(temperature: number, wind: number) {
const wind_kph = 3.6 * wind;
// Low wind speed, or high temperature, negates any perceived wind chill
if (wind_kph <= 4.8 || temperature > 10.0) return temperature;
const wct =
13.12 +
0.6215 * temperature -
11.37 * wind_kph ** 0.16 +
0.3965 * temperature * wind_kph ** 0.16;
// Return the lower of temperature or wind chill temperature
if (wct < temperature) return wct;
else return temperature;
}
/**
* Read weather data from WS1080
* @returns Weather data
*/
async read() {
const block = await WS1080.readBlock(this.device, this.dInterface, 0);
if (!block) throw new Error('No data returned for request.');
if (block[0] !== 0x55)
throw new Error('Invalid data returned for request.');
const offset = block.subarray(30, 32).readUint16LE();
const currentBlock = await WS1080.readBlock(
this.device,
this.dInterface,
offset,
);
if (!currentBlock) throw new Error('No data returned for request.');
// Indoor information
const indoorHumidity = currentBlock[1];
let tlsb = currentBlock[2];
let tmsb = currentBlock[3] & 0x7f;
let tsign = currentBlock[3] >> 7;
let indoorTemperature = (tmsb * 256 + tlsb) * 0.1;
// Check if temperature is less than zero
if (tsign) indoorTemperature *= -1;
// Outdoor information
const outdoorHumidity = currentBlock[4];
tlsb = currentBlock[5];
tmsb = currentBlock[6] & 0x7f;
tsign = currentBlock[6] >> 7;
let outdoorTemperature = (tmsb * 256 + tlsb) * 0.1;
// Check if temperature is less than zero
if (tsign) outdoorTemperature *= -1;
// Bytes 8 and 9 when combined create an unsigned short int
// that we multiply by 0.1 to find the absolute pressure
const absPressure = currentBlock.subarray(7, 9).readUint16LE() * 0.1;
const wind = currentBlock[9];
const gust = currentBlock[10];
const windExtra = currentBlock[11];
const windDir = currentBlock[12];
const windDirection = WIND_DIRS[windDir];
// Bytes 14 and 15 when combined create an unsigned short int
// that we multiply by 0.3 to find the total rain
let totalRain = currentBlock.subarray(13, 15).readUint16LE() * 0.3;
// Calculate wind speeds
const windSpeed = (wind + ((windExtra & 0x0f) << 8)) * 0.38; // Was 0.1
const gustSpeed = (gust + ((windExtra & 0xf0) << 4)) * 0.38; // Was 0.1
const outdoorDewPoint = WS1080.dewPoint(
outdoorTemperature,
outdoorHumidity,
);
const windChillTemp = WS1080.windChill(outdoorTemperature, windSpeed);
// Calculate rainfall rates
if (this.previousRain === 0) this.previousRain = totalRain;
let rainDiff = totalRain - this.previousRain;
if (rainDiff > MAX_RAIN_JUMP) {
// Filter rainfall spikes
rainDiff = 0;
totalRain = this.previousRain;
}
this.previousRain = totalRain;
// Return the data! Finally!
return {
indoorHumidity,
outdoorHumidity,
indoorTemperature,
outdoorTemperature,
outdoorDewPoint,
windChillTemp,
windSpeed,
gustSpeed,
windDirection,
rainDiff,
totalRain,
absPressure,
};
}
close() {
this.device.close();
}
}
export default WS1080;

24
test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}