feat: initial setup backend with default routes and db connection

This commit is contained in:
2024-12-30 01:36:41 +01:00
parent 478a53a0fb
commit 26e6cd0b7e
28 changed files with 3062 additions and 1 deletions

6
server/.env.template Normal file
View File

@ -0,0 +1,6 @@
DB_NAME=""
DB_USER=""
DB_PASSWORD=""
DB_HOST=""
DB_DIALECT=""
DB_PORT=""

314
server/.gitignore vendored Normal file
View File

@ -0,0 +1,314 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
testdata/
---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
config.py
#docker
docker-compose.yml

9
server/LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 localhorst
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

9
server/README.md Normal file
View File

@ -0,0 +1,9 @@
# LocationHub
TODO
### Testing Webhook
To test the webhook use the python script `ttn-webhook-dummy.py` to send prerecorded TTN Uplinks.
To test the script you can use `while true; do echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nSuccess"; nc -l -p 8080 -q 1; done`

1984
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

31
server/package.json Normal file
View File

@ -0,0 +1,31 @@
{
"name": "locationhub",
"version": "1.0.0",
"description": "TODO",
"main": "index.js",
"scripts": {
"dev": "nodemon --exec ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
},
"keywords": [],
"author": "Hendrik Schutter, Philipp Schweizer",
"license": "ISC",
"devDependencies": {
"@types/express": "^5.0.0",
"@types/node": "^22.10.2",
"nodemon": "^3.1.9",
"ts-node": "^10.9.2",
"typescript": "^5.7.2"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
"mariadb": "^3.4.0",
"reflect-metadata": "^0.2.2",
"sequelize": "^6.37.5",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
"tsyringe": "^4.8.0"
}
}

View File

