Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>JavaScript MQTT WebSocket Example</title>
- <!----------------------------------------------------------------------------INCLUDES -->
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <!-- MAPS STUFF -->
- <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="">
- <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin="">
- </script>
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-easybutton@2/src/easy-button.css">
- <script src="https://cdn.jsdelivr.net/npm/leaflet-easybutton@2/src/easy-button.js"></script>
- <!-- MQTT STUFF -->
- <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript">
- </script>
- <!---------------------------------------------------------------------------->
- </head>
- <body>
- <!------------------------------------------------------------------------SET PARAMETERS---->
- <div id="mapid" style="width: 600px; height: 400px; position: relative;"></div>
- <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
- <!---------------------------------------------------------------------------->
- <script>
- //<!------------------------------------------ ASSIGN VARIABLES ---------------------------------->
- var mqtt;
- var mqttCarsSubTopic = "AEV/CARS";
- var carIDs = ["TESTCAR"];
- var reconnectTimeout = 5000;
- var hostIP = "203.45.199.194";
- var port = 9001;
- var topic = "";
- var payload = "";
- var showPath = 0;
- var zoomLevel = 14;
- var latLngAEV = ["-37.81426","145.29286"];
- var latLng1 = [0,0];
- var lat, lon = 0;
- var map = L.map('mapid').setView(latLngAEV, zoomLevel); //SET MAP START POINTS
- var marker1 = L.marker([0,0]).addTo(map).on('click', startTrace); //SET START MARKER
- var polylinePoints = [];
- var polyline = L.polyline(polylinePoints);
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- function askForData(){
- for(var i = 0; i < carIDs.length; i++)
- {
- sendMessage = new Paho.MQTT.Message("1");
- sendMessage.destinationName = mqttCarsSubTopic + "/" + carIDs[i] + "/" + "TRACE";
- mqtt.send(sendMessage);
- console.log("Sent activation message");
- }
- setTimeout(askForData, reconnectTimeout);
- }
- function startTrace(duration){
- for(var i = 0; i < carIDs.length; i++)
- {
- sendMessage = new Paho.MQTT.Message(duration);
- sendMessage.destinationName = mqttCarsSubTopic + "/" + carIDs[i] + "/" + "TRACE";
- mqtt.send(sendMessage);
- console.log("Sent Trace activation message");
- }
- }
- function clearMap() {
- for(i in map._layers) {
- if(map._layers[i]._path != undefined) {
- try {
- map.removeLayer(map._layers[i]);
- }
- catch(e) {
- console.log("problem with " + e + map._layers[i]);
- }
- }
- }
- }
- function onClickB2(e){
- if (showPath)
- {
- showPath = 0;
- polylinePoints = [];
- clearMap();
- } else{
- showPath = 1;
- startTrace("300");
- }
- }
- function onClickB1(e){
- if (showPath)
- {
- showPath = 0;
- polylinePoints = [];
- clearMap();
- } else{
- showPath = 1;
- startTrace("1");
- }
- }
- //MQTT UNABLE TO CONNECT FUNCTION
- function onFailure(message)
- {
- console.log("Connection Attempt to Host " + hostIP + "Failed");
- setTimeout(MQTTconnect, reconnectTimeout);
- }
- //MQTT SUBSCRIBED MESSAGE RECIEVED FUNCTION
- //SPECIFICALLY THIS HANDLES INCOMING GPS DATA FOR CARS
- function onMessageArrived(msg)
- {
- topic = msg.destinationName;
- payload = msg.payloadString;
- var topicSplit = topic.split("/");
- var payloadSplit = payload.split(",");
- out_msg = "Message received " + payload;
- out_msg = out_msg + "\nMessage Topic " + topic;
- console.log(out_msg);
- for (var i = 0; i < carIDs.length; i++)
- {
- if (topicSplit[2] == carIDs[i])
- {
- latLng1[0] = payloadSplit[0];
- latLng1[1] = payloadSplit[1];
- }
- /////////////PLACE MARKER AT UPDATE LAT OR LON
- marker1.setLatLng(payloadSplit);
- if (showPath){
- polylinePoints.push(payloadSplit);
- clearMap();
- polyline = L.polyline(polylinePoints).addTo(map);
- console.log(polylinePoints);
- }
- }
- }
- function onConnect()
- {
- // Once a connection has been made, make a subscription and send a message.
- console.log("Connected ");
- for (var i = 0; i < carIDs.length; i++)
- {
- mqtt.subscribe(mqttCarsSubTopic + "/" + carIDs[i] + "/LATLNG");
- }
- askForData();
- }
- ///////////TRY TO CONNECT TO THE MQTT BROKER/////
- function MQTTconnect()
- {
- console.log("connecting to " + hostIP + ":" + port);
- mqtt = new Paho.MQTT.Client(hostIP, port, "clientjs");
- var options =
- {
- timeout: 3,
- onSuccess: onConnect,
- onFailure: onFailure,
- };
- mqtt.onMessageArrived = onMessageArrived
- mqtt.connect(options); //connect
- }
- //LEAFLET TILES
- L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
- maxZoom: 18,
- attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
- '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
- 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
- id: 'mapbox.streets'
- }).addTo(map);
- L.easyButton('fa-globe', function(btn, map){
- onClickB1();
- }).addTo(map);
- L.easyButton('fa-globe', function(btn, map){
- onClickB2();
- }).addTo(map);
- //MQTT CONNECT///////////////////////////////////////////////////
- MQTTconnect();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement