Initial commit
Some checks failed
CI / main (push) Failing after 1m15s

This commit is contained in:
Felix Dürrwald 2024-09-25 07:32:29 +02:00
commit f11c3d80f6
Signed by: mplabs
GPG Key ID: 6E7D7F464AC5179D
35 changed files with 10396 additions and 0 deletions

13
.editorconfig Normal file
View File

@ -0,0 +1,13 @@
# Editor configuration, see http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false

1
.eslintignore Normal file
View File

@ -0,0 +1 @@
node_modules

42
.eslintrc.json Normal file
View File

@ -0,0 +1,42 @@
{
"root": true,
"ignorePatterns": ["**/*"],
"plugins": ["@nx"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"enforceBuildableLibDependency": true,
"allow": [],
"depConstraints": [
{
"sourceTag": "*",
"onlyDependOnLibsWithTags": ["*"]
}
]
}
]
}
},
{
"files": ["*.ts", "*.tsx"],
"extends": ["plugin:@nx/typescript"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"extends": ["plugin:@nx/javascript"],
"rules": {}
},
{
"files": ["*.spec.ts", "*.spec.tsx", "*.spec.js", "*.spec.jsx"],
"env": {
"jest": true
},
"rules": {}
}
]
}

38
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: CI
on:
push:
branches:
- main
pull_request:
permissions:
actions: read
contents: read
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
# This enables task distribution via Nx Cloud
# Run this command as early as possible, before dependencies are installed
# Learn more at https://nx.dev/ci/reference/nx-cloud-cli#npx-nxcloud-startcirun
- run: npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="build"
# Cache node_modules
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci --legacy-peer-deps
- uses: nrwl/nx-set-shas@v4
# Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud
# - run: npx nx-cloud record -- echo Hello World
# Nx Affected runs only tasks affected by the changes in this PR/commit. Learn more: https://nx.dev/ci/features/affected
- run: npx nx affected -t lint test build

42
.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
dist
tmp
/out-tsc
# dependencies
node_modules
# 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
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
.nx/cache
.nx/workspace-data

1
.npmrc Normal file
View File

@ -0,0 +1 @@
registry=https://registry.npmjs.org

5
.prettierignore Normal file
View File

@ -0,0 +1,5 @@
# Add files here to ignore them from prettier formatting
/dist
/coverage
/.nx/cache
/.nx/workspace-data

7
.prettierrc Normal file
View File

@ -0,0 +1,7 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "es5",
"useTabs": false
}

7
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"recommendations": [
"nrwl.angular-console",
"esbenp.prettier-vscode",
"firsttris.vscode-jest-runner"
]
}

82
README.md Normal file
View File

