Beispiel #1
0
        private object GetResponse(WebResponse response, Type type)
        {
            if (response == null)
            {
                if (trace != null)
                {
                    trace(this, new TraceEventArgs(TraceTypes.Error, null, "Timeout."));
                }
                throw new Exception("Timeout.");
            }
            int length = 0;
            var d      = response.Headers["Content-Length"];

            if (d != null)
            {
                length = int.Parse(d.ToString());
            }
            try
            {
                if (length != 0 && progress != null)
                {
                    progress(this, 0, length);
                }
                MemoryStream ms     = new MemoryStream(length);
                Stream       stream = response.GetResponseStream();
                byte[]       buffer = new byte[length == 0 || length > 1024 ? 1024 : length];
                IAsyncResult read   = stream.BeginRead(buffer, 0, buffer.Length, null, null);
                while (!CancelOperation)
                {
                    // wait for the read operation to complete
                    read.AsyncWaitHandle.WaitOne();
                    int count = stream.EndRead(read);
                    ms.Write(buffer, 0, count);
                    // If read is done.
                    if (ms.Position == length || count == 0)
                    {
                        break;
                    }
                    if (length != 0 && progress != null)
                    {
                        progress(this, (int)ms.Position, length);
                    }
                    read = stream.BeginRead(buffer, 0, buffer.Length, null, null);
                }
                ms.Position = 0;
                if (trace != null)
                {
                    trace(this, new TraceEventArgs(TraceTypes.Received, ASCIIEncoding.ASCII.GetString(ms.GetBuffer()), response.ResponseUri.ToString()));
                }
                return(Parser.Deserialize(ms, type));
            }
            finally
            {
                if (length != 0 && progress != null)
                {
                    progress(this, (int)0, 0);
                }
            }
        }
Beispiel #2
0
        public void ProcessRequest(HttpContext context)
        {
            InvokeHandler handler;

            if (context.Request.ContentType.Contains("json"))
            {
                switch (context.Request.HttpMethod)
                {
                case "GET":
                    handler = RestMethodInfo.Get;
                    break;

                case "POST":
                    handler = RestMethodInfo.Post;
                    break;

                case "PUT":
                    handler = RestMethodInfo.Put;
                    break;

                case "DELETE":
                    handler = RestMethodInfo.Delete;
                    break;

                default:
                    handler = null;
                    break;
                }
                if (handler == null)
                {
                    throw new HttpException(405, string.Format("Method '{0}' not allowed for {1}", context.Request.HttpMethod, RestMethodInfo.RequestType.Name));
                }
                object req;
                if (context.Request.HttpMethod == "POST")
                {
                    req = Parser.Deserialize(context.Request.InputStream, RestMethodInfo.RequestType);
                }
                else
                {
                    string data = "{" + context.Request.QueryString.ToString() + "}";
                    req = Parser.Deserialize(data, RestMethodInfo.RequestType);
                }
                //Get Rest class from cache.
                GXRestService target = RestMap[RestMethodInfo.RestClassType] as GXRestService;
                if (target == null)
                {
                    target = GXJsonParser.CreateInstance(RestMethodInfo.RestClassType) as GXRestService;
                    RestMap[RestMethodInfo.RestClassType] = target;
                }
                //Update user and DB info.

                //If proxy is used.
                string add = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                if (add == null)
                {
                    add = context.Request.UserHostAddress;
                }
                target.Host = Host;
                target.User = context.User;
                target.Db   = Connection;
                object tmp   = handler(target, req);
                string reply = Parser.Serialize(tmp);
                context.Response.Write(reply);
                context.Response.ContentType = "json";
            }
        }
