diff --git a/cmd/main.go b/cmd/main.go index 9e36114..96ef806 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -13,6 +13,7 @@ import ( "strconv" "strings" "syscall" + "time" coap "github.com/absmach/coap-cli/coap" "github.com/fatih/color" @@ -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)) } } diff --git a/coap/client.go b/coap/client.go index a6e1bf7..b54f1d4 100644 --- a/coap/client.go +++ b/coap/client.go @@ -31,17 +31,13 @@ type Client struct { conn *client.Conn } -// New returns new CoAP client connecting it to the server. +// NewClient returns new CoAP client connecting it to the server. func NewClient(addr string, keepAlive uint64) (Client, error) { + var dialOptions []udp.Option if keepAlive > 0 { - c, err := udp.Dial(addr, options.WithKeepAlive(maxRetries, time.Duration(keepAlive)*time.Second, onInactive)) - if err != nil { - return Client{}, errors.Join(errDialFailed, err) - } - return Client{conn: c}, nil + dialOptions = append(dialOptions, options.WithKeepAlive(maxRetries, time.Duration(keepAlive)*time.Second, onInactive)) } - - c, err := udp.Dial(addr) + c, err := udp.Dial(addr, dialOptions...) if err != nil { return Client{}, errors.Join(errDialFailed, err) } @@ -73,17 +69,34 @@ 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)) + bs, err := res.BodySize() + if err != nil { + fmt.Println("Error getting body size: ", err) + return + } + if bs == 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()) + fmt.Printf("Content-Length: %d\n", bs) + 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...) }