aboutsummaryrefslogtreecommitdiff
path: root/mavigator-server/src/main/scala/mavigator/Router.scala
blob: 226d6c1414195fbbf4007237a1e9f8aebb3ffb73 (plain) (blame)
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
package mavigator

import akka.actor._
import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes._
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.Uri.Path
import akka.http.scaladsl.model.ws._
import akka.http.scaladsl.server._
import akka.util._
import akka.stream.scaladsl._
import play.twirl.api.Html
import uav.Uav


object Router {
  import Directives._

  final val SocketEndpoint = "mavlink"

  def withSocketUri: Directive1[Uri] = extractUri.map { uri =>
    uri.withScheme("ws").withPath(Path.Empty / SocketEndpoint)
  }

  def route(implicit system: ActorSystem): Route = (
    path("whoami") {
      get {
        withSocketUri { sock =>
          complete(sock.toString)
        }
      }
    } ~
      path("cockpit" / IntNumber) { id =>
        get {
          withSocketUri { socket =>
            val html = mavigator.views.html.app(
              "Mavigator",
              "mavigator_cockpit_Main",
              Map(
                "socketUrl" -> socket.toString,
	        "remoteSystemId" -> id.toString
              )
            )
            complete(html)
          }
        }
      } ~
      path(SocketEndpoint) {
        get {
          val fromWebSocket = Flow[Message].collect{
            case BinaryMessage.Strict(data) => data
          }

          val toWebSocket = Flow[ByteString].map{bytes =>
            BinaryMessage(bytes)
          }

          val backend = Uav().connect()

          handleWebSocketMessages(fromWebSocket via backend via toWebSocket)
        }
      } ~
      pathEndOrSingleSlash {
        get {
          withSocketUri { socket =>
            val html = mavigator.views.html.app(
              "Index",
              "mavigator_index_Main",
              Map(
                "socketUrl" -> socket.toString
              )
            )
            complete(html)
          }
        }
      } ~
      pathPrefix("assets") {
        get {
          encodeResponse {
            getFromResourceDirectory("assets")
          }
        }
      }
  )

  /** Enables completing requests with html. */
  implicit val twirlHtml : ToEntityMarshaller[Html] =
    Marshaller.StringMarshaller.wrap(`text/html`){ h: Html =>
      h.toString
    }

}