/// <summary> /// Notify listeners of the new temperature /// </summary> /// <param name="temp">The temperature</param> static private void NotifyListeners(int temp) { ArrayList resObservers = coapServer.ObserversList.GetResourceObservers(OBSERVED_RESOURCE_URI); if (resObservers == null || resObservers.Count == 0) { return; } //The next observe sequence number UInt16 obsSeq = (UInt16)Convert.ToInt16(DateTime.Today.ToString("mmss"));//Will get accomodated in 24-bits limit and will give good sequence foreach (CoAPRequest obsReq in resObservers) { UInt16 mId = coapServer.GetNextMessageID(); CoAPRequest notifyReq = new CoAPRequest(CoAPMessageType.CON, CoAPMessageCode.PUT, mId); notifyReq.RemoteSender = obsReq.RemoteSender; notifyReq.Token = obsReq.Token; //Add observe option with sequence number notifyReq.AddOption(CoAPHeaderOption.OBSERVE, AbstractByteUtils.GetBytes(obsSeq)); //The payload will be JSON Hashtable ht = new Hashtable(); ht.Add("temp", temp); string jsonStr = JSONResult.ToJSON(ht); notifyReq.AddPayload(jsonStr); //Tell recipient about the content-type of the response notifyReq.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_JSON)); //send it coapServer.Send(notifyReq); } }
/// <summary> /// Get the request message that was pending response /// </summary> /// <param name="msgId">The message Id corresponding to the message that needs to be extracted</param> /// <returns>A copy of the request object pending response (if found), else null</returns> public CoAPRequest GetRequestPendingResponse(UInt16 msgId) { this._waitEvent.WaitOne();//Wait for thread to release the queue CoAPRequest foundReq = null; try { int count = 0; for (count = 0; count < this._conMessageQ.Count; count++) { AbstractCoAPMessage coapMsgInQ = (AbstractCoAPMessage)this._conMessageQ[count]; if (coapMsgInQ.ID.Value == msgId) { /*Found*/ foundReq = new CoAPRequest(coapMsgInQ.MessageType.Value, coapMsgInQ.Code.Value, coapMsgInQ.ID.Value); foreach (CoAPHeaderOption option in coapMsgInQ.Options) foundReq.AddOption(option.Number, option.Value); foundReq.Token = coapMsgInQ.Token; foundReq.Payload = coapMsgInQ.Payload; foundReq.RemoteSender = coapMsgInQ.RemoteSender; break; } } } catch (Exception e) { AbstractLogUtil.GetLogger().LogError(e.ToString()); ; ;//TOCHECK::nothing for now } finally { this._waitEvent.Set();//Now allow others to work on the queue } return foundReq; }
/// <summary> /// Perform a session request (acquire or terminate). /// </summary> /// <param name="messageCode">CoAPMessageCode.POST for establishing a session or oAPMessageCode.DELETE for terminating a session</param> /// <returns>a boolean indicating success or failure of the request</returns> private bool SessionCall(byte messageCode) { __TimedOut = true; __SessionRequestSucceeded = false; string token = GatewaySettings.Instance.SfdpToken; //api.coap-test.developer.ssni.com string serverIP = AbstractNetworkUtils.GetIPAddressFromHostname(GatewaySettings.Instance.GatewayURI).ToString(); __coapClient.Initialize(GatewaySettings.Instance.GatewayURI, __ServerPort); __coapClient.AckTimeout = __Timeout; __coapClient.CoAPResponseReceived += new CoAPResponseReceivedHandler(OnCoAPSessionResponseReceived); __coapClient.CoAPError += new CoAPErrorHandler(OnCoAPError); coapReq = new CoAPRequest(this.ConfirmableMessageType, messageCode, HdkUtils.MessageId()); string uriToCall = "coap://" + GatewaySettings.Instance.GatewayURI + ":" + __ServerPort + "/sessions?security=none";//?token=" //+ GatewaySettings.Instance.SfdpToken; //+ "&security=none"; coapReq.SetURL(uriToCall); byte[] zero = { 0x00 }; coapReq.AddOption(CoAPHeaderOption.CONTENT_FORMAT, zero); if (messageCode != CoAPMessageCode.DELETE) { coapReq.Payload = new CoAPPayload(GatewaySettings.Instance.SfdpToken); } SetToken(); coapReq.Options.RemoveOption(CoAPHeaderOption.URI_QUERY); // JJK - Change in v2.0.7 FileLogger.Write("About to send session request"); try { FileLogger.Write(coapReq.ToString()); } catch (Exception flErr) { FileLogger.Write(flErr.Message); } __coapClient.Send(coapReq); __Done.WaitOne(GatewaySettings.Instance.RequestTimeout); __Done.Reset(); if (__TimedOut) { this.ErrorResult = "Request timed out"; FileLogger.Write(this.ErrorResult); } __coapClient.CoAPResponseReceived -= new CoAPResponseReceivedHandler(OnCoAPSessionResponseReceived); return(__SessionRequestSucceeded); }
/// <summary> /// Send the request to get the temperature /// </summary> public static void SendRequest() { string urlToCall = "coap://localhost:5683/sensors/temp/observe"; UInt16 mId = coapClient.GetNextMessageID();//Using this method to get the next message id takes care of pending CON requests CoAPRequest tempReq = new CoAPRequest(CoAPMessageType.CON, CoAPMessageCode.GET, mId); tempReq.SetURL(urlToCall); //Important::Add the Observe option tempReq.AddOption(CoAPHeaderOption.OBSERVE, null); //Value of observe option has no meaning in request tempReq.AddTokenValue(DateTime.Today.ToString("HHmmss")); //must be <= 8 bytes /*Uncomment the two lines below to use non-default values for timeout and retransmission count*/ /*Dafault value for timeout is 2 secs and retransmission count is 4*/ //tempReq.Timeout = 10; //tempReq.RetransmissionCount = 5; coapClient.Send(tempReq); }