Ejemplo n.º 1
0
    void OnStateEnd(BattleState endingState)
    {
        switch (endingState.ID)
        {
        case BattleStateID.Start: SetState(BattleStateID.WaitingForInput); break;

        case BattleStateID.WaitingForInput: SetState(BattleStateID.Executing); break;

        case BattleStateID.Executing:
            // TODO: Evaluate win condition.
            bool gameOver = false;

            if (gameOver)
            {
                LogEx.Log <BattleCoordinator>("Game Over!");
            }
            else
            {
                SetState(BattleStateID.PostTurn);
            }
            break;

        case BattleStateID.PostTurn: SetState(BattleStateID.PostTurnExecute); break;

        case BattleStateID.PostTurnExecute: SetState(BattleStateID.WaitingForInput); break;
        }
    }
Ejemplo n.º 2
0
    public void RemoveEffect(FieldEffectType fieldEffectType)
    {
        // TODO.
        LogEx.Log <FieldSide>("Removed effect: " + fieldEffectType);

        _fieldEffects[fieldEffectType].Reset();
    }
Ejemplo n.º 3
0
    void OnCommandsDepleted(BattleQueue queue)
    {
        LogEx.Log <BattleStateExecute>("#--- End Turn " + (Coordinator.TurnCount) + " ---#");

        queue.Emptied -= OnCommandsDepleted;
        End();
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Autofac configuration.
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        private IContainer ConfigureContainer(IConfigurationRoot configuration)
        {
            var config  = new Config(configuration);
            var builder = new ContainerBuilder();

            // Register configuration interfaces
            builder.RegisterInstance(config)
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterInstance(this)
            .AsImplementedInterfaces().SingleInstance();

            // register logger
            builder.RegisterLogger(LogEx.Console(configuration));
            // Register module framework
            builder.RegisterModule <ModuleFramework>();

            // Register test publisher
            builder.RegisterType <TestPublisher>()
            .AsImplementedInterfaces().InstancePerLifetimeScope();

            // Register controllers
            builder.RegisterType <v2.Supervisor.DiagnosticMethodsController>()
            .AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterType <v2.Supervisor.DiagnosticSettingsController>()
            .AsImplementedInterfaces().InstancePerLifetimeScope();

            return(builder.Build());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Configure Dependency injection
        /// </summary>
        /// <returns></returns>
        private static IContainer ConfigureContainer()
        {
            var builder = new ContainerBuilder();

            // Register logger
            builder.RegisterLogger(LogEx.ConsoleOut());

            // Register infrastructure code
            builder.RegisterType <ResourceGroupFactory>()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <AzureSubscription>()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <ConsoleSelector>()
            .AsImplementedInterfaces().SingleInstance();

            builder.RegisterType <VisualStudioCredentials>()
            .AsImplementedInterfaces().SingleInstance();

            builder.RegisterType <IoTHubFactory>()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <VirtualMachineFactory>()
            .AsImplementedInterfaces().SingleInstance();

            return(builder.Build());
        }
Ejemplo n.º 6
0
    public void RegisterCharacter(Character character)
    {
        if (!_activeCharacters.Contains(character))
        {
            LogEx.Log <BattleSystem>("Registered character: '{0}'", character.name);

            _activeCharacters.Add(character);

            character.BattleEntities.ForEach(x => x.Initialize(this));

            // Assign character into player slot.
            //character.Owner.FieldSide.Register(character);

            if (CharacterAddedToSlot != null)
            {
                CharacterAddedToSlot.Invoke(character);
            }

            if (PostCharacterAddedToSlot != null)
            {
                PostCharacterAddedToSlot.Invoke(character);
            }
        }
        else
        {
            LogEx.LogError <BattleSystem>("Cannot register character '{0}' as they are already registered.", character.name);
        }
    }
Ejemplo n.º 7
0
    void RegisterAction(BaseAction action, BattleQueueType type)
    {
        if (_logRegistrations)
        {
            LogEx.Log <BattleQueue>("Registered action: {0} of type '{1}'", action.GetType().Name, type.ToString());
        }

        switch (type)
        {
        case BattleQueueType.GenericUpdate:
            _genericUpdates.Queue.Enqueue(action);
            break;

        case BattleQueueType.PlayerCommand:
            _playerCommands.Queue.Enqueue(action);
            break;

        case BattleQueueType.StatusUpdate:
            _statusUpdates.Queue.Enqueue(action);
            break;

        case BattleQueueType.Weather:
            _weatherUpdates.Queue.Clear();
            _weatherUpdates.Queue.Enqueue(action);
            break;
        }
    }
Ejemplo n.º 8
0
        /// <summary>
        /// Clear registry
        /// </summary>
        private static async Task CleanupAsync(IIoTHubConfig config,
                                               bool includeSupervisors)
        {
            var logger   = LogEx.Console(LogEventLevel.Error);
            var registry = new IoTHubServiceHttpClient(new HttpClient(logger),
                                                       config, logger);
            var result = await registry.QueryDeviceTwinsAsync(
                "SELECT * from devices where IS_DEFINED(tags.DeviceType)");

            foreach (var item in result)
            {
                Console.WriteLine($"Deleting {item.Id} {item.ModuleId ?? ""}");
                await registry.DeleteAsync(item.Id, item.ModuleId);
            }
            if (!includeSupervisors)
            {
                return;
            }
            var query = "SELECT * FROM devices.modules WHERE " +
                        $"properties.reported.{TwinProperty.kType} = 'supervisor'";
            var supers = await registry.QueryDeviceTwinsAsync(query);

            foreach (var item in supers)
            {
                Console.WriteLine($"Deleting {item.Id} {item.ModuleId ?? ""}");
                await registry.DeleteAsync(item.Id, item.ModuleId);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Autofac configuration.
        /// </summary>
        public static ContainerBuilder ConfigureContainer(
            IConfigurationRoot configuration)
        {
            var serviceInfo = new ServiceInfo();
            var config      = new Config(configuration);
            var builder     = new ContainerBuilder();

            builder.RegisterInstance(serviceInfo)
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterInstance(config)
            .AsImplementedInterfaces().SingleInstance();

            // register logger
            builder.RegisterLogger(LogEx.Console());

            // Router host, processor and client ...
            builder.RegisterType <IoTHubFileNotificationHost>()
            .AsImplementedInterfaces();
            builder.RegisterType <BlobUploadNotificationRouter>()
            .AsImplementedInterfaces();
            builder.RegisterType <EventHubNamespaceClient>()
            .AsImplementedInterfaces();

            return(builder);
        }
Ejemplo n.º 10
0
    public void RegisterPlayer(Player player, int fieldSideID)
    {
        if (!_players.Contains(player))
        {
            LogEx.Log <BattleSystem>("Registered player: '{0}'", player.name);

            _players.Add(player);

            fieldSideID = Mathf.Clamp(fieldSideID, 0, _fieldSides.Count - 1);

            player.AssignFieldSide(_fieldSides[fieldSideID]);

            // TEMP!!!
            //RegisterCharacter(player.ActiveCharacter);

            // TEMP!!!
            //player.ActiveCharacter.BattleEntities.ForEach(x => x.Initialize(this));

            if (PlayerAdded != null)
            {
                PlayerAdded.Invoke(player);
            }
        }
        else
        {
            LogEx.LogError <BattleSystem>("Cannot register player '{0}' as they are already registered.", player.name);
        }
    }
Ejemplo n.º 11
0
 public TestServer(int size,
                   Func <string, byte[], string, byte[]> handler)
 {
     MaxMethodPayloadCharacterCount = size;
     _handler = handler;
     _server  = new ChunkMethodServer(this, LogEx.Trace());
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Autofac configuration.
        /// </summary>
        public static ContainerBuilder ConfigureContainer(
            IConfigurationRoot configuration)
        {
            var serviceInfo = new ServiceInfo();
            var config      = new Config(configuration);
            var builder     = new ContainerBuilder();

            builder.RegisterInstance(serviceInfo)
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterInstance(config)
            .AsImplementedInterfaces().SingleInstance();

            // register logger
            builder.RegisterLogger(LogEx.ApplicationInsights(config, configuration));
            // Register metrics logger
            builder.RegisterType <MetricLogger>()
            .AsImplementedInterfaces().SingleInstance();

            // Now Monitor model upload notification using ...
            if (!config.UseFileNotificationHost)
            {
                // ... event processor for fan out (requires blob
                // notification router to be running) ...

                builder.RegisterType <EventProcessorHost>()
                .AsImplementedInterfaces();
                builder.RegisterType <EventProcessorFactory>()
                .AsImplementedInterfaces().SingleInstance();
            }
            else
            {
                // ... or listen for file notifications on hub directly
                // (for simplicity) ...
                builder.RegisterType <IoTHubFileNotificationHost>()
                .AsImplementedInterfaces();
            }

            // ... then call the injected blob processor to load blob ...
            builder.RegisterType <BlobStreamProcessor>()
            .AsImplementedInterfaces();

            // ... and pass to either importer which imports the data ...
            builder.RegisterType <SourceStreamImporter>()
            .AsImplementedInterfaces();
            builder.RegisterType <TaskProcessor>()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <JsonVariantEncoder>()
            .AsImplementedInterfaces().SingleInstance();

            // ... into cosmos db collection with configured name.
            builder.RegisterType <ItemContainerFactory>()
            .AsImplementedInterfaces();
            builder.RegisterType <CosmosDbServiceClient>()
            .AsImplementedInterfaces();

            // ... or ...

            return(builder);
        }
Ejemplo n.º 13
0
    protected override void OnApplyEffect(Character target)
    {
        LogEx.Log <FieldEffectSpikes>("Applying spikes. Multiplier {0}", Level);

        var damage = _parameters.PercentageDamagePerLevel[Level];

        target.Health.ChangeHealth(null, -damage);
    }
Ejemplo n.º 14
0
 void OnEnterWeather(BattleSystem battleSystem)
 {
     if (battleSystem.Weather.Current != null)
     {
         LogEx.Log <BattleQueue>("Found a weather effect.");
         RegisterWeather(battleSystem.Weather.Current);
     }
 }
Ejemplo n.º 15
0
 public void Assign(Character character)
 {
     LogEx.Log <FieldSlot>("Assigned character '{0}'", character.name);
     Character          = character;
     Character.Fainted += OnCharacterFainted;
     Character.AssignSlot(this);
     CharacterAdded.InvokeSafe(Character);
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Delete supervisor
 /// </summary>
 private static async Task DeleteAsync(IIoTHubConfig config,
                                       string deviceId, string moduleId)
 {
     var logger   = LogEx.Console(LogEventLevel.Error);
     var registry = new IoTHubServiceHttpClient(new HttpClient(logger),
                                                config, logger);
     await registry.DeleteAsync(deviceId, moduleId);
 }
Ejemplo n.º 17
0
 void OnHealthChanged(HealthChangeEvent obj)
 {
     if (obj.NewValue <= 0)
     {
         LogEx.Log <Character>("{0} fainted...", name);
         ActiveState = ActiveState.Fainted;
         Fainted.InvokeSafe(this);
     }
 }
Ejemplo n.º 18
0
    void OnPlayerReadyStateChanged(Player player)
    {
        LogEx.Log <BattleCoordinator>("{0} ready state changed to: {1}", player.name, player.IsReady);

        if (Coordinator.System.Players.TrueForAll(x => x.IsReady))
        {
            End();
        }
    }
Ejemplo n.º 19
0
        /// <summary>
        /// Get module connection string
        /// </summary>
        private static async Task GetAsync(
            IIoTHubConfig config, string deviceId, string moduleId)
        {
            var logger   = LogEx.Console(LogEventLevel.Error);
            var registry = new IoTHubServiceHttpClient(new HttpClient(logger),
                                                       config, logger);
            var cs = await registry.GetConnectionStringAsync(deviceId, moduleId);

            Console.WriteLine(cs);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Reset supervisor
        /// </summary>
        private static async Task ResetAsync(IIoTHubConfig config,
                                             string deviceId, string moduleId)
        {
            var logger   = LogEx.Console(LogEventLevel.Error);
            var registry = new IoTHubServiceHttpClient(new HttpClient(logger),
                                                       config, logger);

            await ResetAsync(registry, await registry.GetAsync(deviceId, moduleId,
                                                               CancellationToken.None));
        }
Ejemplo n.º 21
0
        private void PrintRecvMssg(string info)
        {
            LogEx.l(info);
            string sql = string.Format("INSERT INTO {0} ({1},{2}) VALUES('{3}','{4}')", TableName, ColumnInfo, ColumnTime, info, DateTime.Now);
            var    i   = DbHelperSQL.ExecuteSql(sql);

            LogEx.l(i > 0 ? "Insert Success" : "Insert Fail");
            //txtRecvMssg.Text += string.Format("[{0}]:{1}\r\n",
            //    DateTime.Now.ToLongTimeString(), info);
        }
Ejemplo n.º 22
0
    public void RemoveAllEffects()
    {
        // TODO.
        LogEx.Log <FieldSide>("Removed all effects.");

        foreach (var fieldEffect in _fieldEffects)
        {
            fieldEffect.Value.Reset();
        }
    }
Ejemplo n.º 23
0
    public void IncreaseEffect()
    {
        Active = true;

        if (CanApply)
        {
            Level++;
            LogEx.Log <FieldEffectSpikes>("Increased effect multiplier to {0}", Level);
        }
    }
Ejemplo n.º 24
0
        /// <summary>
        /// Create hub container
        /// </summary>
        /// <returns></returns>
        private IContainer CreateHubContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterInstance(this).AsImplementedInterfaces();
            builder.RegisterLogger(LogEx.ConsoleOut());
            builder.RegisterModule <IoTHubMockService>();
            builder.RegisterType <TestIoTHubConfig>()
            .AsImplementedInterfaces();

            // Twin and history clients
            builder.RegisterModule <TwinModuleClients>();

            builder.RegisterType <HistoryRawSupervisorAdapter>()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <TwinSupervisorAdapter>()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <TwinModuleClient>()
            .AsImplementedInterfaces();
            builder.RegisterType <HistoryModuleClient>()
            .AsImplementedInterfaces();

            // Adapts to expanded hda
            builder.RegisterType <HistoricAccessAdapter <string> >()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <HistoricAccessAdapter <EndpointRegistrationModel> >()
            .AsImplementedInterfaces().SingleInstance();
            builder.RegisterType <HistoricAccessAdapter <EndpointApiModel> >()
            .AsImplementedInterfaces().SingleInstance();

            // Supervisor clients
            builder.RegisterType <ActivationClient>()
            .AsImplementedInterfaces();
            builder.RegisterType <DiagnosticsClient>()
            .AsImplementedInterfaces();
            builder.RegisterType <DiscoveryClient>()
            .AsImplementedInterfaces();
            builder.RegisterType <JsonVariantEncoder>()
            .AsImplementedInterfaces();
            builder.RegisterType <JsonVariantEncoder>()
            .AsImplementedInterfaces();

            // Add services
            builder.RegisterModule <RegistryServices>();
            builder.RegisterType <ApplicationTwins>()
            .AsImplementedInterfaces();
            builder.RegisterType <EndpointEventBrokerStub>()
            .AsImplementedInterfaces();
            builder.RegisterType <ApplicationEventBrokerStub>()
            .AsImplementedInterfaces();

            // Register http client module
            builder.RegisterModule <HttpClientModule>();
            return(builder.Build());
        }
Ejemplo n.º 25
0
 public void AddPlayer(Player player, int fieldSide)
 {
     if (Players.Any(x => x.Player == player))
     {
         LogEx.LogError <SetupParams>("Cannot add player as player {0} has already been registered.", player.name);
     }
     else
     {
         Players.Add(new PlayerData(player, fieldSide));
     }
 }
        public TwinService(string serviceUrl, string resource)
        {
            _logger = LogEx.Trace();

            _httpClient = new HttpClient(new HttpClientFactory(new HttpHandlerFactory(new List <IHttpHandler> {
                new HttpBearerAuthentication(new BehalfOfTokenProvider(), _logger)
            }, _logger), _logger), _logger);

            _config             = new TwinServiceConfig(serviceUrl, resource);
            _twinServiceHandler = new TwinServiceClient(_httpClient, _config, _logger);
        }
Ejemplo n.º 27
0
    public override void OnStart()
    {
        Coordinator.System.Players.ForEach(x => x.ReadyStateChanged += OnPlayerReadyStateChanged);

        LogEx.Log <BattleCoordinator>("Waiting for {0} players.", Coordinator.System.Players.Count);

        if (Coordinator.AutoReadyPlayers)
        {
            Coordinator.System.Players.ForEach(x => x.Attack());
        }
    }
        public void UnixDomainSocketHttpRequestTest3()
        {
            var         logger  = LogEx.Trace();
            IHttpClient client  = new HttpClient(new HttpClientFactory(logger), logger);
            var         request = client.NewRequest(new Uri("unix:///var/test/unknown:0/path/to/resource?query=36"));

            Assert.True(request.Headers.Contains(HttpHeader.UdsPath));
            var path = request.Headers.GetValues(HttpHeader.UdsPath).First();

            Assert.Equal("/var/test/unknown", path);
            Assert.Equal("/path/to/resource?query=36", request.Uri.PathAndQuery);
        }
Ejemplo n.º 29
0
    protected override void OnExecute(BattleSystem battleSystem)
    {
        _executionsTotal++;

        TriggerCompletion();

        if (Expired)
        {
            LogEx.Log <Lifetime>(name + "'s life expired.");
            battleSystem.Log(ExpiryMessage);
        }
    }
Ejemplo n.º 30
0
        /// <summary>
        /// Host the supervisor module giving it its connection string.
        /// </summary>
        private static async Task HostAsync(IIoTHubConfig config,
                                            string deviceId, string moduleId)
        {
            Console.WriteLine("Create or retrieve connection string...");
            var logger = LogEx.Console(LogEventLevel.Error);
            var cs     = await Retry.WithExponentialBackoff(logger,
                                                            () => AddOrGetAsync(config, deviceId, moduleId));

            Console.WriteLine("Starting twin module...");
            Twin.Program.Main(new string[] { $"EdgeHubConnectionString={cs}" });
            Console.WriteLine("Twin module exited.");
        }