Пример #1
0
        public RouterUI()
        {
            InitializeComponent();
            serial = new SerialPortWrapper();
            robot  = new Robot.Robot(serial);
            hw     = robot as IHardware;
            router = new Router.Router(hw);
            hw.onPositionUpdate += new EventHandler(PosUpdate);

            // Setup for doing our own form painting
            //this.SetStyle(
            //  ControlStyles.AllPaintingInWmPaint |
            //  ControlStyles.UserPaint |
            //  ControlStyles.DoubleBuffer, true);
            t          = new Timer();
            t.Interval = 25;
            t.Tick    += new EventHandler(t_Tick);
            t.Enabled  = false;
            //t.Start();

            this.propertyGrid.SelectedGridItemChanged += new SelectedGridItemChangedEventHandler(propertyGrid_SelectedGridItemChanged);

            userControl11.SelectedItemChanged += new EventHandler(userControl11_SelectedItemChanged);
            userControl11.AddObject(router);
            //g1 = new InvoluteGear();
            //g2 = new InvoluteGear();
            //userControl11.AddObject(g1);
            //g2.X = 122.5493f * 2;
            //g2.Rotation = 180.0f / 11.0f + 0.425f;
            //userControl11.AddObject(g2);
        }
Пример #2
0
 internal void AddObject(Object o)
 {
     if (o != null)
     {
         objects.Add(o);
         if (o is Router.Router)
         {
             router = o as Router.Router;
         }
     }
 }
Пример #3
0
 public void SetUp()
 {
     _router = new Router();
     _router.Start();
 }
