private static object CoapSetDigitalOutputsTxt(CoapRequest Request, object DecodedPayload)
        {
            string s = DecodedPayload as string;
            byte   Values;

            if (s == null && DecodedPayload is byte[])
            {
                s = System.Text.Encoding.UTF8.GetString((byte[])DecodedPayload);
            }

            if (s == null || !byte.TryParse(s, out Values))
            {
                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
            }

            int  i;
            bool b;

            for (i = 0; i < 8; i++)
            {
                b = (Values & 1) != 0;
                digitalOutputs [i].Value = b;
                state.SetDO(i + 1, b);
                Values >>= 1;
            }

            state.UpdateIfModified();

            return(CoapResponseCode.Success_Changed);
        }
Пример #2
0
        public byte[] Serialize(CoapRequest request)
        {
            using (var output = new MemoryStream())
            {
                using (var writer = new EndianBinaryWriter(EndianBitConverter.Big, output))
                {
                    var version     = (request.ProtocolVersion & 0x3) << 30;
                    var type        = ((int)request.MessageType & 0x3) << 28;
                    var tokenLength = (request.Token.Length & 0xF) << 24;
                    var messageCode = ((int)request.Method & 0xFF) << 16;
                    var messageId   = request.Id & 0xFFFF;

                    var header = version | type | tokenLength | messageCode | messageId;

                    writer.Write(header);
                    writer.Write(request.Token);

                    // Options
                    SerializeOptions(writer, request.Options);

                    // Payload
                    if (request.Payload?.Length > 0)
                    {
                        writer.Write(Convert.ToByte(0xFF));
                        writer.Write(request.Payload);
                    }
                }

                return(output.ToArray());
            }
        }
        private static object CoapSetAlarmOutputTxt(CoapRequest Request, object DecodedPayload)
        {
            string s = Request.PayloadDecoded as string;
            bool   b;

            if (s == null && Request.PayloadDecoded is byte[])
            {
                s = System.Text.Encoding.UTF8.GetString(Request.Payload);
            }

            if (s == null || !XmlUtilities.TryParseBoolean(s, out b))
            {
                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
            }

            if (b)
            {
                AlarmOn();
                state.Alarm = true;
            }
            else
            {
                AlarmOff();
                state.Alarm = false;
            }

            state.UpdateIfModified();

            return(CoapResponseCode.Success_Changed);
        }
Пример #4
0
        public async Task UnobserveAsync(string resourceUriString)
        {
            if (!channel.IsConnected)
            {
                await ConnectAsync();
            }

            session.UpdateKeepAliveTimestamp();

            if (observers.ContainsKey(resourceUriString))
            {
                string tokenString   = observers[resourceUriString];
                byte[] token         = Convert.FromBase64String(tokenString);
                ushort id            = session.CoapSender.NewId(token, false);
                string scheme        = channel.IsEncrypted ? "coaps" : "coap";
                string coapUriString = GetCoapUriString(scheme, resourceUriString);

                CoapRequest request = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.GET,
                                                      new Uri(coapUriString), null)
                {
                    Observe = false
                };
                await channel.SendAsync(request.Encode());

                session.CoapSender.Unobserve(Convert.FromBase64String(tokenString));
            }
        }
Пример #5
0
        public void SendMessage(NAE.Data.Telemetry message)
        {
            string jsonString = JsonConvert.SerializeObject(message);

            byte[] payload = Encoding.UTF8.GetBytes(jsonString);

            if (messageId == ushort.MaxValue || messageId == 0)
            {
                messageId = 1;
            }

            string      resource   = "http://pegasusnae.org/telemetry";
            Uri         requestUri = new Uri(String.Format("coaps://{0}/publish?topic={1}", CoapAuthority, resource));
            CoapRequest request    = new CoapRequest(messageId++, RequestMessageType.NonConfirmable, MethodType.POST, requestUri, MediaType.Json, payload);

            byte[] coap = request.Encode();

            try
            {
                Task task = client.SendAsync(coap);
                Task.WhenAll(task);
                Trace.TraceInformation("Message sent to cloud.");
                Trace.TraceInformation(jsonString);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Web Socket expection.");
                Trace.TraceError(ex.Message);
            }
        }
