Exemple #1
0
        private static void DownloadMapFromUrl(LoadScene sourceCommand, JSONNode args, string name, int?seed, string url)
        {
            //Remove url from args, so download won't be retried
            args.Remove("url");
            var localPath = WebUtilities.GenerateLocalPath("Maps");

            DownloadManager.AddDownloadToQueue(new Uri(url), localPath, null, (success, ex) =>
            {
                if (success)
                {
                    var map = new MapModel()
                    {
                        Name      = name,
                        Url       = url,
                        LocalPath = localPath
                    };

                    using (var db = DatabaseManager.Open())
                    {
                        db.Insert(map);
                    }

                    ApiManager.Instance.StartCoroutine(LoadMapAssets(sourceCommand, map, name, seed));
                }
                else
                {
                    Debug.LogError(
                        $"Vehicle '{name}' is not available. Error occured while downloading from url: {ex}.");
                    ApiManager.Instance.SendError(sourceCommand, $"Vehicle '{name}' is not available");
                    ApiManager.Instance.ActionsSemaphore.Unlock();
                }
            });
        }
Exemple #2
0
        private void DownloadVehicleFromUrl(JSONNode args, string name, string url)
        {
            //Remove url from args, so download won't be retried
            args.Remove("url");
            var localPath = WebUtilities.GenerateLocalPath("Vehicles");

            DownloadManager.AddDownloadToQueue(new System.Uri(url), localPath, null,
                                               (success, ex) =>
            {
                if (success)
                {
                    var vehicleModel = new VehicleModel()
                    {
                        Name       = name,
                        Url        = url,
                        BridgeType = args["bridge_type"],
                        LocalPath  = localPath,
                        Sensors    = null
                    };
                    using (var db = DatabaseManager.Open())
                    {
                        db.Insert(vehicleModel);
                    }
                    Execute(args);
                }
                else
                {
                    Debug.LogError($"Vehicle '{name}' is not available. Error occured while downloading from url: {ex}.");
                    ApiManager.Instance.SendError(this, $"Vehicle '{name}' is not available");
                }
            });
        }
