diff --git a/ESP32/src/utils.cpp b/ESP32/src/utils.cpp index 0332864..73fb803 100644 --- a/ESP32/src/utils.cpp +++ b/ESP32/src/utils.cpp @@ -18,4 +18,19 @@ namespace utils return (biggestValue - from) + to + 1; } } + + uint32_t elapsed(uint32_t from, uint32_t to) + { + if(to >= from) + { + return to - from; + } + else + { + // if the counter overflowed, this computes the real duration + // of course it won't work if the counter made a "full turn" or more + const uint32_t biggestValue = (uint32_t)-1; + return (biggestValue - from) + to + 1; + } + } } diff --git a/ESP32/src/vehicle-monitor.cpp b/ESP32/src/vehicle-monitor.cpp index 465430f..11833bb 100644 --- a/ESP32/src/vehicle-monitor.cpp +++ b/ESP32/src/vehicle-monitor.cpp @@ -33,12 +33,20 @@ const int8_t I2C_SCL = 4; const float wheelDiameterInches = 20; const int numImpulsesPerTurn = 2; const float wheelCircumferenceMeters = wheelDiameterInches * 0.0254f * 3.1415f / (float)numImpulsesPerTurn; +const uint32_t wheelCircumferenceMillimeters = (uint32_t)(wheelCircumferenceMeters * 1000.0f + 0.5f); uint16_t batteryVoltage = 0; // in mV uint16_t batteryOutputCurrent = 0; // in mV int16_t temperature = 0; // in tenth of °C int32_t altitude = 0; // in mm above sea level (can be negative if below sea level, or depending on atmospheric conditions) +// current trip +uint32_t tripDistance = 0; // in meters +uint16_t tripMovingTime = 0; // cumulated seconds, only when moving at non-zero speed +uint16_t tripTotalTime = 0; // total trip time in seconds +uint32_t tripAscendingElevation = 0; // cumulated ascending elevation, in millimeters +uint32_t tripMotorEnergy = 0; // in Joules + WiFiMulti wifiMulti; wl_status_t wifi_STA_status = WL_NO_SHIELD; unsigned long wifiConnexionBegin = 0; @@ -52,6 +60,7 @@ volatile bool speedSensorState = false; volatile unsigned long speedSensorRiseTime = 0; volatile unsigned long speedSensorLastImpulseTime = 0; volatile unsigned long speedSensorLastImpulseInterval = (unsigned long)-1; // in milliseconds +volatile uint32_t speedSensorDistance = 0; // Cumulated measured distance, in millimeters. This value will overflow after about 4000km. void IRAM_ATTR onSpeedSensorChange(bool newState) { if(speedSensorState == newState) return; @@ -78,16 +87,21 @@ void IRAM_ATTR onSpeedSensorChange(bool newState) { // too little time between impulses, probably some bouncing, ignore it } - else if(timeSinceLastImpulse < 4000) - { - speedSensorLastImpulseTime = now; - speedSensorLastImpulseInterval = timeSinceLastImpulse; - } else { - // too much time between impulses, can't compute speed from that - speedSensorLastImpulseTime = now; - speedSensorLastImpulseInterval = (unsigned long)-1; + speedSensorDistance += wheelCircumferenceMillimeters; + + if(timeSinceLastImpulse < 4000) + { + speedSensorLastImpulseTime = now; + speedSensorLastImpulseInterval = timeSinceLastImpulse; + } + else + { + // too much time between impulses, can't compute speed from that + speedSensorLastImpulseTime = now; + speedSensorLastImpulseInterval = (unsigned long)-1; + } } } } @@ -200,17 +214,23 @@ void setup() int v = batteryVoltage; int c = batteryOutputCurrent; int s = (int)(getSpeed() * 1000.0f + 0.5f); - int t = temperature; + int temp = temperature; int alt = altitude; + int td = tripDistance; + int ttt = tripTotalTime; + int tmt = tripMovingTime; + int tae = tripAscendingElevation / 100; // convert mm to dm + int tme = tripMotorEnergy / 360; // convert Joules to dWh (tenth of Wh) + const char* logFileName = DataLogger::get().currentLogFileName(); if(String(logFileName).startsWith("/log/")) logFileName += 5; int totalSize = (int)(SPIFFS.totalBytes() / 1000); int usedSize = (int)(SPIFFS.usedBytes() / 1000); - char json[128]; - sprintf(json, "{\"v\":%d,\"c\":%d,\"s\":%d,\"t\":%d,\"alt\":%d,\"log\":\"%s\",\"tot\":%d,\"used\":%d}", v, c, s, t, alt, logFileName, totalSize, usedSize); + char json[256]; + sprintf(json, "{\"v\":%d,\"c\":%d,\"s\":%d,\"td\":%d,\"ttt\":%d,\"tmt\":%d,\"tae\":%d,\"tme\":%d,\"temp\":%d,\"alt\":%d,\"log\":\"%s\",\"tot\":%d,\"used\":%d}", v, c, s, td, ttt, tmt, tae, tme, temp, alt, logFileName, totalSize, usedSize); request->send(200, "text/json", json); }); @@ -399,6 +419,10 @@ void loop() handle_pressure_measure(); // also measures temperature unsigned long now = millis(); + static unsigned long lastLoopMillis = now; + unsigned long dt = utils::elapsed(lastLoopMillis, now); + lastLoopMillis = now; + static DataLogger::Entry entry; entry.batteryVoltage = (float)batteryVoltage / 1000.0f; entry.batteryOutputCurrent = (float)batteryOutputCurrent / 1000.0f; @@ -413,6 +437,11 @@ void loop() { DebugLog.println("Starting DataLogger"); DataLogger::get().open(); + tripDistance = 0; + tripMovingTime = 0; + tripTotalTime = 0; + tripAscendingElevation = 0; + tripMotorEnergy = 0; } } else @@ -432,5 +461,41 @@ void loop() } DataLogger::get().log(now, entry); - delay(DataLogger::get().isOpen() ? 10 : 1000); + bool isOnTrip = DataLogger::get().isOpen(); + bool isMoving = entry.speed > 0.0f; + + static unsigned long cumulatedMillis = 0; + cumulatedMillis += dt; + unsigned long newSeconds = cumulatedMillis / 1000; + cumulatedMillis -= newSeconds * 1000; + + uint32_t currentMillimeters = speedSensorDistance; + static uint32_t lastLoopMillimeters = currentMillimeters; + uint32_t newMillimeters = utils::elapsed(lastLoopMillimeters, currentMillimeters); + lastLoopMillimeters = currentMillimeters; + + static uint32_t cumulatedMillimeters = 0; + cumulatedMillimeters += newMillimeters; + uint32_t newMeters = cumulatedMillimeters / 1000; + cumulatedMillimeters -= newMeters * 1000; + + uint32_t altitudeMillimeters = (uint32_t)(entry.altitude * 1000.0f + 0.5f); + static uint32_t lastLoopAltitude = altitudeMillimeters; + uint32_t altitudeChange = altitudeMillimeters - lastLoopAltitude; + lastLoopAltitude = altitudeMillimeters; + + if(isOnTrip) + { + tripTotalTime += newSeconds; + if(isMoving) tripMovingTime += newSeconds; + tripDistance += newMeters; + + if(altitudeChange > 0) + tripAscendingElevation += altitudeChange; + + uint32_t newEnergy = entry.batteryVoltage * entry.batteryOutputCurrent * ((float)dt / 1000.0f); + tripMotorEnergy += newEnergy; + } + + delay(isOnTrip ? 10 : 1000); } diff --git a/README.md b/README.md index 5a597d7..018e3f7 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,45 @@ -# vehicle-monitor +vehicle-monitor is a monitoring system for electric vehicles (log various sensors, such as consumed power, solar production, speed, slope, etc.) -Monitoring system for electric vehicles (log various sensors, such as consumed power, solar production, speed, slope, apparent wind, etc.) \ No newline at end of file +# Architecture + +While nothing is very complicated in the vehicle-monitor, it does require knowledge in different domains to understand how it works, and be able to build your own, and especially if you want to modify it. Everything is well documented on the internet (Arduino, ESP32, the used libraries, mithril.js, web development, etc.), and a lot of people from different communities can help you, but be aware that if you are a beginner, you will need time to learn everything that is needed to tinker with this project. + +The system is made of an [ESP32 microcontroller](https://en.wikipedia.org/wiki/ESP32) connected to various sensors. The ESP32 also has an integrated wifi interface, which is used to host a web server. Using any web browser, typically from a smartphone or tablet (also works from PC), the user can then connect to the ESP32 to display the graphical interface and interact with it. + +## ESP32 (hardware) + +The main electronic circuit, showing how sensors are connected to the ESP32 is described in folder `schema/MCU_board`, in [Kicad](https://www.kicad.org/) format. Some sensors are connected to the `I2C` port, this is not shown on this schema (it is possible to link multiple sensors on the same `I2C` port). + +## ESP32 (software) + +The microcontroller is programmed in C++, using the Arduino framework (but keep in mind we target an ESP32 microcontroller,whose capabilities are quite different from the ATmega328P used on Arduino Uno boards). + +The web server is implemented using the [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) library. While the ESP32 hosts the entirety of the web app, most of it are just static files (a single HTML file, which links to CSS and javascript resources). The dynamic part is very simple and consists of a few web services used to retrieve data in JSON format. + +## Web app + +The user interface is implemented as a `single page application`, using the [mithril.js](https://mithril.js.org/) framework. + +# Building + +## Web app + +The web application consists of several files in the `WebApp/src` folder, which are packaged to three files which are generated in the `WebApp/www` folder using [webpack](https://webpack.js.org/). + +Webpack is based on `node.js`, so the first step is to [install node.js](https://nodejs.org/en/) (you should select the "LTS" latest version). + +Once `node.js` is installed, go in folder `vehicle-monitor/WebApp` and run the command `npm install`. This should download all the dependencies needed to build the web app. You need to do this only once. + +Then execute `npm run build` to build the web app. This should generate new files in `vehicle-monitor/WebApp/www`. If you want to work on the code, you can also use `npm run dev` which will generate the files, and then will keep listening for code changes. Each time you save a source file, it will automatically rebuild. + +Now the web app has been built, you can open `vehicle-monitor/WebApp/www/index.html` with you preferred web browser, and this should display the user interface in `test mode`. In this mode, the user interface will display fake data, since it is not connected to any real device and can't collect data from real sensors. + +## ESP32 + +This project has been developped using [PlatformIO](https://platformio.org/) to compile the code. It may or may not be possible to build it in the Arduino IDE, this has not been tested. The first step is to install PlatformIO. You have several choices to use PlatfomIO, ranging from command line to various IDE integrations. The command line interface will be described here for simplicity, but you should consider using an IDE if you want to work on the code. Here are the instructions to [install PlatformIO for command line usage](https://docs.platformio.org/en/latest/core/installation.html). + +Once installed, go in folder `vehicle-monitor/ESP32` and run the command `pio run`. This should compile the program. However, it should complain that the file `vehicle-monitor/ESP32/src/wifi-credentials.h` is missing. You have to copy the existing file `wifi-credentials.h.template` and rename it to `wifi-credentials.h`, and modify its contents to configure your wifi network (details are documented in the file itself). Once this is done, execute `pio run` again, and if everything goes smoothly, this time it should work. + +You can upload to the ESP32 chip with the command `pio run -t upload`. Please refer to the PlatformIO documentation to learn how to configure the connection to your ESP32. + +You will also need to upload some files to the ESP32 file system (SPIFFS). These files are stored in `vehicle-monitor/ESP32/data`, and the subfolder `www` is actually a symlink to the web app you built in the previous section. To upload the files, run `pio run -t uploadfs`. Again, if needed, refer to the PlatformIO documentation for details. \ No newline at end of file diff --git a/WebApp/doc/altitude.png b/WebApp/doc/altitude.png new file mode 100644 index 0000000..6539aeb Binary files /dev/null and b/WebApp/doc/altitude.png differ diff --git a/WebApp/doc/bike.png b/WebApp/doc/bike.png new file mode 100644 index 0000000..c84934f Binary files /dev/null and b/WebApp/doc/bike.png differ diff --git a/WebApp/doc/dashboard.odg b/WebApp/doc/dashboard.odg index 0ba3348..6286f1a 100644 Binary files a/WebApp/doc/dashboard.odg and b/WebApp/doc/dashboard.odg differ diff --git a/WebApp/doc/dashboard.png b/WebApp/doc/dashboard.png new file mode 100644 index 0000000..9cece38 Binary files /dev/null and b/WebApp/doc/dashboard.png differ diff --git a/WebApp/doc/dashboard.xcf b/WebApp/doc/dashboard.xcf deleted file mode 100644 index ae934c9..0000000 Binary files a/WebApp/doc/dashboard.xcf and /dev/null differ diff --git a/WebApp/doc/distance.png b/WebApp/doc/distance.png new file mode 100644 index 0000000..fc8a204 Binary files /dev/null and b/WebApp/doc/distance.png differ diff --git a/WebApp/doc/electricity.png b/WebApp/doc/electricity.png new file mode 100644 index 0000000..f26f95b Binary files /dev/null and b/WebApp/doc/electricity.png differ diff --git a/WebApp/doc/temperature.png b/WebApp/doc/temperature.png new file mode 100644 index 0000000..bad9d8c Binary files /dev/null and b/WebApp/doc/temperature.png differ diff --git a/WebApp/doc/time.png b/WebApp/doc/time.png new file mode 100644 index 0000000..c2b4425 Binary files /dev/null and b/WebApp/doc/time.png differ diff --git a/WebApp/package.json b/WebApp/package.json index e73cbcb..e721be2 100644 --- a/WebApp/package.json +++ b/WebApp/package.json @@ -19,6 +19,7 @@ "purgecss-webpack-plugin": "^4.1.3", "style-loader": "^3.3.1", "ts-loader": "^9.2.8", + "tsconfig-paths-webpack-plugin": "^3.5.2", "typescript": "^4.6.2", "webpack": "^5.70.0", "webpack-cli": "^4.9.2" diff --git a/WebApp/src/app.ts b/WebApp/src/app.ts index 7ec4b0f..05957ff 100644 --- a/WebApp/src/app.ts +++ b/WebApp/src/app.ts @@ -1,8 +1,8 @@ import m from 'mithril'; import Layout from './layout'; -import RawDataPage from './raw-data-page'; -import DashboardPage from './dashboard-page'; +import { RawDataPage } from 'pages/raw-data/raw-data-page'; +import { DashboardPage } from 'pages/dashboard/dashboard-page'; require('../node_modules/bulma/css/bulma.css'); diff --git a/WebApp/src/assets.d.ts b/WebApp/src/assets.d.ts new file mode 100644 index 0000000..4997750 --- /dev/null +++ b/WebApp/src/assets.d.ts @@ -0,0 +1 @@ +declare module "*.png"; diff --git a/WebApp/src/assets/bike.png b/WebApp/src/assets/bike.png new file mode 100644 index 0000000..c84934f Binary files /dev/null and b/WebApp/src/assets/bike.png differ diff --git a/WebApp/src/assets/icons/altitude.png b/WebApp/src/assets/icons/altitude.png new file mode 100644 index 0000000..ae1f982 Binary files /dev/null and b/WebApp/src/assets/icons/altitude.png differ diff --git a/WebApp/src/assets/icons/ascending-elevation.png b/WebApp/src/assets/icons/ascending-elevation.png new file mode 100644 index 0000000..6345fe7 Binary files /dev/null and b/WebApp/src/assets/icons/ascending-elevation.png differ diff --git a/WebApp/src/assets/icons/average.png b/WebApp/src/assets/icons/average.png new file mode 100644 index 0000000..7c32a5e Binary files /dev/null and b/WebApp/src/assets/icons/average.png differ diff --git a/WebApp/src/assets/icons/distance-electricity.png b/WebApp/src/assets/icons/distance-electricity.png new file mode 100644 index 0000000..89cfa8a Binary files /dev/null and b/WebApp/src/assets/icons/distance-electricity.png differ diff --git a/WebApp/src/assets/icons/distance.png b/WebApp/src/assets/icons/distance.png new file mode 100644 index 0000000..36797ec Binary files /dev/null and b/WebApp/src/assets/icons/distance.png differ diff --git a/WebApp/src/assets/icons/electricity.png b/WebApp/src/assets/icons/electricity.png new file mode 100644 index 0000000..a22b105 Binary files /dev/null and b/WebApp/src/assets/icons/electricity.png differ diff --git a/WebApp/src/assets/icons/temperature.png b/WebApp/src/assets/icons/temperature.png new file mode 100644 index 0000000..1496d12 Binary files /dev/null and b/WebApp/src/assets/icons/temperature.png differ diff --git a/WebApp/src/assets/icons/time.png b/WebApp/src/assets/icons/time.png new file mode 100644 index 0000000..6d58f5b Binary files /dev/null and b/WebApp/src/assets/icons/time.png differ diff --git a/WebApp/src/components/component.ts b/WebApp/src/components/component.ts new file mode 100644 index 0000000..22037d4 --- /dev/null +++ b/WebApp/src/components/component.ts @@ -0,0 +1,23 @@ +import m from 'mithril'; + +export abstract class Component { + abstract view(vnode: m.Vnode): m.Children; + + constructor(vnode?: m.Vnode) { + + } + + oninit(vnode: m.Vnode) {} + + oncreate(vnode: m.Vnode) {} + + onbeforeupdate(newVnode: m.Vnode, oldVnode: m.Vnode) { + return true; + } + + onupdate(vnode: m.Vnode) {} + + onbeforeremove(vnode: m.Vnode): Promise | void {} + + onremove(vnode: m.Vnode) {} +} diff --git a/WebApp/src/components/page.ts b/WebApp/src/components/page.ts new file mode 100644 index 0000000..b6edad3 --- /dev/null +++ b/WebApp/src/components/page.ts @@ -0,0 +1,5 @@ +import { Component } from 'components/component'; + +export abstract class Page extends Component { + +} diff --git a/WebApp/src/components/widgets/chronometer.css b/WebApp/src/components/widgets/chronometer.css new file mode 100644 index 0000000..5046bc9 --- /dev/null +++ b/WebApp/src/components/widgets/chronometer.css @@ -0,0 +1,3 @@ +div.widget.chronometer span.integral-value { + font-size: 2.0rem; +} diff --git a/WebApp/src/components/widgets/chronometer.tsx b/WebApp/src/components/widgets/chronometer.tsx new file mode 100644 index 0000000..7e0e114 --- /dev/null +++ b/WebApp/src/components/widgets/chronometer.tsx @@ -0,0 +1,54 @@ +import { NumericValue } from 'components/widgets/numeric-value'; + +require('./chronometer.css'); + +export class Chronometer extends NumericValue { + private realTimeValue = 0; + private realTimeReference = 0; + + private animating = false; + private shuttingDown = false; + + protected mainClassName() { return 'numeric-value chronometer'; } + + protected onValueChange(value: number) { + let now = Date.now() / 1000; + + let realTimeValue = this.realTimeValue + (now - this.realTimeReference); + + if(Math.abs(value - realTimeValue) < 2.0) + return; + + this.realTimeValue = value; + this.realTimeReference = now; + realTimeValue = value; + this.startAnimation(); + } + + private startAnimation() { + if(this.animating) + return; + this.animating = true; + this.animate(); + } + + onbeforeremove(vnode: any) { + this.shuttingDown = true; + super.onbeforeremove(vnode); + } + + private animate() { + if(this.shuttingDown) return; + + let now = Date.now() / 1000; + let realTimeValue = this.realTimeValue + (now - this.realTimeReference); + + let hours = Math.floor(realTimeValue / 3600); + let minutes = Math.floor((realTimeValue - hours * 3600)/60); + let seconds = Math.floor(realTimeValue - hours * 3600 - minutes * 60); + + this.integralValueElement.innerText = (hours < 10 ? '0' : '') + hours + ':' + (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds; + + setTimeout(() => this.animate(), (Math.ceil(realTimeValue) + 0.05 - realTimeValue) * 1000); + } +} diff --git a/WebApp/src/components/widgets/clock.css b/WebApp/src/components/widgets/clock.css new file mode 100644 index 0000000..7d9c7e6 --- /dev/null +++ b/WebApp/src/components/widgets/clock.css @@ -0,0 +1,15 @@ +div.clock { + text-align: center; +} + +div.clock div.date { + display: inline-block; + text-aligne: center; +} + +div.clock p.time { + display: inline-block; + font-family: monospace; + font-size: 3.5rem; + margin-left: 0.8rem; +} diff --git a/WebApp/src/components/widgets/clock.tsx b/WebApp/src/components/widgets/clock.tsx new file mode 100644 index 0000000..3dd38af --- /dev/null +++ b/WebApp/src/components/widgets/clock.tsx @@ -0,0 +1,25 @@ +import m from 'mithril'; +import { Widget } from 'components/widgets/widget'; + +require("./clock.css"); + +export class Clock extends Widget { + constructor(vnode: any) { + super(vnode); + } + + view(vnode: m.Vnode<{}, {}>): m.Children { + var now = new Date(); + var days = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi']; + var nextUpdateDelay = 61 - now.getSeconds(); + setTimeout(() => m.redraw(), nextUpdateDelay * 1000); + + return
+
+

{days[now.getDay()]}

+

{('0'+now.getDate()).slice(-2) + '/' + ('0'+now.getMonth()).slice(-2)}

+
+

{('0'+now.getHours()).slice(-2) + ':' + ('0'+now.getMinutes()).slice(-2)}

+
; + } +} diff --git a/WebApp/src/components/widgets/gauge-battery.tsx b/WebApp/src/components/widgets/gauge-battery.tsx new file mode 100644 index 0000000..869e317 --- /dev/null +++ b/WebApp/src/components/widgets/gauge-battery.tsx @@ -0,0 +1,27 @@ +import m from 'mithril'; +import { GaugeLinear } from 'components/widgets/gauge-linear'; + +export class GaugeBattery extends GaugeLinear { + constructor(vnode: any) { + super(vnode); + this.svgPaddingTop = 0.06; + } + + createSvg(svgElement: SVGElement) { + super.createSvg(svgElement); + + let w = Math.round(svgElement.clientWidth); + let h = Math.round(svgElement.clientHeight); + let paddingTop = Math.round(svgElement.clientHeight * this.svgPaddingTop); + + const batteryTopWidth = 0.5; + + let batteryTop = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); + batteryTop.setAttribute('width', (w * batteryTopWidth).toFixed(1)); + batteryTop.setAttribute('height', (paddingTop).toString()); + batteryTop.setAttribute('x', (w * (1.0 - batteryTopWidth)*0.5).toFixed(1)); + batteryTop.setAttribute('y', '0'); + batteryTop.classList.add('gauge-bg'); + svgElement.append(batteryTop); + } +} diff --git a/WebApp/src/components/widgets/gauge-circular.css b/WebApp/src/components/widgets/gauge-circular.css new file mode 100644 index 0000000..b441413 --- /dev/null +++ b/WebApp/src/components/widgets/gauge-circular.css @@ -0,0 +1,9 @@ +div.gauge svg.gauge-circular path.gauge-bg-outline { + stroke: rgb(0,0,0); + fill: none; +} + +div.gauge svg.gauge-circular path.gauge-bg { + stroke: rgb(255,255,255); + fill: none; +} diff --git a/WebApp/src/components/widgets/gauge-circular.tsx b/WebApp/src/components/widgets/gauge-circular.tsx new file mode 100644 index 0000000..c03986a --- /dev/null +++ b/WebApp/src/components/widgets/gauge-circular.tsx @@ -0,0 +1,94 @@ +import m from 'mithril'; +import { Gauge } from 'components/widgets/gauge'; +import { Pipe } from 'utilities/pipe'; + +require('./gauge-circular.css'); + +export class GaugeCircular extends Gauge { + constructor(vnode: any) { + super(vnode); + } + + createSvg(svgElement: SVGElement) { + let w = Math.round(svgElement.clientWidth); + let h = Math.round(svgElement.clientHeight); + + svgElement.classList.add('gauge-circular'); + + svgElement.setAttribute('viewBox', "0 0 "+w+" "+h); + + let svgRound = (v: number) => Math.round(v * 100.0) / 100.0; + + const arcRatio = 0.75; // from 0.5 for half circle to 1.0 for full circle + const gaugeWidthRatio = 0.15; // relative to the smallest dimension of the drawing area + const lineThickness = 1; + + let gaugeWidth = Math.round(Math.min(w, h) * gaugeWidthRatio); + let gaugeRadius = Math.round(Math.min(w, h) * 0.5 - gaugeWidth * 0.5 - lineThickness - 1); + let cx = Math.round(w * 0.5); let cy = Math.round(h * 0.5); + + let openingHalfAngle = Math.PI * (1.0 - arcRatio); + let arcLength = Math.PI * 2.0 * gaugeRadius * arcRatio; + let startx = svgRound(cx - Math.sin(openingHalfAngle) * gaugeRadius); + let starty = svgRound(cy + Math.cos(openingHalfAngle) * gaugeRadius); + let dx = svgRound(2.0 * Math.sin(openingHalfAngle) * gaugeRadius); + + let outlineArcRatio = (arcLength + lineThickness*2.0) / (Math.PI * 2.0 * gaugeRadius); + let outlineOpeningHalfAngle = Math.PI * (1.0 - outlineArcRatio); + let outlineStartx = svgRound(cx - Math.sin(outlineOpeningHalfAngle) * gaugeRadius); + let outlineStarty = svgRound(cy + Math.cos(outlineOpeningHalfAngle) * gaugeRadius); + let outlineDx = svgRound(2.0 * Math.sin(outlineOpeningHalfAngle) * gaugeRadius); + + let bgOutline = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + bgOutline.setAttribute('d', 'M'+outlineStartx+' '+outlineStarty+' a'+gaugeRadius+' '+gaugeRadius+' 0 1 1 '+outlineDx+' 0'); + bgOutline.setAttribute('style', 'stroke-width: '+(gaugeWidth+lineThickness*2)); + bgOutline.classList.add('gauge-bg-outline'); + svgElement.append(bgOutline); + + let bg = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + bg.setAttribute('d', 'M'+startx+' '+starty+' a'+gaugeRadius+' '+gaugeRadius+' 0 1 1 '+dx+' 0'); + bg.setAttribute('style', 'stroke-width: '+(gaugeWidth)); + bg.classList.add('gauge-bg'); + svgElement.append(bg); + + let barHeight = 10; + const barGap = barHeight * 0.2; + let numBars = Math.round(arcLength / (barHeight + barGap)); + + barHeight = (arcLength - (numBars+1)*barGap) / numBars; + + let computeCircleCoords = function(d: number, r: number, out: {x: number, y: number}) { + let a = outlineOpeningHalfAngle + (2.0 * Math.PI - outlineOpeningHalfAngle * 2.0) * (d / arcLength); + out.x = svgRound(cx - Math.sin(a) * r); + out.y = svgRound(cy + Math.cos(a) * r); + }; + + let points: {x: number, y: number}[] = []; + for(let idx = 0; idx < 4; ++idx) { points[idx] = {x: 0, y: 0}; } + for(let barIdx = 0; barIdx < numBars; ++barIdx) { + let bar = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + bar.classList.add('gauge-bar'); + bar.classList.toggle('lit', false); + + let barStartLen = barGap + barIdx * (barHeight + barGap); + let barEndLen = barStartLen + barHeight; + computeCircleCoords(barStartLen, gaugeRadius - gaugeWidth*0.5 + barGap, points[0]); + computeCircleCoords(barStartLen, gaugeRadius + gaugeWidth*0.5 - barGap, points[1]); + computeCircleCoords(barEndLen, gaugeRadius + gaugeWidth*0.5 - barGap, points[2]); + computeCircleCoords(barEndLen, gaugeRadius - gaugeWidth*0.5 + barGap, points[3]); + + bar.setAttribute('d', 'M'+points[0].x+' '+points[0].y+' L'+points[1].x+' '+points[1].y+' L'+points[2].x+' '+points[2].y+' L'+points[3].x+' '+points[3].y+' Z'); + + svgElement.append(bar); + + this.bars.push(bar); + } + } + + oncreate(vnode: any) { + let svgElement: SVGElement = vnode.dom.querySelector('svg'); + this.createSvg(svgElement); + + super.oncreate(vnode); + } +} diff --git a/WebApp/src/components/widgets/gauge-linear.css b/WebApp/src/components/widgets/gauge-linear.css new file mode 100644 index 0000000..e69de29 diff --git a/WebApp/src/components/widgets/gauge-linear.tsx b/WebApp/src/components/widgets/gauge-linear.tsx new file mode 100644 index 0000000..9620a8e --- /dev/null +++ b/WebApp/src/components/widgets/gauge-linear.tsx @@ -0,0 +1,68 @@ +import m from 'mithril'; +import { Gauge } from 'components/widgets/gauge'; +import { Pipe } from 'utilities/pipe'; + +require('./gauge-linear.css'); + +export class GaugeLinear extends Gauge { + protected svgPaddingTop = 0.0; + private bottomWidth: number; + private topWidth: number; + + constructor(vnode: any) { + super(vnode); + + this.bottomWidth = vnode.attrs.bottomWidth || 1.0; + this.topWidth = vnode.attrs.topWidth || 1.0; + } + + createSvg(svgElement: SVGElement) { + let w = Math.round(svgElement.clientWidth); + let h = Math.round(svgElement.clientHeight); + let paddingTop = Math.round(svgElement.clientHeight * this.svgPaddingTop); + + svgElement.setAttribute('viewBox', "0 0 "+w+" "+h); + + let svgRound = (v: number) => Math.round(v * 100.0) / 100.0; + + let bg = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + //bg.setAttribute('width', w.toString()); + //bg.setAttribute('height', (h - paddingTop).toString()); + //bg.setAttribute('y', paddingTop.toString()); + bg.setAttribute('d', 'M0,'+paddingTop+' L'+svgRound(w*this.topWidth)+','+paddingTop+' L'+svgRound(w*this.bottomWidth)+','+h+' L0,'+h+' Z'); + bg.classList.add('gauge-bg'); + svgElement.append(bg); + + let barHeight = 10; + const barGap = barHeight * 0.2; + let numBars = Math.round((h - paddingTop) / (barHeight + barGap)); + + let bh = ((h - paddingTop) - (numBars+1)*barGap) / numBars; + barHeight = Math.round(bh); + + for(let barIdx = 0; barIdx < numBars; ++barIdx) { + let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); + let barW = w * ((barGap + barIdx * (bh+barGap))/(h - paddingTop) * (this.topWidth - this.bottomWidth) + this.bottomWidth); + let barW1 = w * ((barGap + barIdx * (bh+barGap) + bh)/(h - paddingTop) * (this.topWidth - this.bottomWidth) + this.bottomWidth); + barW = Math.min(barW, barW1); + bar.setAttribute('width', (barW - barGap * 2).toString()); + bar.setAttribute('height', barHeight.toString()); + bar.classList.add('gauge-bar'); + bar.classList.toggle('lit', false); + + bar.setAttribute('x', barGap.toString()); + bar.setAttribute('y', (h - barIdx * (bh+barGap) - barGap - barHeight).toString()); + + svgElement.append(bar); + + this.bars.push(bar); + } + } + + oncreate(vnode: any) { + let svgElement: SVGElement = vnode.dom.querySelector('svg'); + this.createSvg(svgElement); + + super.oncreate(vnode); + } +} diff --git a/WebApp/src/components/widgets/gauge.css b/WebApp/src/components/widgets/gauge.css new file mode 100644 index 0000000..a695329 --- /dev/null +++ b/WebApp/src/components/widgets/gauge.css @@ -0,0 +1,27 @@ +div.gauge { + display: flex; + flex-direction: column; + text-align: center; +} + +div.gauge svg { + flex: 1; +} + +.gauge-bg { + fill: rgb(255,255,255); + stroke-width: 2; + stroke: rgb(0,0,0) +} + +div.gauge .gauge-bar { + fill: rgb(230,230,230); + stroke-width: 1; + stroke: rgb(180,180,180) +} + +div.gauge .gauge-bar.lit { + fill: rgb(180,180,180); + stroke-width: 1; + stroke: rgb(0,0,0) +} diff --git a/WebApp/src/components/widgets/gauge.tsx b/WebApp/src/components/widgets/gauge.tsx new file mode 100644 index 0000000..579da05 --- /dev/null +++ b/WebApp/src/components/widgets/gauge.tsx @@ -0,0 +1,105 @@ +import m from 'mithril'; +import { NumericValue } from 'components/widgets/numeric-value'; +import { Pipe } from 'utilities/pipe'; + +require('./gauge.css'); + +export class Gauge extends NumericValue { + protected bars: SVGGeometryElement[] = []; + + private displayedValue = 0.0; + private targetValue = 0.0; + private valueChangeRate = 0.0; + private litBars = 0; + + private animating = false; + private shuttingDown = false; + + private lastGaugeUpdate = 0.0; + private lastAnimationTick = 0.0; + + constructor(vnode: any) { + super(vnode); + } + + onbeforeremove(vnode: m.Vnode<{}, {}>) { + this.shuttingDown = true; + super.onbeforeremove(vnode); + } + + protected mainClassName() { return 'gauge'; } + + protected graphicalRepresentation(vnode: m.Vnode<{}, {}>): m.Children { + return ; + } + + protected onValueChange(value: number) { + let now = Date.now() / 1000.0; + + super.onValueChange(value); + + let ratio = value / (this.maxValue || 1.0); + let numBars = this.bars.length; + let threshold = 0.33 / numBars; + + if(ratio > this.targetValue + threshold || ratio < this.targetValue - threshold) { + let animationTime = this.lastGaugeUpdate == 0.0 ? 0.0001 : Math.max(0.0001, Math.min(0.75, now - this.lastGaugeUpdate)); + + this.valueChangeRate = (ratio - this.displayedValue) / animationTime; + this.targetValue = ratio; + + this.enableAnimation(); + } + + this.lastGaugeUpdate = now; + } + + private enableAnimation() { + if(this.animating) return; + this.animating = true; + this.lastAnimationTick = Date.now() / 1000.0 - 0.016; + requestAnimationFrame(() => this.animate()); + } + + private animate() { + if(this.shuttingDown) return; + + if(this.valueChangeRate == 0.0) { + this.animating = false; + return; + } + + requestAnimationFrame(() => this.animate()); + + let now = Date.now() / 1000.0; + if(now > this.lastAnimationTick + 0.75) { + this.displayedValue = this.targetValue; + this.valueChangeRate = 0.0; + } + else { + let dt = now - this.lastAnimationTick; + if(dt < 0.04) return; // limit framerate to save battery + + this.displayedValue += this.valueChangeRate * dt; + if((this.displayedValue > this.targetValue) == (this.valueChangeRate > 0.0)) { + this.displayedValue = this.targetValue; + this.valueChangeRate = 0.0; + } + } + + this.lastAnimationTick = now; + + let numBars = this.bars.length; + let litBars = Math.round(this.displayedValue * numBars); + if(litBars == this.litBars) + return; + this.litBars = litBars; + + for(let barIdx = 0; barIdx < numBars; ++barIdx) { + let bar = this.bars[barIdx]; + let isLit = barIdx < litBars; + if(bar.classList.contains('lit') != isLit) + bar.classList.toggle('lit', isLit); + } + } +} diff --git a/WebApp/src/components/widgets/numeric-value.css b/WebApp/src/components/widgets/numeric-value.css new file mode 100644 index 0000000..ddb1d33 --- /dev/null +++ b/WebApp/src/components/widgets/numeric-value.css @@ -0,0 +1,37 @@ +div.widget span.integral-value { + font-size: 2.2rem; + font-family: monospace; +} + +div.widget span.decimal-value { + font-size: 1.6rem; + font-family: monospace; +} + +div.widget span.unit { + font-size: 1.6rem; +} + +div.widget div.value-icon { + display: inline-block; + height: 2.3rem; + width: 4rem; + text-align: center; + margin-right: 0.2rem; +} + +div.widget div.value-icon img { + display: inline-block; + height: 100%; + position: relative; + top: 0.2rem; +} + +div.numeric-value { + padding-left: 0.5rem; +} + +div.numeric-value span.unit { + font-size: 1.1rem; + margin-left: 0.2rem; +} diff --git a/WebApp/src/components/widgets/numeric-value.tsx b/WebApp/src/components/widgets/numeric-value.tsx new file mode 100644 index 0000000..b07dda8 --- /dev/null +++ b/WebApp/src/components/widgets/numeric-value.tsx @@ -0,0 +1,72 @@ +import m from 'mithril'; +import { Widget } from 'components/widgets/widget'; +import { Pipe } from 'utilities/pipe'; + +require('./numeric-value.css'); + +export class NumericValue extends Widget { + protected value: Pipe; + protected minValue?: number; + protected maxValue?: number; + protected unit: string; + protected decimals: number; + + protected icon?: string; + + protected integralValueElement: HTMLElement; + protected decimalValueElement: HTMLElement; + + constructor(vnode: any) { + super(vnode); + + this.value = vnode.attrs.value || new Pipe(0.0); + this.minValue = vnode.attrs.minValue || null; + this.maxValue = vnode.attrs.maxValue || null; + this.unit = vnode.attrs.unit || ''; + this.decimals = vnode.attrs.decimals || 0; + + this.icon = vnode.attrs.icon || null; + + this.value.onChange(() => this.onValueChange(this.getClampedValue())); + } + + view(vnode: m.Vnode<{}, {}>): m.Children { + return
+

+ {this.icon ?

: null} + + + {this.unit} +

+ {this.graphicalRepresentation(vnode)} +
; + } + + protected mainClassName() { return 'numeric-value'; } + + protected graphicalRepresentation(vnode: m.Vnode<{}, {}>): m.Children { + return []; + } + + private getClampedValue() { + let value = this.value.get(); + if(this.minValue !== null) value = Math.max(value, this.minValue); + if(this.maxValue !== null) value = Math.min(value, this.maxValue); + return value; + } + + protected onValueChange(newValue: number) { + let valueStr = newValue.toFixed(this.decimals); + let parts = valueStr.split('.'); + + this.integralValueElement.innerText = parts[0]; + this.decimalValueElement.innerText = this.decimals > 0 ? '.' + parts[1] : ''; + } + + oncreate(vnode: any) { + this.integralValueElement = vnode.dom.querySelector('span.integral-value'); + this.decimalValueElement = vnode.dom.querySelector('span.decimal-value'); + + this.onValueChange(this.getClampedValue()); + } +} diff --git a/WebApp/src/components/widgets/widget.css b/WebApp/src/components/widgets/widget.css new file mode 100644 index 0000000..da638e6 --- /dev/null +++ b/WebApp/src/components/widgets/widget.css @@ -0,0 +1,11 @@ +div.widgets-row { + padding-top: 0.5rem; + padding-bottom: 0.5rem; + display: flex; + flex-direction: row; +} + +div.widget { + flex: 1; + margin: 0.2rem; +} diff --git a/WebApp/src/components/widgets/widget.ts b/WebApp/src/components/widgets/widget.ts new file mode 100644 index 0000000..840133f --- /dev/null +++ b/WebApp/src/components/widgets/widget.ts @@ -0,0 +1,19 @@ +import m from 'mithril'; +import { Component } from 'components/component' + +require('./widget.css'); + +interface WidgetAttrs +{ + widgetWidth: number; +} + +export abstract class Widget extends Component { + public widgetWidth = 1.0; + + constructor(vnode?: m.Vnode) { + super(vnode); + if(vnode.attrs.widgetWidth !== undefined) + this.widgetWidth = vnode.attrs.widgetWidth; + } +}; diff --git a/WebApp/src/dashboard-page.tsx b/WebApp/src/dashboard-page.tsx deleted file mode 100644 index 3d914a0..0000000 --- a/WebApp/src/dashboard-page.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import m from 'mithril'; -import { MonitorApi, Status } from './monitor-api'; - -export default class DashboardPage { - status: Status = null; - autoRefresh = true; - - oninit() { - this.status = MonitorApi.get().getStatus(); - this.refresh(); - } - - onbeforeremove() { - this.autoRefresh = false; - } - - async refresh() { - this.status = await MonitorApi.get().fetchStatus(); - if(this.autoRefresh) - setTimeout(() => { if(this.autoRefresh) this.refresh(); }, 500); - } - - view() { - return this.status - ?
-
- :

Chargement...

; - } -} diff --git a/WebApp/src/layout.css b/WebApp/src/layout.css index 7cb6790..fffb86a 100644 --- a/WebApp/src/layout.css +++ b/WebApp/src/layout.css @@ -1,3 +1,13 @@ -/*html body { - font-size: 3rem; -}*/ +html, html > body { + height: 100%; + width: 100%; +} + +html > body { + display: flex; + flex-direction: column; +} + +html > body > section { + flex: 1; +} diff --git a/WebApp/src/layout.tsx b/WebApp/src/layout.tsx index f1497ef..89e3bf6 100644 --- a/WebApp/src/layout.tsx +++ b/WebApp/src/layout.tsx @@ -4,8 +4,11 @@ require("./layout.css"); export default class Layout { private menuActive = false; + private drawCount = 0; view(vnode: m.Vnode) { + this.drawCount = this.drawCount + 1; + return [