/// <summary> /// Send a CoAP message to the server. Please note, you must handle all exceptions /// and no event is raised. /// </summary> /// <param name="coapMsg">The CoAP message to send to server</param> /// <returns>Number of bytes sent</returns> public override int Send(AbstractCoAPMessage coapMsg) { if (coapMsg == null) { throw new ArgumentNullException("Message is NULL"); } if (this._clientSocket == null) { throw new InvalidOperationException("CoAP client not yet started"); } int bytesSent = 0; byte[] coapBytes = coapMsg.ToByteStream(); if (coapBytes.Length > AbstractNetworkUtils.GetMaxMessageSize()) { throw new UnsupportedException("Message size too large. Not supported. Try block option"); } bytesSent = this._clientSocket.Send(coapBytes); if (coapMsg.MessageType.Value == CoAPMessageType.CON) { //confirmable message...need to wait for a response coapMsg.DispatchDateTime = DateTime.Now; } return(bytesSent); }
public byte[] ToBytes(AbstractCoAPMessage coapMsg) { byte[] coapBytes = coapMsg.ToByteStream(); if (coapBytes.Length > AbstractNetworkUtils.GetMaxMessageSize()) { throw new UnsupportedException("Message size too large. Not supported. Try block option"); } return(coapBytes); }
/// <summary> /// Creates a payload with byte stream /// </summary> /// <param name="payloadData">Payload as byte stream</param> public CoAPPayload(byte[] payloadData) { if (payloadData == null || payloadData.Length == 0) { throw new ArgumentNullException("Payload data cannot be NULL or empty byte stream"); } if (payloadData.Length > AbstractNetworkUtils.GetMaxMessageSize() / 2) { throw new ArgumentException("Payload size cannot be more than " + AbstractNetworkUtils.GetMaxMessageSize() / 2); } this.Value = payloadData; }
/// <summary> /// Creates a payload with string data /// </summary> /// <param name="payloadData">Payload data as string</param> public CoAPPayload(string payloadData) { if (payloadData == null || payloadData.Trim().Length == 0) { throw new ArgumentNullException("Payload data cannot be NULL or empty string"); } if (payloadData.Trim().Length > AbstractNetworkUtils.GetMaxMessageSize() / 2) { throw new ArgumentException("Payload size cannot be more than " + AbstractNetworkUtils.GetMaxMessageSize() / 2); } this.Value = AbstractByteUtils.StringToByteUTF8(payloadData.Trim()); }
/// <summary> /// Send a CoAP message to the server /// </summary> /// <param name="coapMsg">The CoAP message to send to server</param> /// <returns>Number of bytes sent</returns> public override int Send(AbstractCoAPMessage coapMsg) { if (coapMsg == null) { throw new ArgumentNullException("Message is NULL"); } if (this._clientSocket == null) { throw new InvalidOperationException("CoAP client not yet started"); } int bytesSent = 0; try { byte[] coapBytes = coapMsg.ToByteStream(); if (coapBytes.Length > AbstractNetworkUtils.GetMaxMessageSize()) { throw new UnsupportedException("Message size too large. Not supported. Try block option"); } bytesSent = this._clientSocket.Send(coapBytes); if (coapMsg.MessageType.Value == CoAPMessageType.CON) { //confirmable message...need to wait for a response if (coapMsg.Timeout <= 0) { coapMsg.Timeout = AbstractCoAPChannel.DEFAULT_ACK_TIMEOUT_SECS; } coapMsg.DispatchDateTime = DateTime.Now; this._msgPendingAckQ.AddToWaitQ(coapMsg); } } catch (Exception e) { this._msgPendingAckQ.RemoveFromWaitQ(coapMsg.ID.Value); this.HandleError(e, coapMsg); } return(bytesSent); }
/// <summary> /// This thread continuously looks for messages on the socket /// Once available, it will post them for handling downstream /// </summary> protected void ProcessReceivedMessages() { byte[] buffer = null; int maxSize = AbstractNetworkUtils.GetMaxMessageSize(); while (!this._isDone) { Thread.Sleep(1000); try { if (this._clientSocket.Available >= 4 /*Min size of CoAP block*/) { buffer = new byte[maxSize * 2]; int bytesRead = this._clientSocket.Receive(buffer); byte[] udpMsg = new byte[bytesRead]; Array.Copy(buffer, udpMsg, bytesRead); byte mType = AbstractCoAPMessage.PeekMessageType(udpMsg); if ((mType == CoAPMessageType.CON || mType == CoAPMessageType.NON) && AbstractCoAPMessage.PeekIfMessageCodeIsRequestCode(udpMsg)) { //This is a request CoAPRequest coapReq = new CoAPRequest(); coapReq.FromByteStream(udpMsg); coapReq.RemoteSender = this._remoteEP;//Setup who sent this message string uriHost = ((IPEndPoint)this._remoteEP).Address.ToString(); UInt16 uriPort = (UInt16)((IPEndPoint)this._remoteEP).Port; //setup the default values of host and port //setup the default values of host and port if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_HOST)) { coapReq.Options.AddOption(CoAPHeaderOption.URI_HOST, AbstractByteUtils.StringToByteUTF8(uriHost)); } if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_PORT)) { coapReq.Options.AddOption(CoAPHeaderOption.URI_PORT, AbstractByteUtils.GetBytes(uriPort)); } this.HandleRequestReceived(coapReq); } else { //This is a response CoAPResponse coapResp = new CoAPResponse(); coapResp.FromByteStream(udpMsg); coapResp.RemoteSender = this._remoteEP;//Setup who sent this message //Remove the waiting confirmable message from the timeout queue if (coapResp.MessageType.Value == CoAPMessageType.ACK || coapResp.MessageType.Value == CoAPMessageType.RST) { this._msgPendingAckQ.RemoveFromWaitQ(coapResp.ID.Value); } this.HandleResponseReceived(coapResp); } } } catch (SocketException se) { //Close this client connection this._isDone = true; this.HandleError(se, null); } catch (ArgumentNullException argEx) { this.HandleError(argEx, null); } catch (ArgumentException argEx) { this.HandleError(argEx, null); } catch (CoAPFormatException fEx) { //Invalid message.. this.HandleError(fEx, null); } } }
/// <summary> /// This is the thread where the socket server will accept client connections and process /// </summary> protected void WaitForConnections() { EndPoint sender = null; byte[] buffer = null; ArrayList previousBytes = new ArrayList(); int bytesRead = 0; byte mType = 0; UInt16 mId = 0; byte[] udpMsg = null; int maxSize = AbstractNetworkUtils.GetMaxMessageSize(); while (!this._isDone) { try { if (this._socket.Available >= 4 /*Min size of CoAP block*/) { sender = new IPEndPoint(IPAddress.Any, 0); buffer = new byte[maxSize * 2]; bytesRead = this._socket.ReceiveFrom(buffer, ref sender); udpMsg = new byte[bytesRead]; Array.Copy(buffer, udpMsg, bytesRead); mType = AbstractCoAPMessage.PeekMessageType(udpMsg); mId = AbstractCoAPMessage.PeekMessageID(udpMsg); if ((mType == CoAPMessageType.CON || mType == CoAPMessageType.NON) && AbstractCoAPMessage.PeekIfMessageCodeIsRequestCode(udpMsg)) { this.ProcessRequestMessageReceived(udpMsg, ref sender); } else { this.ProcessResponseMessageReceived(udpMsg, ref sender); } } else { //Nothing on the socket...wait Thread.Sleep(5000); } } catch (SocketException se) { //Try to re-initialize socket, and proceed only when the socket //is successfully re-initialized this._isDone = !this.ReInitSocket(); this.HandleError(se, null); } catch (ArgumentNullException argEx) { if (mType == CoAPMessageType.CON) { this.RespondToBadCONRequest(mId); } this.HandleError(argEx, null); } catch (ArgumentException argEx) { if (mType == CoAPMessageType.CON) { this.RespondToBadCONRequest(mId); } this.HandleError(argEx, null); } catch (CoAPFormatException fEx) { //Invalid message.. if (mType == CoAPMessageType.CON) { this.RespondToBadCONRequest(mId); } this.HandleError(fEx, null); } } }
/// <summary> /// Receive a message from the server. This will block if there /// are no messages. Please note, you must handle all errors (except timeout) /// and no error is raised. /// </summary> /// <param name="rxTimeoutMillis"> /// The timeout value in milliseconds.The default value is 0, which indicates an infinite time-out period. /// Specifying -1 also indicates an infinite time-out period /// </param> /// <param name="timedOut">Is set to true on timeout</param> /// <returns>An instance of AbstractCoAPMessage on success, else null on error/timeout</returns> public AbstractCoAPMessage ReceiveMessage(int rxTimeoutMillis, ref bool timedOut) { byte[] buffer = null; int maxSize = AbstractNetworkUtils.GetMaxMessageSize(); CoAPRequest coapReq = null; CoAPResponse coapResp = null; try { this._clientSocket.ReceiveTimeout = rxTimeoutMillis; buffer = new byte[maxSize * 2]; int bytesRead = this._clientSocket.Receive(buffer); byte[] udpMsg = new byte[bytesRead]; Array.Copy(buffer, udpMsg, bytesRead); byte mType = AbstractCoAPMessage.PeekMessageType(udpMsg); if ((mType == CoAPMessageType.CON || mType == CoAPMessageType.NON) && AbstractCoAPMessage.PeekIfMessageCodeIsRequestCode(udpMsg)) { //This is a request coapReq = new CoAPRequest(); coapReq.FromByteStream(udpMsg); coapReq.RemoteSender = this._remoteEP;//Setup who sent this message string uriHost = ((IPEndPoint)this._remoteEP).Address.ToString(); UInt16 uriPort = (UInt16)((IPEndPoint)this._remoteEP).Port; //setup the default values of host and port //setup the default values of host and port if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_HOST)) { coapReq.Options.AddOption(CoAPHeaderOption.URI_HOST, AbstractByteUtils.StringToByteUTF8(uriHost)); } if (!coapReq.Options.HasOption(CoAPHeaderOption.URI_PORT)) { coapReq.Options.AddOption(CoAPHeaderOption.URI_PORT, AbstractByteUtils.GetBytes(uriPort)); } return(coapReq); } else { //This is a response coapResp = new CoAPResponse(); coapResp.FromByteStream(udpMsg); coapResp.RemoteSender = this._remoteEP;//Setup who sent this message return(coapResp); } } catch (SocketException se) { if (se.ErrorCode == (int)SocketError.TimedOut) { timedOut = true; } else { throw se; } } return(null); }