Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved the issue of device not connecting #119 #146

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions services/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,65 @@ type Service interface {
SendCommand(ctx context.Context, input SendCommandInput) (SendCommandOutput, error)
BuildClient(BuildClientBinaryInput) (string, error)
}

// function to handle reconnection
func (c *Client) reconnect() error {
backoff := time.Second
for {
c.conn, _, err := websocket.DefaultDialer.Dial(c.url, nil)
if err == nil {
return nil
}
if backoff > time.Minute {
return err
}
time.Sleep(backoff)
backoff *= 2
}
}
// Modify the main loop to handle unexpected termination
func (c *Client) run() {
for {
err := c.readPump()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
// Log the error here
log.Printf("Unexpected websocket closure: %v", err)
}
// Attempt to reconnect
if err := c.reconnect(); err != nil {
log.Printf("Failed to reconnect: %v", err)
return
}
// Reset any necessary client state here
}
}
}
// Modify the health check and device request functions
func (c *Client) sendHealthCheck() error {
if c.conn == nil {
return errors.New("Connection is not established")
}
return c.conn.WriteMessage(websocket.TextMessage, []byte("GET /health"))
}
func (c *Client) sendDeviceRequest() error {
if c.conn == nil {
return errors.New("Connection is not established")
}
return c.conn.WriteMessage(websocket.TextMessage, []byte("POST /device"))
}

func connectWithRetry(url string, maxAttempts int) (*websocket.Conn, error) {
var conn *websocket.Conn
var err error
for attempt := 1; attempt <= maxAttempts; attempt++ {
conn, _, err = websocket.DefaultDialer.Dial(url, nil)
if err == nil {
return conn, nil
}
log.Printf("Connection attempt %d failed: %v. Retrying...", attempt, err)
time.Sleep(time.Second * time.Duration(attempt))
}
return nil, fmt.Errorf("failed to establish connection after %d attempts", maxAttempts)
}