Exemple #1
0
            /// <summary>
            /// Seperate code string into blocks of code
            /// </summary>
            /// <param name="_lines"></param>
            private static void Read_Blocks(string [] _lines)
            {
                string tokenSubValue = string.Empty;

                for (int i = 0; i < _lines.Length; i++)
                {
                    if (Get_Token(_lines [i]) [0] == "format" || Get_Token(_lines [i]) [0] == "naming")
                    {
                        tokenSubValue = Get_Token(_lines [i]) [1];

                        for (int j = i; j < _lines.Length; j++, i++)
                        {
                            if (Get_Token(_lines [j]) [0] == "/format" || Get_Token(_lines [j]) [0] == "/naming")
                            {
                                if (Get_Token(_lines [j]) [0] == "/naming")
                                {
                                    BlockDetails block = new BlockDetails(tokenSubValue, G_Name, G_Info, G_Room, G_GridName, G_ShowInTerminal);
                                    Blocks.Add(block);
                                    NumberOfBlocks++;
                                }

                                break;
                            }


                            if (_lines [j].Contains("="))
                            {
                                Execute(_lines [j]);
                            }
                        }
                    }
                }
            }
Exemple #2
0
        public static Block MarshalBlock(BlockDetails b)
        {
            var hash = new Sha256Hash(b.Hash.ToByteArray());
            var height = b.Height;
            var unixTime = b.Timestamp;
            var transactions = b.Transactions.Select(MarshalWalletTransaction).ToList();

            return new Block(hash, height, unixTime, transactions);
        }
Exemple #3
0
        public static Block MarshalBlock(BlockDetails b)
        {
            var hash         = new Sha256Hash(b.Hash.ToByteArray());
            var height       = b.Height;
            var unixTime     = b.Timestamp;
            var transactions = b.Transactions.Select(MarshalWalletTransaction).ToList();

            return(new Block(hash, height, unixTime, transactions));
        }
Exemple #4
0
 public PlayerViewGameBoard(string[] vs) : base(vs)
 {
     for (int i = 0; i < Height; i++)
     {
         BlockDetails.Add(new List <string>());
         for (int j = 0; j < Width; j++)
         {
             BlockDetails[i].Add(null);
         }
     }
 }
Exemple #5
0
 PlayerViewGameBoard(int w, int h) : base(w, h)
 {
     for (int i = 0; i < Height; i++)
     {
         BlockDetails.Add(new List <string>());
         for (int j = 0; j < Width; j++)
         {
             BlockDetails[i].Add(null);
             Blocks[i][j] = GameBoardBlock.Unknown;
         }
     }
     BlockRangeChanged?.Invoke(0, 0, Height - 1, Width - 1);
 }
Exemple #6
0
        /// <summary>
        /// Seperate code string into blocks of code
        /// </summary>
        /// <param name="_lines"></param>
        private static void Read_Blocks(string [] _lines)
        {
            string tokenSubValue = string.Empty;

            for (int i = 0; i < _lines.Length; i++)
            {
                if (Get_Token(_lines [i]) [0] == "format" || Get_Token(_lines [i]) [0] == "naming")
                {
                    Console.WriteLine($"Found start of block: {_lines [i]}");

                    tokenSubValue = Get_Token(_lines [i]) [1];

                    for (int j = i; j < _lines.Length; j++, i++)
                    {
                        if (Get_Token(_lines [j]) [0] == "/format" || Get_Token(_lines [j]) [0] == "/naming")
                        {
                            if (Get_Token(_lines [j]) [0] == "/naming")
                            {
                                BlockDetails block = new BlockDetails(tokenSubValue, G_Name, G_Info, G_Room, G_GridName);
                                Console.WriteLine($"Storing Block data: {block.ToString ()}");
                                Blocks.Add(block);
                            }

                            Console.WriteLine($"Found end of block: {_lines [j]}");
                            break;
                        }

                        //Console.WriteLine ( $"Found statement: {_lines [j]}" );

                        if (_lines [j].Contains("="))
                        {
                            Execute(_lines [j]);
                        }
                    }
                }
            }
            //Console.WriteLine ( $"{this.wrappingValues [this.order [0] - 1] [0]}{this.orderValues [this.order [0]]}{this.wrappingValues [this.order [0] - 1] [1]}{this.wrappingValues [this.order [1] - 1] [0]}{this.orderValues [this.order [1]]}{this.wrappingValues [this.order [1] - 1] [1]}{this.wrappingValues [this.order [2] - 1] [0]}{this.orderValues [this.order [2]]}{this.wrappingValues [this.order [2] - 1] [1]}{this.wrappingValues [this.order [3] - 1] [0]}{this.orderValues [this.order [3]]}{this.wrappingValues [this.order [3] - 1] [1]}" );
        }