@ -0,0 +1,82 @@
# Awekas
<a alt="Nx logo" href="https://nx.dev" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-logo.png" width="45"></a>
✨ Your new, shiny [Nx workspace](https://nx.dev) is almost ready ✨.
[Learn more about this workspace setup and its capabilities](https://nx.dev/nx-api/node?utm_source=nx_project&amp;utm_medium=readme&amp;utm_campaign=nx_projects) or run `npx nx graph` to visually explore what was created. Now, let's get you up to speed!
## Finish your CI setup
[Click here to finish setting up your workspace!](https://cloud.nx.app/connect/rv5AoQ5kFR)
## Run tasks
To run the dev server for your app, use:
```sh
npx nx serve mqtt-gateway
```
To create a production bundle:
```sh
npx nx build mqtt-gateway
```
To see all available targets to run for a project, run:
```sh
npx nx show project mqtt-gateway
```
These targets are either [inferred automatically](https://nx.dev/concepts/inferred-tasks?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects) or defined in the `project.json` or `package.json` files.
[More about running tasks in the docs &raquo;](https://nx.dev/features/run-tasks?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
## Add new projects
While you could add new projects to your workspace manually, you might want to leverage [Nx plugins](https://nx.dev/concepts/nx-plugins?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects) and their [code generation](https://nx.dev/features/generate-code?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects) feature.
Use the plugin's generator to create new projects.
To generate a new application, use:
```sh
npx nx g @nx/node:app demo
```
To generate a new library, use:
```sh
npx nx g @nx/node:lib mylib
```
You can use `npx nx list` to get a list of installed plugins. Then, run `npx nx list <plugin-name>` to learn about more specific capabilities of a particular plugin. Alternatively, [install Nx Console](https://nx.dev/getting-started/editor-setup?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects) to browse plugins and generators in your IDE.
[Learn more about Nx plugins &raquo;](https://nx.dev/concepts/nx-plugins?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects) | [Browse the plugin registry &raquo;](https://nx.dev/plugin-registry?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
[Learn more about Nx on CI](https://nx.dev/ci/intro/ci-with-nx#ready-get-started-with-your-provider?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
## Install Nx Console
Nx Console is an editor extension that enriches your developer experience. It lets you run tasks, generate code, and improves code autocompletion in your IDE. It is available for VSCode and IntelliJ.
[Install Nx Console &raquo;](https://nx.dev/getting-started/editor-setup?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
## Useful links
Learn more:
- [Learn more about this workspace setup](https://nx.dev/nx-api/node?utm_source=nx_project&amp;utm_medium=readme&amp;utm_campaign=nx_projects)
- [Learn about Nx on CI](https://nx.dev/ci/intro/ci-with-nx?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
- [Releasing Packages with Nx release](https://nx.dev/features/manage-releases?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
- [What are Nx plugins?](https://nx.dev/concepts/nx-plugins?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)
And join the Nx community:
- [Discord](https://go.nx.dev/community)
- [Follow us on X](https://twitter.com/nxdevtools) or [LinkedIn](https://www.linkedin.com/company/nrwl)
- [Our Youtube channel](https://www.youtube.com/@nxdevtools)
- [Our blog](https://nx.dev/blog?utm_source=nx_project&utm_medium=readme&utm_campaign=nx_projects)

View File

@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}

View File

@ -0,0 +1,19 @@
/* eslint-disable */
export default {
displayName: 'mqtt-gateway-e2e',
preset: '../../jest.preset.js',
globalSetup: '<rootDir>/src/support/global-setup.ts',
globalTeardown: '<rootDir>/src/support/global-teardown.ts',
setupFiles: ['<rootDir>/src/support/test-setup.ts'],
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': [
'ts-jest',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
},
],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/mqtt-gateway-e2e',
};

View File

@ -0,0 +1,17 @@
{
"name": "mqtt-gateway-e2e",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"implicitDependencies": ["mqtt-gateway"],
"targets": {
"e2e": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{e2eProjectRoot}"],
"options": {
"jestConfig": "apps/mqtt-gateway-e2e/jest.config.ts",
"passWithNoTests": true
},
"dependsOn": ["mqtt-gateway:build"]
}
}
}

View File

@ -0,0 +1,10 @@
import axios from 'axios';
describe('GET /', () => {
it('should return a message', async () => {
const res = await axios.get(`/`);
expect(res.status).toBe(200);
expect(res.data).toEqual({ message: 'Hello API' });
});
});

View File

@ -0,0 +1,10 @@
/* eslint-disable */
var __TEARDOWN_MESSAGE__: string;
module.exports = async function () {
// Start services that that the app needs to run (e.g. database, docker-compose, etc.).
console.log('\nSetting up...\n');
// Hint: Use `globalThis` to pass variables to global teardown.
globalThis.__TEARDOWN_MESSAGE__ = '\nTearing down...\n';
};

View File

@ -0,0 +1,7 @@
/* eslint-disable */
module.exports = async function () {
// Put clean up logic here (e.g. stopping services, docker-compose, etc.).
// Hint: `globalThis` is shared between setup and teardown.
console.log(globalThis.__TEARDOWN_MESSAGE__);
};

View File

@ -0,0 +1,10 @@
/* eslint-disable */
import axios from 'axios';
module.exports = async function () {
// Configure axios for tests to use.
const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ?? '3000';
axios.defaults.baseURL = `http://${host}:${port}`;
};

View File

@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.spec.json"
}
],
"compilerOptions": {
"esModuleInterop": true
}
}

View File

@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": ["jest.config.ts", "src/**/*.ts"]
}

View File

@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}

View File

@ -0,0 +1,24 @@
# This file is generated by Nx.
#
# Build the docker image with `npx nx docker-build mqtt-gateway`.
# Tip: Modify "docker-build" options in project.json to change docker build args.
#
# Run the container with `docker run -p 3000:3000 -t mqtt-gateway`.
FROM docker.io/node:lts-alpine
ENV HOST=0.0.0.0
ENV PORT=3000
WORKDIR /app
RUN addgroup --system mqtt-gateway && \
adduser --system -G mqtt-gateway mqtt-gateway
COPY dist/apps/mqtt-gateway mqtt-gateway/
RUN chown -R mqtt-gateway:mqtt-gateway .
# You can remove this install step if you build with `--bundle` option.
# The bundled output will include external dependencies.
RUN npm --prefix mqtt-gateway --omit=dev -f install
CMD [ "node", "mqtt-gateway" ]

View File

@ -0,0 +1,11 @@
/* eslint-disable */
export default {
displayName: 'mqtt-gateway',
preset: '../../jest.preset.js',
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/apps/mqtt-gateway',
};

View File

@ -0,0 +1,63 @@
{
"name": "mqtt-gateway",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/mqtt-gateway/src",
"projectType": "application",
"tags": [],
"targets": {
"build": {
"executor": "@nx/esbuild:esbuild",
"outputs": ["{options.outputPath}"],
"defaultConfiguration": "production",
"options": {
"platform": "node",
"outputPath": "dist/apps/mqtt-gateway",
"format": ["cjs"],
"bundle": false,
"main": "apps/mqtt-gateway/src/main.ts",
"tsConfig": "apps/mqtt-gateway/tsconfig.app.json",
"assets": ["apps/mqtt-gateway/src/assets"],
"generatePackageJson": true,
"esbuildOptions": {
"sourcemap": true,
"outExtension": {
".js": ".js"
}
}
},
"configurations": {
"development": {},
"production": {
"generateLockfile": true,
"esbuildOptions": {
"sourcemap": false,
"outExtension": {
".js": ".js"
}
}
}
}
},
"serve": {
"executor": "@nx/js:node",
"defaultConfiguration": "development",
"dependsOn": ["build"],
"options": {
"buildTarget": "mqtt-gateway:build",
"runBuildTargetDependencies": false
},
"configurations": {
"development": {
"buildTarget": "mqtt-gateway:build:development"
},
"production": {
"buildTarget": "mqtt-gateway:build:production"
}
}
},
"docker-build": {
"dependsOn": ["build"],
"command": "docker build -f apps/mqtt-gateway/Dockerfile . -t mqtt-gateway"
}
}
}

View File

View File

@ -0,0 +1,66 @@
import type { ParsedQs } from 'qs'
import express, { Request, Response } from 'express'
import morgan from 'morgan'
const app = express()
const port = 3000
// Utility function to check required fields
const checkRequiredFields = (params: ParsedQs): boolean => {
const requiredFields = ['ID', 'PASSWORD', 'dateutc', 'action']
for (const field of requiredFields) {
if (!params[field]) {
return false
}
}
return true
}
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'))
// Route to handle weather station updates
app.get(
'/weatherstation/updateweatherstation.php',
(req: Request, res: Response) => {
const params = req.query
// Check if required fields are present
if (!checkRequiredFields(params)) {
return res
.status(400)
.send(
'RapidFire Server<br><br><b>usage</b><br>Required fields missing: ID, PASSWORD, action, and dateutc'
)
}
const { ID, PASSWORD, action, dateutc } = params as Record<string, string>
// Validate action and dateutc
if (action !== 'updateraw') {
return res.status(400).send('Invalid action')
}
if (dateutc !== 'now' && isNaN(Date.parse(dateutc))) {
return res.status(400).send('Invalid dateutc format')
}
// Validate ID and PASSWORD (this is where you would verify against your database)
// For now, we'll mock this validation
if (ID !== 'KCASANFR5' || PASSWORD !== 'XXXXXX') {
return res
.status(401)
.send('INVALIDPASSWORDID|Password and/or id are incorrect')
}
// Success response
res.status(200).send('success')
// Log the incoming data
console.log('Received weather data:', params)
}
)
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`)
})

View File

@ -0,0 +1,43 @@
import express from 'express';
import { checkSchema, Schema } from 'express-validator'
const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : 3000;
const app = express();
const FtoC: (f: number) => number = (f) => (f - 32) * 5 / 9
const inHgTohpa: (inHg: number) => number = (inHg) => inHg * 33.86389
const mphToKmh: (mph: number) => number = (mph) => mph * 1.609344
const mphToMs: (mph: number) => number = (mph) => mph * 0.44704
type UpdateweatherstationQuery = Record<string, unknown> & {
action: 'updateraw'
ID: string
KEY: string
}
app.get('/weatherstation/updateweatherstation.php', (req, res) => {
const query = req.query as Record<string, string>
// Validate only the required fields for now
const { action, ID, KEY } = query
const timestamp = new Date().getTime()
const pressure_inhg = parseFloat(query.baromin)
const pressure_hpa = inHgTohpa(parseFloat(query.baromin))
const temperature_f = parseFloat(query.tempf)
const temperature_c = FtoC(parseFloat(query.tempf))
const dew_point_f = parseFloat(query.dewptf)
const dew_point_c = FtoC(parseFloat(query.dewptf))
const humidity = parseFloat(query.humidity)
const wind_speed_mph = parseFloat(query.windspeedmph)
const wind_speed_mph = mphToKmh(parseFloat(query.windspeedmph))
const wind_speed_ms = mphToMs(parseFloat(query.windspeedmph))
res.send('OK')
});
app.listen(port, host, () => {
console.log(`[ ready ] http://${host}:${port}`);
});

View File

@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["node"]
},
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
}

View File

@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"compilerOptions": {
"esModuleInterop": true
}
}

View File

@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

5
jest.config.ts Normal file
View File

@ -0,0 +1,5 @@
import { getJestProjectsAsync } from '@nx/jest';
export default async () => ({
projects: await getJestProjectsAsync(),
});

3
jest.preset.js Normal file
View File

@ -0,0 +1,3 @@
const nxPreset = require('@nx/jest/preset').default;
module.exports = { ...nxPreset };

40
nx.json Normal file
View File

@ -0,0 +1,40 @@
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/.eslintrc.json",
"!{projectRoot}/eslint.config.js",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/jest.config.[jt]s",
"!{projectRoot}/src/test-setup.[jt]s",
"!{projectRoot}/test-setup.[jt]s"
],
"sharedGlobals": ["{workspaceRoot}/.github/workflows/ci.yml"]
},
"nxCloudId": "66e833ec9b27f24ac3758e9d",
"targetDefaults": {
"@nx/esbuild:esbuild": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
}
},
"plugins": [
{
"plugin": "@nx/eslint/plugin",
"options": {
"targetName": "lint"
}
},
{
"plugin": "@nx/jest/plugin",
"options": {
"targetName": "test"
},
"exclude": ["apps/mqtt-gateway-e2e/**/*"]
}
]
}