Пример #6
0
        public async Task SubscribeAsync(Uri uri)
        {
            CoapRequest request = new CoapRequest(messageId++, RequestMessageType.NonConfirmable, MethodType.POST, uri, MediaType.Json);

            byte[] message = request.Encode();
            await client.SendAsync(message);
        }
Пример #7
0
        public async Task PublishAsync(string resourceUriString, string contentType, byte[] payload, bool confirmable,
                                       Action <CodeType, string, byte[]> action)
        {
            if (!channel.IsConnected)
            {
                await ConnectAsync();
            }

            session.UpdateKeepAliveTimestamp();

            byte[] token         = CoapToken.Create().TokenBytes;
            ushort id            = session.CoapSender.NewId(token, null, action);
            string scheme        = channel.IsEncrypted ? "coaps" : "coap";
            string coapUriString = GetCoapUriString(scheme, resourceUriString);

            RequestMessageType mtype = confirmable ? RequestMessageType.Confirmable : RequestMessageType.NonConfirmable;
            CoapRequest        cr    = new CoapRequest(id, mtype, MethodType.POST, token, new Uri(coapUriString),
                                                       MediaTypeConverter.ConvertToMediaType(contentType), payload);

            queue.Enqueue(cr.Encode());

            while (queue.Count > 0)
            {
                byte[] message = queue.Dequeue();
                Task   t       = channel.SendAsync(message);
                await Task.WhenAll(t);
            }
        }
Пример #8
0
        public static async Task <T> RequestAsync <T>(this ICoapClient client, CoapRequest request, CancellationToken cancellationToken)
        {
            var response = await client.RequestAsync(request, cancellationToken);

            var message = Encoding.UTF8.GetString(response.Payload);

            return(JsonSerializer.Deserialize <T>(message));
        }
        private static object CoapGetJson(CoapRequest Request, object Payload)
        {
            StringBuilder     sb = new StringBuilder();
            ISensorDataExport SensorDataExport = new SensorDataJsonExport(sb);

            ExportSensorData(SensorDataExport, new ReadoutRequest(Request.ToHttpRequest()));

            return(JsonUtilities.Parse(sb.ToString()));
        }