Exemple #7
0
    void UpdateUIPanel()
    {
        while (ShallRun)
        {
            ulong newBlockNumber = GetCurrentBlockNumber();
            UpdateBalances();
            if (StartBlockNumber == 0)
            {
                StartBlockNumber         = newBlockNumber;
                LastBlockNumberProcessed = newBlockNumber;
            }

            //Web3.Eth.Blocks.GetBlockNumber();
            if (newBlockNumber > LastBlockNumber)
            {
                var blockNumber = new Nethereum.Hex.HexTypes.HexBigInteger(new BigInteger(newBlockNumber));

                var blockTask = Web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(blockNumber);
                blockTask.Wait();
                var block = blockTask.Result;

                BlockDetails blockDetails = new BlockDetails();
                blockDetails.BlockInfo = block;

                StringBuilder txInfos = new StringBuilder();
                txInfos.AppendLine(newBlockNumber.ToString());
                txInfos.AppendLine(block.BlockHash);

                List <Task <TransactionReceipt> > transactionReceiptTasks = new List <Task <TransactionReceipt> >();
                foreach (var tx in block.Transactions)
                {
                    //TODO: maybe just pick up transaction that point to one of our contracts ? see mapping ContractMappingAddressToName

                    txInfos.AppendLine(" - " + tx.TransactionHash);
                    //tx.TransactionHash;
                    //tx.
                    //tx.

                    Task <TransactionReceipt> receiptTask = Web3.Eth.TransactionManager.TransactionReceiptService.PollForReceiptAsync(tx.TransactionHash);
                    //receiptTask.Start();
                    transactionReceiptTasks.Add(receiptTask);
                }

                TimeSpan timeout = TimeSpan.FromSeconds(10);
                foreach (var task in transactionReceiptTasks)
                {
                    task.Wait(timeout);
                    TransactionDetails details = new TransactionDetails();
                    if (task.IsCompleted)
                    {
                        details.TransactionReceipt = task.Result;

                        if (!string.IsNullOrEmpty(details.TransactionReceipt.ContractAddress) && ContractMappingAddressToName.ContainsKey(details.TransactionReceipt.ContractAddress))
                        {
                            details.ContractName = ContractMappingAddressToName[details.TransactionReceipt.ContractAddress];
                        }

                        AddEventsFromReceipt(details.TransactionReceipt, details.FishEvents, details.AllEvents);
                        AddEventsFromReceipt(details.TransactionReceipt, details.LandEvents, details.AllEvents);
                        AddEventsFromReceipt(details.TransactionReceipt, details.LandOwner, details.AllEvents);
                        AddEventsFromReceipt(details.TransactionReceipt, details.DoggerWasBuild, details.AllEvents);
                        // AddEventsFromReceipt(details.TransactionReceipt, details.TimberMintEvents, details.AllEvents);
                        // AddEventsFromReceipt(details.TransactionReceipt, details.CopperMintEvents , details.AllEvents);



                        LatestTransactionInformations.TryAdd(details.TransactionReceipt.TransactionHash, details);
                        blockDetails.TransactionDetails.Add(details);
                    }
                    else
                    {
                        if (task.IsCanceled)
                        {
                            Debug.LogWarning("Receiving Transaction details was cancelled");
                        }

                        if (task.IsFaulted)
                        {
                            Debug.LogWarning("Receiving Transaction details Rand into an Error.");
                        }
                    }

                    //var fishEvents = details.TransactionReceipt.DecodeAllEvents<Galleass3D.Contracts.Bay.ContractDefinition.FishEventDTO>();
                    //details.
                    //task.Result
                }

                LatestBlockInformation = txInfos.ToString();

                if (!LatestBlockDetails.TryAdd(newBlockNumber, blockDetails))
                {
                    Debug.LogError("Could not add Block #" + newBlockNumber);
                }

                LastBlockNumber = newBlockNumber;
                //block.Result.Transactions
            }

            System.Threading.Thread.Sleep(BlockTimeMs);
        }
    }
        private async Task ConnectToDevice(DeploymentUser dUser)
        {
            DeploymentUser deploymentUser = _deploymentUsers.SingleOrDefault(du => du.device.macAddress == dUser.device.macAddress);

            // if deploymentUser is found
            if (deploymentUser != default(DeploymentUser))
            {
                IAxLE device = null;
                try
                {
                    await _axLEManager.StopScan();

                    Console.WriteLine($"CONNECTION: ConnectDevice()");

                    for (var retry = 0; ; retry++)
                    {
                        try
                        {
                            device = await _axLEManager.ConnectDevice(deploymentUser.device.macAddress);

                            break;
                        }
                        catch (OpenMovement.AxLE.Comms.Exceptions.CommandFailedException e)
                        {
                            Console.WriteLine($"CONNECTION: GATT error, retry {retry}");
                            Crashes.TrackError(e);
                            if (retry > 10)
                            {
                                throw;
                            }
                        }
                        catch (OpenMovement.AxLE.Comms.Exceptions.ConnectException e)
                        {
                            Console.WriteLine($"CONNECTION: ConnectException error, retry {retry}");
                            Crashes.TrackError(e);
                            if (retry > 10)
                            {
                                throw;
                            }
                        }
                    }

                    // try auth with known password
                    Console.WriteLine($"CONNECTION: Authenticate()");
                    bool authSuccess = await device.Authenticate(deploymentUser.device.password);

                    // if fails, reset device
                    if (!authSuccess)
                    {
                        Console.WriteLine($"CONNECTION: ResetPassword()");
                        await device.ResetPassword();

                        Console.WriteLine($"CONNECTION: Authenticate()");
                        await device.Authenticate(device.SerialNumber.Substring(device.SerialNumber.Length - 6));

                        Console.WriteLine($"CONNECTION: SetPassword()");
                        await device.SetPassword(deploymentUser.device.password);

                        deploymentUser.device.lastBlockSynced = null;
                        deploymentUser.device.lastRTC         = null;
                        deploymentUser.device.lastSyncTime    = null;
                    }

                    // buzz device
                    Console.WriteLine($"FLASH AND BUZZ START:{ DateTime.Now }");
                    //await device.LEDFlash();
                    await device.VibrateDevice();

                    Console.WriteLine($"FLASH AND BUZZ END:{ DateTime.Now }");

                    // HACK: Use this butchered version to skip updating cueing
                    //await ((OpenMovement.AxLE.Comms.AxLEv1_5)device).UpdateDeviceState((uint)(0xffffffff & ~0x0010));   // Don't update cueing status
                    await device.UpdateDeviceState();

                    // proceed with sync and update deployment user
                    if (device.EpochPeriod != 300)
                    {
                        device.EpochPeriod = 300; // 5 minutes (300 seconds)
                    }

                    if (!deploymentUser.device.lastBlockSynced.HasValue || !deploymentUser.device.lastRTC.HasValue || !deploymentUser.device.lastSyncTime.HasValue)
                    {
                        BlockDetails blockDetails = await device.ReadBlockDetails();

                        deploymentUser.device.lastBlockSynced = blockDetails.ActiveBlock;
                        deploymentUser.device.lastRTC         = blockDetails.Time;
                        deploymentUser.device.lastSyncTime    = DateTime.UtcNow;
                        // send off server request to update these details
                        DeviceSyncAttempt _deviceSyncAttempt = new DeviceSyncAttempt
                        {
                            deploymentUserId   = deploymentUser.id,
                            batteryLevel       = device.Battery,
                            deploymentDeviceId = deploymentUser.device.id,
                            samples            = new DeviceSampleRecord[0],
                            lastBlockSynced    = (blockDetails.ActiveBlock),
                            lastRTC            = blockDetails.Time,
                            lastSyncTime       = DateTime.UtcNow,
                            raw = new byte[0][]
                        };
                        RunOnUiThread(() =>
                        {
                            _webViewClient.RecievedData(_webView, _deviceSyncAttempt);
                        });

                        WriteSyncAttemptToDisk(deploymentUser.deploymentId, deploymentUser.device.macAddress, _deviceSyncAttempt);
                    }
                    else
                    {
                        var start = DateTime.Now;
                        // we have data on the device, sync the data using previous deploymentUser.device...
                        Console.WriteLine($"BLOCK READ START:{ DateTime.Now }");
                        var blocks = await device.SyncEpochData((UInt16)deploymentUser.device.lastBlockSynced, (UInt32)deploymentUser.device.lastRTC, (DateTimeOffset)deploymentUser.device.lastSyncTime);

                        Console.WriteLine($"BLOCK READ END:{ DateTime.Now }");
                        var end = DateTime.Now;

                        /*
                         * {
                         *      deploymentUserId: 15,
                         *      batteryLevel: 15,
                         *      deploymentDeviceId: 1,
                         *      epochInterval: 60000
                         *      samples: [
                         *          {
                         *              steps: 123,
                         *              batteryLevel: 15
                         *              recordedOn: 2018-05-31 14:23:01Z4
                         *          }
                         *      ],
                         *      raw: "RAW BYTES FROM SYNC"
                         * }
                         */
                        DeviceSampleRecord[] samples = blocks.SelectMany(b =>
                        {
                            var deviceSampleRecords = new List <DeviceSampleRecord>();
                            ulong samplesLength     = (ulong)b.Samples.Length;
                            for (ulong i = 0; i < samplesLength; i++)
                            {
                                deviceSampleRecords.Add(new DeviceSampleRecord()
                                {
                                    steps        = b.Samples[i].Steps,
                                    batteryLevel = b.Samples[i].Battery,
                                    recordedOn   = b.BlockInfo.Timestamp.AddSeconds(i * b.BlockInfo.EpochPeriod)
                                });
                            }

                            return(deviceSampleRecords);
                        }).ToArray();

                        var lastBlock = blocks.LastOrDefault();

                        var lastBlockNumber = lastBlock == default(EpochBlock) ?
                                              deploymentUser.device.lastBlockSynced : lastBlock.BlockInfo.BlockNumber;

                        DeviceSyncAttempt _deviceSyncAttempt = new DeviceSyncAttempt
                        {
                            deploymentUserId   = deploymentUser.id,
                            batteryLevel       = device.Battery,
                            deploymentDeviceId = deploymentUser.device.id,
                            samples            = samples,
                            lastBlockSynced    = (ushort)lastBlockNumber,
                            lastRTC            = device.DeviceTime,
                            lastSyncTime       = DateTime.UtcNow,
                            raw = blocks.Select(b => b.Raw).ToArray()
                        };

                        WriteSyncAttemptToDisk(deploymentUser.deploymentId, deploymentUser.device.macAddress, _deviceSyncAttempt);

                        // save locally
                        // post data off to tablet
                        RunOnUiThread(() =>
                        {
                            _webViewClient.RecievedData(_webView, _deviceSyncAttempt);
                        });
                    }
                }
                catch (BlockSyncFailedException e)
                {
                    // move read head to active block
                    Console.WriteLine("BlockSyncFailedException:" + e.ToString());
                    Crashes.TrackError(e);
                    RunOnUiThread(() =>
                    {
                        _webViewClient.RequestDataFailed(_webView);
                    });
                }
                catch (DeviceNotInRangeException e)
                {
                    // display not in range
                    Console.WriteLine("DeviceNotInRangeException:" + e.ToString());
                    Crashes.TrackError(e);
                    RunOnUiThread(() =>
                    {
                        _webViewClient.RequestDataFailed(_webView);
                    });
                }
                catch (CommandFailedException e)
                {
                    // display not in range
                    Console.WriteLine("Command Failed Exception:" + e.ToString());
                    Crashes.TrackError(e);
                    RunOnUiThread(() =>
                    {
                        _webViewClient.RequestDataFailed(_webView);
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception:" + e.ToString());
                    Crashes.TrackError(e);
                    // restart this process
                    RunOnUiThread(() =>
                    {
                        _webViewClient.RequestDataFailed(_webView);
                    });
                }
                finally
                {
                    if (device != null)
                    {
                        await _axLEManager.DisconnectDevice(device);
                    }

                    //DisableBluetooth();
                }
            }
            else
            {
                Toast.MakeText(ApplicationContext, "Could not connect to your activity tracker", ToastLength.Short).Show();
            }
        }