Skip to content

Commit

Permalink
First implementation (#1)
Browse files Browse the repository at this point in the history
First implementation with installation doc, usage, example, license.
  • Loading branch information
teemoo7 committed Dec 14, 2023
1 parent 6f2a995 commit 75664c2
Show file tree
Hide file tree
Showing 8 changed files with 264 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,6 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# IDE
.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Micael Paquier

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.
15 changes: 15 additions & 0 deletions MMM-TomTomCalculateRouteTraffic.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.MMM-TomTomCalculateRouteTraffic .error {
color: #ad1212
}

.MMM-TomTomCalculateRouteTraffic .route {
padding: 15px;
}

.MMM-TomTomCalculateRouteTraffic .delay {
color: #bf553c
}

.MMM-TomTomCalculateRouteTraffic .symbol {
margin-right: 10px;
}
142 changes: 142 additions & 0 deletions MMM-TomTomCalculateRouteTraffic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
Module.register("MMM-TomTomCalculateRouteTraffic", {
defaults: {
apiTomTomBaseUrl: "https://api.tomtom.com/routing/1/calculateRoute",
apiTomTomKey: "",
refresh: (5 * 60 * 1000),
animationSpeed: 2000,
routes: [],
},

start: function () {
Log.info(`Starting module: ${this.name}`);
if (this.config.apiTomTomKey === "") {
Log.error(`${this.name}: TomTom API key not set. Please read the README.md for details.`);
return;
}

this.calculatedRoutes = [];
this.errorMessage = undefined;

var self = this;
setInterval(function () {
self.calculateRoutes();
}, this.config.refresh);
self.calculateRoutes();
},

getStyles: function () {
return ["MMM-TomTomCalculateRouteTraffic.css", "font-awesome.css"];
},

getScripts: function () {
return [];
},

getTranslations: function () {
return {
en: "translations/en.json",
de: "translations/fr.json",
};
},

getDom: function () {
let wrapper = document.createElement("div");

if (this.errorMessage !== undefined) {
let errorDiv = document.createElement("div");
errorDiv.className = "error";
errorDiv.innerHTML = "ERROR: " + this.errorMessage;
wrapper.appendChild(errorDiv);
}

this.calculatedRoutes.forEach(calculatedRoute => {
let routeDiv = document.createElement("div");
routeDiv.className = "route";

let travelDiv = document.createElement("div");
routeDiv.appendChild(travelDiv);

let timeDiv = document.createElement("div");
let numbersSpan = document.createElement("span");
numbersSpan.className = "bright large";
numbersSpan.innerHTML = calculatedRoute.calculated.timeMin;
timeDiv.appendChild(numbersSpan);
let minutesSpan = document.createElement("span");
minutesSpan.className = "normal medium";
minutesSpan.innerHTML = " " + this.translate("minutes");
timeDiv.appendChild(minutesSpan);
travelDiv.appendChild(timeDiv);
if (calculatedRoute.calculated.delayMin > 0) {
let delayDiv = document.createElement("div");
delayDiv.innerHTML = "(" + this.translate("including minutes delay", {"delayInMinutes": calculatedRoute.calculated.delayMin}) + ")";
delayDiv.className = "medium delay";
travelDiv.appendChild(delayDiv);
}

let infoDiv = document.createElement("div");
routeDiv.appendChild(infoDiv);

if (calculatedRoute.route.symbol !== undefined) {
let symbolSpan = document.createElement("span");
symbolSpan.className = `fa fa-${calculatedRoute.route.symbol} symbol`;
infoDiv.appendChild(symbolSpan);
}
let nameSpan = document.createElement("span");
nameSpan.className = "normal small";
nameSpan.innerHTML = calculatedRoute.route.name + " (" + calculatedRoute.calculated.lengthKm + " km)";
infoDiv.appendChild(nameSpan);

wrapper.appendChild(routeDiv);
});

return wrapper;
},

calculateRoutes: function () {
this.calculatedRoutes = [];
this.config.routes.forEach(route => {
this.calculateRoute(route);
});
},

calculateRoute: function (route) {
let locations = `${route.from.latitude},${route.from.longitude}:${route.to.latitude},${route.to.longitude}`;
let url = `${this.config.apiTomTomBaseUrl}/${locations}/json?key=${this.config.apiTomTomKey}`;

let self = this;
let request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
self.processData(JSON.parse(this.response), route);
} else {
var errorMessage = `${self.name}: TomTom API returned an error: ${this.status}. `;
if (this.status === 400) {
errorMessage += "Incorrect request (locations)";
} else if (this.status === 403) {
errorMessage += "Authentication / permissions issue";
}
Log.error(errorMessage);
self.errorMessage = errorMessage;
}
self.updateDom(self.config.animationSpeed);
}
};
request.send();
},

