-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
346 lines (301 loc) · 7.6 KB
/
main.go
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write the file to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
var (
addr = flag.String("addr", ":8080", "http service address")
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
type VehicleTimestamp struct {
time.Time
}
// UnmarshalJSON
// We need a special unmarshal method for this string timestamp. It's of the
// form "YYYYMMDD hh:mm"
func (t *VehicleTimestamp) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
loc, err := time.LoadLocation("America/Chicago")
if err != nil {
return err
}
// "YYYYMMDD hh:mm" https://pkg.go.dev/time#pkg-constants
format := "20060102 15:04"
time, err := time.ParseInLocation(format, s, loc)
if err != nil {
return err
}
t.Time = time
return nil
}
// Vehicle represents an individual reading of a vehicle and it's location
// at that point in time
// Example:
//
// {
// "vid": "155",
// "tmstmp": "20200827 11:51",
// "lat": "29.962149326173048",
// "lon": "-90.05214051918121",
// "hdg": "357",
// "pid": 275,
// "rt": "5",
// "des": "Saratoga at Canal",
// "pdist": 10122,
// "dly": false,
// "spd": 20,
// "tatripid": "3130339",
// "tablockid": "15",
// "zone": "",
// "srvtmstmp": "20200827 11:51",
// "oid": "445",
// "or": true,
// "rid": "501",
// "blk": 2102,
// "tripid": 982856020
// }
type Vehicle struct {
Vid string `json:"vid"`
Tmstmp VehicleTimestamp `json:"tmstmp"`
SrvTimstmp VehicleTimestamp `json:"srvtmstmp"`
Lat float64 `json:"lat,string"`
Lon float64 `json:"lon,string"`
Hdg string `json:"hdg"`
Rt string `json:"rt"`
Tatripid string `json:"tatripid"`
Tablockid string `json:"tablockid"`
Zone string `json:"zone"`
Oid string `json:"oid"`
Rid string `json:"rid"`
Des string `json:"des"`
Pdist int `json:"pdist"`
Pid int `json:"pid"`
Spd int `json:"spd"`
Blk int `json:"blk"`
Tripid int `json:"tripid"`
Dly bool `json:"dly"`
Or bool `json:"or"`
}
type BusErr struct {
Rt string `json:"rt"`
Msg string `json:"msg"`
}
type BustimeData struct {
Vehicles []Vehicle `json:"vehicle"`
Errors []BusErr `json:"error"`
}
type BustimeResponse struct {
Data BustimeData `json:"bustime-response"`
}
type Config struct {
Key string `yaml:"key"`
Interval time.Duration `yaml:"interval"`
Url string `yaml:"url"`
}
type Scraper struct {
client *http.Client
config *Config
}
func NewScraper() *Scraper {
api_key, ok := os.LookupEnv("CLEVER_DEVICES_KEY")
if !ok {
panic("Need to set environment variable CLEVER_DEVICES_KEY. Try `make run CLEVER_DEVICES_KEY=thekey`. Get key from Ben on slack")
}
ip, ok := os.LookupEnv("CLEVER_DEVICES_IP")
if !ok {
panic("Need to set environment variable CLEVER_DEVICES_KEY. Try `make run CLEVER_DEVICES_KEY=thekey`. Get key from Ben on slack")
}
config := &Config{
Url: fmt.Sprintf("https://%s/bustime/api/v3/getvehicles", ip),
Interval: 10 * time.Second,
Key: api_key,
}
tr := &http.Transport{
MaxIdleConnsPerHost: 1024,
TLSHandshakeTimeout: 0 * time.Second,
}
client := &http.Client{Transport: tr}
return &Scraper{
client,
config,
}
}
func (s *Scraper) Start(vs chan []Vehicle) {
for {
result := s.fetch()
log.Printf("Found %d vehicles\n", len(result.Vehicles))
vs <- result.Vehicles
time.Sleep(s.config.Interval)
}
}
func (v *Scraper) fetch() *BustimeData {
key := v.config.Key
baseURL := v.config.Url
url := fmt.Sprintf("%s?key=%s&tmres=m&rtpidatafeed=bustime&format=json", baseURL, key)
resp, err := v.client.Get(url)
if resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
log.Println(err)
}
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
log.Fatal(readErr)
}
result := &BustimeResponse{}
json.Unmarshal(body, result)
return &result.Data
}
func (v *Scraper) Close() {
v.client.CloseIdleConnections()
}
type VehicleChannel = chan []Vehicle
type VehicleBroadcaster struct {
incoming VehicleChannel
vehicles []Vehicle
receivers map[VehicleChannel]bool
}
func NewVehicleBroadCaster() *VehicleBroadcaster {
return &VehicleBroadcaster{
incoming: make(VehicleChannel),
receivers: make(map[VehicleChannel]bool),
}
}
func (b *VehicleBroadcaster) Register(c VehicleChannel) {
b.receivers[c] = true
}
func (b *VehicleBroadcaster) Unregister(c VehicleChannel) {
delete(b.receivers, c)
}
func (b *VehicleBroadcaster) Start() {
//config := bustime.GetConfig()
scraper := NewScraper()
defer scraper.Close()
log.Println("start sraper")
go scraper.Start(b.incoming)
b.broadcast()
}
func (b *VehicleBroadcaster) broadcast() {
for vs := range b.incoming {
log.Println("Caching Vehicles")
b.vehicles = vs
log.Printf("%d listeners \n", len(b.receivers))
for r, _ := range b.receivers {
log.Println("Broadcasting Vehicles")
select {
case r <- vs:
default:
log.Println("Closing")
close(r)
b.Unregister(r)
}
}
log.Println("Done Broadcasting")
}
}
type Server struct {
broadcaster *VehicleBroadcaster
}
func NewServer() *Server {
return &Server{
broadcaster: NewVehicleBroadCaster(),
}
}
func (s *Server) Start() {
go s.broadcaster.Start()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/index.html")
})
fs := http.FileServer(http.Dir("./public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
// Handle websocket connection
http.HandleFunc("/ws", s.serveWs)
log.Println("Starting server")
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal(err)
}
}
func (s *Server) reader(ws *websocket.Conn) {
defer ws.Close()
ws.SetReadLimit(512)
//ws.SetReadDeadline(time.Now().Add(pongWait))
//ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, _, err := ws.ReadMessage()
if err != nil {
break
}
}
}
func (s *Server) writeVehicles(ws *websocket.Conn, vehicles []Vehicle) error {
if len(vehicles) > 0 {
payload, err := json.Marshal(vehicles)
if err != nil {
return err
}
ws.SetWriteDeadline(time.Now().Add(writeWait))
err = ws.WriteMessage(websocket.TextMessage, payload)
if err != nil {
return err
}
} else {
log.Println("No Vehicles to write")
}
return nil
}
func (s *Server) writer(ws *websocket.Conn) {
pingTicker := time.NewTicker(pingPeriod)
defer func() {
pingTicker.Stop()
ws.Close()
}()
vehicleChan := make(VehicleChannel)
s.broadcaster.Register(vehicleChan)
log.Println("Sending cached vehicles")
s.writeVehicles(ws, s.broadcaster.vehicles)
for vehicles := range vehicleChan {
err := s.writeVehicles(ws, vehicles)
if err != nil {
break
}
}
log.Println("Got close. Stopping WS writer")
}
func (s *Server) serveWs(w http.ResponseWriter, r *http.Request) {
log.Println("serving ws")
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
go s.writer(ws)
s.reader(ws)
}
func main() {
server := NewServer()
server.Start()
}