Skip to content

Commit

Permalink
refactor: refactor msg output
Browse files Browse the repository at this point in the history
Signed-off-by: 1998-felix <[email protected]>
  • Loading branch information
felixgateru committed May 15, 2024
1 parent bf48ff9 commit fceaaee
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
17 changes: 15 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"strconv"
"strings"
"syscall"
"time"

coap "github.com/absmach/coap-cli/coap"
"github.com/fatih/color"
Expand Down Expand Up @@ -92,14 +93,26 @@ func main() {

func printMsg(m *pool.Message, verbose bool) {
if m != nil && verbose {
log.Printf("\nMESSAGE:\n%s", m.String())
fmt.Printf("Date: %s\n", time.Now().Format(time.RFC1123))
fmt.Printf("Code: %s\n", m.Code().String())
fmt.Printf("Type: %s\n", m.Type().String())
fmt.Printf("Token: %s\n", m.Token().String())
fmt.Printf("Message-ID: %d\n", m.MessageID())
cf, err := m.ContentFormat()
if err == nil {
fmt.Printf("Content-Format: %s \n", cf.String())
}
bs, err := m.BodySize()
if err == nil {
fmt.Printf("Content-Length: %d\n", bs)
}
}
body, err := m.ReadBody()
if err != nil {
log.Fatalf("failed to read body %v", err)
}
if len(body) > 0 {
log.Printf("MESSAGE BODY:\n %s", string(body))
fmt.Printf("\n%s\n", string(body))
}
}

Expand Down
22 changes: 17 additions & 5 deletions coap/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,29 @@ func (c Client) Receive(path string, verbose bool, opts ...message.Option) (mux.
defer cancel()

return c.conn.Observe(ctx, path, func(res *pool.Message) {
if verbose {
fmt.Printf("RECEIVED OBSERVE: %v\n", res)
}
body, err := res.ReadBody()
if err != nil {
fmt.Println("Error reading message body: ", err)

return
}
if len(body) > 0 {
fmt.Println("Payload: ", string(body))
if len(body) == 0 {
fmt.Println("Received observe")
}
switch verbose {
case true:
fmt.Printf("Date: %s\n", time.Now().Format(time.RFC1123))
fmt.Printf("Code: %s\n", res.Code().String())
fmt.Printf("Type: %s\n", res.Type().String())
fmt.Printf("Token: %s\n", res.Token().String())
fmt.Printf("Message-ID: %d\n", res.MessageID())
if len(body) > 0 {
fmt.Printf("Payload: %s\n\n", string(body))
}
case false:
if len(body) > 0 {
fmt.Printf("Payload: %s\n", string(body))
}
}
}, opts...)
}
Expand Down

0 comments on commit fceaaee

Please sign in to comment.