/// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = "";// (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (coapResp != null) { if (coapResp.Token != null) { tokenRx = AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value); } } try { FileLogger.Write("Received response from server - token = " + tokenRx); FileLogger.Write(coapResp.ToString()); } catch { } if (tokenRx == __Token) { if (BreakIfError(coapResp.Code.Value)) { return; } if (coapResp.Code.Value == CoAPMessageCode.CHANGED) { __Response = coapResp; __Done.Set(); } else { // Will come here if an error occurred. // For now, let the request time out. } } }
/// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> private void OnCoAPSessionResponseReceived(CoAPResponse coapResp) { __TimedOut = false; string tokenRx = "";// (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (coapResp != null) { if (coapResp.Token != null) { tokenRx = AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value); } } try { FileLogger.Write("Received response from server - token = " + tokenRx); FileLogger.Write(coapResp.ToString()); } catch { } if (tokenRx == __Token) { int classCode = ((coapResp.Code.Value & 0xE0) >> 5); if (classCode == 2) { __SessionRequestSucceeded = true; FileLogger.Write("Session request completed successfully"); } else { FileLogger.Write("Session call code " + coapResp.Code.Value.ToString()); //Will come here if an error occurred.. } __Done.Set(); } }
/// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == __Token) { if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT); if (options.Count > 0) { bool proceed = false; foreach (CoAPHeaderOption o in options) { CoAPContentFormatOption ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value)); if (ccformat.Value == CoAPContentFormatOption.APPLICATION_LINK_FORMAT) { proceed = true; } } if (proceed) { string discovery = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); Console.WriteLine("Discovery " + __coapClient.EndPoint.ToString() + " = " + discovery); __DiscoveryResult = discovery; } } } else { //Will come here if an error occurred.. } } __Done.Set(); }
private void AcknowledgeResponse(CoAPResponse coapResp) { string serverIP = __IpAddress; // Response handlers already set - leave them alone coapReq = new CoAPRequest(CoAPMessageType.ACK, CoAPMessageCode.GET, HdkUtils.MessageId()); string uriToCall = "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + __ServerPort + __URI; coapReq.SetURL(uriToCall); __Token = DateTime.Now.ToString("HHmmss");//Token value must be less than 8 bytes coapReq.Token = coapResp.Token; string blat = coapReq.ToString(); // JJK - Changes in v2.0.7 //coapReq.Options.AddOption(CoAPHeaderOption.PROXY_SCHEME, "coap"); // make Proxy packet coapReq.Options.AddOption(CoAPHeaderOption.BLOCK2, new byte[] { CoAPBlockOption.BLOCK_SIZE_128 }); coapReq.Options.AddOption(CoAPHeaderOption.PROXY_URI, "coap://" + HdkUtils.UriFromMac(__IpAddress) + ":" + "4849" + __URI); coapReq.Options.RemoveOption(CoAPHeaderOption.URI_HOST); coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY); coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PATH); coapReq.Options.RemoveOption(CoAPHeaderOption.URI_PORT); coapReq.Options.RemoveOption(CoAPHeaderOption.CONTENT_FORMAT); // JJK - end of Changes in v2.0.7 FileLogger.Write("About to send CoAP ACK request"); FileLogger.Write(coapReq.ToString()); CoApGatewaySessionManager.Instance.Client.Send(coapReq); }
/// <summary> /// Handle response message received from remote clients /// </summary> /// <param name="msgStream">The byte stream that represents a response message</param> /// <param name="sender">The remote sender endpoint</param> protected virtual void ProcessResponseMessageReceived(byte[] msgStream, ref EndPoint sender) { CoAPResponse coapResp = new CoAPResponse(); IPEndPoint remoteSender = (IPEndPoint)sender; try { //This is a response coapResp.FromByteStream(msgStream); coapResp.RemoteSender = new IPEndPoint(remoteSender.Address, remoteSender.Port);//Setup who sent this message //Remove the waiting confirmable message from the timeout queue if (coapResp.MessageType.Value == CoAPMessageType.RST || coapResp.MessageType.Value == CoAPMessageType.ACK) { this._msgPendingAckQ.RemoveFromWaitQ(coapResp.ID.Value); } //If this is a RST, remove any observers if (coapResp.MessageType.Value == CoAPMessageType.RST) { this._observers.RemoveResourceObserver(coapResp); } this.HandleResponseReceived(coapResp); } catch { ;//TOCHECK::Do nothing, we do not want to crash the server just because we //could not process one received message...will check later how to improve this } }
private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == _mToken) { //This response is against the NON request for getting temperature we issued earlier if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { //Get the temperature string tempAsJSON = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); // Light light = Light.Deserialize(tempAsJSON); // Hashtable tempValues = JSONResult.FromJSON(tempAsJSON); // int temp = Convert.ToInt32(tempValues["temp"].ToString()); // int temp = Convert.ToInt32(tempAsJSON); //Now do something with this temperature received from the server Application.Current.Dispatcher.BeginInvoke((Action)(() => { gridError.Visibility = Visibility.Visible; })); Application.Current.Dispatcher.BeginInvoke((Action)(() => { txtError.Text = $"Response received: {tempAsJSON}"; })); } else { //Will come here if an error occurred.. } } }
/// <summary> /// Called when CoAP response is received (ACK, RST). Not used in this sample /// </summary> /// <param name="coapResp">CoAPResponse</param> static void OnCoAPResponseReceived(CoAPResponse coapResp) { //If we receive a RST, then remve that client from notifications if (coapResp.MessageType.Value == CoAPMessageType.RST) { coapServer.ObserversList.RemoveResourceObserver(coapResp); } }
/// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; FileLogger.Write("Received response from server - token = " + tokenRx); FileLogger.Write(coapResp.ToString()); if (tokenRx == __Token) { if (BreakIfError(coapResp.Code.Value)) { return; } if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT); if (options.Count > 0) { CoAPContentFormatOption ccformat = new CoAPContentFormatOption(); bool proceed = false; foreach (CoAPHeaderOption o in options) { ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value)); if (ccformat.IsValid()) { proceed = true; break; } } if (proceed) { if (ccformat.Value == CoAPContentFormatOption.TEXT_PLAIN) { string result = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); __PingResult = result; } if (ccformat.Value == CoAPContentFormatOption.APPLICATION_OCTET_STREAM) { string result = HdkUtils.BytesToHexView(coapResp.Payload.Value); __PingResult = result; } if (ccformat.Value == CoAPContentFormatOption.APPLICATION_JSON) { string result = HdkUtils.BytesToHexView(coapResp.Payload.Value); __PingResult = result; } __Response = coapResp; __Done.Set(); } } } else { //Will come here if an error occurred.. } } }
///// <summary> ///// Called when a request is received... ///// </summary> ///// <param name="coapReq">The CoAPRequest object</param> //private void OnCoAPRequestReceived(CoAPRequest coapReq) //{ // Console.WriteLine(coapReq.QueryString); //} /// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == __Token) { if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT); if (options.Count > 0) { CoAPContentFormatOption ccformat = new CoAPContentFormatOption(); bool proceed = false; foreach (CoAPHeaderOption o in options) { ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value)); if (ccformat.IsValid()) { proceed = true; break; } } if (proceed) { if (ccformat.Value == CoAPContentFormatOption.TEXT_PLAIN) { string result = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); Console.WriteLine("Get on Olimex " + __coapClient.EndPoint.ToString() + " = " + result); __GetResult = result; } if (ccformat.Value == CoAPContentFormatOption.APPLICATION_OCTET_STREAM) { string result = SSNUtils.Conversion.BytesToHexView(coapResp.Payload.Value); Console.WriteLine("Get on Olimex " + __coapClient.EndPoint.ToString() + " = " + result); __GetResult = result; } if (ccformat.Value == CoAPContentFormatOption.APPLICATION_JSON) { string result = SSNUtils.Conversion.BytesToHexView(coapResp.Payload.Value); Console.WriteLine("Get on Olimex " + __coapClient.EndPoint.ToString() + " = " + result); __GetResult = result; } __Response = coapResp; } } } else { //Will come here if an error occurred.. } } __Done.Set(); }
/// <summary> /// We should receive an ACK to indicate we successfully registered with /// the server to observe the resource /// </summary> /// <param name="coapResp">CoAPResponse</param> static void OnCoAPResponseReceived(CoAPResponse coapResp) { if (coapResp.MessageType.Value == CoAPMessageType.ACK && coapResp.Code.Value == CoAPMessageCode.EMPTY) { Debug.WriteLine("Registered successfully to observe temperature"); } else { Debug.WriteLine("Failed to register for temperature observation"); } }
/// <summary> /// We should receive the temperature from sever in the response /// </summary> /// <param name="coapResp">CoAPResponse</param> private static void OnCoAPResponseReceived(CoAPResponse coapResp) { if (coapResp.MessageType.Value == CoAPMessageType.ACK && coapResp.Code.Value == CoAPMessageCode.CONTENT) { //We got the temperature..it will be in payload in JSON string payload = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); Hashtable keyVal = JSONResult.FromJSON(payload); int temp = Convert.ToInt32(keyVal["temp"].ToString()); //do something with the temperature now } }
/// <summary> /// Remove the resource observer based on the token value in the response /// </summary> /// <param name="coapResp">CoAPResponse</param> public void RemoveResourceObserver(CoAPResponse coapResp) { if (coapResp == null) { throw new ArgumentNullException("Invalid CoAP response type. Must not be NULL"); } string observedResourceURL = this.FindResourceBeingObserved(coapResp.Token); if (observedResourceURL != null) { this.RemoveResourceObserver(observedResourceURL, coapResp.Token.Value); } }
private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == _mToken) { if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { tempAsJSON = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); } else { } } }
/// <summary> /// Process GET responses related to observe. /// </summary> /// <param name="coapResp">the CoAPResponse object that we are going to report</param> private void HandleObserveResponse(CoAPResponse coapResp) { string toAdd = ""; try { toAdd = coapResp.ToString(); // Setting the text in a method that may have to be Invoked. SetText(txtResult, txtResult.Text + toAdd); } catch (Exception oops) { FileLogger.Write(oops.Message); FileLogger.Write(oops.StackTrace); } }
/// <summary> /// Once a response is received, check if that has block option set. /// If yes, server has responded back. Ensure you check the more flag. /// If that falg was set in the response, that means, server is still /// getting the data that you sent in the previous PUT request. So wait /// for a final ACK /// </summary> /// <param name="coapResp">CoAPResponse</param> private static void OnCoAPResponseReceived(CoAPResponse coapResp) { if (coapResp.MessageType.Value == CoAPMessageType.ACK) { CoAPBlockOption returnedBlockOption = coapResp.GetBlockOption(CoAPHeaderOption.BLOCK1); if (returnedBlockOption != null && !returnedBlockOption.HasMoreBlocks) { //send the next block _blockSeqNo++; if (HasDataToSend()) { TransferToServerInBlocks(); } } } }
/// <summary> /// Raised when a CoAP response is received /// </summary> /// <param name="coapResp">CoAPResponse</param> protected void HandleResponseReceived(CoAPResponse coapResp) { CoAPResponseReceivedHandler respRxHandler = CoAPResponseReceived; try { if (respRxHandler != null) { respRxHandler(coapResp); } } catch (Exception e) { AbstractLogUtil.GetLogger().LogError(e.ToString()); //Do nothing else...do not want to bring down the whole thing because handler failed } }
/// <summary> /// Send the CoAP message to client /// </summary> /// <param name="coapMsg">The CoAP message to send</param> /// <returns>Number of bytes sent</returns> public override int Send(AbstractCoAPMessage coapMsg) { if (coapMsg == null) { throw new ArgumentNullException("Message is NULL"); } if (this._socket == null) { throw new InvalidOperationException("CoAP server not yet started"); } int bytesSent = 0; try { //We do not want server to die when a socket send error occurs... //just clean all settings specific to the remote client and //keep going byte[] coapBytes = coapMsg.ToByteStream(); bytesSent = this._socket.SendTo(coapBytes, coapMsg.RemoteSender); if (coapMsg.MessageType.Value == CoAPMessageType.CON) { //confirmable message...need to wait for a response coapMsg.DispatchDateTime = DateTime.Now; this._msgPendingAckQ.AddToWaitQ(coapMsg); } } catch (Exception e) { this._msgPendingAckQ.RemoveFromWaitQ(coapMsg.ID.Value); if (coapMsg.GetType() == typeof(CoAPRequest)) { CoAPRequest coapReq = (CoAPRequest)coapMsg; this._observers.RemoveResourceObserver(coapReq.GetURL(), coapReq.Token.Value); } else if (coapMsg.GetType() == typeof(CoAPResponse)) { CoAPResponse coapResp = (CoAPResponse)coapMsg; this._observers.RemoveResourceObserver(coapResp); } this.HandleError(e, coapMsg); } return(bytesSent); }
/// <summary> /// Called when a CoAP request is received...we will only support CON requests /// of type GET... the path is sensors/temp /// </summary> /// <param name="coapReq">CoAPRequest object</param> private static void OnCoAPRequestReceived(CoAPRequest coapReq) { string reqPath = (coapReq.GetPath() != null) ? coapReq.GetPath().ToLower() : ""; if (coapReq.MessageType.Value == CoAPMessageType.CON) { if (coapReq.Code.Value != CoAPMessageCode.GET) { CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.METHOD_NOT_ALLOWED, coapReq /*Copy all necessary values from request in the response*/); //When you use the constructor that accepts a request, then automatically //the message id , token and remote sender values are copied over to the response coapServer.Send(resp); } else if (reqPath != "sensors/temp") { //We do not understand this.. CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.NOT_FOUND, coapReq /*Copy all necessary values from request in the response*/); coapServer.Send(resp); } else { Debug.WriteLine(coapReq.ToString()); CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.CONTENT, coapReq /*Copy all necessary values from request in the response*/); //The payload will be JSON Hashtable ht = new Hashtable(); ht.Add("temp", GetRoomTemperature()); string jsonStr = JSONResult.ToJSON(ht); resp.AddPayload(jsonStr); //Tell recipient about the content-type of the response resp.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_JSON)); //send it coapServer.Send(resp); } } }
/// <summary> /// Going forward, we will receive temperature notifications from /// server in a CON request /// </summary> /// <param name="coapReq">CoAPRequest</param> static void OnCoAPRequestReceived(CoAPRequest coapReq) { if (coapReq.MessageType.Value == CoAPMessageType.CON) { //Extract the temperature..but first, check if the notification is fresh //The server sends a 4-digit sequence number int newObsSeq = AbstractByteUtils.ToUInt16(coapReq.Options.GetOption(CoAPHeaderOption.OBSERVE).Value); if ((lastObsSeq < newObsSeq && ((newObsSeq - lastObsSeq) < (System.Math.Pow(2.0, 23.0)))) || (lastObsSeq > newObsSeq && ((lastObsSeq - newObsSeq) > (System.Math.Pow(2.0, 23.0)))) || DateTime.Today > lastObsRx.AddSeconds(128)) { //The value received from server is new....read the new temperature //We got the temperature..it will be in payload in JSON string payload = AbstractByteUtils.ByteToStringUTF8(coapReq.Payload.Value); Hashtable keyVal = JSONResult.FromJSON(payload); int temp = Convert.ToInt32(keyVal["temp"].ToString()); //do something with the temperature now Debug.WriteLine(coapReq.ToString()); } //update how many notifications received countOfNotifications++; if (countOfNotifications > 5) { //We are no longer interested...send RST to de-register CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.EMPTY, coapReq.ID.Value); resp.RemoteSender = coapReq.RemoteSender; resp.Token = coapReq.Token;//Do not forget this...this is how messages are correlated coapClient.Send(resp); } else { //we are still interested...send ACK CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.EMPTY, coapReq.ID.Value); resp.RemoteSender = coapReq.RemoteSender; resp.Token = coapReq.Token;//Do not forget this...this is how messages are correlated coapClient.Send(resp); } lastObsSeq = newObsSeq; lastObsRx = DateTime.Today; } }
/// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> static void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == _mToken) { //This response is against the NON request for getting temperature we issued earlier if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { //Get the temperature string tempAsJSON = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); Hashtable tempValues = JSONResult.FromJSON(tempAsJSON); int temp = Convert.ToInt32(tempValues["temp"].ToString()); //Now do something with this temperature received from the server } else { //Will come here if an error occurred.. } } }
/// <summary> /// Called when a CoAP request is received...we will only support CON requests /// of type GET... the path is sensors/temp /// </summary> /// <param name="coapReq">CoAPRequest object</param> static void OnCoAPRequestReceived(CoAPRequest coapReq) { string reqPath = (coapReq.GetPath() != null) ? coapReq.GetPath().ToLower() : ""; /*We have skipped error handling in code below to just focus on observe option*/ if (coapReq.MessageType.Value == CoAPMessageType.CON && coapReq.Code.Value == CoAPMessageCode.GET) { if (!coapReq.IsObservable() /*Does the request have "Observe" option*/) { /*Request is not to observe...we do not support anything no-observable*/ CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.NOT_IMPLEMENTED, coapReq /*Copy all necessary values from request in the response*/); coapServer.Send(resp); } else if (!coapServer.ObserversList.IsResourceBeingObserved(coapReq.GetURL()) /*do we support observation on this path*/) { //Observation is not supported on this path..just to tell you how to check CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.NOT_FOUND, coapReq /*Copy all necessary values from request in the response*/); coapServer.Send(resp); } else { //This is a request to observe this resource...register this client coapServer.ObserversList.AddResourceObserver(coapReq); /*Request contains observe option and path is correct*/ CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.EMPTY, coapReq /*Copy all necessary values from request in the response*/); //send it..tell client we registered it's request to observe coapServer.Send(resp); } } }
/// <summary> /// For implementations whose communications approach doesn't fit in the standard model, /// this allows an inheriting class to set the response payload. /// </summary> /// <param name="payload"></param> public void SetDeleteResult(byte[] payload) { __InternalPayload = payload; CoAPResponse coapResp = new CoAPResponse(); try { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == __Token) { if (coapResp.Code.Value == CoAPMessageCode.DELETED) { __Response = coapResp; } else { //Will come here if an error occurred.. } } } catch { } }
/// <summary> /// This is where we will get the PUT request /// </summary> /// <param name="coapReq">CoAPRequest</param> static void OnCoAPRequestReceived(CoAPRequest coapReq) { string path = coapReq.GetPath(); /*Error checking not done to simplify example*/ if (coapReq.MessageType.Value == CoAPMessageType.CON && coapReq.Code.Value == CoAPMessageCode.PUT && path == "largedata/blockput") { if (_rxBytes == null) { _rxBytes = new Hashtable(); } CoAPBlockOption rxBlockOption = coapReq.GetBlockOption(CoAPHeaderOption.BLOCK1); if (rxBlockOption != null) { byte[] rxBytes = coapReq.Payload.Value; if (_rxBytes.Contains(rxBlockOption.SequenceNumber)) { _rxBytes[rxBlockOption.SequenceNumber] = rxBytes;//Update } else { _rxBytes.Add(rxBlockOption.SequenceNumber, rxBytes);//Add } //Now send an ACK CoAPBlockOption ackBlockOption = new CoAPBlockOption(rxBlockOption.SequenceNumber, false /*incidate to client that we have guzzled all the bytes*/, rxBlockOption.SizeExponent); CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.CONTENT, coapReq.ID.Value); resp.Token = coapReq.Token; resp.RemoteSender = coapReq.RemoteSender; resp.SetBlockOption(CoAPHeaderOption.BLOCK1, ackBlockOption); _server.Send(resp); } } }
/// <summary> /// Called when a response is received against a sent request /// </summary> /// <param name="coapResp">The CoAPResponse object</param> private void OnCoAPResponseReceived(CoAPResponse coapResp) { string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; FileLogger.Write("Received response from server - token = " + tokenRx); FileLogger.Write(coapResp.ToString()); __Response = coapResp; if (tokenRx == __Token) { if (BreakIfError(coapResp.Code.Value)) { return; } if (coapResp.Code.Value == CoAPMessageCode.DELETED) { __Done.Set(); } else { //Will come here if an error occurred.. } } }
/// <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> /// When a CON is received but we cannot understand the message any further for any reason /// (e.g. invalid format), we want to send a RST. We make a best case attempt to /// find out the message ID if possible, else we send zero /// </summary> /// <param name="mId">The message Id</param> protected virtual void RespondToBadCONRequest(UInt16 mId) { CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.BAD_REQUEST, mId); this.Send(resp); }
/// <summary> /// When a CON is received with EMPTY message type from the client, it means the /// client is simply pinging. We need to send a RST message /// </summary> /// <param name="pingReq">The ping request</param> protected virtual void RespondToPing(CoAPRequest pingReq) { CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.EMPTY, pingReq); this.Send(resp); }
public void SetGetResult(byte[] payload) { string discovery = AbstractByteUtils.ByteToStringUTF8(payload); Console.WriteLine("Discovery = " + discovery); __GetResult = discovery; __InternalPayload = payload; CoAPResponse coapResp = new CoAPResponse(); try { coapResp.FromByteStream(payload); string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : ""; if (tokenRx == __Token) { if (coapResp.Code.Value == CoAPMessageCode.CONTENT) { ArrayList options = coapResp.Options.GetOptions((ushort)CoAPHeaderOption.CONTENT_FORMAT); if (options.Count > 0) { CoAPContentFormatOption ccformat = new CoAPContentFormatOption(); bool proceed = false; foreach (CoAPHeaderOption o in options) { ccformat = new CoAPContentFormatOption(AbstractByteUtils.ToUInt16(o.Value)); if (ccformat.IsValid()) { proceed = true; break; } } if (proceed) { if (ccformat.Value == CoAPContentFormatOption.TEXT_PLAIN) { string result = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value); Console.WriteLine("Get " + " = " + result); __GetResult = result; } if (ccformat.Value == CoAPContentFormatOption.APPLICATION_OCTET_STREAM) { string result = HdkUtils.BytesToHexView(coapResp.Payload.Value); Console.WriteLine("Get " + " = " + result); __GetResult = result; } if (ccformat.Value == CoAPContentFormatOption.APPLICATION_JSON) { string result = HdkUtils.BytesToHexView(coapResp.Payload.Value); Console.WriteLine("Get " + " = " + result); __GetResult = result; } __Response = coapResp; } } } else { //Will come here if an error occurred.. } } } catch { } }
/// <summary> /// Called when CoAP response is received (ACK, RST). Not used in this sample /// </summary> /// <param name="coapResp">CoAPResponse</param> private static void OnCoAPResponseReceived(CoAPResponse coapResp) { //not used in this sample }
/// <summary> /// Called when a CoAP request is received (NON, CON) /// </summary> /// <param name="coapReq">CoAPRequest object</param> private static void OnCoAPRequestReceived(CoAPRequest coapReq) { string reqPath = (coapReq.GetPath() != null) ? coapReq.GetPath().ToLower() : ""; /* * For well-know path, we should support both CON and NON. * For NON request, we send back the details in another NON message * For CON request, we send back the details in an ACK */ /*Well known should be a GET*/ if (coapReq.Code.Value != CoAPMessageCode.GET) { if (coapReq.MessageType.Value == CoAPMessageType.CON) { CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.METHOD_NOT_ALLOWED, coapReq /*Copy all necessary values from request in the response*/); //When you use the constructor that accepts a request, then automatically //the message id , token and remote sender values are copied over to the response coapServer.Send(resp); } else { //For NON, we can only send back a RST CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.METHOD_NOT_ALLOWED, coapReq /*Copy all necessary values from request in the response*/); //When you use the constructor that accepts a request, then automatically //the message id , token and remote sender values are copied over to the response coapServer.Send(resp); } } else { //Message type is GET...check the path..this server only supports well-known path if (reqPath != ".well-known/core") { if (coapReq.MessageType.Value == CoAPMessageType.CON) { CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.NOT_FOUND, coapReq /*Copy all necessary values from request in the response*/); coapServer.Send(resp); } else { //For NON, we can only send back a RST CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.NOT_FOUND, coapReq /*Copy all necessary values from request in the response*/); coapServer.Send(resp); } } else { //Request is GET and path is right if (coapReq.MessageType.Value == CoAPMessageType.CON) { CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.CONTENT, coapReq /*Copy all necessary values from request in the response*/); //Add response payload resp.AddPayload(GetSupportedResourceDescriptions()); //Tell recipient about the content-type of the response resp.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_LINK_FORMAT)); coapServer.Send(resp); } else { //Its a NON, send a NON back...in CoAPSharp, NON is always considered as request CoAPResponse resp = new CoAPResponse(CoAPMessageType.NON, CoAPMessageCode.CONTENT, coapReq.ID.Value); //Copy over other needed values from the reqeust resp.Token = coapReq.Token; resp.RemoteSender = coapReq.RemoteSender; resp.AddPayload(GetSupportedResourceDescriptions()); //Tell recipient about the content-type of the response resp.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_LINK_FORMAT)); //send it coapServer.Send(resp); } } } }