You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by cc...@apache.org on 2017/08/04 19:28:13 UTC
[mynewt-newtmgr] 03/06: nmxact - CoAP server
This is an automated email from the ASF dual-hosted git repository.
ccollins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit b2dd9feb0a329d83937abcd7b6b41813f8cd451b
Author: Christopher Collins <cc...@apache.org>
AuthorDate: Thu Jul 27 17:57:40 2017 -0700
nmxact - CoAP server
---
newtmgr/bll/bll_oic_sesn.go | 7 +-
nmxact/bledefs/bledefs.go | 11 +--
nmxact/nmble/ble_act.go | 76 +++++++++++++++++++++
nmxact/nmble/ble_coap_sesn.go | 16 ++---
nmxact/nmble/ble_fsm.go | 10 ++-
nmxact/nmble/ble_oic_sesn.go | 12 ++--
nmxact/nmble/ble_oic_svr.go | 59 ++++++++++++++++
nmxact/nmble/ble_plain_sesn.go | 6 +-
nmxact/nmble/ble_proto.go | 52 +++++++++++++-
nmxact/nmble/ble_util.go | 128 ++++++++++++++++++++++++++++++++++-
nmxact/nmble/ble_xport.go | 2 +
nmxact/nmble/chrmgr.go | 17 ++---
nmxact/nmble/dispatch.go | 4 ++
nmxact/nmserial/serial_oic_sesn.go | 19 +++---
nmxact/nmserial/serial_plain_sesn.go | 6 +-
nmxact/oic/dispatch.go | 38 +++--------
nmxact/oic/oic.go | 36 +++++++---
nmxact/oic/receiver.go | 36 ++++++++++
nmxact/oic/resmgr.go | 73 ++++++++++++++++++++
nmxact/oic/server.go | 64 ++++++++++++++++++
nmxact/omp/omp.go | 38 +++++------
nmxact/sesn/sesn.go | 4 +-
nmxact/sesn/sesn_util.go | 10 +--
nmxact/udp/udp_oic_sesn.go | 19 +++---
nmxact/udp/udp_plain_sesn.go | 6 +-
nmxact/xact/getres.go | 6 +-
26 files changed, 627 insertions(+), 128 deletions(-)
diff --git a/newtmgr/bll/bll_oic_sesn.go b/newtmgr/bll/bll_oic_sesn.go
index 0aca6ca..28c4c53 100644
--- a/newtmgr/bll/bll_oic_sesn.go
+++ b/newtmgr/bll/bll_oic_sesn.go
@@ -115,7 +115,8 @@ func (bls *BllOicSesn) discoverAll() error {
if bledefs.CompareUuids(uuid, reqChrUuid) == 0 {
bls.nmpReqChr = c
- } else if bledefs.CompareUuids(uuid, rspChrUuid) == 0 {
+ }
+ if bledefs.CompareUuids(uuid, rspChrUuid) == 0 {
bls.nmpRspChr = c
}
}
@@ -282,7 +283,7 @@ func (bls *BllOicSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
}
defer bls.d.RemoveOicListener(token)
- req, err := oic.EncodeGet(uri, token)
+ req, err := oic.EncodeGet(true, uri, token)
if err != nil {
return 0, nil, err
}
@@ -298,7 +299,7 @@ func (bls *BllOicSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
case err := <-ol.ErrChan:
return 0, nil, err
case rsp := <-ol.RspChan:
- return rsp.Code, rsp.Payload, nil
+ return rsp.Code(), rsp.Payload(), nil
case <-ol.AfterTimeout(opt.Timeout):
msg := fmt.Sprintf("CoAP timeout; uri=%s", uri)
return 0, nil, nmxutil.NewRspTimeoutError(msg)
diff --git a/nmxact/bledefs/bledefs.go b/nmxact/bledefs/bledefs.go
index 0a0ece3..5cbc4ef 100644
--- a/nmxact/bledefs/bledefs.go
+++ b/nmxact/bledefs/bledefs.go
@@ -769,13 +769,14 @@ const (
)
type BleGattAccess struct {
- Op BleGattOp
- SvcUuid BleUuid
- ChrUuid BleUuid
- Data []byte
+ Op BleGattOp
+ ConnHandle uint16
+ SvcUuid BleUuid
+ ChrUuid BleUuid
+ Data []byte
}
-type BleGattAccessFn func(access BleGattAccess) uint8
+type BleGattAccessFn func(access BleGattAccess) (uint8, []byte)
type BleDsc struct {
Uuid BleUuid
diff --git a/nmxact/nmble/ble_act.go b/nmxact/nmble/ble_act.go
index cfa4c14..5be1a3f 100644
--- a/nmxact/nmble/ble_act.go
+++ b/nmxact/nmble/ble_act.go
@@ -299,6 +299,82 @@ func writeCmd(x *BleXport, bl *Listener, r *BleWriteCmdReq) error {
}
// Blocking.
+func notify(x *BleXport, bl *Listener, r *BleNotifyReq) error {
+ const rspType = MSG_TYPE_NOTIFY
+
+ j, err := json.Marshal(r)
+ if err != nil {
+ return err
+ }
+
+ if err := x.Tx(j); err != nil {
+ return err
+ }
+
+ for {
+ select {
+ case err := <-bl.ErrChan:
+ return err
+
+ case bm := <-bl.MsgChan:
+ switch msg := bm.(type) {
+ case *BleNotifyRsp:
+ bl.Acked = true
+ if msg.Status != 0 {
+ return StatusError(MSG_OP_RSP, rspType, msg.Status)
+ } else {
+ return nil
+ }
+
+ default:
+ }
+
+ case <-bl.AfterTimeout(x.RspTimeout()):
+ return BhdTimeoutError(rspType, r.Seq)
+ }
+ }
+}
+
+// Blocking.
+func findChr(x *BleXport, bl *Listener, r *BleFindChrReq) (
+ uint16, uint16, error) {
+
+ const rspType = MSG_TYPE_NOTIFY
+
+ j, err := json.Marshal(r)
+ if err != nil {
+ return 0, 0, err
+ }
+
+ if err := x.Tx(j); err != nil {
+ return 0, 0, err
+ }
+
+ for {
+ select {
+ case err := <-bl.ErrChan:
+ return 0, 0, err
+
+ case bm := <-bl.MsgChan:
+ switch msg := bm.(type) {
+ case *BleFindChrRsp:
+ bl.Acked = true
+ if msg.Status != 0 {
+ return 0, 0, StatusError(MSG_OP_RSP, rspType, msg.Status)
+ } else {
+ return msg.DefHandle, msg.ValHandle, nil
+ }
+
+ default:
+ }
+
+ case <-bl.AfterTimeout(x.RspTimeout()):
+ return 0, 0, BhdTimeoutError(rspType, r.Seq)
+ }
+ }
+}
+
+// Blocking.
func exchangeMtu(x *BleXport, bl *Listener, r *BleExchangeMtuReq) (
int, error) {
diff --git a/nmxact/nmble/ble_coap_sesn.go b/nmxact/nmble/ble_coap_sesn.go
index a96127e..7817912 100644
--- a/nmxact/nmble/ble_coap_sesn.go
+++ b/nmxact/nmble/ble_coap_sesn.go
@@ -148,29 +148,25 @@ func (bcs *BleCoapSesn) ConnInfo() (BleConnDesc, error) {
}
func (bcs *BleCoapSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- []byte, error) {
+ coap.COAPCode, []byte, error) {
token := nmxutil.NextToken()
ol, err := bcs.d.AddListener(token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
defer bcs.d.RemoveListener(token)
- req, err := oic.EncodeGet(uri, token)
+ req, err := oic.EncodeGet(true, uri, token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
rsp, err := bcs.bf.TxOic(req, ol, opt.Timeout)
if err != nil {
- return nil, err
+ return 0, nil, err
}
- if rsp.Code != coap.Content {
- return nil, fmt.Errorf("UNEXPECTED OIC ACK: %#v", rsp)
- }
-
- return rsp.Payload, nil
+ return rsp.Code(), rsp.Payload(), nil
}
diff --git a/nmxact/nmble/ble_fsm.go b/nmxact/nmble/ble_fsm.go
index f319db5..036499b 100644
--- a/nmxact/nmble/ble_fsm.go
+++ b/nmxact/nmble/ble_fsm.go
@@ -535,7 +535,10 @@ func (bf *BleFsm) exchangeMtu() error {
// If the operation failed because the peer already initiated the
// exchange, just pretend it was successful.
bhe := nmxutil.ToBleHost(err)
- if bhe != nil && bhe.Status == ERR_CODE_EALREADY {
+ if bhe != nil &&
+ (bhe.Status == ERR_CODE_EALREADY ||
+ bhe.Status == ERR_CODE_ATT_BASE+ERR_CODE_ATT_REQ_NOT_SUPPORTED) {
+
return nil
}
return err
@@ -745,7 +748,8 @@ func (bf *BleFsm) StartConnected(
return err
}
- bf.state = SESN_STATE_EXCHANGE_MTU
+ bf.state = SESN_STATE_GET_INFO
+
if _, err := bf.startOnce(); err != nil {
nmxutil.Assert(!bf.IsOpen())
nmxutil.Assert(bf.IsClosed())
@@ -819,7 +823,7 @@ func (bf *BleFsm) TxNmp(payload []byte, nl *nmp.Listener,
}
func (bf *BleFsm) TxOic(payload []byte, ol *oic.Listener,
- timeout time.Duration) (*coap.Message, error) {
+ timeout time.Duration) (coap.Message, error) {
log.Debugf("Tx OIC request: %s", hex.Dump(payload))
if err := bf.writeCmd(payload); err != nil {
diff --git a/nmxact/nmble/ble_oic_sesn.go b/nmxact/nmble/ble_oic_sesn.go
index 9d86e67..b3f8fa3 100644
--- a/nmxact/nmble/ble_oic_sesn.go
+++ b/nmxact/nmble/ble_oic_sesn.go
@@ -202,25 +202,25 @@ func (bos *BleOicSesn) ConnInfo() (BleConnDesc, error) {
}
func (bos *BleOicSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- int, []byte, error) {
+ coap.COAPCode, []byte, error) {
token := nmxutil.NextToken()
ol, err := bos.d.AddOicListener(token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
defer bos.d.RemoveOicListener(token)
- req, err := oic.EncodeGet(uri, token)
+ req, err := oic.EncodeGet(true, uri, token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
rsp, err := bos.bf.TxOic(req, ol, opt.Timeout)
if err != nil {
- return nil, err
+ return 0, nil, err
}
- return rsp.Status, rsp.Payload, nil
+ return rsp.Code(), rsp.Payload(), nil
}
diff --git a/nmxact/nmble/ble_oic_svr.go b/nmxact/nmble/ble_oic_svr.go
new file mode 100644
index 0000000..b892d3d
--- /dev/null
+++ b/nmxact/nmble/ble_oic_svr.go
@@ -0,0 +1,59 @@
+package nmble
+
+import (
+ log "github.com/Sirupsen/logrus"
+
+ . "mynewt.apache.org/newtmgr/nmxact/bledefs"
+ "mynewt.apache.org/newtmgr/nmxact/oic"
+)
+
+type BleOicSvr struct {
+ s oic.Server
+ x *BleXport
+ rspSvcUuid BleUuid
+ rspChrUuid BleUuid
+}
+
+func NewBleOicSvr(x *BleXport,
+ rspSvcUuid BleUuid, rspChrUuid BleUuid) BleOicSvr {
+
+ return BleOicSvr{
+ s: oic.NewServer(true),
+ x: x,
+ rspSvcUuid: rspSvcUuid,
+ rspChrUuid: rspChrUuid,
+ }
+}
+
+func (b *BleOicSvr) AddResource(r oic.Resource) error {
+ return b.s.AddResource(r)
+}
+
+func (b *BleOicSvr) Rx(access BleGattAccess) uint8 {
+ ml, err := b.s.Rx(access.Data)
+ if err != nil {
+ log.Debugf("Error processing incoming CoAP message: %s", err.Error())
+ return 0
+ }
+
+ if ml == nil {
+ // Partial CoAP message; remainder forthcoming.
+ return 0
+ }
+
+ data, err := ml.MarshalBinary()
+ if err != nil {
+ return ERR_CODE_ATT_UNLIKELY
+ }
+
+ _, valHandle, err := FindChrXact(b.x, b.rspSvcUuid, b.rspChrUuid)
+ if err != nil {
+ return ERR_CODE_ATT_UNLIKELY
+ }
+
+ if err := NotifyXact(b.x, access.ConnHandle, valHandle, data); err != nil {
+ return ERR_CODE_ATT_UNLIKELY
+ }
+
+ return 0
+}
diff --git a/nmxact/nmble/ble_plain_sesn.go b/nmxact/nmble/ble_plain_sesn.go
index be8c900..1cbb3e6 100644
--- a/nmxact/nmble/ble_plain_sesn.go
+++ b/nmxact/nmble/ble_plain_sesn.go
@@ -24,6 +24,8 @@ import (
"sync"
"time"
+ "github.com/runtimeco/go-coap"
+
"mynewt.apache.org/newt/util"
. "mynewt.apache.org/newtmgr/nmxact/bledefs"
"mynewt.apache.org/newtmgr/nmxact/nmp"
@@ -182,7 +184,7 @@ func (bps *BlePlainSesn) ConnInfo() (BleConnDesc, error) {
}
func (bps *BlePlainSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- []byte, error) {
+ coap.COAPCode, []byte, error) {
- return nil, fmt.Errorf("BlePlainSesn.GetResourceOnce() unsupported")
+ return 0, nil, fmt.Errorf("BlePlainSesn.GetResourceOnce() unsupported")
}
diff --git a/nmxact/nmble/ble_proto.go b/nmxact/nmble/ble_proto.go
index 0716be2..c0b712d 100644
--- a/nmxact/nmble/ble_proto.go
+++ b/nmxact/nmble/ble_proto.go
@@ -306,6 +306,8 @@ const (
MSG_TYPE_ADD_SVCS = 27
MSG_TYPE_COMMIT_SVCS = 28
MSG_TYPE_ACCESS_STATUS = 29
+ MSG_TYPE_NOTIFY = 30
+ MSG_TYPE_FIND_CHR = 31
MSG_TYPE_SYNC_EVT = 2049
MSG_TYPE_CONNECT_EVT = 2050
@@ -356,6 +358,8 @@ var MsgTypeStringMap = map[MsgType]string{
MSG_TYPE_ADD_SVCS: "add_svcs",
MSG_TYPE_COMMIT_SVCS: "commit_svcs",
MSG_TYPE_ACCESS_STATUS: "access_status",
+ MSG_TYPE_NOTIFY: "notify",
+ MSG_TYPE_FIND_CHR: "find_chr",
MSG_TYPE_SYNC_EVT: "sync_evt",
MSG_TYPE_CONNECT_EVT: "connect_evt",
@@ -1181,7 +1185,8 @@ type BleAccessStatusReq struct {
Seq BleSeq `json:"seq"`
// Mandatory
- AttStatus uint8 `json:"att_status"`
+ AttStatus uint8 `json:"att_status"`
+ Data BleBytes `json:"data"`
}
type BleAccessStatusRsp struct {
@@ -1194,6 +1199,51 @@ type BleAccessStatusRsp struct {
Status int `json:"status"`
}
+type BleNotifyReq struct {
+ // Header
+ Op MsgOp `json:"op"`
+ Type MsgType `json:"type"`
+ Seq BleSeq `json:"seq"`
+
+ // Mandatory
+ ConnHandle uint16 `json:"conn_handle"`
+ AttrHandle uint16 `json:"attr_handle"`
+ Data BleBytes `json:"data"`
+}
+
+type BleNotifyRsp struct {
+ // Header
+ Op MsgOp `json:"op"`
+ Type MsgType `json:"type"`
+ Seq BleSeq `json:"seq"`
+
+ // Mandatory
+ Status int `json:"status"`
+}
+
+type BleFindChrReq struct {
+ // Header
+ Op MsgOp `json:"op"`
+ Type MsgType `json:"type"`
+ Seq BleSeq `json:"seq"`
+
+ // Mandatory
+ SvcUuid BleUuid `json:"svc_uuid"`
+ ChrUuid BleUuid `json:"chr_uuid"`
+}
+
+type BleFindChrRsp struct {
+ // Header
+ Op MsgOp `json:"op"`
+ Type MsgType `json:"type"`
+ Seq BleSeq `json:"seq"`
+
+ // Mandatory
+ Status int `json:"status"`
+ DefHandle uint16 `json:"def_handle"`
+ ValHandle uint16 `json:"val_handle"`
+}
+
func ErrCodeToString(e int) string {
var s string
diff --git a/nmxact/nmble/ble_util.go b/nmxact/nmble/ble_util.go
index aecf4dd..f46e209 100644
--- a/nmxact/nmble/ble_util.go
+++ b/nmxact/nmble/ble_util.go
@@ -344,6 +344,22 @@ func NewAccessStatusReq() *BleAccessStatusReq {
}
}
+func NewNotifyReq() *BleNotifyReq {
+ return &BleNotifyReq{
+ Op: MSG_OP_REQ,
+ Type: MSG_TYPE_NOTIFY,
+ Seq: NextSeq(),
+ }
+}
+
+func NewFindChrReq() *BleFindChrReq {
+ return &BleFindChrReq{
+ Op: MSG_OP_REQ,
+ Type: MSG_TYPE_FIND_CHR,
+ Seq: NextSeq(),
+ }
+}
+
func ConnFindXact(x *BleXport, connHandle uint16) (BleConnDesc, error) {
r := NewBleConnFindReq()
r.ConnHandle = connHandle
@@ -449,9 +465,10 @@ func CommitSvcsXact(x *BleXport) ([]BleRegSvc, error) {
return commitSvcs(x, bl, r)
}
-func AccessStatusXact(x *BleXport, attStatus uint8) error {
+func AccessStatusXact(x *BleXport, attStatus uint8, data []byte) error {
r := NewAccessStatusReq()
r.AttStatus = attStatus
+ r.Data.Bytes = data
bl, err := x.AddListener(SeqKey(r.Seq))
if err != nil {
@@ -462,6 +479,39 @@ func AccessStatusXact(x *BleXport, attStatus uint8) error {
return accessStatus(x, bl, r)
}
+func NotifyXact(x *BleXport, connHandle uint16, attrHandle uint16,
+ data []byte) error {
+
+ r := NewNotifyReq()
+ r.ConnHandle = connHandle
+ r.AttrHandle = attrHandle
+ r.Data.Bytes = data
+
+ bl, err := x.AddListener(SeqKey(r.Seq))
+ if err != nil {
+ return err
+ }
+ defer x.RemoveListener(bl)
+
+ return notify(x, bl, r)
+}
+
+func FindChrXact(x *BleXport, svcUuid BleUuid, chrUuid BleUuid) (
+ uint16, uint16, error) {
+
+ r := NewFindChrReq()
+ r.SvcUuid = svcUuid
+ r.ChrUuid = chrUuid
+
+ bl, err := x.AddListener(SeqKey(r.Seq))
+ if err != nil {
+ return 0, 0, err
+ }
+ defer x.RemoveListener(bl)
+
+ return findChr(x, bl, r)
+}
+
func DiscoverDeviceWithName(
bx *BleXport,
ownAddrType BleAddrType,
@@ -530,3 +580,79 @@ func BleSvcToAddSvc(svc BleSvc) BleAddSvc {
return as
}
+
+func GapService(devName string) BleSvc {
+ return BleSvc{
+ Uuid: BleUuid{0x1800, [16]byte{}},
+ SvcType: BLE_SVC_TYPE_PRIMARY,
+ Chrs: []BleChr{
+ // Device name.
+ BleChr{
+ Uuid: BleUuid{0x2a00, [16]byte{}},
+ Flags: BLE_GATT_F_READ,
+ MinKeySize: 0,
+ AccessCb: func(access BleGattAccess) (uint8, []byte) {
+ return 0, []byte(devName)
+ },
+ },
+
+ // Appearance.
+ BleChr{
+ Uuid: BleUuid{0x2a01, [16]byte{}},
+ Flags: BLE_GATT_F_READ,
+ MinKeySize: 0,
+ AccessCb: func(access BleGattAccess) (uint8, []byte) {
+ return 0, []byte{0, 0}
+ },
+ },
+
+ // Peripheral privacy flag.
+ BleChr{
+ Uuid: BleUuid{0x2a02, [16]byte{}},
+ Flags: BLE_GATT_F_READ,
+ MinKeySize: 0,
+ AccessCb: func(access BleGattAccess) (uint8, []byte) {
+ return 0, []byte{0}
+ },
+ },
+
+ // Reconnection address.
+ BleChr{
+ Uuid: BleUuid{0x2a03, [16]byte{}},
+ Flags: BLE_GATT_F_READ,
+ MinKeySize: 0,
+ AccessCb: func(access BleGattAccess) (uint8, []byte) {
+ return 0, []byte{0, 0, 0, 0, 0, 0}
+ },
+ },
+
+ // Peripheral preferred connection parameters.
+ BleChr{
+ Uuid: BleUuid{0x2a04, [16]byte{}},
+ Flags: BLE_GATT_F_READ,
+ MinKeySize: 0,
+ AccessCb: func(access BleGattAccess) (uint8, []byte) {
+ return 0, []byte{0, 0, 0, 0, 0, 0, 0, 0}
+ },
+ },
+ },
+ }
+}
+
+func GattService() BleSvc {
+ return BleSvc{
+ Uuid: BleUuid{0x1801, [16]byte{}},
+ SvcType: BLE_SVC_TYPE_PRIMARY,
+ Chrs: []BleChr{
+ // Device name.
+ BleChr{
+ Uuid: BleUuid{0x2a05, [16]byte{}},
+ Flags: BLE_GATT_F_INDICATE,
+ MinKeySize: 0,
+ AccessCb: func(access BleGattAccess) (uint8, []byte) {
+ return 0, []byte{0, 0, 0, 0}
+ },
+ },
+ },
+ }
+}
diff --git a/nmxact/nmble/ble_xport.go b/nmxact/nmble/ble_xport.go
index 071f3e0..f67354a 100644
--- a/nmxact/nmble/ble_xport.go
+++ b/nmxact/nmble/ble_xport.go
@@ -27,11 +27,13 @@ import (
"time"
log "github.com/Sirupsen/logrus"
+ "github.com/runtimeco/go-coap"
"mynewt.apache.org/newt/util/unixchild"
"mynewt.apache.org/newtmgr/nmxact/adv"
. "mynewt.apache.org/newtmgr/nmxact/bledefs"
"mynewt.apache.org/newtmgr/nmxact/nmxutil"
+ "mynewt.apache.org/newtmgr/nmxact/oic"
"mynewt.apache.org/newtmgr/nmxact/scan"
"mynewt.apache.org/newtmgr/nmxact/sesn"
)
diff --git a/nmxact/nmble/chrmgr.go b/nmxact/nmble/chrmgr.go
index 24eacf1..4bc78c8 100644
--- a/nmxact/nmble/chrmgr.go
+++ b/nmxact/nmble/chrmgr.go
@@ -103,20 +103,21 @@ func (cm *ChrMgr) findByAttHandle(handle uint16) *chrMgrElem {
func (cm *ChrMgr) Access(x *BleXport, evt *BleAccessEvt) error {
chr := cm.findByAttHandle(evt.AttHandle)
if chr == nil {
- return AccessStatusXact(x, uint8(ERR_CODE_ATT_INVALID_HANDLE))
+ return AccessStatusXact(x, uint8(ERR_CODE_ATT_INVALID_HANDLE), nil)
}
if chr.Cb == nil {
- return AccessStatusXact(x, 0)
+ return AccessStatusXact(x, 0, nil)
}
access := BleGattAccess{
- Op: evt.GattOp,
- SvcUuid: chr.SvcUuid,
- ChrUuid: chr.ChrUuid,
- Data: evt.Data.Bytes,
+ Op: evt.GattOp,
+ ConnHandle: evt.ConnHandle,
+ SvcUuid: chr.SvcUuid,
+ ChrUuid: chr.ChrUuid,
+ Data: evt.Data.Bytes,
}
- status := chr.Cb(access)
- return AccessStatusXact(x, status)
+ status, val := chr.Cb(access)
+ return AccessStatusXact(x, status, val)
}
diff --git a/nmxact/nmble/dispatch.go b/nmxact/nmble/dispatch.go
index 1e8f767..e721270 100644
--- a/nmxact/nmble/dispatch.go
+++ b/nmxact/nmble/dispatch.go
@@ -80,6 +80,8 @@ func clearSvcsRspCtor() Msg { return &BleClearSvcsRsp{} }
func addSvcsRspCtor() Msg { return &BleAddSvcsRsp{} }
func commitSvcsRspCtor() Msg { return &BleCommitSvcsRsp{} }
func accessStatusRspCtor() Msg { return &BleAccessStatusRsp{} }
+func notifyRspCtor() Msg { return &BleNotifyRsp{} }
+func findChrRspCtor() Msg { return &BleFindChrRsp{} }
func syncEvtCtor() Msg { return &BleSyncEvt{} }
func connectEvtCtor() Msg { return &BleConnectEvt{} }
@@ -122,6 +124,8 @@ var msgCtorMap = map[OpTypePair]msgCtor{
{MSG_OP_RSP, MSG_TYPE_ADD_SVCS}: addSvcsRspCtor,
{MSG_OP_RSP, MSG_TYPE_COMMIT_SVCS}: commitSvcsRspCtor,
{MSG_OP_RSP, MSG_TYPE_ACCESS_STATUS}: accessStatusRspCtor,
+ {MSG_OP_RSP, MSG_TYPE_NOTIFY}: notifyRspCtor,
+ {MSG_OP_RSP, MSG_TYPE_FIND_CHR}: findChrRspCtor,
{MSG_OP_EVT, MSG_TYPE_SYNC_EVT}: syncEvtCtor,
{MSG_OP_EVT, MSG_TYPE_CONNECT_EVT}: connectEvtCtor,
diff --git a/nmxact/nmserial/serial_oic_sesn.go b/nmxact/nmserial/serial_oic_sesn.go
index 0ab7fc0..fd38477 100644
--- a/nmxact/nmserial/serial_oic_sesn.go
+++ b/nmxact/nmserial/serial_oic_sesn.go
@@ -153,36 +153,33 @@ func (sos *SerialOicSesn) TxNmpOnce(m *nmp.NmpMsg, opt sesn.TxOptions) (
}
func (sos *SerialOicSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- []byte, error) {
+ coap.COAPCode, []byte, error) {
token := nmxutil.NextToken()
ol, err := sos.d.AddOicListener(token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
defer sos.d.RemoveOicListener(token)
- req, err := oic.EncodeGet(uri, token)
+ req, err := oic.EncodeGet(false, uri, token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
if err := sos.sx.Tx(req); err != nil {
- return nil, err
+ return 0, nil, err
}
for {
select {
case err := <-ol.ErrChan:
- return nil, err
+ return 0, nil, err
case rsp := <-ol.RspChan:
- if rsp.Code != coap.Content {
- return nil, fmt.Errorf("UNEXPECTED OIC ACK: %#v", rsp)
- }
- return rsp.Payload, nil
+ return rsp.Code(), rsp.Payload(), nil
case <-ol.AfterTimeout(opt.Timeout):
- return nil, nmxutil.NewRspTimeoutError("OIC timeout")
+ return 0, nil, nmxutil.NewRspTimeoutError("OIC timeout")
}
}
}
diff --git a/nmxact/nmserial/serial_plain_sesn.go b/nmxact/nmserial/serial_plain_sesn.go
index 9abd00c..6348410 100644
--- a/nmxact/nmserial/serial_plain_sesn.go
+++ b/nmxact/nmserial/serial_plain_sesn.go
@@ -23,6 +23,8 @@ import (
"fmt"
"sync"
+ "github.com/runtimeco/go-coap"
+
"mynewt.apache.org/newtmgr/nmxact/nmp"
"mynewt.apache.org/newtmgr/nmxact/nmxutil"
"mynewt.apache.org/newtmgr/nmxact/sesn"
@@ -156,7 +158,7 @@ func (sps *SerialPlainSesn) TxNmpOnce(m *nmp.NmpMsg, opt sesn.TxOptions) (
}
func (sps *SerialPlainSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- []byte, error) {
+ coap.COAPCode, []byte, error) {
- return nil, fmt.Errorf("SerialPlainSesn.GetResourceOnce() unsupported")
+ return 0, nil, fmt.Errorf("SerialPlainSesn.GetResourceOnce() unsupported")
}
diff --git a/nmxact/oic/dispatch.go b/nmxact/oic/dispatch.go
index 33f0ac9..e8388ba 100644
--- a/nmxact/oic/dispatch.go
+++ b/nmxact/oic/dispatch.go
@@ -50,7 +50,7 @@ func NewToken(rawToken []byte) (Token, error) {
}
type Listener struct {
- RspChan chan *coap.Message
+ RspChan chan coap.Message
ErrChan chan error
tmoChan chan time.Time
timer *time.Timer
@@ -58,7 +58,7 @@ type Listener struct {
func NewListener() *Listener {
return &Listener{
- RspChan: make(chan *coap.Message, 1),
+ RspChan: make(chan coap.Message, 1),
ErrChan: make(chan error, 1),
tmoChan: make(chan time.Time, 1),
}
@@ -86,7 +86,7 @@ func (ol *Listener) Close() {
// dispatcher writes to these listeners.
type Dispatcher struct {
tokenListenerMap map[Token]*Listener
- reassembler *Reassembler
+ rxer Receiver
logDepth int
mtx sync.Mutex
}
@@ -94,13 +94,10 @@ type Dispatcher struct {
func NewDispatcher(isTcp bool, logDepth int) *Dispatcher {
d := &Dispatcher{
tokenListenerMap: map[Token]*Listener{},
+ rxer: NewReceiver(isTcp),
logDepth: logDepth + 2,
}
- if isTcp {
- d.reassembler = NewReassembler()
- }
-
return d
}
@@ -146,7 +143,7 @@ func (d *Dispatcher) RemoveListener(token []byte) *Listener {
return ol
}
-func (d *Dispatcher) dispatchRsp(ot Token, msg *coap.Message) bool {
+func (d *Dispatcher) dispatchRsp(ot Token, msg coap.Message) bool {
d.mtx.Lock()
defer d.mtx.Unlock()
@@ -163,32 +160,17 @@ func (d *Dispatcher) dispatchRsp(ot Token, msg *coap.Message) bool {
// Returns true if the response was dispatched.
func (d *Dispatcher) Dispatch(data []byte) bool {
- var msg *coap.Message
-
- if d.reassembler != nil {
- // TCP.
- tm := d.reassembler.RxFrag(data)
- if tm == nil {
- return false
- }
-
- msg = &tm.Message
- } else {
- // UDP.
- m, err := coap.ParseMessage(data)
- if err != nil {
- log.Printf("CoAP parse failure: %s", err.Error())
- return false
- }
- msg = &m
+ m := d.rxer.Rx(data)
+ if m == nil {
+ return false
}
- ot, err := NewToken(msg.Token)
+ ot, err := NewToken(m.Token())
if err != nil {
return false
}
- return d.dispatchRsp(ot, msg)
+ return d.dispatchRsp(ot, m)
}
func (d *Dispatcher) ErrorOne(token Token, err error) error {
diff --git a/nmxact/oic/oic.go b/nmxact/oic/oic.go
index 7cf925d..278840b 100644
--- a/nmxact/oic/oic.go
+++ b/nmxact/oic/oic.go
@@ -21,26 +21,44 @@ package oic
import (
"fmt"
+ "sync"
"github.com/runtimeco/go-coap"
)
-func EncodeGet(resUri string, token []byte) ([]byte, error) {
+var messageIdMtx sync.Mutex
+var nextMessageId uint16
+
+func NextMessageId() uint16 {
+ messageIdMtx.Lock()
+ defer messageIdMtx.Unlock()
+
+ id := nextMessageId
+ nextMessageId++
+ return id
+}
+
+func EncodeGet(isTcp bool, resUri string, token []byte) ([]byte, error) {
if len(token) > 8 {
return nil,
fmt.Errorf("Invalid token; len=%d, must be < 8", len(token))
}
- req := &coap.TcpMessage{
- Message: coap.Message{
- Type: coap.Confirmable,
- Code: coap.GET,
- Token: token,
- },
+ p := coap.MessageParams{
+ Type: coap.Confirmable,
+ Code: coap.GET,
+ Token: token,
+ }
+
+ var m coap.Message
+ if isTcp {
+ m = coap.NewTcpMessage(p)
+ } else {
+ m = coap.NewDgramMessage(p)
}
- req.SetPathString(resUri)
+ m.SetPathString(resUri)
- b, err := req.MarshalBinary()
+ b, err := m.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("Failed to encode CoAP: %s\n", err.Error())
}
diff --git a/nmxact/oic/receiver.go b/nmxact/oic/receiver.go
new file mode 100644
index 0000000..4d2217e
--- /dev/null
+++ b/nmxact/oic/receiver.go
@@ -0,0 +1,36 @@
+package oic
+
+import (
+ log "github.com/Sirupsen/logrus"
+ "github.com/runtimeco/go-coap"
+)
+
+type Receiver struct {
+ reassembler *Reassembler
+}
+
+func NewReceiver(isTcp bool) Receiver {
+ r := Receiver{}
+
+ if isTcp {
+ r.reassembler = NewReassembler()
+ }
+
+ return r
+}
+
+func (r *Receiver) Rx(data []byte) coap.Message {
+ if r.reassembler != nil {
+ // TCP.
+ return r.reassembler.RxFrag(data)
+ } else {
+ // UDP.
+ m, err := coap.ParseDgramMessage(data)
+ if err != nil {
+ log.Printf("CoAP parse failure: %s", err.Error())
+ return nil
+ }
+
+ return m
+ }
+}
diff --git a/nmxact/oic/resmgr.go b/nmxact/oic/resmgr.go
new file mode 100644
index 0000000..9a1a651
--- /dev/null
+++ b/nmxact/oic/resmgr.go
@@ -0,0 +1,73 @@
+package oic
+
+import (
+ "fmt"
+
+ log "github.com/Sirupsen/logrus"
+ "github.com/runtimeco/go-coap"
+)
+
+type ResWriteFn func(data []byte) coap.COAPCode
+type ResReadFn func(data []byte) (coap.COAPCode, []byte)
+
+type Resource struct {
+ Name string
+ WriteCb ResWriteFn
+ ReadCb ResReadFn
+}
+
+type ResMgr struct {
+ nameResMap map[string]Resource
+}
+
+func NewResMgr() ResMgr {
+ return ResMgr{
+ nameResMap: map[string]Resource{},
+ }
+}
+
+func (rm *ResMgr) Add(r Resource) error {
+ if _, ok := rm.nameResMap[r.Name]; ok {
+ return fmt.Errorf("Registration of duplicate CoAP resource: %s",
+ r.Name)
+ }
+
+ rm.nameResMap[r.Name] = r
+ return nil
+}
+
+func (rm *ResMgr) Access(m coap.Message) (coap.COAPCode, []byte) {
+ paths := m.Path()
+ if len(paths) == 0 {
+ log.Debugf("Incoming CoAP message does not specify a URI path")
+ return coap.NotFound, nil
+ }
+ path := paths[0]
+
+ r, ok := rm.nameResMap[path]
+ if !ok {
+ log.Debugf("Incoming CoAP message specifies unknown resource: %s", path)
+ return coap.NotFound, nil
+ }
+
+ switch m.Code() {
+ case coap.GET:
+ if r.ReadCb == nil {
+ return coap.MethodNotAllowed, nil
+ } else {
+ return r.ReadCb(m.Payload())
+ }
+
+ case coap.PUT:
+ if r.WriteCb == nil {
+ return coap.MethodNotAllowed, nil
+ } else {
+ return r.WriteCb(m.Payload()), nil
+ }
+
+ default:
+ log.Debugf("Don't know how to handle CoAP message with code=%d (%s)",
+ m.Code(), m.Code().String())
+ return coap.MethodNotAllowed, nil
+ }
+}
diff --git a/nmxact/oic/server.go b/nmxact/oic/server.go
new file mode 100644
index 0000000..0e8ee69
--- /dev/null
+++ b/nmxact/oic/server.go
@@ -0,0 +1,64 @@
+package oic
+
+import (
+ "fmt"
+
+ "github.com/runtimeco/go-coap"
+)
+
+type Server struct {
+ rxer Receiver
+ rm ResMgr
+ isTcp bool
+}
+
+func NewServer(isTcp bool) Server {
+ s := Server{
+ rxer: NewReceiver(isTcp),
+ rm: NewResMgr(),
+ isTcp: isTcp,
+ }
+
+ return s
+}
+
+func (s *Server) AddResource(r Resource) error {
+ return s.rm.Add(r)
+}
+
+// @return Response to send back, if any.
+func (s *Server) Rx(data []byte) (coap.Message, error) {
+ m := s.rxer.Rx(data)
+ if m == nil {
+ return nil, nil
+ }
+
+ var typ coap.COAPType
+ switch m.Type() {
+ case coap.Confirmable:
+ typ = coap.Acknowledgement
+
+ case coap.NonConfirmable:
+ typ = coap.NonConfirmable
+
+ default:
+ return nil, fmt.Errorf("Don't know how to handle CoAP message with "+
+ "type=%d (%s)", m.Type(), m.Type().String())
+ }
+
+ code, payload := s.rm.Access(m)
+
+ p := coap.MessageParams{
+ Type: typ,
+ Code: code,
+ MessageID: NextMessageId(),
+ Token: m.Token(),
+ Payload: payload,
+ }
+
+ if !s.isTcp {
+ return coap.NewDgramMessage(p), nil
+ } else {
+ return coap.NewTcpMessage(p), nil
+ }
+}
diff --git a/nmxact/omp/omp.go b/nmxact/omp/omp.go
index 74c662b..b8e3b14 100644
--- a/nmxact/omp/omp.go
+++ b/nmxact/omp/omp.go
@@ -44,22 +44,22 @@ type OicMsg struct {
* codec. So we need to decode the whole response, and then re-encode the
* newtmgr response part.
*/
-func DecodeOmp(tm *coap.Message) (nmp.NmpRsp, error) {
+func DecodeOmp(m coap.Message) (nmp.NmpRsp, error) {
// Ignore non-responses.
- if tm.Code == coap.GET || tm.Code == coap.PUT {
+ if m.Code() == coap.GET || m.Code() == coap.PUT {
return nil, nil
}
- if tm.Code != coap.Created && tm.Code != coap.Deleted &&
- tm.Code != coap.Valid && tm.Code != coap.Changed &&
- tm.Code != coap.Content {
+ if m.Code() != coap.Created && m.Code() != coap.Deleted &&
+ m.Code() != coap.Valid && m.Code() != coap.Changed &&
+ m.Code() != coap.Content {
return nil, fmt.Errorf(
- "OMP response specifies unexpected code: %d (%s)", int(tm.Code),
- tm.Code.String())
+ "OMP response specifies unexpected code: %d (%s)", int(m.Code()),
+ m.Code().String())
}
var om OicMsg
- err := codec.NewDecoderBytes(tm.Payload, new(codec.CborHandle)).Decode(&om)
+ err := codec.NewDecoderBytes(m.Payload(), new(codec.CborHandle)).Decode(&om)
if err != nil {
return nil, fmt.Errorf("Invalid incoming cbor: %s", err.Error())
}
@@ -73,7 +73,7 @@ func DecodeOmp(tm *coap.Message) (nmp.NmpRsp, error) {
return nil, err
}
- rsp, err := nmp.DecodeRspBody(hdr, tm.Payload)
+ rsp, err := nmp.DecodeRspBody(hdr, m.Payload())
if err != nil {
return nil, fmt.Errorf("Error decoding OMP response: %s", err.Error())
}
@@ -85,19 +85,19 @@ func DecodeOmp(tm *coap.Message) (nmp.NmpRsp, error) {
}
type encodeRecord struct {
- m coap.Message
+ tm *coap.TcpMessage
hdrBytes []byte
fieldMap map[string]interface{}
}
func encodeOmpBase(nmr *nmp.NmpMsg) (encodeRecord, error) {
er := encodeRecord{
- m: coap.Message{
+ tm: coap.NewTcpMessage(coap.MessageParams{
Type: coap.Confirmable,
Code: coap.PUT,
- },
+ }),
}
- er.m.SetPathString("/omgr")
+ er.tm.SetPathString("/omgr")
payload := []byte{}
enc := codec.NewEncoderBytes(&payload, new(codec.CborHandle))
@@ -117,7 +117,7 @@ func encodeOmpBase(nmr *nmp.NmpMsg) (encodeRecord, error) {
if err := enc.Encode(er.fieldMap); err != nil {
return er, err
}
- er.m.Payload = payload
+ er.tm.SetPayload(payload)
return er, nil
}
@@ -128,16 +128,14 @@ func EncodeOmpTcp(nmr *nmp.NmpMsg) ([]byte, error) {
return nil, err
}
- tm := coap.TcpMessage{er.m}
-
- data, err := tm.MarshalBinary()
+ data, err := er.tm.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("Failed to encode: %s\n", err.Error())
}
log.Debugf("Serialized OMP TCP request:\n"+
"Hdr %+v:\n%s\nPayload:%s\nData:\n%s",
- nmr.Hdr, hex.Dump(er.hdrBytes), hex.Dump(tm.Payload),
+ nmr.Hdr, hex.Dump(er.hdrBytes), hex.Dump(er.tm.Payload()),
hex.Dump(data))
return data, nil
@@ -149,14 +147,14 @@ func EncodeOmpDgram(nmr *nmp.NmpMsg) ([]byte, error) {
return nil, err
}
- data, err := er.m.MarshalBinary()
+ data, err := er.tm.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("Failed to encode: %s\n", err.Error())
}
log.Debugf("Serialized OMP datagram request:\n"+
"Hdr %+v:\n%s\nPayload:%s\nData:\n%s",
- nmr.Hdr, hex.Dump(er.hdrBytes), hex.Dump(er.m.Payload),
+ nmr.Hdr, hex.Dump(er.hdrBytes), hex.Dump(er.tm.Payload()),
hex.Dump(data))
return data, nil
diff --git a/nmxact/sesn/sesn.go b/nmxact/sesn/sesn.go
index b13fa66..981e7be 100644
--- a/nmxact/sesn/sesn.go
+++ b/nmxact/sesn/sesn.go
@@ -22,6 +22,8 @@ package sesn
import (
"time"
+ "github.com/runtimeco/go-coap"
+
"mynewt.apache.org/newtmgr/nmxact/nmp"
)
@@ -100,6 +102,6 @@ type Sesn interface {
// * other error
TxNmpOnce(m *nmp.NmpMsg, opt TxOptions) (nmp.NmpRsp, error)
- GetResourceOnce(uri string, opt TxOptions) ([]byte, error)
+ GetResourceOnce(uri string, opt TxOptions) (coap.COAPCode, []byte, error)
//SetResource(uri string, value []byte, opt TxOptions) error
}
diff --git a/nmxact/sesn/sesn_util.go b/nmxact/sesn/sesn_util.go
index 20db346..b964639 100644
--- a/nmxact/sesn/sesn_util.go
+++ b/nmxact/sesn/sesn_util.go
@@ -20,6 +20,8 @@
package sesn
import (
+ "github.com/runtimeco/go-coap"
+
"mynewt.apache.org/newtmgr/nmxact/nmp"
"mynewt.apache.org/newtmgr/nmxact/nmxutil"
)
@@ -38,16 +40,16 @@ func TxNmp(s Sesn, m *nmp.NmpMsg, o TxOptions) (nmp.NmpRsp, error) {
}
}
-func GetResource(s Sesn, uri string, o TxOptions) (int, []byte, error) {
+func GetResource(s Sesn, uri string, o TxOptions) (coap.COAPCode, []byte, error) {
retries := o.Tries - 1
for i := 0; ; i++ {
- status, r, err := s.GetResourceOnce(uri, o)
+ code, r, err := s.GetResourceOnce(uri, o)
if err == nil {
- return status, r, nil
+ return code, r, nil
}
if !nmxutil.IsRspTimeout(err) || i >= retries {
- return status, nil, err
+ return code, nil, err
}
}
}
diff --git a/nmxact/udp/udp_oic_sesn.go b/nmxact/udp/udp_oic_sesn.go
index c464255..da1c68c 100644
--- a/nmxact/udp/udp_oic_sesn.go
+++ b/nmxact/udp/udp_oic_sesn.go
@@ -146,36 +146,33 @@ func (uos *UdpOicSesn) AbortRx(seq uint8) error {
}
func (uos *UdpOicSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- []byte, error) {
+ coap.COAPCode, []byte, error) {
token := nmxutil.NextToken()
ol, err := uos.d.AddOicListener(token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
defer uos.d.RemoveOicListener(token)
- req, err := oic.EncodeGet(uri, token)
+ req, err := oic.EncodeGet(false, uri, token)
if err != nil {
- return nil, err
+ return 0, nil, err
}
if _, err := uos.conn.WriteToUDP(req, uos.addr); err != nil {
- return nil, err
+ return 0, nil, err
}
for {
select {
case err := <-ol.ErrChan:
- return nil, err
+ return 0, nil, err
case rsp := <-ol.RspChan:
- if rsp.Code != coap.Content {
- return nil, fmt.Errorf("UNEXPECTED OIC ACK: %#v", rsp)
- }
- return rsp.Payload, nil
+ return rsp.Code(), rsp.Payload(), nil
case <-ol.AfterTimeout(opt.Timeout):
- return nil, nmxutil.NewRspTimeoutError("OIC timeout")
+ return 0, nil, nmxutil.NewRspTimeoutError("OIC timeout")
}
}
}
diff --git a/nmxact/udp/udp_plain_sesn.go b/nmxact/udp/udp_plain_sesn.go
index a8a1b4f..9e0ce2d 100644
--- a/nmxact/udp/udp_plain_sesn.go
+++ b/nmxact/udp/udp_plain_sesn.go
@@ -23,6 +23,8 @@ import (
"fmt"
"net"
+ "github.com/runtimeco/go-coap"
+
"mynewt.apache.org/newtmgr/nmxact/nmp"
"mynewt.apache.org/newtmgr/nmxact/nmxutil"
"mynewt.apache.org/newtmgr/nmxact/omp"
@@ -133,7 +135,7 @@ func (ups *UdpPlainSesn) AbortRx(seq uint8) error {
}
func (ups *UdpPlainSesn) GetResourceOnce(uri string, opt sesn.TxOptions) (
- []byte, error) {
+ coap.COAPCode, []byte, error) {
- return nil, fmt.Errorf("UdpPlainSesn.GetResourceOnce() unsupported")
+ return 0, nil, fmt.Errorf("UdpPlainSesn.GetResourceOnce() unsupported")
}
diff --git a/nmxact/xact/getres.go b/nmxact/xact/getres.go
index 609dadc..1bf85bc 100644
--- a/nmxact/xact/getres.go
+++ b/nmxact/xact/getres.go
@@ -47,7 +47,11 @@ func newGetResResult() *GetResResult {
}
func (r *GetResResult) Status() int {
- return int(r.Code)
+ if r.Code == coap.Content {
+ return 0
+ } else {
+ return int(r.Code)
+ }
}
func (c *GetResCmd) Run(s sesn.Sesn) (Result, error) {
--
To stop receiving notification emails like this one, please contact
"commits@mynewt.apache.org" <co...@mynewt.apache.org>.