Beispiel #3
0
        public void Open()
        {
            Close();
            mqttClient = factory.CreateMqttClient();
            if (string.IsNullOrEmpty(userClientId))
            {
                clientId = Guid.NewGuid().ToString();
            }
            else
            {
                clientId = userClientId;
            }
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(serverAddress, port).WithClientId(clientId)
                          .Build();

            mqttClient.UseApplicationMessageReceivedHandler(t =>
            {
                string str          = ASCIIEncoding.ASCII.GetString(t.ApplicationMessage.Payload);
                GXJsonParser parser = new GXJsonParser();
                GXMessage msg       = parser.Deserialize <GXMessage>(str);
                if (msg.id == messageId || (MesssageType)msg.type == MesssageType.Close || (MesssageType)msg.type == MesssageType.Exception)
                {
                    switch ((MesssageType)msg.type)
                    {
                    case MesssageType.Open:
                        m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Open));
                        replyReceivedEvent.Set();
                        break;

                    case MesssageType.Send:
                        break;

                    case MesssageType.Receive:
                        byte[] bytes = Gurux.Common.GXCommon.HexToBytes(msg.frame);
                        replyReceivedEvent.Set();
                        if (bytes.Length != 0)
                        {
                            HandleReceivedData(bytes.Length, bytes, t.ClientId);
                        }
                        break;

                    case MesssageType.Close:
                        m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Closed));
                        replyReceivedEvent.Set();
                        break;

                    case MesssageType.Exception:
                        lastException = msg.exception;
                        replyReceivedEvent.Set();
                        break;
                    }
                }
                else
                {
                    m_OnTrace?.Invoke(this, new TraceEventArgs(TraceTypes.Info, "Unknown reply. " + msg, msg.sender));
                }
            });
            mqttClient.UseConnectedHandler(t =>
            {
                // Subscribe to a topic
                mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(clientId).WithExactlyOnceQoS().Build()).Wait();
                m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Opening));
                GXMessage msg = new GXMessage()
                {
                    id = MessageId, type = (int)MesssageType.Open, sender = clientId
                };
                PublishMessage(msg);
            });
            mqttClient.UseDisconnectedHandler(t =>
            {
                m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Closed));
                replyReceivedEvent.Set();
            });
            try
            {
                replyReceivedEvent.Reset();
                if (AsyncWaitTime == 0)
                {
                    mqttClient.ConnectAsync(options).Wait();
                }
                else
                {
                    mqttClient.ConnectAsync(options).Wait((int)AsyncWaitTime * 1000);
                }
            }
            catch (AggregateException ex)
            {
                if (mqttClient != null)
                {
                    mqttClient.DisconnectAsync().Wait(10000);
                }
                mqttClient = null;
                throw ex.InnerException;
            }
            if (AsyncWaitTime == 0)
            {
                replyReceivedEvent.WaitOne();
            }
            else
            {
                if (!replyReceivedEvent.WaitOne((int)AsyncWaitTime * 1000))
                {
                    throw new TimeoutException("Invalid topic '" + topic + "'.");
                }
            }
            if (lastException != null)
            {
                throw new Exception(lastException);
            }
        }
        /// <summary>
        /// Get showed device profiles.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceDlg_Load(object sender, EventArgs e)
        {
            if (Arguments.OnInitialize != null)
            {
                Arguments.OnInitialize(this, Arguments);
            }
            if (Arguments.DeviceProfiles.Count != 0)
            {
                ShowEarlierVersionsCB.Enabled = DownloadCB.Enabled = CustomCB.Enabled = false;
                if (Arguments.DeviceProfiles.Count == 0)
                {
                    throw new Exception(Gurux.Device.Properties.Resources.NoDevicesPublishedTxt);
                }
            }
            else
            {
                GXDeviceManufacturerCollection.Load(items);
                if (GXDeviceList.DeviceProfiles.Count == 0 && items.Count == 0)
                {
                    throw new Exception(Gurux.Device.Properties.Resources.NoDevicesPublishedTxt);
                }
            }
            if (!string.IsNullOrEmpty(Arguments.Settings))
            {
                try
                {
                    GXJsonParser parser = new GXJsonParser();
                    GXDeviceProfileFormSettings settings = parser.Deserialize<GXDeviceProfileFormSettings>(Arguments.Settings);
                    CustomCB.Checked = settings.Custom;
                    DownloadCB.Checked = settings.Download;
                    SearchTB.Text = settings.SearchText;
                    ShowEarlierVersionsCB.Checked = settings.Earlier;

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    Arguments.Settings = null;
                }
            }
            ShowTemplates();
            if (DeviceProfiles.SelectedItems.Count == 0)
            {
                SearchTB.Select();
            }
        }
