func connect()

in nmxact/nmble/ble_act.go [34:101]


func connect(x *BleXport, bl *Listener, r *BleConnectReq) (uint16, error) {
	const rspType = MSG_TYPE_CONNECT

	j, err := json.Marshal(r)
	if err != nil {
		return 0, err
	}

	if err := x.Tx(j); err != nil {
		return 0, err
	}

	// Give blehostd three seconds of leeway to tell us the connection attempt
	// timed out.
	rspTimeout := time.Duration(r.DurationMs+3000) * time.Millisecond
	rspTmoChan := time.After(rspTimeout)
	bhdTmoChan := bl.AfterTimeout(x.RspTimeout())
	for {
		select {
		case err := <-bl.ErrChan:
			return 0, err

		case bm := <-bl.MsgChan:
			switch msg := bm.(type) {
			case *BleConnectRsp:
				bl.Acked = true
				if msg.Status != 0 {
					str := fmt.Sprintf("BLE connection attempt failed; "+
						"status=%s (%d)",
						ErrCodeToString(msg.Status), msg.Status)
					log.Debugf(str)
					return 0, nmxutil.NewBleHostError(msg.Status, str)
				}

			case *BleConnectEvt:
				if msg.Status == 0 {
					return msg.ConnHandle, nil
				} else {
					str := fmt.Sprintf("BLE connection attempt failed; "+
						"status=%s (%d)",
						ErrCodeToString(msg.Status), msg.Status)
					log.Debugf(str)
					return 0, nmxutil.NewBleHostError(msg.Status, str)
				}

			case *BleConnCancelEvt:
				str := "BLE connection attempt cancelled"
				log.Debugf(str)
				return 0, fmt.Errorf("%s", str)

			default:
			}

		case _, ok := <-bhdTmoChan:
			if ok {
				x.Restart("Blehostd timeout: " + MsgTypeToString(rspType))
			}
			bhdTmoChan = nil

		case _, ok := <-rspTmoChan:
			if ok {
				return 0, fmt.Errorf("Failed to connect to peer after %s",
					rspTimeout.String())
			}
			rspTmoChan = nil
		}
	}
}