processData: function (jsonBody, route) {
let summary = jsonBody.routes[0].summary;
let calculatedRoute = {
route: route,
calculated: {
lengthKm: Math.ceil(summary.lengthInMeters / 1000),
timeMin: Math.ceil(summary.travelTimeInSeconds / 60),
delayMin: Math.ceil(summary.trafficDelayInSeconds / 60),
}
};
this.calculatedRoutes.push(calculatedRoute);
},

});
76 changes: 75 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,76 @@
# MMM-TomTomCalculateRouteTraffic
MagicMirror module to calculat routes with TomTom API and display time with delay

[MagicMirror²](https://github.com/MichMich/MagicMirror/) module to calculate routes with TomTom API (free), and display travel time with traffic delays.

![ScreenShot](screenshots/route.png)

## Installation

1. Navigate to the `MagicMirror/modules` directory.
2. Execute `git clone https://github.com/teemoo7/MMM-TomTomCalculateRouteTraffic.git`
3. Configure the module with your routes as per below
4. Restart MagicMirror

## Usage

To use this module, add the following configuration block to the modules array in the `config/config.js` file:
```js
modules: [
{
module: "MMM-TomTomCalculateRouteTraffic",
position: "top_right",
header: "TomTom Calculated Routes",
config: {
apiTomTomKey: "<YOUR_API_KEY_HERE>",
refresh: (5 * 60 * 1000), // in milliseconds
animationSpeed: 2000, // in milliseconds
routes: [{
name: "Lausanne City Center",
symbol: "city",
from: {latitude: 46.4510653, longitude: 6.8192693},
to: {latitude: 46.5287271, longitude: 6.652336}
}, {
name: "Zermatt chalet",
symbol: "mountain",
from: {latitude: 46.4510653, longitude: 6.8192693},
to: {latitude: 45.9904832, longitude: 7.6594364}
}]
}
},
]
```

## Configuration

### Options

| Field | Required | Description | Default |
|-------------------|----------|-----------------------------------------------------------|-------------------------------|
| `apiTomTomKey` | `true` | Your API key for TomTom API | |
| `routes ` | `true` | Routes definition, with an array. See `route` specs below | |
| `refresh ` | `false` | Refresh interval (in milliseconds) | `(5 * 60 * 1000)` (5 minutes) |
| `animationSpeed ` | `false` | Animation time to display results (in milliseconds) | `2000` |

### `route` specs

| Field | Required | Description |
|-----------|----------|------------------------------------------------------------------------|
| `name` | `true` | Any name to identify the route |
| `symbol ` | `false` | A symbol name, from [Font Awesome icons](http://fontawesome.io/icons/) |
| `from ` | `true` | Starting position, see `position` specs below |
| `to ` | `true` | Destination position, see `position` specs below |

### `position` specs

| Field | Required | Description |
|--------------|----------|----------------------|
| `latitude` | `true` | Latitude coordinate |
| `longitude ` | `true` | Longitude coordinate |

## TomTom routing API

Relies on [TomTom routing API Calculate Route v1](https://developer.tomtom.com/routing-api/documentation/routing/calculate-route).

Note that contrary to many services like Google, **TomTom provides free APIs that can be used without credit card or any billing info**, with a reasonable **daily limit set to 2500 calls**.

To get an API key, just [create a developer account](https://developer.tomtom.com/user/register) and go to your [API & SDK keys](https://developer.tomtom.com/user/me/apps) page.
Binary file added screenshots/route.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions translations/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"minutes": "minutes",
"including minutes delay": "incl. {delayInMinutes} min delay"
}
4 changes: 4 additions & 0 deletions translations/fr.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"minutes": "minutes",
"including minutes delay": "y.c. {delayInMinutes} min de retard"
}

0 comments on commit 75664c2

Please sign in to comment.