github.com/simpleiot/simpleiot@v0.18.3/api/coap.go (about)

     1  package api
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	coap "github.com/go-ocf/go-coap"
     9  	"github.com/go-ocf/go-coap/codes"
    10  )
    11  
    12  func sendResponse(w coap.ResponseWriter, _ *coap.Request, subded time.Time) error {
    13  	resp := w.NewResponse(codes.Content)
    14  	resp.SetOption(coap.ContentFormat, coap.TextPlain)
    15  	resp.SetPayload([]byte(fmt.Sprintf("Been running for %v", time.Since(subded))))
    16  	return w.WriteMsg(resp)
    17  }
    18  
    19  func periodicTransmitter(w coap.ResponseWriter, req *coap.Request) {
    20  	subded := time.Now()
    21  	for {
    22  		err := sendResponse(w, req, subded)
    23  		if err != nil {
    24  			log.Printf("Error on transmitter, stopping: %v", err)
    25  			return
    26  		}
    27  		time.Sleep(time.Second)
    28  	}
    29  }
    30  
    31  // CoapServer manages all the coap requests for this platform
    32  type CoapServer struct {
    33  	port string
    34  }
    35  
    36  // NewCoapServer creates a new coap server
    37  func NewCoapServer(port string) *CoapServer {
    38  	return &CoapServer{
    39  		port: port,
    40  	}
    41  }
    42  
    43  // Start the coap server
    44  func (cs *CoapServer) Start() error {
    45  	log.Fatal(coap.ListenAndServe("udp", ":5688",
    46  		coap.HandlerFunc(func(w coap.ResponseWriter, req *coap.Request) {
    47  			log.Printf("Got message path=%q: %#v from %v", req.Msg.Path(), req.Msg, req.Client.RemoteAddr())
    48  			switch {
    49  			case req.Msg.Code() == codes.GET && req.Msg.Option(coap.Observe) != nil && req.Msg.Option(coap.Observe).(uint32) == 0:
    50  				go periodicTransmitter(w, req)
    51  			case req.Msg.Code() == codes.GET:
    52  				subded := time.Now()
    53  				err := sendResponse(w, req, subded)
    54  				if err != nil {
    55  					log.Printf("Error on transmitter: %v", err)
    56  				}
    57  			}
    58  		})))
    59  	return nil
    60  }