Пример #10
0
        CoapResponse ExecuteCoapRequest(CoapRequest coapRequest, PythonDictionary parameters)
        {
            var clientUid = Convert.ToString(parameters.get("client_uid", null));
            var timeout   = Convert.ToInt32(parameters.get("timeout", 1000));

            if (!string.IsNullOrEmpty(clientUid))
            {
                ICoapClient coapClient;
                lock (_clients)
                {
                    if (!_clients.TryGetValue(clientUid, out coapClient))
                    {
                        coapClient          = CreateClient(parameters).GetAwaiter().GetResult();
                        _clients[clientUid] = coapClient;
                    }
                }

                try
                {
                    using (var cancellationTokenSource = new CancellationTokenSource(timeout))
                    {
                        lock (coapClient)
                        {
                            Console.WriteLine("SENDING COAP REQUEST");
                            return(coapClient.RequestAsync(coapRequest, cancellationTokenSource.Token).GetAwaiter().GetResult());
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("CLOSING EXISTING COAP CLIENT");
                    coapClient.Dispose();

                    lock (_clients)
                    {
                        _clients.Remove(clientUid);
                    }

                    throw;
                }
            }

            CoapResponse coapResponse;

            using (var coapClient = CreateClient(parameters).GetAwaiter().GetResult())
            {
                using (var cancellationTokenSource = new CancellationTokenSource(timeout))
                {
                    Console.WriteLine("SENDING COAP REQUEST");
                    coapResponse = coapClient.RequestAsync(coapRequest, cancellationTokenSource.Token).GetAwaiter().GetResult();
                }

                Console.WriteLine("CLOSING COAP CLIENT");
            }

            return(coapResponse);
        }
Пример #11
0
        public static byte[] ConvertToCoap(CoapSession session, EventMessage message, byte[] observableToken = null)
        {
            CoapMessage coapMessage = null;
            CoapToken   token       = CoapToken.Create();

            ushort id = observableToken == null?session.CoapSender.NewId(token.TokenBytes) : session.CoapSender.NewId(observableToken);

            string uriString = CoapUri.Create(session.Config.Authority, message.ResourceUri, IsEncryptedChannel);

            if (message.Protocol == ProtocolType.MQTT)
            {
                MqttMessage    msg = MqttMessage.DecodeMessage(message.Message);
                PublishMessage pub = msg as PublishMessage;
                MqttUri        uri = new MqttUri(pub.Topic);
                if (observableToken == null)
                {
                    RequestMessageType messageType = msg.QualityOfService == QualityOfServiceLevelType.AtMostOnce ? RequestMessageType.NonConfirmable : RequestMessageType.Confirmable;
                    //request
                    coapMessage = new CoapRequest(id, messageType, MethodType.POST, new Uri(uriString), MediaTypeConverter.ConvertToMediaType(message.ContentType));
                }
                else
                {
                    //response
                    coapMessage = new CoapResponse(id, ResponseMessageType.NonConfirmable, ResponseCodeType.Content, observableToken, MediaTypeConverter.ConvertToMediaType(uri.ContentType), msg.Payload);
                }
            }
            else if (message.Protocol == ProtocolType.COAP)
            {
                CoapMessage msg = CoapMessage.DecodeMessage(message.Message);
                if (observableToken == null)
                {
                    //request
                    coapMessage = new CoapRequest(id, msg.MessageType == CoapMessageType.Confirmable ? RequestMessageType.Confirmable : RequestMessageType.NonConfirmable, MethodType.POST, new Uri(uriString), MediaTypeConverter.ConvertToMediaType(message.ContentType), msg.Payload);
                }
                else
                {
                    //response
                    coapMessage = new CoapResponse(id, ResponseMessageType.NonConfirmable, ResponseCodeType.Content, observableToken, MediaTypeConverter.ConvertToMediaType(message.ContentType), msg.Payload);
                }
            }
            else
            {
                if (observableToken == null)
                {
                    //request
                    coapMessage = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.POST, new Uri(uriString), MediaTypeConverter.ConvertToMediaType(message.ContentType), message.Message);
                }
                else
                {
                    //response
                    coapMessage = new CoapResponse(id, ResponseMessageType.NonConfirmable, ResponseCodeType.Content, observableToken, MediaTypeConverter.ConvertToMediaType(message.ContentType), message.Message);
                }
            }

            return(coapMessage.Encode());
        }
Пример #12
0
        public void Subscribe(Uri uri)
        {
            CoapRequest request = new CoapRequest(messageId++, RequestMessageType.NonConfirmable, MethodType.POST, uri, MediaType.Json);

            byte[] message = request.Encode();
            Task   task    = client.SendAsync(message);

            Task.WaitAny(task);

            Trace.TraceInformation("Subscribed - {0}", uri.ToString());
        }
        private static object CoapGetDigitalOutputTxt(CoapRequest Request, object DecodedPayload)
        {
            int Index;

            if (!GetDigitalOutputIndex(Request, out Index))
            {
                throw new CoapException(CoapResponseCode.ClientError_NotFound);
            }

            return(digitalOutputs [Index - 1].Value ? "1" : "0");
        }
        private static object CoapGetXml(CoapRequest Request, object Payload)
        {
            StringBuilder     sb = new StringBuilder();
            ISensorDataExport SensorDataExport = new SensorDataXmlExport(sb, false, true);

            ExportSensorData(SensorDataExport, new ReadoutRequest(Request.ToHttpRequest()));

            XmlDocument Xml = new XmlDocument();

            Xml.LoadXml(sb.ToString());
            return(Xml);
        }
Пример #15
0
        private async Task RunViaWebSocket()
        {
            if (!this.ws.IsConnected)
            {
                Thread.Sleep(5000);
            }

            int    index       = 0;
            ushort id          = 0;
            double gpsLatStart = 0;
            double gpsLonStart = 0;

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(Properties.Resources.RT_Telemetry_Test2)))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        id++;
                        string line = await reader.ReadLineAsync();

                        NAE.Data.Telemetry t = NAE.Data.Telemetry.Load(line);

                        if (gpsLatStart == 0)
                        {
                            gpsLatStart = t.GpsLatitude;
                            gpsLonStart = t.GpsLongitude;
                        }

                        t.GpsLatitudeStart  = gpsLatStart;
                        t.GpsLongitudeStart = gpsLonStart;
                        t.RunId             = this.runId;

                        string      jsonString    = JsonConvert.SerializeObject(t);
                        string      coapUriString = String.Format("coaps://pegasusmission.io/publish?topic={0}", telemetryUriString);
                        CoapRequest request       = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.POST,
                                                                    new Uri(coapUriString), MediaType.Json, Encoding.UTF8.GetBytes(jsonString));

                        byte[] message = request.Encode();
                        await ws.SendAsync(message);

                        index++;
                        Console.WriteLine("Sending message {0}  sleeping 500ms AirSpeed {1}", index, t.GpsSpeedMph);
                        Thread.Sleep(500);
                    }
                }
            }
        }
        private static object CoapGetDigitalOutputsTxt(CoapRequest Request, object DecodedPayload)
        {
            int  i;
            byte b = 0;

            for (i = 7; i >= 0; i--)
            {
                b <<= 1;
                if (digitalOutputs [i].Value)
                {
                    b |= 1;
                }
            }

            return(b.ToString());
        }
        private static object CoapGetTurtle(CoapRequest Request, object Payload)
        {
            try
            {
                StringBuilder     sb               = new StringBuilder();
                HttpServerRequest HttpRequest      = Request.ToHttpRequest();
                ISensorDataExport SensorDataExport = new SensorDataTurtleExport(sb, HttpRequest);
                ExportSensorData(SensorDataExport, new ReadoutRequest(HttpRequest));

                return(sb.ToString());
            } catch (Exception ex)
            {
                Log.Exception(ex);
                return(ex.Message);
            }
        }
