Skip to content

Support for ota download progress #156

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

Merged
merged 7 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
21 changes: 11 additions & 10 deletions cli/ota/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,28 +38,29 @@ type statusFlags struct {

func initOtaStatusCommand() *cobra.Command {
flags := &statusFlags{}
uploadCommand := &cobra.Command{
statusCommand := &cobra.Command{
Use: "status",
Short: "OTA status",
Long: "Get OTA status by OTA or device ID",
Run: func(cmd *cobra.Command, args []string) {
if err := runPrintOtaStatusCommand(flags); err != nil {
feedback.Errorf("Error during ota get status: %v", err)
if err := runPrintOtaStatusCommand(flags, cmd); err != nil {
feedback.Errorf("\nError during ota get status: %v", err)
os.Exit(errorcodes.ErrGeneric)
}
},
}
uploadCommand.Flags().StringVarP(&flags.otaID, "ota-id", "o", "", "OTA ID")
uploadCommand.Flags().StringVarP(&flags.otaIDs, "ota-ids", "", "", "OTA IDs (comma separated)")
uploadCommand.Flags().StringVarP(&flags.deviceId, "device-id", "d", "", "Device ID")
uploadCommand.Flags().Int16VarP(&flags.limit, "limit", "l", 10, "Output limit (default: 10)")
uploadCommand.Flags().StringVarP(&flags.sort, "sort", "s", "desc", "Sorting (default: desc)")
statusCommand.Flags().StringVarP(&flags.otaID, "ota-id", "o", "", "OTA ID")
statusCommand.Flags().StringVarP(&flags.otaIDs, "ota-ids", "", "", "OTA IDs (comma separated)")
statusCommand.Flags().StringVarP(&flags.deviceId, "device-id", "d", "", "Device ID")
statusCommand.Flags().Int16VarP(&flags.limit, "limit", "l", 10, "Output limit (default: 10)")
statusCommand.Flags().StringVarP(&flags.sort, "sort", "s", "desc", "Sorting (default: desc)")

return uploadCommand
return statusCommand
}

func runPrintOtaStatusCommand(flags *statusFlags) error {
func runPrintOtaStatusCommand(flags *statusFlags, command *cobra.Command) error {
if flags.otaID == "" && flags.deviceId == "" && flags.otaIDs == "" {
command.Help()
return fmt.Errorf("required flag(s) \"ota-id\" or \"device-id\" or \"ota-ids\" not set")
}

Expand Down
5 changes: 3 additions & 2 deletions command/ota/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ func PrintOtaStatus(otaid, otaids, device string, cred *config.Credentials, limi
res, err := otapi.GetOtaStatusByOtaID(otaid, limit, order)
if err == nil && res != nil {
feedback.PrintResult(otaapi.OtaStatusDetail{
Ota: res.Ota,
Details: res.States,
FirmwareSize: res.FirmwareSize,
Ota: res.Ota,
Details: res.States,
})
} else if err != nil {
return err
Expand Down
57 changes: 52 additions & 5 deletions internal/ota-api/dto.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package otaapi

import (
"strconv"
"strings"
"time"

Expand All @@ -28,8 +29,9 @@ import (

type (
OtaStatusResponse struct {
Ota Ota `json:"ota"`
States []State `json:"states,omitempty"`
FirmwareSize *int64 `json:"firmware_size,omitempty"`
Ota Ota `json:"ota"`
States []State `json:"states,omitempty"`
}

OtaStatusList struct {
Expand All @@ -53,8 +55,9 @@ type (
}

OtaStatusDetail struct {
Ota Ota `json:"ota"`
Details []State `json:"details,omitempty"`
FirmwareSize *int64 `json:"firmware_size,omitempty"`
Ota Ota `json:"ota"`
Details []State `json:"details,omitempty"`
}
)

Expand Down Expand Up @@ -155,14 +158,58 @@ func (r OtaStatusDetail) String() string {
t = table.New()
t.SetHeader("Time", "Status", "Detail")
for _, s := range r.Details {
t.AddRow(formatHumanReadableTs(s.Timestamp), upperCaseFirst(s.State), s.StateData)
stateData := formatStateData(s.State, s.StateData, r.FirmwareSize, hasReachedFlashState(r.Details))
t.AddRow(formatHumanReadableTs(s.Timestamp), upperCaseFirst(s.State), stateData)
}
output += "\nDetails:\n" + t.Render()
}

return output
}

func hasReachedFlashState(states []State) bool {
for _, s := range states {
if s.State == "flash" {
return true
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sometimes we aren't receiving all the states from the board, so I will change this to just check that there is at least another state after fetch

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to map possible state after fetch. I've added reboot also.
If fetch fail, error is written in state_data for fetch or is added an additional fail state?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If fetch fail, error is written in state_data for fetch or is added an additional fail state?

the board will send a fail state

return false
}

func formatStateData(state, data string, firmware_size *int64, hasReceivedFlashState bool) string {
if data == "" {
return ""
}
if state == "fetch" {
// This is the state 'fetch' of OTA progress. This contains a number that represents the number of bytes fetched
if hasReceivedFlashState {
return buildSimpleProgressBar(float64(100))
}
if strings.ToLower(data) == "unknown" {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all the errors in the data part always start with the upper case letter, so you could only check against

Suggested change
if strings.ToLower(data) == "unknown" {
if data == "Unknown" {

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, I was not sure, so I moved to a more flexible approach. BTW, since you have confirmed, I've removed toLower()

return ""
}
actualDownloadedData, err := strconv.Atoi(data)
if err != nil || firmware_size == nil || actualDownloadedData <= 0 || *firmware_size <= 0 { // Sanitize and avoid division by zero
return data
}
percentage := (float64(actualDownloadedData) / float64(*firmware_size)) * 100
return buildSimpleProgressBar(percentage)
}
if strings.ToLower(data) == "unknown" {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you want to check state here not data right?

Suggested change
if strings.ToLower(data) == "unknown" {
if state == "unknown" {

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No I want to check data. I received 'Unknown' from api on state_data
{ "state": "start", "state_data": "Unknown", "timestamp": "2024-06-26T07:28:31.000001Z" },

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mhm in that case I think you can add only one unknown check at the top instead of two one inside the fetch branch and another outside

return ""
}
return data
}

func buildSimpleProgressBar(progress float64) string {
progressInt := int(progress) / 10
bar := "["
bar = bar + strings.Repeat("=", progressInt)
bar = bar + strings.Repeat(" ", 10-progressInt)
bar = bar + "] " + strconv.FormatFloat(progress, 'f', 2, 64) + "%"
return bar
}

func upperCaseFirst(s string) string {
if len(s) > 0 {
s = strings.ReplaceAll(s, "_", " ")
Expand Down
25 changes: 25 additions & 0 deletions internal/ota-api/dto_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package otaapi

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestProgressBar_notCompletePct(t *testing.T) {
firmwareSize := int64(25665 * 2)
bar := formatStateData("fetch", "25665", &firmwareSize, false)
assert.Equal(t, "[===== ] 50.00%", bar)
}

func TestProgressBar_ifFlashState_goTo100Pct(t *testing.T) {
firmwareSize := int64(25665 * 2)
bar := formatStateData("fetch", "25665", &firmwareSize, true) // If in flash status, go to 100%
assert.Equal(t, "[==========] 100.00%", bar)
}

func TestProgressBar_ifFlashStateAndUnknown_goTo100Pct(t *testing.T) {
firmwareSize := int64(25665 * 2)
bar := formatStateData("fetch", "Unknown", &firmwareSize, true) // If in flash status, go to 100%
assert.Equal(t, "[==========] 100.00%", bar)
}
Loading