コード例 #1
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public SendEvent(DateTime time, TimeSpan interval, DeviceAgent initiator, AsyncBox <bool> completionBox, byte[] payload, int bytesSent) : base(time)
 {
     Interval      = interval;
     Initiator     = initiator;
     CompletionBox = completionBox;
     Payload       = payload;
     BytesSent     = bytesSent;
 }
コード例 #2
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
            public SimulationConnectionContext(DeviceAgent firstAgent, DeviceAgent secondAgent)
            {
                this.firstAgent  = firstAgent;
                this.secondAgent = secondAgent;

                this.firstInboundChannel  = new DisconnectableChannel <byte[], NotConnectedException>(firstDisconnectChannel, ChannelFactory.Nonblocking <byte[]>());
                this.secondInboundChannel = new DisconnectableChannel <byte[], NotConnectedException>(secondDisconnectChannel, ChannelFactory.Nonblocking <byte[]>());
            }
コード例 #3
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
            public async Task SendAsync(DeviceAgent sender, byte[] contents)
            {
                var interval      = TimeSpan.FromMilliseconds(SimulationBluetoothConstants.SEND_TICK_INTERVAL);
                var completionBox = new AsyncBox <bool>();
                var sendEvent     = new SendEvent(DateTime.Now + interval, interval, sender, completionBox, contents, 0);
                await ChannelsExtensions.WriteAsync(adapterEventQueueChannel, sendEvent).ConfigureAwait(false);

                await completionBox.GetResultAsync().ConfigureAwait(false);
            }
コード例 #4
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
        public static SimulationBluetoothConnectivity ComputeConnectivity(DeviceAgent a, DeviceAgent b)
        {
            var quality = 1.0 - (a.Position - b.Position).LengthSquared() / SimulationBluetoothConstants.RANGE_SQUARED;

            return(new SimulationBluetoothConnectivity {
                InRange = quality > 0.0,
                IsSufficientQuality = quality > SimulationBluetoothConstants.MIN_VIABLE_SIGNAL_QUALITY,
                SignalQuality = (float)Math.Max(0, quality)
            });
        }
コード例 #5
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
            public async Task ConnectAsync(DeviceAgent sender)
            {
                var now          = DateTime.Now;
                var connectEvent = new BeginConnectEvent(now + TimeSpan.FromMilliseconds(SimulationBluetoothConstants.BASE_HANDSHAKE_DELAY_MILLIS), sender);
                await ChannelsExtensions.WriteAsync(adapterEventQueueChannel, connectEvent).ConfigureAwait(false);

                var timeoutEvent = new TimeoutConnectEvent(now + TimeSpan.FromMilliseconds(SimulationBluetoothConstants.HANDSHAKE_TIMEOUT_MILLIS), connectEvent);
                await ChannelsExtensions.WriteAsync(adapterEventQueueChannel, timeoutEvent).ConfigureAwait(false);

                await connectEvent.ResultBox.GetResultAsync().ConfigureAwait(false);
            }
