main
Theenoro 2022-05-20 07:55:08 +02:00
parent 270c31ad07
commit d521488087
12 changed files with 1621 additions and 0 deletions

5
.gitignore vendored
View File

@ -116,3 +116,8 @@ dist
.yarn/install-state.gz
.pnp.*
config/config.js
data/weather.json
start.sh
source.sh
test.http

View File

@ -0,0 +1,15 @@
/**
* EXAMPLE
*/
export class Config{
// https://openweathermap.org/
static WEATHER_API = {
API_KEY: "",
CITY: "",
READING: 60000 // 10 Min
};
static WEB_SERVER = {
PORT: 8989,
WSPORT: 8990
};
}

View File

@ -0,0 +1,21 @@
import express from 'express';
import { Config } from '../config/config.js';
import { Storage } from './storage.js';
export class Web{
constructor(){
let app = express();
app.get('/temp',async (req,res)=>{
if(Storage.hub==null){
res.statusCode(500);
res.send("err");
}
res.json(await Storage.hub.getTemp());
})
app.use(express.static('static'));
app.listen(Config.WEB_SERVER.PORT);
}
}

View File

@ -0,0 +1,19 @@
import SensorHub from 'dockerpi-sensorhub';
export class Hub {
constructor() {
let hub = new SensorHub();
if (!hub || !hub.read) throw new Error('Unable to init the hub.');
this.hub = hub;
}
async getTemp() {
let x = null;
await this.hub.read().then(c=>{
x = c;
})
return x;
}
}

View File

@ -0,0 +1,4 @@
export class Storage{
static hub = null;
static dir = null;
}

View File

@ -0,0 +1,61 @@
import fs from 'fs';
import fetch from 'node-fetch';
import { Config } from '../config/config.js';
import { Storage } from "./storage.js";
class WeatherData {
timestamp = 0;
humidity = 0;
temp = 0;
weather = [];
wind_speed = 0;
wind_deg = 0;
}
export class Weather {
constructor() {
//let x = new WeatherData();
//this.writeFile(x);
Storage.weather = this;
this.data = this.readFile();
this.readApi();
this.inter = setInterval(this.readApi, 1000 * 60);
}
async readApi() {
let me = Storage.weather;
//console.log(`DIFF FROM TO ${(Math.floor((+ new Date) / 1000))} ${me.data.timestamp}`);
if (((Math.floor((+ new Date) / 1000)) - me.data.timestamp) > Config.WEATHER_API.READING) {
console.log("GET NEW DATA")
let d = Math.floor((+ new Date) / 1000)
me.data.timestamp = d;
let url = `http://api.openweathermap.org/data/2.5/weather?q=${Config.WEATHER_API.CITY}&units=metric&appid=${Config.WEATHER_API.API_KEY}`;
const response = await fetch(url, {
method: 'get',
headers: { 'Content-Type': 'application/json' }
});
const data = await response.json();
data.timestamp = data.dt;
me.data = data;
me.writeFile(me.data);
}
}
readFile() {
let jso = {};
try {
let data = fs.readFileSync(`${Storage.dir}/data/weather.json`);
jso = JSON.parse(data);
} catch (e) {
jso = {timestamp:0};
}
console.log(jso);
return jso;
}
writeFile(data) {
fs.writeFileSync(`${Storage.dir}/data/weather.json`, JSON.stringify(data));
}
}

View File

@ -0,0 +1,26 @@
import { WebSocketServer } from 'ws';
import { Config } from '../config/config.js';
import { Storage } from './storage.js';
export class WebSock {
constructor() {
let wss = new WebSocketServer({ port: Config.WEB_SERVER.WSPORT });
wss.on('connection', function connection(ws) {
let sendData = setInterval(()=>{
Storage.hub.getTemp().then(r=>{
let data = {type:'temp',inside:r,outside:Storage.weather.data};
ws.send(JSON.stringify(data));
//console.log(ws)
})
},10000)
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.on('close',()=>{
clearInterval(sendData);
})
ws.send('something');
});
this.wss = wss;
}
}

18
index.js 100644
View File

