From 358cd15dec98da95d87d370175a166602f448665 Mon Sep 17 00:00:00 2001 From: Janne Alatalo <janne.alatalo@jamk.fi> Date: Tue, 22 Oct 2019 16:01:46 +0300 Subject: [PATCH] Update the app to use the new mqtt websocket api --- src/App.js | 6 +++--- src/utils/api-client.js | 34 +++++++++++++++++++++++++++------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/App.js b/src/App.js index 19f086b..3d5e279 100644 --- a/src/App.js +++ b/src/App.js @@ -27,10 +27,10 @@ class App extends Component { let width = window.innerWidth; let height = window.innerHeight; this.state = { lam_points: Map(), mapSize: { width, height } }; - get_lam_points("http://tie.digitraffic.fi", this.update_state.bind(this)) + get_lam_points("https://tie.digitraffic.fi", this.update_state.bind(this)) .then(() => { - connect_lam_ws("ws://tie.digitraffic.fi", this.update_state.bind(this)); - }) + return connect_lam_ws("mqtts://tie.digitraffic.fi:61619", this.update_state.bind(this)); + }); this.handleResize = this.handleResize.bind(this); } diff --git a/src/utils/api-client.js b/src/utils/api-client.js index 54b4c28..32cecb4 100644 --- a/src/utils/api-client.js +++ b/src/utils/api-client.js @@ -1,4 +1,5 @@ import { Map } from 'immutable'; +import mqtt from 'mqtt'; import LamStation from './lam-station.js'; @@ -86,20 +87,38 @@ export function get_lam_station_data(api_url, set_state) { export function connect_lam_ws(api_url, update_state) { let data_buff = []; - let url = `${api_url}/api/v1/plain-websockets/tmsdata`; - let socket = new WebSocket(url); - socket.addEventListener('open', () => { - console.info(`WebSocket open to ${url}`); + let url = `${api_url}/mqtt`; + // The username and password is documented on digitraffic api documentation site here: + // https://www.digitraffic.fi/tieliikenne/#websocket-rajapinnat + let client = mqtt.connect(url, { + username: 'digitraffic', + password: 'digitrafficPassword', }); - socket.addEventListener('message', (msg) => { - let data = JSON.parse(msg.data).sensorValue; + client.on('connect', () => { + console.info(`MQTT connection open to ${url}`); + const topic = "tms/#"; + client.subscribe(topic, (err) => { + if (err) { + console.error(`Subscription error: ${err}`); + } else { + console.log(`Subscribed to ${topic}`); + } + }); + }); + client.on('error', (err) => { + console.error(`error: ${err}`); + }); + client.on('message', (topic, msg) => { + let data = JSON.parse(msg.toString()); if (!data) { return } let id = data.roadStationId; let value = data.sensorValue; let name = data.name; - data_buff.push({id, value, name}) + if (id && value && name) { + data_buff.push({ id, value, name }); + } }); function buffer_flusher() { @@ -111,6 +130,7 @@ export function connect_lam_ws(api_url, update_state) { let { id, value, name } = obj; let point = lam_points.get(id); if (!point) { + console.error(`point not found ${id}`); continue; } if (name === "KESKINOPEUS_5MIN_LIUKUVA_SUUNTA1") { -- GitLab