@@ -17,6 +17,10 @@ import (
1717 i "saml.dev/gome-assistant/internal"
1818)
1919
20+ var (
21+ ErrInvalidToken = errors .New ("invalid authentication token" )
22+ )
23+
2024type AuthMessage struct {
2125 MsgType string `json:"type"`
2226 AccessToken string `json:"access_token"`
@@ -47,39 +51,43 @@ func ReadMessage(conn *websocket.Conn, ctx context.Context) ([]byte, error) {
4751 return msg , nil
4852}
4953
50- func SetupConnection (ip , port , authToken string ) (* websocket.Conn , context.Context , context.CancelFunc ) {
54+ func SetupConnection (ip , port , authToken string ) (* websocket.Conn , context.Context , context.CancelFunc , error ) {
5155 ctx , ctxCancel := context .WithTimeout (context .Background (), time .Second * 3 )
5256
5357 // Init websocket connection
5458 dialer := websocket .DefaultDialer
5559 conn , _ , err := dialer .DialContext (ctx , fmt .Sprintf ("ws://%s:%s/api/websocket" , ip , port ), nil )
5660 if err != nil {
5761 ctxCancel ()
58- log .Fatalf ("ERROR: Failed to connect to websocket at ws://%s:%s/api/websocket. Check IP address and port\n " , ip , port )
62+ log .Printf ("ERROR: Failed to connect to websocket at ws://%s:%s/api/websocket. Check IP address and port\n " , ip , port )
63+ return nil , nil , nil , err
5964 }
6065
6166 // Read auth_required message
6267 _ , err = ReadMessage (conn , ctx )
6368 if err != nil {
6469 ctxCancel ()
65- log .Fatalf ("Unknown error creating websocket client\n " )
70+ log .Printf ("Unknown error creating websocket client\n " )
71+ return nil , nil , nil , err
6672 }
6773
6874 // Send auth message
6975 err = SendAuthMessage (conn , ctx , authToken )
7076 if err != nil {
7177 ctxCancel ()
72- log .Fatalf ("Unknown error creating websocket client\n " )
78+ log .Printf ("Unknown error creating websocket client\n " )
79+ return nil , nil , nil , err
7380 }
7481
7582 // Verify auth message was successful
7683 err = VerifyAuthResponse (conn , ctx )
7784 if err != nil {
7885 ctxCancel ()
79- log .Fatalf ("ERROR: Auth token is invalid. Please double check it or create a new token in your Home Assistant profile\n " )
86+ log .Printf ("ERROR: Auth token is invalid. Please double check it or create a new token in your Home Assistant profile\n " )
87+ return nil , nil , nil , err
8088 }
8189
82- return conn , ctx , ctxCancel
90+ return conn , ctx , ctxCancel , nil
8391}
8492
8593func SendAuthMessage (conn * websocket.Conn , ctx context.Context , token string ) error {
@@ -105,7 +113,7 @@ func VerifyAuthResponse(conn *websocket.Conn, ctx context.Context) error {
105113 json .Unmarshal (msg , & authResp )
106114 // log.Println(authResp.MsgType)
107115 if authResp .MsgType != "auth_ok" {
108- return errors . New ( "invalid auth token" )
116+ return ErrInvalidToken
109117 }
110118
111119 return nil
0 commit comments