コード例 #6
0
        private static DeviceAgent[] ConstructAgents(SimulatorConfiguration configuration)
        {
            var random = new Random(2);

            var agents = new DeviceAgent[configuration.AgentCount];

            for (int i = 0; i < agents.Length; i++)
            {
                agents[i] = new DeviceAgent {
                    BluetoothAdapterId = Guid.NewGuid(),
                    Position           = new Vector2(
                        random.Next(configuration.AgentRadius, configuration.FieldWidth - configuration.AgentRadius),
                        random.Next(configuration.AgentRadius, configuration.FieldHeight - configuration.AgentRadius)
                        ),
                    Velocity = Vector2.Transform(new Vector2(10, 0), Matrix.CreateRotationZ((float)(random.NextDouble() * Math.PI * 2)))
                };
            }

            agents[0].Position = new Vector2(300, 300);
            agents[1].Position = new Vector2(310, 300);

            var agentsPerRow = (4 * (int)Math.Sqrt(agents.Length)) / 3;
            var hSPacing     = 60;
            var vSPacing     = 60;
            var gw           = agentsPerRow * hSPacing;
            var gh           = (agents.Length / agentsPerRow) * vSPacing;
            var ox           = (configuration.FieldWidth - gw) / 2;
            var oy           = (configuration.FieldHeight - gh) / 2;

            for (var i = 0; i < agents.Length; i++)
            {
                agents[i].Position = new Vector2((i % agentsPerRow) * hSPacing + ox, (i / agentsPerRow) * vSPacing + oy);
            }

            for (var i = 0; i < agents.Length; i++)
            {
                agents[i].Position += agents[i].Velocity * 10;
                agents[i].Velocity  = Vector2.Zero;
            }

            var agentIndexToNeighborsByAdapterId = Enumerable.Range(0, agents.Length).ToDictionary(
                i => i,
                i => new Dictionary <Guid, SimulationBluetoothAdapter.SimulationBluetoothNeighbor>());

            for (int i = 0; i < agents.Length; i++)
            {
                var agent            = agents[i];
                var bluetoothAdapter = agent.BluetoothAdapter = new SimulationBluetoothAdapter(agent, agentIndexToNeighborsByAdapterId[i]);
                agent.BluetoothAdapter.Permit(SimulationBluetoothAdapter.MAX_RATE_LIMIT_TOKENS * (float)random.NextDouble());

                var broadcastMessageSerializer = new BroadcastMessageSerializer();
                var merkleTreeFactory          = new ClientMerkleTreeFactory(broadcastMessageSerializer, new InMemoryCampfireNetObjectStore());
                var identity = agent.CampfireNetIdentity = (Identity) new Identity(new IdentityManager(), $"Agent_{i}");
                if (i == 0 || i == 1)
                {
                    agent.CampfireNetIdentity.GenerateRootChain();
                }
                else
                {
                    var rootAgent = agents[i % 2];
                    agent.CampfireNetIdentity.AddTrustChain(rootAgent.CampfireNetIdentity.GenerateNewChain(identity.PublicIdentity, Permission.All, Permission.None, identity.Name));
                }

                var client = agent.Client = new CampfireNetClient(identity, bluetoothAdapter, broadcastMessageSerializer, merkleTreeFactory);
                client.MessageReceived += e => {
                    var epoch = BitConverter.ToInt32(e.Message.DecryptedPayload, 0);
//               Console.WriteLine($"{client.AdapterId:n} recv {epoch}");
                    agent.Value = Math.Max(agent.Value, epoch);
                };
                client.RunAsync().ContinueWith(task => {
                    if (task.IsFaulted)
                    {
                        Console.WriteLine(task.Exception);
                    }
                });
            }

            return(agents);
        }
コード例 #7
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public SimulationBluetoothNeighbor(DeviceAgent self, SimulationConnectionContext connectionContext)
 {
     this.self = self;
     this.connectionContext = connectionContext;
 }
コード例 #8
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public SimulationBluetoothAdapter(DeviceAgent agent, Dictionary <Guid, SimulationBluetoothNeighbor> neighborsByAdapterId)
 {
     this.agent = agent;
     this.neighborsByAdapterId = neighborsByAdapterId;
 }
コード例 #9
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public BeginConnectEvent(DateTime time, DeviceAgent initiator) : base(time)
 {
     Initiator = initiator;
 }
コード例 #10
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public bool GetIsConnected(DeviceAgent self) => self == firstAgent ? !firstDisconnectChannel.IsClosed : !secondDisconnectChannel.IsClosed;
コード例 #11
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public ReadableChannel <byte[]> GetOtherInboundChannel(DeviceAgent self) => GetOtherInboundChannelInternal(self);
コード例 #12
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 private Channel <byte[]> GetOtherInboundChannelInternal(DeviceAgent self) => GetInboundChannelInternal(GetOther(self));
コード例 #13
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 private Channel <byte[]> GetInboundChannelInternal(DeviceAgent self) => self == firstAgent ? firstInboundChannel : secondInboundChannel;
コード例 #14
0
ファイル: SimulatorGame.cs プロジェクト: jpaberc/CampfireNet
 public DeviceAgent GetOther(DeviceAgent self) => self == firstAgent ? secondAgent : firstAgent;