Exemple #3
0
        void RestartPendingDownloads()
        {
            using (var db = DatabaseManager.Open())
            {
                foreach (var map in DatabaseManager.PendingMapDownloads())
                {
                    SIM.LogWeb(SIM.Web.MapDownloadStart, map.Name);
                    Uri uri = new Uri(map.Url);
                    DownloadManager.AddDownloadToQueue(
                        uri,
                        map.LocalPath,
                        progress =>
                    {
                        Debug.Log($"Map Download at {progress}%");
                        NotificationManager.SendNotification("MapDownload", new { map.Id, progress }, map.Owner);
                    },
                        (success, ex) =>
                    {
                        var updatedModel      = db.Single <MapModel>(map.Id);
                        bool passesValidation = false;
                        if (success)
                        {
                            passesValidation = Validation.BeValidAssetBundle(map.LocalPath);
                            if (!passesValidation)
                            {
                                updatedModel.Error = "You must specify a valid AssetBundle";
                            }
                        }

                        updatedModel.Status = passesValidation ? "Valid" : "Invalid";

                        if (ex != null)
                        {
                            updatedModel.Error = ex.Message;
                        }

                        db.Update(updatedModel);
                        NotificationManager.SendNotification("MapDownloadComplete", updatedModel, map.Owner);

                        SIM.LogWeb(SIM.Web.MapDownloadFinish, map.Name);
                    }
                        );
                }

                var added    = new HashSet <Uri>();
                var vehicles = new VehicleService();

                foreach (var vehicle in DatabaseManager.PendingVehicleDownloads())
                {
                    Uri uri = new Uri(vehicle.Url);
                    if (added.Contains(uri))
                    {
                        continue;
                    }
                    added.Add(uri);

                    SIM.LogWeb(SIM.Web.VehicleDownloadStart, vehicle.Name);
                    DownloadManager.AddDownloadToQueue(
                        uri,
                        vehicle.LocalPath,
                        progress =>
                    {
                        Debug.Log($"Vehicle Download at {progress}%");
                        NotificationManager.SendNotification("VehicleDownload", new { vehicle.Id, progress }, vehicle.Owner);
                    },
                        (success, ex) =>
                    {
                        bool passesValidation = success && Validation.BeValidAssetBundle(vehicle.LocalPath);

                        string status = passesValidation ? "Valid" : "Invalid";
                        vehicles.SetStatusForPath(status, vehicle.LocalPath);
                        vehicles.GetAllMatchingUrl(vehicle.Url).ForEach(v =>
                        {
                            if (!passesValidation)
                            {
                                v.Error = "You must specify a valid AssetBundle";
                            }

                            if (ex != null)
                            {
                                v.Error = ex.Message;
                            }

                            NotificationManager.SendNotification("VehicleDownloadComplete", v, v.Owner);
                            SIM.LogWeb(SIM.Web.VehicleDownloadFinish, vehicle.Name);
                        });
                    }
                        );
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Download required for the simulation vehicle bundles from the server
        /// </summary>
        /// <param name="load">Load command from the server</param>
        /// <param name="bundles">Paths where bundles will be saved</param>
        /// <param name="finished">Callback invoked when downloading is completed</param>
        private void DownloadVehicleBundles(Commands.Load load, List <string> bundles, Action finished)
        {
            try
            {
                int count = 0;

                var agents           = load.Agents;
                var agentsToDownload = load.Agents.Length;
                if (agentsToDownload == 0)
                {
                    finished();
                    return;
                }

                for (int i = 0; i < agentsToDownload; i++)
                {
                    //Check if downloading is already being processed, if true this may be a quick rerun of the simulation
                    if (processedDownloads.Contains(agents[i].Name))
                    {
                        Interlocked.Increment(ref count);
                        continue;
                    }
                    VehicleModel vehicleModel;
                    using (var db = DatabaseManager.Open())
                    {
                        var sql = Sql.Builder.Where("name = @0", agents[i].Name);
                        vehicleModel = db.SingleOrDefault <VehicleModel>(sql);
                    }

                    if (vehicleModel == null)
                    {
                        Debug.Log($"Downloading {agents[i].Name} from {agents[i].Url}");

                        vehicleModel = new VehicleModel()
                        {
                            Name       = agents[i].Name,
                            Url        = agents[i].Url,
                            BridgeType = agents[i].Bridge,
                            LocalPath  = WebUtilities.GenerateLocalPath("Vehicles"),
                            Sensors    = agents[i].Sensors,
                        };
                        bundles.Add(vehicleModel.LocalPath);

                        processedDownloads.Add(vehicleModel.Name);
                        DownloadManager.AddDownloadToQueue(new Uri(vehicleModel.Url), vehicleModel.LocalPath, null,
                                                           (success, ex) =>
                        {
                            //Check if downloaded vehicle model is still valid in current load command
                            if (CurrentLoadCommand.Agents.All(loadAgent => loadAgent.Name != vehicleModel.Name))
                            {
                                return;
                            }
                            processedDownloads.Remove(vehicleModel.Name);
                            if (ex != null)
                            {
                                var err = new Commands.LoadResult()
                                {
                                    Success      = false,
                                    ErrorMessage = ex.ToString(),
                                };
                                var errData        = PacketsProcessor.Write(err);
                                var message        = MessagesPool.Instance.GetMessage(errData.Length);
                                message.AddressKey = Key;
                                message.Content.PushBytes(errData);
                                message.Type = DistributedMessageType.ReliableOrdered;
                                UnicastMessage(MasterPeer.PeerEndPoint, message);
                                return;
                            }

                            using (var db = DatabaseManager.Open())
                            {
                                db.Insert(vehicleModel);
                            }

                            if (Interlocked.Increment(ref count) == agentsToDownload)
                            {
                                finished();
                            }
                        }
                                                           );
                    }
                    else
                    {
                        Debug.Log($"Vehicle {agents[i].Name} exists");

                        bundles.Add(vehicleModel.LocalPath);
                        if (Interlocked.Increment(ref count) == agentsToDownload)
                        {
                            finished();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);

                var err = new Commands.LoadResult()
                {
                    Success      = false,
                    ErrorMessage = ex.ToString(),
                };
                var errData = PacketsProcessor.Write(err);
                var message = MessagesPool.Instance.GetMessage(errData.Length);
                message.AddressKey = Key;
                message.Content.PushBytes(errData);
                message.Type = DistributedMessageType.ReliableOrdered;
                UnicastMessage(MasterPeer.PeerEndPoint, message);

                Loader.ResetLoaderScene();
            }
        }
Exemple #5
0
        /// <summary>
        /// Method invoked when manager receives load command
        /// </summary>
        /// <param name="load">Received load command</param>
        private void OnLoadCommand(Commands.Load load)
        {
            Debug.Assert(State == SimulationState.Connected);
            CurrentLoadCommand = load;
            State = SimulationState.Loading;

            Debug.Log("Preparing simulation");

            try
            {
                //Check if downloading is already being processed, if true this may be a quick rerun of the simulation
                if (processedDownloads.Contains(load.MapUrl))
                {
                    return;
                }
                MapModel map;
                using (var db = DatabaseManager.Open())
                {
                    var sql = Sql.Builder.Where("name = @0", load.MapName);
                    map = db.SingleOrDefault <MapModel>(sql);
                }

                if (map == null)
                {
                    Debug.Log($"Downloading {load.MapName} from {load.MapUrl}");

                    map = new MapModel()
                    {
                        Name      = load.MapName,
                        Url       = load.MapUrl,
                        LocalPath = WebUtilities.GenerateLocalPath("Maps"),
                    };

                    using (var db = DatabaseManager.Open())
                    {
                        db.Insert(map);
                    }

                    processedDownloads.Add(map.Name);
                    DownloadManager.AddDownloadToQueue(new Uri(map.Url), map.LocalPath, null, (success, ex) =>
                    {
                        processedDownloads.Remove(map.Name);
                        //Check if downloaded map is still valid in current load command
                        if (CurrentLoadCommand.MapName != map.Name)
                        {
                            return;
                        }
                        if (ex != null)
                        {
                            map.Error = ex.Message;
                            using (var db = DatabaseManager.Open())
                            {
                                db.Update(map);
                            }

                            Debug.LogException(ex);
                        }

                        if (success)
                        {
                            LoadMapBundle(load, map.LocalPath);
                        }
                        else
                        {
                            var err = new Commands.LoadResult()
                            {
                                Success      = false,
                                ErrorMessage = ex.ToString(),
                            };
                            var errData        = PacketsProcessor.Write(err);
                            var message        = MessagesPool.Instance.GetMessage(errData.Length);
                            message.AddressKey = Key;
                            message.Content.PushBytes(errData);
                            message.Type = DistributedMessageType.ReliableOrdered;
                            UnicastMessage(MasterPeer.PeerEndPoint, message);
                        }
                    });
                }
                else
                {
                    Debug.Log($"Map {load.MapName} exists");
                    LoadMapBundle(load, map.LocalPath);
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);

                var err = new Commands.LoadResult()
                {
                    Success      = false,
                    ErrorMessage = ex.ToString(),
                };
                var errData = PacketsProcessor.Write(err);
                var message = MessagesPool.Instance.GetMessage(errData.Length);
                message.AddressKey = Key;
                message.Content.PushBytes(errData);
                message.Type = DistributedMessageType.ReliableOrdered;
                UnicastMessage(MasterPeer.PeerEndPoint, message);

                Loader.ResetLoaderScene();
            }
        }
Exemple #6
0
        void RestartPendingDownloads()
        {
            using (var db = DatabaseManager.Open())
            {
                foreach (var map in DatabaseManager.PendingMapDownloads())
                {
                    SIM.LogWeb(SIM.Web.MapDownloadStart, map.Name);
                    Uri uri = new Uri(map.Url);
                    DownloadManager.AddDownloadToQueue(
                        uri,
                        map.LocalPath,
                        progress =>
                    {
                        Debug.Log($"Map Download at {progress}%");
                        NotificationManager.SendNotification("MapDownload", new { map.Id, progress }, map.Owner);
                    },
                        success =>
                    {
                        var updatedModel    = db.Single <MapModel>(map.Id);
                        updatedModel.Status = success ? "Valid" : "Invalid";
                        db.Update(updatedModel);
                        NotificationManager.SendNotification("MapDownloadComplete", updatedModel, map.Owner);
                        SIM.LogWeb(SIM.Web.MapDownloadFinish, map.Name);
                    }
                        );
                }

                var added    = new HashSet <Uri>();
                var vehicles = new VehicleService();

                foreach (var vehicle in DatabaseManager.PendingVehicleDownloads())
                {
                    Uri uri = new Uri(vehicle.Url);
                    if (added.Contains(uri))
                    {
                        continue;
                    }
                    added.Add(uri);

                    SIM.LogWeb(SIM.Web.VehicleDownloadStart, vehicle.Name);
                    DownloadManager.AddDownloadToQueue(
                        uri,
                        vehicle.LocalPath,
                        progress =>
                    {
                        Debug.Log($"Vehicle Download at {progress}%");
                        NotificationManager.SendNotification("VehicleDownload", new { vehicle.Id, progress }, vehicle.Owner);
                    },
                        success =>
                    {
                        string status = success ? "Valid" : "Invalid";
                        vehicles.SetStatusForPath(status, vehicle.LocalPath);
                        vehicles.GetAllMatchingUrl(vehicle.Url).ForEach(v =>
                        {
                            NotificationManager.SendNotification("VehicleDownloadComplete", v, v.Owner);
                            SIM.LogWeb(SIM.Web.VehicleDownloadFinish, vehicle.Name);
                        });
                    }
                        );
                }
            }
        }
Exemple #7
0
 public void AddDownload(Uri uri, string localPath, Action <int> update, Action <bool> completed)
 => DownloadManager.AddDownloadToQueue(uri, localPath, update, completed);
        void DownloadVehicleBundles(Commands.Load load, List <string> bundles, Action finished)
        {
            try
            {
                int count = 0;

                var agents = load.Agents;
                for (int i = 0; i < load.Agents.Length; i++)
                {
                    VehicleModel vehicleModel;
                    using (var db = DatabaseManager.Open())
                    {
                        var sql = Sql.Builder.Where("url = @0", agents[i].Url);
                        vehicleModel = db.SingleOrDefault <VehicleModel>(sql);
                    }

                    if (vehicleModel == null)
                    {
                        Debug.Log($"Downloading {agents[i].Name} from {agents[i].Url}");

                        vehicleModel = new VehicleModel()
                        {
                            Name       = agents[i].Name,
                            Url        = agents[i].Url,
                            BridgeType = agents[i].Bridge,
                            LocalPath  = WebUtilities.GenerateLocalPath("Vehicles"),
                            Sensors    = agents[i].Sensors,
                        };
                        bundles.Add(vehicleModel.LocalPath);

                        DownloadManager.AddDownloadToQueue(new Uri(vehicleModel.Url), vehicleModel.LocalPath, null,
                                                           (success, ex) =>
                        {
                            if (ex != null)
                            {
                                var err = new Commands.LoadResult()
                                {
                                    Success      = false,
                                    ErrorMessage = ex.ToString(),
                                };
                                Packets.Send(Master, err, DeliveryMethod.ReliableOrdered);
                                return;
                            }

                            using (var db = DatabaseManager.Open())
                            {
                                db.Insert(vehicleModel);
                            }

                            if (Interlocked.Increment(ref count) == bundles.Count)
                            {
                                finished();
                            }
                        }
                                                           );
                    }
                    else
                    {
                        Debug.Log($"Vehicle {agents[i].Name} exists");

                        bundles.Add(vehicleModel.LocalPath);
                        if (Interlocked.Increment(ref count) == bundles.Count)
                        {
                            finished();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);

                var err = new Commands.LoadResult()
                {
                    Success      = false,
                    ErrorMessage = ex.ToString(),
                };
                Packets.Send(Master, err, DeliveryMethod.ReliableOrdered);

                Loader.ResetLoaderScene();
            }
        }
        public void OnLoadCommand(Commands.Load load)
        {
            Debug.Assert(ClientState == State.Connected);
            ClientState = State.Loading;

            Debug.Log("Preparing simulation");

            try
            {
                MapModel map;
                using (var db = DatabaseManager.Open())
                {
                    var sql = Sql.Builder.Where("url = @0", load.MapUrl);
                    map = db.SingleOrDefault <MapModel>(sql);
                }

                if (map == null)
                {
                    Debug.Log($"Downloading {load.MapName} from {load.MapUrl}");

                    map = new MapModel()
                    {
                        Name      = load.MapName,
                        Url       = load.MapUrl,
                        LocalPath = WebUtilities.GenerateLocalPath("Maps"),
                    };

                    using (var db = DatabaseManager.Open())
                    {
                        db.Insert(map);
                    }

                    DownloadManager.AddDownloadToQueue(new Uri(map.Url), map.LocalPath, null, (success, ex) =>
                    {
                        if (ex != null)
                        {
                            map.Error = ex.Message;
                            using (var db = DatabaseManager.Open())
                            {
                                db.Update(map);
                            }

                            Debug.LogException(ex);
                        }

                        if (success)
                        {
                            LoadMapBundle(load, map.LocalPath);
                        }
                        else
                        {
                            var err = new Commands.LoadResult()
                            {
                                Success      = false,
                                ErrorMessage = ex.ToString(),
                            };
                            Packets.Send(Master, err, DeliveryMethod.ReliableOrdered);
                            return;
                        }
                    });
                }
                else
                {
                    Debug.Log($"Map {load.MapName} exists");
                    LoadMapBundle(load, map.LocalPath);
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);

                var err = new Commands.LoadResult()
                {
                    Success      = false,
                    ErrorMessage = ex.ToString(),
                };
                Packets.Send(Master, err, DeliveryMethod.ReliableOrdered);

                Loader.ResetLoaderScene();
            }
        }