Beispiel #5
0
        public static void Start(TraceLevel trace, string server, int port, Connection connection)
        {
            // Create a new MQTT client.
            var mqttClient = factory.CreateMqttClient();
            int pos        = 1;

            foreach (var it in connection.Connections)
            {
                if (it.Type == "Net")
                {
                    it.Target = new GXNet()
                    {
                        Settings = it.Settings
                    };
                }
                else if (it.Type == "Serial")
                {
                    it.Target = new GXSerial()
                    {
                        Settings = it.Settings
                    };
                }
                else
                {
                    throw new Exception("Unknown media type." + it.Type);
                }
                if (string.IsNullOrEmpty(it.Name))
                {
                    it.Name = connection.Name + "/" + pos.ToString();
                    ++pos;
                }
                else
                {
                    it.Name = connection.Name + "/" + it.Name;
                }
                it.Target.OnReceived += (s, e) =>
                {
                    string tmp = GXCommon.ToHex((byte[])e.Data, true);
                    if (trace == TraceLevel.Verbose)
                    {
                        Console.WriteLine("Received: " + tmp);
                    }
                    foreach (var it2 in connection.Connections)
                    {
                        if (it2.Target == s)
                        {
                            GXMessage msg = new GXMessage()
                            {
                                id = it2.Message.id, type = (int)MesssageType.Receive, sender = it2.Name, frame = tmp
                            };
                            GXJsonParser parser  = new GXJsonParser();
                            string       str     = parser.Serialize(msg);
                            var          message = new MqttApplicationMessageBuilder()
                                                   .WithTopic(it2.Message.sender)
                                                   .WithPayload(str)
                                                   .WithExactlyOnceQoS()
                                                   .Build();
                            mqttClient.PublishAsync(message);
                            break;
                        }
                    }
                };
            }
            ShowInformation(connection);

            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(server, port)
                          .WithClientId(connection.Name)
                          .Build();

            mqttClient.UseApplicationMessageReceivedHandler(t =>
            {
                string str          = ASCIIEncoding.ASCII.GetString(t.ApplicationMessage.Payload);
                GXJsonParser parser = new GXJsonParser();
                GXMessage msg       = parser.Deserialize <GXMessage>(str);
                if (trace == TraceLevel.Verbose)
                {
                    Console.WriteLine("---Received message");
                    Console.WriteLine($"+ Topic = {t.ApplicationMessage.Topic}");
                    Console.WriteLine($"+ Payload = {msg.frame}");
                    Console.WriteLine($"+ QoS = {t.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"+ Retain = {t.ApplicationMessage.Retain}");
                }
                GXMessage msg2;
                MqttApplicationMessage message;
                foreach (var it in connection.Connections)
                {
                    if (it.Name == t.ApplicationMessage.Topic)
                    {
                        it.Message = msg;
                        try
                        {
                            switch ((MesssageType)msg.type)
                            {
                            case MesssageType.Open:
                                it.Target.Open();
                                try
                                {
                                    //Move to mode E if optical head is used.
                                    if (it.Target is GXSerial && it.UseOpticalHead)
                                    {
                                        InitializeIEC(trace, it);
                                    }
                                    if (it.Target is IGXMedia2)
                                    {
                                        ((IGXMedia2)it.Target).ReceiveDelay = 500;
                                    }
                                    //Mark EOP so reading is faster.
                                    //   it.Target.Eop = (byte)0x7e;
                                }
                                catch (Exception ex)
                                {
                                    it.Target.Close();
                                    throw ex;
                                }
                                msg2 = new GXMessage()
                                {
                                    id = msg.id, type = (int)MesssageType.Open, sender = it.Name
                                };
                                str     = parser.Serialize(msg2);
                                message = new MqttApplicationMessageBuilder()
                                          .WithTopic(msg.sender)
                                          .WithPayload(str)
                                          .WithExactlyOnceQoS()
                                          .Build();
                                mqttClient.PublishAsync(message);
                                break;

                            case MesssageType.Send:
                                it.Target.Send(GXCommon.HexToBytes(msg.frame), null);
                                break;

                            case MesssageType.Close:
                                it.Target.Close();
                                msg2 = new GXMessage()
                                {
                                    id = msg.id, type = (int)MesssageType.Close, sender = it.Name
                                };
                                str     = parser.Serialize(msg2);
                                message = new MqttApplicationMessageBuilder()
                                          .WithTopic(msg.sender)
                                          .WithPayload(str)
                                          .WithExactlyOnceQoS()
                                          .Build();
                                mqttClient.PublishAsync(message);
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            msg2 = new GXMessage()
                            {
                                id = msg.id, type = (int)MesssageType.Exception, sender = it.Name, exception = ex.Message
                            };
                            str     = parser.Serialize(msg2);
                            message = new MqttApplicationMessageBuilder()
                                      .WithTopic(msg.sender)
                                      .WithPayload(str)
                                      .WithExactlyOnceQoS()
                                      .Build();
                            mqttClient.PublishAsync(message);
                        }
                        break;
                    }
                }
            });
            mqttClient.UseConnectedHandler(t =>
            {
                if (trace > TraceLevel.Warning)
                {
                    Console.WriteLine("--- Connected with the server. " + t.AuthenticateResult.IsSessionPresent);
                }
                // Subscribe to a topic
                List <TopicFilter> topics = new List <TopicFilter>();
                foreach (Media it in connection.Connections)
                {
                    topics.Add(new TopicFilterBuilder().WithTopic(it.Name).Build());
                }
                mqttClient.SubscribeAsync(topics.ToArray());
                if (trace > TraceLevel.Warning)
                {
                    Console.WriteLine("--- Subscribed. ");
                }
            });
            mqttClient.UseDisconnectedHandler(t =>
            {
                Console.WriteLine("--- Disconnected from the server. " + t.Exception);
                //Try to re-connect.
                while (true)
                {
                    try
                    {
                        foreach (var it in connection.Connections)
                        {
                            it.Target.Close();
                        }
                        Console.WriteLine("--- Try to reconnect to the server.");
                        mqttClient.ConnectAsync(options).Wait(10000);
                        Console.WriteLine("--- Connected with the server. ");
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("--- Failed to reconnect to the server. " + ex.Message);
                    }
                }
            });
            mqttClient.ConnectAsync(options).Wait();
        }