@ -0,0 +1,92 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Author: Hendrik Schutter, mail@hendrikschutter.com
"""
import requests
import os
import json
import argparse
import random
def send_post_request(uri, data):
try:
requests.post(uri, json=data, timeout=1)
except requests.exceptions.RequestException as e:
pass
def main():
parser = argparse.ArgumentParser(
description="Read JSON files and send them as POST requests to simulate a webhook request."
)
parser.add_argument(
"uri",
type=str,
help="The URI to send POST requests to (e.g., http://127.0.0.1:8080/api)",
)
parser.add_argument(
"directory",
type=str,
nargs="?",
default="./testdata/",
help="Directory containing JSON files (default: './testdata/')",
)
parser.add_argument(
"mode",
type=str,
choices=["send_all", "send_one", "send_random"],
default="send_one",
help="Mode for sending files: 'send_all', 'send_one', or 'send_random' (default: 'send_one')",
)
args = parser.parse_args()
if not os.path.exists(args.directory):
print(f"Directory {args.directory} does not exist.")
return
json_files = [f for f in os.listdir(args.directory) if f.endswith(".json")]
if not json_files:
print(f"No JSON files found in {args.directory}.")
return
if args.mode == "send_all":
for filename in json_files:
filepath = os.path.join(args.directory, filename)
with open(filepath, "r", encoding="utf-8") as file:
try:
data = json.load(file)
print(f"Sending {filename} to {args.uri}")
send_post_request(args.uri, data)
except json.JSONDecodeError as e:
print(f"Error reading {filename}: {e}")
elif args.mode == "send_one":
for filename in json_files:
filepath = os.path.join(args.directory, filename)
with open(filepath, "r", encoding="utf-8") as file:
try:
data = json.load(file)
print(f"Sending {filename} to {args.uri}")
send_post_request(args.uri, data)
input("Press Enter to send the next file...")
except json.JSONDecodeError as e:
print(f"Error reading {filename}: {e}")
elif args.mode == "send_random":
while json_files:
filename = random.choice(json_files)
filepath = os.path.join(args.directory, filename)
with open(filepath, "r", encoding="utf-8") as file:
try:
data = json.load(file)
print(f"Sending {filename} to {args.uri}")
send_post_request(args.uri, data)
input("Press Enter to send another random file...")
except json.JSONDecodeError as e:
print(f"Error reading {filename}: {e}")
if __name__ == "__main__":
main()

58
server/sql/tables.sql Normal file
View File

@ -0,0 +1,58 @@
CREATE TABLE IF NOT EXISTS lp_ttn_end_device_uplinks (
lp_ttn_end_device_uplinks_id UUID PRIMARY KEY,
device_id VARCHAR(255) NOT NULL,
application_ids VARCHAR(255),
dev_eui VARCHAR(255),
join_eui VARCHAR(255),
dev_addr VARCHAR(255),
received_at_utc DATE,
battery NUMERIC,
latitude DOUBLE,
longitude DOUBLE,
created_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX idx_unique_device ON lp_ttn_end_device_uplinks (
device_id,
application_ids,
dev_eui,
join_eui,
dev_addr
);
CREATE TABLE IF NOT EXISTS wifi_scan (
wifi_scan_id UUID PRIMARY KEY,
lp_ttn_end_device_uplinks_id UUID,
mac VARCHAR(255),
rssi NUMERIC,
created_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (lp_ttn_end_device_uplinks_id) REFERENCES lp_ttn_end_device_uplinks(lp_ttn_end_device_uplinks_id)
);
CREATE TABLE IF NOT EXISTS ttn_gateway_reception (
ttn_gateway_reception_id UUID PRIMARY KEY,
lp_ttn_end_device_uplinks_id UUID,
gateway_id VARCHAR(255),
eui VARCHAR(255),
rssi NUMERIC,
latitude DOUBLE,
longitude DOUBLE,
altitude NUMERIC,
created_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (lp_ttn_end_device_uplinks_id) REFERENCES lp_ttn_end_device_uplinks(lp_ttn_end_device_uplinks_id)
);
CREATE TABLE IF NOT EXISTS location (
location_id UUID PRIMARY KEY,
lp_ttn_end_device_uplinks_id UUID,lp_ttn_end_device_uplinks
wifi_latitude DOUBLE,
wifi_longitude DOUBLE,
gnss_latitude DOUBLE,
gnss_longitude DOUBLE,
created_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at_utc TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (lp_ttn_end_device_uplinks_id) REFERENCES lp_ttn_end_device_uplinks(lp_ttn_end_device_uplinks_id)
);

View File

@ -0,0 +1,17 @@
import dotenv from "dotenv";
dotenv.config();
console.log(process.env.NODE_ENV);
export const config = {
username: process.env.DB_USER!,
password: process.env.DB_PASSWORD!,
database: process.env.DB_NAME!,
host: process.env.DB_HOST!,
dialect: process.env.DB_DIALECT! as
| "mysql"
| "mariadb"
| "postgres"
| "sqlite"
| "mssql",
port: parseInt(process.env.DB_PORT as string, 10),
};

View File

@ -0,0 +1,68 @@
import express, { Request, Response } from "express";
import { container } from "tsyringe";
import { LocationService } from "../services/locationService";
const locationService = container.resolve(LocationService);
const router = express.Router();
router.get("/", async (req: Request, res: Response) => {
try {
const locations = await locationService.getAllLocations();
res.status(200).json(locations);
} catch (error) {
res.status(500).json({ error: "Error retrieving locations" });
}
});
router.get("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const location = await locationService.getLocationById(id);
if (!location) {
res.status(404).json({ error: "Location not found" });
return;
}
res.status(200).json(location);
} catch (error) {
res.status(500).json({ error: "Error retrieving location" });
}
});
router.post("/", async (req: Request, res: Response) => {
try {
const newLocation = await locationService.createLocation(req.body);
res.status(201).json(newLocation);
} catch (error) {
res.status(500).json({ error: "Error creating location" });
}
});
router.put("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const updatedLocation = await locationService.updateLocation(id, req.body);
if (!updatedLocation) {
res.status(404).json({ error: "Location not found" });
return;
}
res.status(200).json(updatedLocation);
} catch (error) {
res.status(500).json({ error: "Error updating location" });
}
});
router.delete("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const deleted = await locationService.deleteLocation(id);
if (!deleted) {
res.status(404).json({ error: "Location not found" });
return;
}
res.status(204).send();
} catch (error) {
res.status(500).json({ error: "Error deleting location" });
}
});
export default router;

View File

@ -0,0 +1,75 @@
import express, { Request, Response } from "express";
import { container } from "tsyringe";
import { LpTtnEndDeviceUplinksService } from "../services/lpTtnEndDeviceUplinksService";
const lpTtnEndDeviceUplinksService = container.resolve(
LpTtnEndDeviceUplinksService
);
const router = express.Router();
router.get("/", async (req: Request, res: Response) => {
try {
const uplinks = await lpTtnEndDeviceUplinksService.getAllUplinks();
res.status(200).json(uplinks);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Error retrieving uplinks" });
}
});
router.get("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const uplink = await lpTtnEndDeviceUplinksService.getUplinkById(id);
if (!uplink) {
res.status(404).json({ error: "Uplink not found" });
return;
}
res.status(200).json(uplink);
} catch (error) {
res.status(500).json({ error: "Error retrieving uplink" });
}
});
router.post("/", async (req: Request, res: Response) => {
try {
const newUplink = await lpTtnEndDeviceUplinksService.createUplink(req.body);
res.status(201).json(newUplink);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Error creating uplink" });
}
});
router.put("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const updatedUplink = await lpTtnEndDeviceUplinksService.updateUplink(
id,
req.body
);
if (!updatedUplink) {
res.status(404).json({ error: "Uplink not found" });
return;
}
res.status(200).json(updatedUplink);
} catch (error) {
res.status(500).json({ error: "Error updating uplink" });
}
});
router.delete("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const deleted = await lpTtnEndDeviceUplinksService.deleteUplink(id);
if (!deleted) {
res.status(404).json({ error: "Uplink not found" });
return;
}
res.status(204).send();
} catch (error) {
res.status(500).json({ error: "Error deleting uplink" });
}
});
export default router;

View File

@ -0,0 +1,74 @@
import express, { Request, Response } from "express";
import { TtnGatewayReceptionService } from "../services/ttnGatewayReceptionService";
import { container } from "tsyringe";
const ttnGatewayReceptionService = container.resolve(
TtnGatewayReceptionService
);
const router = express.Router();
router.get("/", async (req: Request, res: Response) => {
try {
const gatewayReceptions =
await ttnGatewayReceptionService.getAllGatewayReceptions();
res.status(200).json(gatewayReceptions);
} catch (error) {
res.status(500).json({ error: "Error retrieving gateway receptions" });
}
});
router.get("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const gatewayReception =
await ttnGatewayReceptionService.getGatewayReceptionById(id);
if (!gatewayReception) {
res.status(404).json({ error: "Gateway reception not found" });
return;
}
res.status(200).json(gatewayReception);
} catch (error) {
res.status(500).json({ error: "Error retrieving gateway reception" });
}
});
router.post("/", async (req: Request, res: Response) => {
try {
const newGatewayReception =
await ttnGatewayReceptionService.createGatewayReception(req.body);
res.status(201).json(newGatewayReception);
} catch (error) {
res.status(500).json({ error: "Error creating gateway reception" });
}
});
router.put("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const updatedGatewayReception =
await ttnGatewayReceptionService.updateGatewayReception(id, req.body);
if (!updatedGatewayReception) {
res.status(404).json({ error: "Gateway reception not found" });
return;
}
res.status(200).json(updatedGatewayReception);
} catch (error) {
res.status(500).json({ error: "Error updating gateway reception" });
}
});
router.delete("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const deleted = await ttnGatewayReceptionService.deleteGatewayReception(id);
if (!deleted) {
res.status(404).json({ error: "Gateway reception not found" });
return;
}
res.status(204).send();
} catch (error) {
res.status(500).json({ error: "Error deleting gateway reception" });
}
});
export default router;

View File

@ -0,0 +1,70 @@
import express, { Request, Response } from "express";
import { container } from "tsyringe";
import { WifiScanService } from "../services/wifiScanService";
const wifiScanService = container.resolve(WifiScanService);
const router = express.Router();
router.get("/", async (req: Request, res: Response) => {
try {
const wifiScans = await wifiScanService.getAllWifiScans();
res.status(200).json(wifiScans);
} catch (error) {
res.status(500).json({ error: "Error retrieving wifi scans" });
}
});
router.get("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const wifiScan = await wifiScanService.getWifiScanById(id);
if (!wifiScan) {
res.status(404).json({ error: "Wifi scan not found" });
return;
}
res.status(200).json(wifiScan);
} catch (error) {
res.status(500).json({ error: "Error retrieving wifi scan" });
}
});
router.post("/", async (req: Request, res: Response) => {
try {
const newWifiScan = await wifiScanService.createWifiScan(req.body);
res.status(201).json(newWifiScan);
} catch (error) {
res.status(500).json({ error: "Error creating wifi scan" });
}
});
router.put("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const updatedWifiScan = await wifiScanService.updateWifiScan(id, req.body);
if (!updatedWifiScan) {
res.status(404).json({ error: "Wifi scan not found" });
return;
}
res.status(200).json(updatedWifiScan);
} catch (error) {
res.status(500).json({ error: "Error updating wifi scan" });
}
});
router.delete("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;
const deleted = await wifiScanService.deleteWifiScan(id);
if (!deleted) {
res.status(404).json({ error: "Wifi scan not found" });
return;
}
res.status(204).send();
} catch (error) {
res.status(500).json({ error: "Error deleting wifi scan" });
}
});
router.delete("/:id", async (req: Request, res: Response) => {});
export default router;

View File

@ -0,0 +1,14 @@
import { Sequelize } from "sequelize";
import { config } from "../config/config";
export const sequelize = new Sequelize(
config.database,
config.username,
config.password,
{
host: config.host,
dialect: config.dialect,
port: config.port,
logging: false,
}
);

26
server/src/index.ts Normal file
View File

@ -0,0 +1,26 @@
import dotenv from "dotenv";
import express from "express";
import "reflect-metadata";
const cors = require("cors");
import locationRoutes from "./controller/locationController";
import lpTtnEndDeviceUplinksRoutes from "./controller/lpTtnEndDeviceUplinksController";
import ttnGatewayReceptionRoutes from "./controller/ttnGatewayReceptionController";
import wifiScanRoutes from "./controller/wifiScanController";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
app.use("/api/lp-ttn-end-device-uplinks", lpTtnEndDeviceUplinksRoutes);
app.use("/api/wifi-scans", wifiScanRoutes);
app.use("/api/ttn-gateway-receptions", ttnGatewayReceptionRoutes);
app.use("/api/locations", locationRoutes);
app.listen(PORT, () => {
console.log(`🚀 Server läuft auf http://localhost:${PORT}`);
});

View File

@ -0,0 +1,60 @@
import { DataTypes, Model } from "sequelize";
import { sequelize } from "../database/database";
export class Location extends Model {
public location_id!: string;
public lp_ttn_end_device_uplinks_id!: string;
public wifi_latitude!: number;
public wifi_longitude!: number;
public gnss_latitude!: number;
public gnss_longitude!: number;
public created_at_utc!: Date;
public updated_at_utc!: Date;
}
Location.init(
{
location_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
},
lp_ttn_end_device_uplinks_id: {
type: DataTypes.UUID,
allowNull: false,
},
wifi_latitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
wifi_longitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
gnss_latitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
gnss_longitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
created_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
updated_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
},
{
sequelize,
modelName: "Location",
tableName: "location",
timestamps: false,
}
);

View File

@ -0,0 +1,80 @@
import { DataTypes, Model } from "sequelize";
import { sequelize } from "../database/database";
export class LpTtnEndDeviceUplinks extends Model {
public lp_ttn_end_device_uplinks_id!: string;
public device_id!: string;
public application_ids!: string;
public dev_eui!: string;
public join_eui!: string;
public dev_addr!: string;
public received_at_utc!: Date;
public battery!: number;
public latitude!: number;
public longitude!: number;
public created_at_utc!: Date;
public updated_at_utc!: Date;
}
LpTtnEndDeviceUplinks.init(
{
lp_ttn_end_device_uplinks_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
},
device_id: {
type: DataTypes.STRING,
allowNull: false,
},
application_ids: {
type: DataTypes.STRING,
allowNull: true,
},
dev_eui: {
type: DataTypes.STRING,
allowNull: true,
},
join_eui: {
type: DataTypes.STRING,
allowNull: true,
},
dev_addr: {
type: DataTypes.STRING,
allowNull: true,
},
received_at_utc: {
type: DataTypes.DATE,
allowNull: true,
},
battery: {
type: DataTypes.NUMBER,
allowNull: true,
},
latitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
longitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
created_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
updated_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
},
{
sequelize,
modelName: "LpTtnEndDeviceUplinks",
tableName: "lp_ttn_end_device_uplinks",
timestamps: false,
}
);

View File

@ -0,0 +1,70 @@
import { DataTypes, Model } from "sequelize";
import { sequelize } from "../database/database";
export class TtnGatewayReception extends Model {
public ttn_gateway_reception_id!: string;
public lp_ttn_end_device_uplinks_id!: string;
public gateway_id!: string;
public eui!: string;
public rssi!: number;
public latitude!: number;
public longitude!: number;
public altitude!: number;
public created_at_utc!: Date;
public updated_at_utc!: Date;
}
TtnGatewayReception.init(
{
ttn_gateway_reception_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
},
lp_ttn_end_device_uplinks_id: {
type: DataTypes.UUID,
allowNull: false,
},
gateway_id: {
type: DataTypes.STRING,
allowNull: false,
},
eui: {
type: DataTypes.STRING,
allowNull: false,
},
rssi: {
type: DataTypes.NUMBER,
allowNull: true,
},
latitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
longitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
altitude: {
type: DataTypes.NUMBER,
allowNull: true,
},
created_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
updated_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
},
{
sequelize,
modelName: "TtnGatewayReception",
tableName: "ttn_gateway_reception",
timestamps: false,
}
);

View File

@ -0,0 +1,50 @@
import { DataTypes, Model } from "sequelize";
import { sequelize } from "../database/database";
export class WifiScan extends Model {
public wifi_scan_id!: string;
public lp_ttn_end_device_uplinks_id!: string;
public mac!: string;
public rssi!: number;
public created_at_utc!: Date;
public updated_at_utc!: Date;
}
WifiScan.init(
{
wifi_scan_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
},
lp_ttn_end_device_uplinks_id: {
type: DataTypes.UUID,
allowNull: false,
},
mac: {
type: DataTypes.STRING,
allowNull: false,
},
rssi: {
type: DataTypes.NUMBER,
allowNull: true,
},
created_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
updated_at_utc: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false,
},
},
{
sequelize,
modelName: "WifiScan",
tableName: "wifi_scan",
timestamps: false,
}
);

View File

@ -0,0 +1,34 @@
import { injectable } from "tsyringe";
import { Location } from "../models/location";
@injectable()
export class LocationRepository {
public async findAll() {
return await Location.findAll();
}
public async findById(id: string) {
return await Location.findByPk(id);
}
public async create(data: Partial<Location>) {
return await Location.create(data);
}
public async update(id: string, data: Partial<Location>) {
const location = await this.findById(id);
if (location) {
return await location.update(data);
}
return null;
}
public async delete(id: string) {
const location = await this.findById(id);
if (location) {
await location.destroy();
return true;
}
return false;
}
}

View File

@ -0,0 +1,34 @@
import { injectable } from "tsyringe";
import { LpTtnEndDeviceUplinks } from "../models/lpTtnEndDeviceUplinks";
@injectable()
export class LpTtnEndDeviceUplinksRepository {
public async findAll() {
return await LpTtnEndDeviceUplinks.findAll();
}
public async findById(id: string) {
return await LpTtnEndDeviceUplinks.findByPk(id);
}
public async create(data: Partial<LpTtnEndDeviceUplinks>) {
return await LpTtnEndDeviceUplinks.create(data);
}
public async update(id: string, data: Partial<LpTtnEndDeviceUplinks>) {
const uplink = await this.findById(id);
if (uplink) {
return await uplink.update(data);
}
return null;
}
public async delete(id: string) {
const uplink = await this.findById(id);
if (uplink) {
await uplink.destroy();
return true;
}
return false;
}
}

View File

@ -0,0 +1,34 @@
import { injectable } from "tsyringe";
import { TtnGatewayReception } from "../models/ttnGatewayReception";
@injectable()
export class TtnGatewayReceptionRepository {
public async findAll() {
return await TtnGatewayReception.findAll();
}
public async findById(id: string) {
return await TtnGatewayReception.findByPk(id);
}
public async create(data: Partial<TtnGatewayReception>) {
return await TtnGatewayReception.create(data);
}
public async update(id: string, data: Partial<TtnGatewayReception>) {
const gatewayReception = await this.findById(id);
if (gatewayReception) {
return await gatewayReception.update(data);
}
return null;
}
public async delete(id: string) {
const gatewayReception = await this.findById(id);
if (gatewayReception) {
await gatewayReception.destroy();
return true;
}
return false;
}
}

View File

@ -0,0 +1,34 @@
import { injectable } from "tsyringe";
import { WifiScan } from "../models/wifiScan";
@injectable()
export class WifiScanRepository {
public async findAll() {
return await WifiScan.findAll();
}
public async findById(id: string) {
return await WifiScan.findByPk(id);
}
public async create(data: Partial<WifiScan>) {
return await WifiScan.create(data);
}
public async update(id: string, data: Partial<WifiScan>) {
const wifiScan = await this.findById(id);
if (wifiScan) {
return await wifiScan.update(data);
}
return null;
}
public async delete(id: string) {
const wifiScan = await this.findById(id);
if (wifiScan) {
await wifiScan.destroy();
return true;
}
return false;
}
}

View File

@ -0,0 +1,31 @@
import { inject, injectable } from "tsyringe";
import { Location } from "../models/location";
import { LocationRepository } from "../repositories/locationRepository";
@injectable()
export class LocationService {
constructor(
@inject(LocationRepository)
private repository: LocationRepository
) {}
public async getAllLocations() {
return this.repository.findAll();
}
public async getLocationById(id: string) {
return this.repository.findById(id);
}
public async createLocation(data: Partial<Location>) {
return this.repository.create(data);
}
public async updateLocation(id: string, data: Partial<Location>) {
return this.repository.update(id, data);
}
public async deleteLocation(id: string) {
return this.repository.delete(id);
}
}

View File

@ -0,0 +1,31 @@
import { inject, injectable } from "tsyringe";
import { LpTtnEndDeviceUplinks } from "../models/lpTtnEndDeviceUplinks";
import { LpTtnEndDeviceUplinksRepository } from "../repositories/lpTtnEndDeviceUplinksRepository";
@injectable()
export class LpTtnEndDeviceUplinksService {
constructor(
@inject(LpTtnEndDeviceUplinksRepository)
private repository: LpTtnEndDeviceUplinksRepository
) {}
public async getAllUplinks() {
return this.repository.findAll();
}
public async getUplinkById(id: string) {
return this.repository.findById(id);
}
public async createUplink(data: Partial<LpTtnEndDeviceUplinks>) {
return this.repository.create(data);
}
public async updateUplink(id: string, data: Partial<LpTtnEndDeviceUplinks>) {
return this.repository.update(id, data);
}
public async deleteUplink(id: string) {
return this.repository.delete(id);
}
}

View File

@ -0,0 +1,34 @@
import { inject, injectable } from "tsyringe";
import { TtnGatewayReception } from "../models/ttnGatewayReception";
import { TtnGatewayReceptionRepository } from "../repositories/ttnGatewayReceptionRepository";
@injectable()
export class TtnGatewayReceptionService {
constructor(
@inject(TtnGatewayReceptionRepository)
private repository: TtnGatewayReceptionRepository
) {}
public async getAllGatewayReceptions() {
return this.repository.findAll();
}
public async getGatewayReceptionById(id: string) {
return this.repository.findById(id);
}
public async createGatewayReception(data: Partial<TtnGatewayReception>) {
return this.repository.create(data);
}
public async updateGatewayReception(
id: string,
data: Partial<TtnGatewayReception>
) {
return this.repository.update(id, data);
}
public async deleteGatewayReception(id: string) {
return this.repository.delete(id);
}
}

View File

@ -0,0 +1,30 @@
import { inject, injectable } from "tsyringe";
import { WifiScan } from "../models/wifiScan";
import { WifiScanRepository } from "../repositories/wifiScanRepository";
@injectable()
export class WifiScanService {
constructor(
@inject(WifiScanRepository) private repository: WifiScanRepository
) {}
public async getAllWifiScans() {
return this.repository.findAll();
}
public async getWifiScanById(id: string) {
return this.repository.findById(id);
}
public async createWifiScan(data: Partial<WifiScan>) {
return this.repository.create(data);
}
public async updateWifiScan(id: string, data: Partial<WifiScan>) {
return this.repository.update(id, data);
}
public async deleteWifiScan(id: string) {
return this.repository.delete(id);
}
}

113
server/tsconfig.json Normal file
View File

@ -0,0 +1,113 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
"rootDir": "src" /* Specify the root folder within your source files. */,
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}