Пример #4
0
        private static async void StartKestralAsync() {

            routers = new Dictionary<string, IRouter>();
            pushClients = new List<WebSocket>();

            Random random = new Random();

            void newRouter(int desiredCnt) {
                Console.WriteLine($"creating {desiredCnt - routers.Count} new routers to {pushClients.Count} stored clients");

                if (desiredCnt > routers.Count) {
                    for (int i = routers.Count ; i < desiredCnt; i++) {

                        var router_key = Guid.NewGuid().ToString();

                        var random_town  = UKLocations.UK_Towns[ random.Next(0, UKLocations.UK_Towns.Length)];
                        var random_lat =  Convert.ToDouble(random_town[1]) + Convert.ToDouble(random.Next(-100, 100)/1000.0);
                        var random_long =  Convert.ToDouble(random_town[2]) + Convert.ToDouble(random.Next(-100, 100)/1000.0);
                        var router_val = new {id = router_key, address = random_town[0], latlong = new double[]{  random_lat, random_long}};
                    
                        IRouter r = new Router.Router();
                        r.InitRouterAsync (10000, router_key, random_town[0].ToString(), random_lat, random_long, "connected", CancellationToken.None);
                    
                        routers.Add(router_key, r);

                        pushClients.ForEach(async (WebSocket ws) =>  {
                            try {
                                if (ws.State == WebSocketState.Open) {
                                    Console.WriteLine ("Sending...");
                                    var rprops = await r.GetProps( CancellationToken.None);
                                    var encoded = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new{type = "router", value = new []{new {id = rprops.Item1, address = rprops.Item2, latlong = new double[]{  rprops.Item3, rprops.Item4}}}}));
                                    await ws.SendAsync(new ArraySegment<Byte>(encoded, 0, encoded.Length), WebSocketMessageType.Text, true, CancellationToken.None);
                                }
                            } catch (Exception e) {
                                Console.WriteLine($"Caught Error {e}");
                            }
                        });
                    }
                } else {
                    for (int i = routers.Count ; i < desiredCnt; i++) {
                }
            }

            async Task listenForMessages (WebSocket ws) {
                var buffer = new byte[1024 * 4];

                Console.WriteLine ($"Keep Socket open, keep a receiver on it. (ws.State = {ws.State}) (to close, send {CancellationToken.None}");

                // send  current routers
                if (routers.Count > 0) {

                    foreach (IRouter r in routers.Values) {

                    }
                    var encoded = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new{type = "router", value = routers.Values.Select(r => {
                        var rprops = r.GetProps(CancellationToken.None).Result;
                        return new {id = rprops.Item1, address = rprops.Item2, latlong = new double[]{  rprops.Item3, rprops.Item4}};
                    }).ToArray()}));
                     await ws.SendAsync(new ArraySegment<Byte>(encoded, 0, encoded.Length), WebSocketMessageType.Text, true, CancellationToken.None);
                }
                // keep socket open
                while (ws.State == WebSocketState.Open)
                {
                    WebSocketReceiveResult result = null;
                    try {  
                        result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                        if (!result.CloseStatus.HasValue) {
                            Console.WriteLine ($"got message, handle it, then listen for another one {new ArraySegment<byte>(buffer, 0, result.Count)}, type:  {result.MessageType}" );
                        } else {
                            await ws.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
                        }
                    } catch (Exception e) {
                        //Console.WriteLine($"Caught Error");
                    }
                }
                Console.WriteLine ("Socket has been closed");
            }

            Console.WriteLine ($"PATH: {Path.Combine(Directory.GetCurrentDirectory(), "public")}");

            Action<IApplicationBuilder> appPipeline = (app) => {

/*
                var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
                applicationLifetime.ApplicationStopping.Register(() => {
                    Console.WriteLine ("Gracfully shutting down Sockets");
                    pushClients.ForEach(async (WebSocket ws) =>  {
                        Console.WriteLine($"Open");
                    });
                });
*/
                app.UseDefaultFiles();
                app.UseStaticFiles();
                app.UseWebSockets(); // build in middleware 

                app.Map("/setActors", (app1) => {
                    app1.Run(async context => {

                        if (context.Request.Method == "POST") {
                            using (StreamReader inputStream = new StreamReader(context.Request.Body))
                            {
                                var payload = inputStream.ReadToEnd();
                                var body = JsonConvert.DeserializeObject<Dictionary<string, string>>(payload);
                                var cnt = Int32.Parse(body["number"]);

                                newRouter(cnt);
                                // await context.Response.WriteAsync(JsonConvert.SerializeObject(new{host = Dns.GetHostName(), os = RuntimeInformation.OSDescription}));
                            }
                        } else {
                            context.Response.StatusCode = 400;
                            //var paths = context.Request.Path.Value.Split('/');
                            //if (paths.Length < 2  || String.IsNullOrEmpty(paths[1])) {
                        }
                    });
                });

                app.Map("/getActor", (app1) => {
                    app1.Run(async context => {

                        if (context.Request.Method == "GET") {
                            var id = context.Request.Query["id"].First();
                            var rprops = await routers[id].GetProps(CancellationToken.None);
                            byte[] data = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new {id = rprops.Item1, address = rprops.Item2, latlong = new double[]{  rprops.Item3, rprops.Item4}}));
                            context.Response.ContentType = "application/json";
                            await context.Response.Body.WriteAsync(data, 0, data.Length);

                        } else {
                            context.Response.StatusCode = 400;
                            //var paths = context.Request.Path.Value.Split('/');
                            //if (paths.Length < 2  || String.IsNullOrEmpty(paths[1])) {
                        }
                    });
                });


                app.Map("/test", (app1) => {
                    app1.Run(async context => {

                        var paths = context.Request.Path.Value.Split('/');
                        if (paths.Length < 2  || String.IsNullOrEmpty(paths[1])) {
                            await context.Response.WriteAsync(JsonConvert.SerializeObject(new{host = Dns.GetHostName(), os = RuntimeInformation.OSDescription}));
                        } else {
                            context.Response.StatusCode = 400;
                        }

                    });
                });

                app.Map("/ws", (app1) => {
                    app1.Run(async context => {
                        if (context.WebSockets.IsWebSocketRequest) {
                            Console.WriteLine ("New Websocket connection from client, lets accept");
                            WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                            pushClients.Add(webSocket);
                            await listenForMessages(webSocket); // await to keep the socket open!
                            
                        }
                        else {
                            Console.WriteLine ("New Websocket connection - sending 400");
                            context.Response.StatusCode = 400;
                        }
                    });
                });
            };

            var host = new WebHostBuilder()
                .UseKestrel()
                .Configure(appPipeline)
                .UseContentRoot(Directory.GetCurrentDirectory())
                //.UseWebRoot(Path.Combine(Directory.GetCurrentDirectory(), "public/"))
                .ConfigureLogging((hostingContext, logging) =>  logging.AddConsole())
                .Build();

            await host.RunAsync();
            Console.WriteLine("any key to terminate"); 
            
            
        }
Пример #5
0
 public void AssignRouter(Router.Router router)
 {
     this.router = router;
     this.robot = new Robot.Robot(serial);
     this.robot.onRobotStatusChange += new EventHandler(RobotStatusUpdate);
 }
Пример #6
0
 internal void AddObject(Object o)
 {
     if (o != null)
     {
         objects.Add(o);
         if (o is Router.Router)
         {
             router = o as Router.Router;
         }
     }
 }
Пример #7
0
 public void AssignRouter(Router.Router router)
 {
     this.router = router;
     this.robot  = new Robot.Robot(serial);
     this.robot.onRobotStatusChange += new EventHandler(RobotStatusUpdate);
 }