Пример #18
0
        public async Task UnsubscribeAsync(string resourceUriString, bool confirmable, Action <CodeType, string, byte[]> action)
        {
            if (!channel.IsConnected)
            {
                await ConnectAsync();
            }

            session.UpdateKeepAliveTimestamp();

            byte[]             token         = CoapToken.Create().TokenBytes;
            ushort             id            = session.CoapSender.NewId(token, null, action);
            string             scheme        = channel.IsEncrypted ? "coaps" : "coap";
            string             coapUriString = GetCoapUriString(scheme, config.Authority, resourceUriString);
            RequestMessageType mtype         = confirmable ? RequestMessageType.Confirmable : RequestMessageType.NonConfirmable;
            CoapRequest        cr            = new CoapRequest(id, mtype, MethodType.DELETE, token, new Uri(coapUriString), null);
            await channel.SendAsync(cr.Encode());
        }
Пример #19
0
        private void KeepaliveTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (keepaliveTimestamp <= DateTime.UtcNow)
            {
                CoapToken   token = CoapToken.Create();
                ushort      id    = CoapSender.NewId(token.TokenBytes);
                CoapRequest ping  = new CoapRequest
                {
                    MessageId   = id,
                    Token       = token.TokenBytes,
                    Code        = CodeType.EmptyMessage,
                    MessageType = CoapMessageType.Confirmable
                };

                OnKeepAlive?.Invoke(this, new CoapMessageEventArgs(ping));
            }
        }
Пример #20
0
        static async Task MainAsync(string[] args)
        {
            //using (var client = new HttpClient())
            //{
            //    var request = new HttpRequest(HttpMethod.Get)
            //    {
            //        Uri = new Uri("https://www.google.co.nz/")
            //    };

            //    //request.SetHeader("Accept", "*/*");
            //    request.SetHeader("Connection", "close");

            //    Console.WriteLine("My request headers:");
            //    Console.WriteLine(request.BuildRequestHeader());

            //    var response = await client.Send(request);
            //    Console.WriteLine("My response:");
            //    Console.WriteLine(response);
            //}


            // Test CoAP
            var request = new CoapRequest(CoapMethod.Post, CoapMessageType.Confirmable)
            {
                Id      = 23,
                Options = new List <CoapOption>
                {
                    new CoapOption(Option.UriPath, "storage"),
                    new CoapOption(Option.ContentFormat, (int)MediaType.TextPlain)
                },
                Payload = Encoding.UTF8.GetBytes("")
            };


            var data = request.Serialize();

            using (var client = new CoapUdpClient())
            {
                var uri      = new Uri("coap://localhost:5683");
                var response = await client.Send(uri, data);
            }



            Console.ReadLine();
        }
