11package handlers
22
33import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
47 "fmt"
58 "net/http"
69 "os"
10+ "strconv"
711 "strings"
12+ "sync"
813 "time"
914
10- "github.com/byuoitav/central-event-system/hub/base"
11- "github.com/byuoitav/central-event-system/messenger"
1215 "github.com/byuoitav/common/v2/events"
13- "github.com/byuoitav/device-monitoring/localsystem"
1416 "github.com/byuoitav/scheduler/calendars"
1517 "github.com/byuoitav/scheduler/log"
1618 "github.com/byuoitav/scheduler/schedule"
1719 "github.com/labstack/echo"
1820 "go.uber.org/zap"
1921)
2022
21- var start time.Time
23+ var lastRequest time.Time
2224
2325// GetConfig returns the config for this device, based on it's SYSTEM_ID
2426func GetConfig (c echo.Context ) error {
@@ -36,14 +38,12 @@ func GetConfig(c echo.Context) error {
3638 if err != nil {
3739 return c .String (http .StatusInternalServerError , err .Error ())
3840 }
39- start = time .Now ()
40- go connectionCheck ()
4141
42+ lastRequest = time .Now ()
4243 return c .JSON (http .StatusOK , config )
4344}
4445
4546func GetEvents (c echo.Context ) error {
46- start = time .Now ()
4747 roomID := c .Param ("roomID" )
4848
4949 log .P .Info ("Getting events" , zap .String ("room" , roomID ))
@@ -53,6 +53,7 @@ func GetEvents(c echo.Context) error {
5353 return c .String (http .StatusInternalServerError , fmt .Sprintf ("unable to get events in %q: %s" , roomID , err ))
5454 }
5555
56+ lastRequest = time .Now ()
5657 return c .JSON (http .StatusOK , events )
5758}
5859
@@ -85,55 +86,103 @@ func GetStaticElements(c echo.Context) error {
8586}
8687
8788func SendHelpRequest (c echo.Context ) error {
88-
89- var request schedule.HelpReqeust
89+ var request schedule.HelpRequest
9090 if err := c .Bind (& request ); err != nil {
9191 return c .String (http .StatusBadRequest , err .Error ())
9292 }
9393
94- if err := schedule .SendHelpRequest (request ); err != nil {
95- return c .String (http .StatusInternalServerError , fmt .Sprintf ("failed to send help request for device: %s" , request .DeviceID ))
94+ id := os .Getenv ("SYSTEM_ID" )
95+ deviceInfo := events .GenerateBasicDeviceInfo (id )
96+ roomInfo := events .GenerateBasicRoomInfo (deviceInfo .RoomID )
97+
98+ event := events.Event {
99+ GeneratingSystem : id ,
100+ Timestamp : time .Now (),
101+ EventTags : []string {events .DetailState },
102+ TargetDevice : deviceInfo ,
103+ AffectedRoom : roomInfo ,
104+ Key : "help-request" ,
105+ Value : "confirm" ,
96106 }
97107
108+ sendEvent (c .Request ().Context (), event )
98109 return c .JSON (http .StatusOK , fmt .Sprintf ("Help request sent for device: %s" , request .DeviceID ))
99110}
100111
101- func connectionCheck ( ) {
102- id := localsystem . MustSystemID ( )
112+ func SendWebsocketCount ( frequency time. Duration ) {
113+ id := os . Getenv ( "SYSTEM_ID" )
103114 deviceInfo := events .GenerateBasicDeviceInfo (id )
104115 roomInfo := events .GenerateBasicRoomInfo (deviceInfo .RoomID )
105- messenger , err := messenger . BuildMessenger ( os . Getenv ( "HUB_ADDRESS" ), base . Messenger , 1000 )
106- if err != nil {
107- log . P . Error ( "unable to build websocket count messenger: %s" , zap . String ( "error" , err . Error ()) )
108- }
109- for {
110- var countEvent events.Event
111- log . P . Debug ( "Time since start" , zap . String ( "time" , time . Since ( start ). String ()))
112- if time .Since ( start ). Seconds () > 120 {
113- //time to worry
114- countEvent . GeneratingSystem = id
115- countEvent . Timestamp = time . Now ()
116- countEvent . EventTags = [] string { events . DetailState }
117- countEvent . TargetDevice = deviceInfo
118- countEvent . AffectedRoom = roomInfo
119- countEvent . Key = "websocket-count"
120- countEvent .Value = fmt . Sprintf ( "%d" , 0 )
116+
117+ ticker := time . NewTicker ( frequency )
118+ defer ticker . Stop ( )
119+
120+ for range ticker . C {
121+ event := events.Event {
122+ GeneratingSystem : id ,
123+ Timestamp : time .Now (),
124+ EventTags : [] string { events . DetailState },
125+ TargetDevice : deviceInfo ,
126+ AffectedRoom : roomInfo ,
127+ Key : "websocket-count" ,
128+ }
129+
130+ if time . Since ( lastRequest ). Seconds () >= 120 {
131+ event .Value = strconv . Itoa ( 0 )
121132 } else {
122- countEvent .GeneratingSystem = id
123- countEvent .Timestamp = time .Now ()
124- countEvent .EventTags = []string {events .DetailState }
125- countEvent .TargetDevice = deviceInfo
126- countEvent .AffectedRoom = roomInfo
127- countEvent .Key = "websocket-count"
128- countEvent .Value = fmt .Sprintf ("%d" , 1 )
133+ event .Value = strconv .Itoa (1 )
129134 }
130135
131- if messenger != nil {
132- log .P .Debug ("Sending websocket count of" , zap .String ("value" , countEvent .Value ))
133- messenger .SendEvent (countEvent )
136+ sendEvent (context .Background (), event )
137+ }
138+ }
139+
140+ func sendEvent (ctx context.Context , event events.Event ) {
141+ eventProcs := strings .Split (os .Getenv ("EVENT_URLS" ), "," )
142+
143+ body , err := json .Marshal (event )
144+ if err != nil {
145+ log .P .Warn ("unable to marshal event" , zap .Error (err ))
146+ return
147+ }
148+
149+ ctx , cancel := context .WithTimeout (ctx , 10 * time .Second )
150+ defer cancel ()
151+
152+ wg := & sync.WaitGroup {}
153+
154+ for i := range eventProcs {
155+ if len (eventProcs [i ]) == 0 {
156+ continue
134157 }
135158
136- time .Sleep (3 * time .Minute )
159+ wg .Add (1 )
160+
161+ go func (url string ) {
162+ log .P .Info ("Sending event" , zap .String ("url" , url ), zap .String ("key" , event .Key ), zap .String ("value" , event .Value ))
163+ defer wg .Done ()
164+
165+ req , err := http .NewRequestWithContext (ctx , http .MethodPost , url , bytes .NewReader (body ))
166+ if err != nil {
167+ log .P .Warn ("unable to create request" , zap .Error (err ), zap .String ("url" , url ))
168+ return
169+ }
170+
171+ req .Header .Add ("content-type" , "application/json" )
172+
173+ resp , err := http .DefaultClient .Do (req )
174+ if err != nil {
175+ log .P .Warn ("unable to send request" , zap .Error (err ), zap .String ("url" , url ))
176+ return
177+ }
178+ defer resp .Body .Close ()
179+
180+ if resp .StatusCode / 100 != 2 {
181+ log .P .Warn ("non 200 response" , zap .String ("url" , url ), zap .Int ("statusCode" , resp .StatusCode ))
182+ return
183+ }
184+ }(eventProcs [i ])
137185 }
138186
187+ wg .Wait ()
139188}
0 commit comments