@@ -38,6 +38,7 @@ const (
3838)
3939
4040var ErrAlreadyInProgress = fmt .Errorf ("already in progress" )
41+ var ErrAlreadyCancelled = fmt .Errorf ("already cancelled" )
4142
4243type OtaApiClient struct {
4344 client * http.Client
@@ -58,7 +59,11 @@ func NewClient(credentials *config.Credentials) *OtaApiClient {
5859}
5960
6061func (c * OtaApiClient ) performGetRequest (endpoint , token string ) (* http.Response , error ) {
61- req , err := http .NewRequest ("GET" , endpoint , nil )
62+ return c .performRequest (endpoint , "GET" , token )
63+ }
64+
65+ func (c * OtaApiClient ) performRequest (endpoint , method , token string ) (* http.Response , error ) {
66+ req , err := http .NewRequest (method , endpoint , nil )
6267 if err != nil {
6368 return nil , err
6469 }
@@ -205,3 +210,35 @@ func (c *OtaApiClient) GetOtaStatusByDeviceID(deviceID string, limit int, order
205210
206211 return nil , err
207212}
213+
214+ func (c * OtaApiClient ) CancelOta (otaid string ) (bool , error ) {
215+
216+ if otaid == "" {
217+ return false , fmt .Errorf ("invalid ota-id: empty" )
218+ }
219+
220+ userRequestToken , err := c .src .Token ()
221+ if err != nil {
222+ if strings .Contains (err .Error (), "401" ) {
223+ return false , errors .New ("wrong credentials" )
224+ }
225+ return false , fmt .Errorf ("cannot retrieve a valid token: %w" , err )
226+ }
227+
228+ endpoint := c .host + "/ota/v1/ota/" + otaid + "/cancel"
229+ res , err := c .performRequest (endpoint , "PUT" , userRequestToken .AccessToken )
230+ if err != nil {
231+ return false , err
232+ }
233+ defer res .Body .Close ()
234+
235+ if res .StatusCode == 200 {
236+ return true , nil
237+ } else if res .StatusCode == 404 || res .StatusCode == 400 {
238+ return false , fmt .Errorf ("ota-id %s not found" , otaid )
239+ } else if res .StatusCode == 409 {
240+ return false , ErrAlreadyCancelled
241+ }
242+
243+ return false , err
244+ }
0 commit comments