@ -0,0 +1,18 @@
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { Storage } from "./controller/storage.js";
Storage.dir = dirname(fileURLToPath(import.meta.url));
import { Web } from "./controller/express.js";
import { Hub } from "./controller/sensorhub.js";
import { WebSock } from "./controller/websocket.js";
import { Weather } from './controller/weather_api.js';
let x = new Hub();
Storage.hub = x;
let web = new Web();
let sock = new WebSock();
let weather = new Weather();

1260
package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

19
package.json 100644
View File

@ -0,0 +1,19 @@
{
"name": "sensor",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dockerpi-sensorhub": "^1.0.3",
"express": "^4.18.1",
"moment": "^2.29.3",
"node-fetch": "^3.2.4",
"ws": "^8.6.0"
}
}

154
static/index.html 100644
View File

@ -0,0 +1,154 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Temp</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');
* {
font-family: 'Roboto', sans-serif;
}
#box-top-left {
position: absolute;
left: 0;
top: 0;
background: #000000ad;
color: #FFF;
font-weight: bold;
width: 200px;
height: 50px;
}
#box-top-left:before {
content: '';
width: 0;
height: 0;
border-style: solid;
border-width: 0px 0px 25px 25px;
border-color: transparent transparent transparent #00aee7;
left: 0;
top: 0;
position: absolute;
}
#box-top-left:after {
content: '';
width: 0;
height: 0;
border-style: solid;
border-width: 25px 0px 25px 25px;
border-color: transparent transparent #00aee7 transparent;
right: 0;
top: 0;
position: absolute;
}
div#temp-inside {
position: absolute;
top: 5px;
left: 50px;
/* transform: rotateZ(-45deg);*/
}
div#temp-inside:before {
content: "i ";
display: inline-block;
margin-right: 5px;
}
div#temp-inside:after {
content: "°C";
display: inline-block;
margin-right: 5px;
}
div#temp-outside {
position: absolute;
top: 25px;
left: 10px;
/* transform: rotateZ(-45deg);*/
}
div#temp-outside:before {
content: "o ";
display: inline-block;
margin-right: 5px;
}
div#temp-outside:after {
content: "°C";
display: inline-block;
margin-right: 5px;
}
img#weather {
width: 40px;
height: 40px;
position: absolute;
left: 125px;
/* filter: brightness(0.5); */
background: #999;
border-radius: 50px;
margin-top: 5px;
}
</style>
</head>
<body>
<div id="box-top-left">
<div id="temp-inside">
</div>
<div id="temp-outside">
</div>
<div id="weather-img">
<img id="weather" src="http://openweathermap.org/img/wn/10d@2x.png" />
</div>
</div>
<div id="content"></div>
<script type="text/javascript">
var content = document.getElementById('content');
var temp_inside = document.getElementById('temp-inside');
var temp_outside = document.getElementById('temp-outside');
//var socket = new WebSocket(`ws://${window.location.hostname}:8990`);
var socket = new WebSocket(`ws://192.168.2.7:8990`);
socket.onopen = function () {
socket.send('hello from the client');
};
socket.onmessage = function (message) {
try {
let d = JSON.parse(message.data);
console.log(d);
switch (d.type) {
case "temp":
temp_inside.innerHTML = d.inside.externalTemp
temp_outside.innerHTML = Math.ceil(d.outside.main.temp)
document.getElementById("weather").src = `http://openweathermap.org/img/wn/${d.outside.weather[0].icon}@2x.png`;
break;
default:
content.innerHTML += message.data + '<br />';
break;
}
} catch (e) {
}
};
socket.onerror = function (error) {
console.log('WebSocket error: ' + error);
};
</script>
</body>
</html>

19
test.js 100644
View File

@ -0,0 +1,19 @@
//import SensorHub from 'dockerpi-sensorhub';
//
//const hub = new SensorHub();
//
//if (!hub || !hub.read) throw new Error('Unable to init the hub.');
//hub.read().then(x => {
// console.log('There are the sensorHub values:', x);
// console.log(x.externalTemp);
//});
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { Storage } from "./controller/storage.js";
import { Weather } from './controller/weather_api.js';
Storage.dir = dirname(fileURLToPath(import.meta.url));
let z = new Weather();
//z.writeFile();