aboutsummaryrefslogtreecommitdiff
path: root/lib/Server/Frontend/OnboardUnit.hs
blob: 6a8fe6ebc15d4501f81c9a497b2466a4098ea87c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
{-# LANGUAGE DataKinds       #-}
{-# LANGUAGE LambdaCase      #-}
{-# LANGUAGE QuasiQuotes     #-}
{-# LANGUAGE RecordWildCards #-}

module Server.Frontend.OnboardUnit (getOnboardTrackerR) where

import           Server.Frontend.Routes

import           Data.Functor           ((<&>))
import qualified Data.Map               as M
import           Data.Maybe             (fromJust)
import           Data.Text              (Text)
import           Data.Time              (UTCTime (..), getCurrentTime)
import           Data.UUID              (UUID)
import qualified Data.UUID              as UUID
import qualified Data.Vector            as V
import qualified GTFS
import           Persist                (EntityField (..), Key (..), Stop (..),
                                         Ticket (..))
import           Text.Blaze.Html        (Html)
import           Yesod


getOnboardTrackerR :: Handler Html
getOnboardTrackerR = do defaultLayout [whamlet|
  <h1>_{MsgOBU}

  <section>
    <h2>Tracker
    <strong>Token:</strong> <span id="token">
  <section>
    <h2>Status
    <p id="status">_{MsgNone}
    <p id>_{MsgError}: <span id="error">
  <section>
    <h2>_{MsgLive}
    <p><strong>Position: </strong><span id="lat"></span>, <span id="long"></span>
    <p><strong>Accuracy: </strong><span id="acc">
  <section>
    <h2>_{MsgEstimated}
    <p><strong>_{MsgDelay}</strong>: <span id="delay">
    <p><strong>_{MsgSequence}</strong>: <span id="sequence">


  <script>
    var token = null;

    let euclid = (a,b) => {
      let x = a[0]-b[0];
      let y = a[1]-b[1];
      return x*x+y*y;
    }

    let minimalDist = (point, list, proj, norm) => {
      return list.reduce (
        (min, x) => {
          let dist = norm(point, proj(x));
          return dist < min[0] ? [dist,x] : min
        },
        [norm(point, proj(list[0])), list[0]]
      )[1]
    }

    let counter = 0;
    let ws;
    let id;

    function setStatus(msg) {
      document.getElementById("status").innerText = msg
    }

    async function geoError(error) {
      setStatus("error");
      alert(`_{MsgPermissionFailed}: \n${error.message}`);
      console.error(error);
      main();
    }

    async function wsError(error) {
      // alert(`_{MsgWebsocketError}: \n${error.message === undefined ? error.reason : error.message}`);
      console.log(error);
      navigator.geolocation.clearWatch(id);
    }

    async function wsClose(error) {
      console.log(error);
      document.getElementById("error").innerText = `websocket closed (reason: ${error.reason}). reconnecting `;
      navigator.geolocation.clearWatch(id);
      setTimeout(openWebsocket, 1000);
    }

    function wsMsg(msg) {
      let json = JSON.parse(msg.data);
      console.log(json);
      document.getElementById("delay").innerText =
        `${json.delay}s (${Math.floor(json.delay / 60)}min)`;
      document.getElementById("sequence").innerText = json.sequence;
    }


    function initGeopos() {
      document.getElementById("error").innerText = "";
      id = navigator.geolocation.watchPosition(
        geoPing,
        geoError,
        {enableHighAccuracy: true}
      );
    }


    function openWebsocket () {
      ws = new WebSocket((location.protocol == "http:" ? "ws" : "wss") + "://" + location.host + "/api/tracker/ping/ws");
      ws.onerror = wsError;
      ws.onclose = wsClose;
      ws.onmessage = wsMsg;
      ws.onopen = (event) => {
        setStatus("connected");
      };
    }

    async function geoPing(geoloc) {
      console.log("got position update " + counter);
      document.getElementById("lat").innerText = geoloc.coords.latitude;
      document.getElementById("long").innerText = geoloc.coords.longitude;
      document.getElementById("acc").innerText = geoloc.coords.accuracy;

      if (ws !== undefined && ws.readyState == 1) {
          ws.send(JSON.stringify({
              token: token,
              geopos: [ geoloc.coords.latitude, geoloc.coords.longitude ],
              timestamp: (new Date()).toISOString()
          }));
          counter += 1;
          setStatus(`sent ${counter} pings`);
      } else {
          setStatus(`websocket readystate ${ws.readyState}`);
      }
    }


    async function main() {
      initGeopos();

      let urlparams = new URLSearchParams(window.location.search);

      token = urlparams.get("token");

        if (token === null) {
          token = await (await fetch("/api/tracker/register/", {
               method: "POST",
               body: JSON.stringify({agent: "tracktrain-website"}),
               headers: {"Content-Type": "application/json"}
          })).json();

          if (token.error) {
              alert("could not obtain token: \n" + token.msg);
              setStatus("_{MsgTokenFailed}");
          } else {
              console.log("got token");
              window.location.search = `?token=${token}`;
          }
      }

      console.log(token)

      if (token !== null) {
          document.getElementById("token").innerText = token;
          openWebsocket();
      }
    }

    main()
  |]