9670
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

42
package.json Normal file
View File

@ -0,0 +1,42 @@
{
"name": "@awekas/source",
"version": "0.0.0",
"license": "MIT",
"scripts": {},
"private": true,
"dependencies": {
"@types/morgan": "^1.9.9",
"axios": "^1.6.0",
"express": "~4.18.1",
"express-validator": "^7.2.0",
"morgan": "^1.10.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@nx/esbuild": "19.7.3",
"@nx/eslint": "19.7.3",
"@nx/eslint-plugin": "19.7.3",
"@nx/jest": "19.7.3",
"@nx/js": "19.7.3",
"@nx/node": "19.7.3",
"@nx/workspace": "19.7.3",
"@swc-node/register": "~1.9.1",
"@swc/core": "~1.5.7",
"@swc/helpers": "~0.5.11",
"@types/express": "~4.17.13",
"@types/jest": "^29.5.12",
"@types/node": "~18.16.9",
"@typescript-eslint/eslint-plugin": "^7.16.0",
"@typescript-eslint/parser": "^7.16.0",
"esbuild": "^0.19.2",
"eslint": "~8.57.0",
"eslint-config-prettier": "^9.0.0",
"jest": "^29.7.0",
"jest-environment-node": "^29.7.0",
"nx": "19.7.3",
"prettier": "^2.8.8",
"ts-jest": "^29.1.0",
"ts-node": "10.9.1",
"typescript": "~5.5.2"
}
}

20
tsconfig.base.json Normal file
View File

@ -0,0 +1,20 @@
{
"compileOnSave": false,
"compilerOptions": {
"rootDir": ".",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "ES6",
"module": "CommonJS",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {}
},
"exclude": ["node_modules", "tmp"]
}