zoap

A WiP CoAP implementation for bare-metal constrained devices in Zig

git clone https://git.8pit.net/zoap.git

  1package main
  2
  3import (
  4	"os"
  5	"log"
  6	"path/filepath"
  7
  8	"github.com/plgd-dev/go-coap/v2/message/codes"
  9	"github.com/plgd-dev/go-coap/v2/udp/message"
 10	coap "github.com/plgd-dev/go-coap/v2/message"
 11)
 12
 13type genFn func() ([]byte, error)
 14
 15func withPayload() ([]byte, error) {
 16	return message.Message{
 17		Code:      codes.DELETE,
 18		Token:     []byte{},
 19		Payload:   []byte("Hello"),
 20		MessageID: 1,
 21		Type:      message.Reset,
 22	}.Marshal()
 23}
 24
 25func basicHeader() ([]byte, error) {
 26	return message.Message{
 27		Code:      codes.GET,
 28		Token:     []byte{},
 29		Payload:   []byte{},
 30		MessageID: 2342,
 31		Type:      message.Confirmable,
 32	}.Marshal()
 33}
 34
 35func withToken() ([]byte, error) {
 36	return message.Message{
 37		Code:      codes.PUT,
 38		Token:     []byte{23, 42},
 39		Payload:   []byte{},
 40		MessageID: 5,
 41		Type:      message.Acknowledgement,
 42	}.Marshal()
 43}
 44
 45func withOptions() ([]byte, error) {
 46	var opts coap.Options = []coap.Option{
 47		coap.Option{2, []byte{0xff}},
 48		coap.Option{23, []byte{13, 37}},
 49		coap.Option{65535, []byte{}},
 50	}
 51
 52	return message.Message{
 53		Code:      codes.GET,
 54		Token:     []byte{},
 55		Payload:   []byte{},
 56		MessageID: 2342,
 57		Type:      message.Confirmable,
 58		Options:   opts,
 59	}.Marshal()
 60}
 61
 62func payloadAndOptions() ([]byte, error) {
 63	var opts coap.Options = []coap.Option{
 64		coap.Option{0, []byte("test")},
 65	}
 66
 67	return message.Message{
 68		Code:      codes.DELETE,
 69		Token:     []byte{},
 70		Payload:   []byte("foobar"),
 71		MessageID: 255,
 72		Type:      message.NonConfirmable,
 73		Options:   opts,
 74	}.Marshal()
 75}
 76
 77func main() {
 78	log.SetFlags(log.Lshortfile)
 79
 80	testCases := []struct{
 81		Name string
 82		Func genFn
 83	}{
 84		{ "with-payload", withPayload },
 85		{ "basic-header", basicHeader },
 86		{ "with-token", withToken },
 87		{ "with-options", withOptions },
 88		{ "payload-and-options", payloadAndOptions },
 89	}
 90
 91	// Directory where source file is located.
 92	dir := filepath.Dir(os.Args[0])
 93
 94	for _, testCase := range testCases {
 95		fp := filepath.Join(dir, testCase.Name+".bin")
 96		file, err := os.Create(fp)
 97		if err != nil {
 98			log.Fatal(err)
 99		}
100
101		data, err := testCase.Func()
102		if err != nil {
103			file.Close()
104			log.Fatal(err)
105		}
106
107		_, err = file.Write(data)
108		if err != nil {
109			file.Close()
110			log.Fatal(err)
111		}
112		file.Close()
113	}
114}