Пример #21
0
        public async Task SubscribeAsync(string resourceUriString, NoResponseType nrt)
        {
            if (!channel.IsConnected)
            {
                await ConnectAsync();
            }

            session.UpdateKeepAliveTimestamp();

            byte[]      token         = CoapToken.Create().TokenBytes;
            ushort      id            = session.CoapSender.NewId(token);
            string      scheme        = channel.IsEncrypted ? "coaps" : "coap";
            string      coapUriString = GetCoapUriString(scheme, config.Authority, resourceUriString);
            CoapRequest cr            = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.PUT, token, new Uri(coapUriString), null);

            cr.NoResponse = nrt;
            await channel.SendAsync(cr.Encode());
        }
        private static object CoapGetRdf(CoapRequest Request, object Payload)
        {
            try
            {
                StringBuilder     sb               = new StringBuilder();
                HttpServerRequest HttpRequest      = Request.ToHttpRequest();
                ISensorDataExport SensorDataExport = new SensorDataRdfExport(sb, HttpRequest);
                ExportSensorData(SensorDataExport, new ReadoutRequest(HttpRequest));

                XmlDocument Xml = new XmlDocument();
                Xml.LoadXml(sb.ToString());
                return(Xml);
            } catch (Exception ex)
            {
                Log.Exception(ex);
                return(ex.Message);
            }
        }
        private static bool GetDigitalOutputIndex(CoapRequest Request, out int Index)
        {
            CoapOptionUriPath Path;

            Index = 0;

            foreach (CoapOption Option in Request.Options)
            {
                if ((Path = Option as CoapOptionUriPath) != null && Path.Value.StartsWith("do"))
                {
                    if (int.TryParse(Path.Value.Substring(2), out Index))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #24
0
        public async Task ObserveAsync(string resourceUriString, Action <CodeType, string, byte[]> action)
        {
            if (!channel.IsConnected)
            {
                await ConnectAsync();
            }

            session.UpdateKeepAliveTimestamp();

            byte[]      token         = CoapToken.Create().TokenBytes;
            ushort      id            = session.CoapSender.NewId(token, true, action);
            string      scheme        = channel.IsEncrypted ? "coaps" : "coap";
            string      coapUriString = GetCoapUriString(scheme, config.Authority, resourceUriString);
            CoapRequest cr            = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.GET, token, new Uri(coapUriString), null);

            cr.Observe = true;
            observers.Add(resourceUriString, Convert.ToBase64String(token));
            byte[] observeRequest = cr.Encode();
            await channel.SendAsync(observeRequest);
        }
Пример #25
0
        public Task PublishAsync(string resourceUriString, string contentType, byte[] payload, NoResponseType nrt)
        {
            if (!channel.IsConnected)
            {
                Open();
                Receive();
            }

            session.UpdateKeepAliveTimestamp();

            byte[] token         = CoapToken.Create().TokenBytes;
            ushort id            = session.CoapSender.NewId(token);
            string scheme        = channel.IsEncrypted ? "coaps" : "coap";
            string coapUriString = GetCoapUriString(scheme, config.Authority, resourceUriString);


            CoapRequest cr = new CoapRequest(id, RequestMessageType.NonConfirmable, MethodType.POST, new Uri(coapUriString), MediaTypeConverter.ConvertToMediaType(contentType), payload);

            cr.NoResponse = nrt;
            return(channel.SendAsync(cr.Encode()));
        }
        private static object CoapSetDigitalOutputTxt(CoapRequest Request, object DecodedPayload)
        {
            int Index;

            if (!GetDigitalOutputIndex(Request, out Index))
            {
                throw new CoapException(CoapResponseCode.ClientError_NotFound);
            }

            string s = Request.PayloadDecoded as string;
            bool   b;

            if (s == null && Request.PayloadDecoded is byte[])
            {
                s = System.Text.Encoding.UTF8.GetString(Request.Payload);
            }

            if (s == null || !XmlUtilities.TryParseBoolean(s, out b))
            {
                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
            }

            if (b)
            {
                digitalOutputs [Index - 1].High();
                state.SetDO(Index, true);
            }
            else
            {
                digitalOutputs [Index - 1].Low();
                state.SetDO(Index, false);
            }

            state.UpdateIfModified();

            return(CoapResponseCode.Success_Changed);
        }
Пример #27
0
        static async Task Main()
        {
            var optionBuilder = new CoapMessageOptionFactory();

            var coapClient = new CoapFactory().CreateClient();

            Console.WriteLine("CONNECTING...");

            var request = new CoapRequest
            {
                Method = CoapRequestMethod.Get,
                Uri    = "15001"
            };

            await coapClient.ConnectAsync(new CoapClientConnectOptions
            {
                Host           = "192.168.1.228",
                Port           = 5684,
                TransportLayer = new UdpWithDtlsCoapTransportLayer()
                {
                    Credentials = new PreSharedKey
                    {
                        Identity = Encoding.ASCII.GetBytes("IDENTITY"),
                        Key      = Encoding.ASCII.GetBytes("lqxbBH6o2eAKSo5A")
                    }
                }
            }, CancellationToken.None);

            var response = await coapClient.Request(request, CancellationToken.None);

            Console.WriteLine("DATA RECEIVED");

            Console.WriteLine("Code = " + response.StatusCode);
            Console.WriteLine("Payload = " + Encoding.ASCII.GetString(response.Payload.ToArray()));

            Console.ReadLine();
        }
Пример #28
0
		private static object CoapGetXml (CoapRequest Request, object Payload)
		{
			StringBuilder sb = new StringBuilder ();
			ISensorDataExport SensorDataExport = new SensorDataXmlExport (sb, false, true);
			ExportSensorData (SensorDataExport, new ReadoutRequest (Request.ToHttpRequest ()));

			XmlDocument Xml = new XmlDocument ();
			Xml.LoadXml (sb.ToString ());
			return Xml;
		}
Пример #29
0
		private static object CoapSetAlarmOutputTxt (CoapRequest Request, object DecodedPayload)
		{
			string s = Request.PayloadDecoded as string;
			bool b;

			if (s == null && Request.PayloadDecoded is byte[])
				s = System.Text.Encoding.UTF8.GetString (Request.Payload);

			if (s == null || !XmlUtilities.TryParseBoolean (s, out b))
				throw new CoapException (CoapResponseCode.ClientError_BadRequest);

			if (b)
			{
				AlarmOn ();
				state.Alarm = true;
			} else
			{
				AlarmOff ();
				state.Alarm = false;
			}

			state.UpdateIfModified ();

			return CoapResponseCode.Success_Changed;
		}
Пример #30
0
		private static object CoapGetAlarmOutputTxt (CoapRequest Request, object DecodedPayload)
		{
			return alarmThread != null ? "1" : "0";
		}
Пример #31
0
		private static object CoapSetDigitalOutputsTxt (CoapRequest Request, object DecodedPayload)
		{
			string s = DecodedPayload as string;
			byte Values;

			if (s == null && DecodedPayload is byte[])
				s = System.Text.Encoding.UTF8.GetString ((byte[])DecodedPayload);

			if (s == null || !byte.TryParse (s, out Values))
				throw new CoapException (CoapResponseCode.ClientError_BadRequest);

			int i;
			bool b;

			for (i = 0; i < 8; i++)
			{
				b = (Values & 1) != 0;
				digitalOutputs [i].Value = b;
				state.SetDO (i + 1, b);
				Values >>= 1;
			}

			state.UpdateIfModified ();

			return CoapResponseCode.Success_Changed;
		}
Пример #32
0
		private static object CoapGetDigitalOutputsTxt (CoapRequest Request, object DecodedPayload)
		{
			int i;
			byte b = 0;

			for (i = 7; i >= 0; i--)
			{
				b <<= 1;
				if (digitalOutputs [i].Value)
					b |= 1;
			}

			return b.ToString ();
		}
Пример #33
0
		private static object CoapSetDigitalOutputTxt (CoapRequest Request, object DecodedPayload)
		{
			int Index;

			if (!GetDigitalOutputIndex (Request, out Index))
				throw new CoapException (CoapResponseCode.ClientError_NotFound);

			string s = Request.PayloadDecoded as string;
			bool b;

			if (s == null && Request.PayloadDecoded is byte[])
				s = System.Text.Encoding.UTF8.GetString (Request.Payload);

			if (s == null || !XmlUtilities.TryParseBoolean (s, out b))
				throw new CoapException (CoapResponseCode.ClientError_BadRequest);

			if (b)
			{
				digitalOutputs [Index - 1].High ();
				state.SetDO (Index, true);
			} else
			{
				digitalOutputs [Index - 1].Low ();
				state.SetDO (Index, false);
			}

			state.UpdateIfModified ();

			return CoapResponseCode.Success_Changed;
		}
Пример #34
0
		private static bool GetDigitalOutputIndex (CoapRequest Request, out int Index)
		{
			CoapOptionUriPath Path;

			Index = 0;

			foreach (CoapOption Option in Request.Options)
			{
				if ((Path = Option as CoapOptionUriPath) != null && Path.Value.StartsWith ("do"))
				{
					if (int.TryParse (Path.Value.Substring (2), out Index))
						return true;
				}
			}

			return false;
		}
Пример #35
0
		private static object CoapGetDigitalOutputTxt (CoapRequest Request, object DecodedPayload)
		{
			int Index;

			if (!GetDigitalOutputIndex (Request, out Index))
				throw new CoapException (CoapResponseCode.ClientError_NotFound);

			return digitalOutputs [Index - 1].Value ? "1" : "0";
		}
Пример #36
0
		private static object CoapGetRdf (CoapRequest Request, object Payload)
		{
			try
			{
				StringBuilder sb = new StringBuilder ();
				HttpServerRequest HttpRequest = Request.ToHttpRequest ();
				ISensorDataExport SensorDataExport = new SensorDataRdfExport (sb, HttpRequest);
				ExportSensorData (SensorDataExport, new ReadoutRequest (HttpRequest));

				XmlDocument Xml = new XmlDocument ();
				Xml.LoadXml (sb.ToString ());
				return Xml;
			} catch (Exception ex)
			{
				Log.Exception (ex);
				return ex.Message;
			}
		}
Пример #37
0
		private static object CoapGetTurtle (CoapRequest Request, object Payload)
		{
			StringBuilder sb = new StringBuilder ();
			HttpServerRequest HttpRequest = Request.ToHttpRequest ();
			ISensorDataExport SensorDataExport = new SensorDataTurtleExport (sb, HttpRequest);
			ExportSensorData (SensorDataExport, new ReadoutRequest (HttpRequest));

			return sb.ToString ();
		}
Пример #38
0
        public void Connect()
        {
            if (client != null && client.IsConnected)
            {
                return;
            }

            if (client == null)
            {
                client = new WebSocketClient();
            }

            if (client.IsConnected)
            {
                Task closeTask = client.CloseAsync();
                Task.WaitAny(closeTask);

                if (OnStatusChange != null)
                {
                    OnStatusChange(this, "Closed");
                }

                client = null;
            }

            if (OnStatusChange != null)
            {
                OnStatusChange(this, "Connecting");
            }

            client = new WebSocketClient();

            client.OnClose   += client_OnClose;
            client.OnError   += client_OnError;
            client.OnOpen    += client_OnOpen;
            client.OnMessage += client_OnMessage;

            Task task = Task.Factory.StartNew(async() =>
            {
                await client.ConnectAsync(host, subprotocol, token);
            });

            Task.WhenAll(task);

            while (!client.IsConnected)
            {
                Thread.Sleep(100);
            }


            if (OnStatusChange != null)
            {
                OnStatusChange(this, "Connected");
            }

            foreach (Uri uri in subscriptions)
            {
                CoapRequest request = new CoapRequest(messageId++, RequestMessageType.NonConfirmable, MethodType.POST, uri, MediaType.Json);
                client.Send(request.Encode());
                //Task subTask = client.SendAsync(request.Encode());
                //Task.WaitAll(subTask);
            }
        }
 private static object CoapGetAlarmOutputTxt(CoapRequest Request, object DecodedPayload)
 {
     return(alarmThread != null ? "1" : "0");
 }
Пример #40
0
		private static object CoapGetJson (CoapRequest Request, object Payload)
		{
			StringBuilder sb = new StringBuilder ();
			ISensorDataExport SensorDataExport = new SensorDataJsonExport (sb);
			ExportSensorData (SensorDataExport, new ReadoutRequest (Request.ToHttpRequest ()));

			return JsonUtilities.Parse (sb.ToString ());
		}
Пример #41
0
		private static object CoapGetTurtle (CoapRequest Request, object Payload)
		{
			try
			{
				StringBuilder sb = new StringBuilder ();
				HttpServerRequest HttpRequest = Request.ToHttpRequest ();
				ISensorDataExport SensorDataExport = new SensorDataTurtleExport (sb, HttpRequest);
				ExportSensorData (SensorDataExport, new ReadoutRequest (HttpRequest));

				return sb.ToString ();
			} catch (Exception ex)
			{
				Log.Exception (ex);
				return ex.Message;
			}
		}
        public override object GET(CoapRequest Request, object DecodedPayload)
        {
            CoapOptionUriPath[] Path = Request.SubPath;
            int  c = Path.Length;
            Node Node;

            if (c == 0)
            {
                Node = Topology.Root;
                if (!Node.IsVisible(this.user))
                {
                    Node = null;
                }
            }
            else
            {
                Node = Topology.GetNode(HttpUtilities.UrlDecode(Path[c - 1].Value), false, this.user);
            }

            if (Node == null)
            {
                throw new CoapException(CoapResponseCode.ClientError_NotFound);
            }

            if (!Node.IsReadable)
            {
                return(string.Empty);
            }

            ReadoutType        Types = (ReadoutType)0;
            DateTime           From  = DateTime.MinValue;
            DateTime           To    = DateTime.MaxValue;
            CoapOptionUriQuery Parameter;
            DateTime           TP;
            string             s, Name, Value;
            int  i;
            bool b;

            foreach (CoapOption Option in Request.Options)
            {
                if ((Parameter = Option as CoapOptionUriQuery) != null)
                {
                    s = Parameter.Value;
                    i = s.IndexOf('=');
                    if (i < 0)
                    {
                        continue;
                    }

                    Name  = s.Substring(0, i);
                    Value = s.Substring(i + 1);
                    switch (Name.ToLower())
                    {
                    case "all":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.All;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historical":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValues;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "momentary":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.MomentaryValues;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "peak":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.PeakValues;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "status":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.StatusValues;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "computed":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.Computed;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "identity":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.Identity;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalSecond":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesSecond;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalMinute":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesMinute;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalHour":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesHour;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalDay":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesDay;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalWeek":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesWeek;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalMonth":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesMonth;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalQuarter":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesQuarter;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalYear":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesYear;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "historicalOther":
                        if (XmlUtilities.TryParseBoolean(Value, out b))
                        {
                            if (b)
                            {
                                Types |= ReadoutType.HistoricalValuesOther;
                            }
                            else
                            {
                                throw new CoapException(CoapResponseCode.ClientError_BadRequest);
                            }
                        }
                        break;

                    case "from":
                        if (XmlUtilities.TryParseDateTimeXml(Value, out TP))
                        {
                            From = TP;
                        }
                        break;

                    case "to":
                        if (XmlUtilities.TryParseDateTimeXml(Value, out TP))
                        {
                            To = TP;
                        }
                        break;
                    }
                }
            }

            if ((int)Types == 0)
            {
                Types = ReadoutType.All;
            }

            try
            {
                Field[]     Fields = Node.SynchronousReadout(Types, From, To, 10000);
                FieldResult Result = new FieldResult(Node, true, null, Fields);
                string      Xml    = Result.ExportXmppXep0323XmlString(0);

                XmlDocument Doc = new XmlDocument();
                Doc.LoadXml(Xml);

                return(Doc);
            }
            catch (Exception)
            {
                throw new CoapException(CoapResponseCode.ServerError_ServiceUnavailable);
            }
        }