Ejemplo n.º 1
0
        /// <summary>
        /// Query the devices connected. Not ready until this finishes.
        /// </summary>
        private async Task QueryDevices()
        {
            await Task.Run(async() =>
            {
                DeviceStream.Write(new byte[] { 0x20, 0x03 });
                while (true)
                {
                    byte[] readBuf = DeviceStream.Read();

                    if (readBuf[0] == 0x21 && readBuf[1] == 0x03)
                    {
                        // We received the device query reply
                        byte[] device1 = new byte[6];
                        byte[] device2 = new byte[6];
                        Array.Copy(readBuf, 15, device1, 0, 6);
                        Array.Copy(readBuf, 21, device2, 0, 6);
                        string deviceStr1 = Util.ByteArrayToString(device1);
                        string deviceStr2 = Util.ByteArrayToString(device2);

                        Channel1 = NzxtLedDevice.FromDeviceIdentifier(deviceStr1);
                        Channel2 = NzxtLedDevice.FromDeviceIdentifier(deviceStr2);

                        break;
                    }
                    await Task.Delay(10).ConfigureAwait(false);
                }
                Ready = true;
            });
        }
Ejemplo n.º 2
0
        static void verifyNabto1861(NabtoClient nabto, Session session)
        {
            DeviceStream stream = session.CreateStream("mystream.nabto.net");

            byte[] buf = new byte[1];
            int    n   = stream.Read(buf, 0, 1);

            Console.WriteLine("Read returned {0}", n);
        }
Ejemplo n.º 3
0
        public TimeSpan Read()
        {
            if (stream is null)
            {
                try
                {
                    stream = hid.Open();
                }
                catch (IOException ex)
                {
                    throw new HardwareException(DeviceType.Hrm, ErrorCode.CommunicationError, "HRM is unplugged", "Plug the HRM back in");
                }
            }

            byte[] buffer = new byte[1024];
            try
            {
                int x = stream.Read(buffer, 0, 1024);
            }
            catch (IOException ex)
            {
                stream.Close();
                stream = null;
                throw new HardwareException(DeviceType.Hrm, ErrorCode.CommunicationError, "HRM is unplugged", "Plug the HRM back in");
            }
            catch (TimeoutException)
            {
                stream.Close();
                stream = null;
                throw new HardwareException(DeviceType.Hrm, ErrorCode.Timeout, "Unable to detect heart rate", "Attach the sensor correctly");
            }
            catch
            {
                stream.Close();
                stream = null;
                throw new HardwareException(DeviceType.Hrm, ErrorCode.OtherError, "General error", "Plug the device back in");
            }
            var  b0    = buffer[3];
            var  b1    = buffer[4];
            var  b2    = buffer[5];
            long ticks = b0 << 16 | b1 << 8 | b2;

            ticks *= 40;
            return(new TimeSpan(ticks));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Reads the specified file entry.
        /// </summary>
        public byte[] ReadFile(FileEntry file)
        {
            ushort nextCluster = file.FirstCluster;
            uint   sizeLeft    = file.FileSize;
            uint   clusterSize = (uint)(PhysicalDevice.SectorSize * device.BootSector.SectorsPerCluster);
            uint   sector;

            int offset = 0;

            byte[] data = new Byte[file.FileSize];
            while (true)
            {
                // Calculate next sector
                sector = (uint)(device.RootDirectorySector + ((((nextCluster == 0) ? (0) : (nextCluster + 2))) * device.BootSector.SectorsPerCluster));
                // Jump to data sector
                DeviceStream.Seek((device.Partition.RelativeSector + sector) * device.BootSector.BytesPerSector, SeekOrigin.Begin);
                // Read correct size
                if (sizeLeft < clusterSize)
                {
                    DeviceStream.Read(data, offset, (int)sizeLeft);
                    break;
                }
                else
                {
                    DeviceStream.Read(data, offset, (int)clusterSize);
                    offset   += (int)clusterSize;
                    sizeLeft -= clusterSize;
                }
                // Get next cluster
                nextCluster = device.Data[nextCluster];
                if ((nextCluster == 0x0000) || (nextCluster == 0xFFF7))
                {
                    break;    // Bad cluster pointer
                }
                if ((nextCluster >= 0xFFF8) && (nextCluster <= 0xFFFF))
                {
                    break;    // End of cluster of file
                }
            }
            return(data);
        }
 protected override void When()
 {
     ReadCount = DeviceStream.Read(ReadBuffer, 0, 10);
 }
Ejemplo n.º 6
0
        public Lumia.PhoneInfo GetPhoneInfo(uint diskNumber)
        {
            var time = DateTime.Now;

            Log.Debug("Initializing Device Stream...");

            var deviceName = @"\\.\PhysicalDrive" + diskNumber;

            var diskSectorSize = (int)GetDiskSize.GetDiskSectorSize(deviceName);

            byte[]            platconfig;
            byte[]            dppconfig;
            QualcommPartition part;

            using (var devicestream = new DeviceStream(deviceName))
            {
                ulong platStart = 0;
                ulong platEnd   = 0;
                ulong dppStart  = 0;
                ulong dppEnd    = 0;

                ulong sbl1Start = 0;
                ulong sbl1End   = 0;

                Log.Debug("Reading device GPT...");

                // Code to find the PLAT and DPP FAT partition offsets
                devicestream.Seek(0, SeekOrigin.Begin);
                var buffer = new byte[diskSectorSize];

                while (Encoding.ASCII.GetString(buffer, 0, 8) != "EFI PART")
                {
                    devicestream.Read(buffer, 0, diskSectorSize);
                }

                var partentrycount = BitConverter.ToUInt32(buffer, 0x50);
                var partentrysize  = BitConverter.ToUInt32(buffer, 0x54);
                var bytestoread    = (int)Math.Round(partentrycount * partentrysize / (double)diskSectorSize,
                                                     MidpointRounding.AwayFromZero) * diskSectorSize;
                var partarray = new byte[bytestoread];
                devicestream.Read(partarray, 0, bytestoread);
                devicestream.Seek(0, SeekOrigin.Begin);

                using (var br = new BinaryReader(new MemoryStream(partarray)))
                {
                    var name = new byte[72]; // fixed name size
                    while (true)
                    {
                        var type = new Guid(br.ReadBytes(16));
                        if (type == Guid.Empty)
                        {
                            break;
                        }

                        br.BaseStream.Seek(16, SeekOrigin.Current);
                        var firstLba = br.ReadUInt64();
                        var lastLba  = br.ReadUInt64();
                        br.BaseStream.Seek(0x8, SeekOrigin.Current);
                        name = br.ReadBytes(name.Length);

                        var convname        = Encoding.Unicode.GetString(name).TrimEnd('\0');
                        var diskstartoffset = firstLba * (uint)diskSectorSize;
                        var diskendoffset   = lastLba * (uint)diskSectorSize;

                        if (convname == "PLAT")
                        {
                            Log.Debug("Found PLAT");

                            platStart = diskstartoffset;
                            platEnd   = diskendoffset;
                        }

                        if (convname == "DPP")
                        {
                            Log.Debug("Found DPP");

                            dppStart = diskstartoffset;
                            dppEnd   = diskendoffset;
                        }

                        if (convname == "SBL1")
                        {
                            Log.Debug("Found SBL1");

                            sbl1Start = diskstartoffset;
                            sbl1End   = diskendoffset;
                        }
                    }
                }

                var sbl1Partition = new byte[platEnd - platStart];

                Log.Debug("Reading SBL1 Partition");
                ChunkReader(devicestream, sbl1Partition, sbl1Start, sbl1End,
                            (int)sbl1End - (int)sbl1Start); // We can just read the whole thing in a single run from testing

                part = new QualcommPartition(sbl1Partition);

                // Initialize DiscUtils
                SetupHelper.SetupComplete();

                Log.Debug("Reading pconf.bin from file system...");

                using (var platFileSystem =
                           new FatFileSystem(new PartialStream(devicestream, (long)platStart, (long)platEnd))
                       ) //new MemoryStream(PLATPartition)))
                {
                    using (Stream platConf = platFileSystem.OpenFile(@"pconf.bin", FileMode.Open, FileAccess.Read))
                        using (var platConfigStream = new MemoryStream())
                        {
                            platConf.CopyTo(platConfigStream);
                            platconfig = platConfigStream.ToArray();
                        }
                }

                Log.Debug("Reading product.dat from file system...");

                using (var dppFileSystem =
                           new FatFileSystem(new PartialStream(devicestream, (long)dppStart, (long)dppEnd))
                       ) //new MemoryStream(DPPPartition)))
                {
                    var isMmo = dppFileSystem.DirectoryExists("MMO");
                    Log.Debug("Is the device a MMO device: " + isMmo);

                    // Properly handle earlier 950s/RX130s with Nokia folders.
                    using (Stream dppConf = dppFileSystem.OpenFile(isMmo ? @"MMO\product.dat" : @"Nokia\product.dat",
                                                                   FileMode.Open, FileAccess.Read))
                        using (var dppConfigStream = new MemoryStream())
                        {
                            dppConf.CopyTo(dppConfigStream);
                            dppconfig = dppConfigStream.ToArray();
                        }
                }
            }

            var ndate = DateTime.Now - time;

            Log.Debug("Finished in: " + ndate.TotalSeconds + " seconds.");

            Log.Debug("Drumroll...");
            Log.Debug("//////////////////");
            Log.Debug("product.dat");
            Log.Debug("//////////////////");

            // We now did read both product.dat and pconf.bin, you want to detect a device with pconf and check for the ID, if needed you can also read product.dat
            // Below are samples of pconf, you want to read NAME property. This is the device platform identifier.
            //
            // pconf.bin
            //
            // NAME=P6148
            // PKEY = 3
            // SWVERSION = 03030.00000.14256.02000

            var ddp  = ParseDpp(Encoding.ASCII.GetString(dppconfig));
            var plat = ParsePlat(Encoding.ASCII.GetString(platconfig));

            Log.Debug(BitConverter.ToString(part.RootKeyHash));

            return(new Lumia.PhoneInfo(ddp, plat, part.RootKeyHash));
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            if (args.Length != 3 && args.Length != 1 && args.Length != 2 && args.Length != 4)
            {
                Console.WriteLine("Usage:   StreamTerminal [<email> <password>] <device_id> [--echo]");
                Console.WriteLine("Example: StreamTerminal.exe echo.u.nabto.net");
                Console.WriteLine("         When the stream to echo.u.nabto.net is created select the echo service by typing 'echo<enter>' at the prompt.");
                Console.WriteLine("         Default user is 'guest'.");
                Console.WriteLine("         To enable local echo use the '--echo' switch.");
                Environment.Exit(1);
            }

            string email    = "guest";
            string password = "";
            string deviceId = "";

            if (args[0].Contains("@"))
            {
                email    = args[0];
                password = args[1];
                deviceId = args[2];
            }
            else
            {
                deviceId = args[0];
            }

            var localEcho = false;

            if (args[args.Length - 1] == "--echo")
            {
                localEcho = true;
            }

            if (!deviceId.Contains("."))
            {
                throw new Exception("Invalid device ID");
            }

            Console.WriteLine("Connecting...");

            try
            {
                Console.WriteLine("Starting Nabto...");
                NabtoClient nabto = new NabtoClient(); // Get a reference to the Nabto client runtime and start it up.

                Console.WriteLine("Creating session...");
                using (Session session = nabto.CreateSession(email, password)) // Create a session using the specified user credentials.
                {
                    Console.WriteLine("Creating connection to device...");
                    using (DeviceConnection deviceConnection = session.CreateDeviceConnection(deviceId)) // create connection to device
                    {
                        Console.WriteLine("Creating stream...");
                        using (DeviceStream stream = deviceConnection.CreateStream()) // create stream to device
                        {
                            var encoding      = new UTF8Encoding();
                            var run           = true;
                            var buffer        = new byte[1500];
                            var stringBuilder = new StringBuilder();

                            Console.WriteLine("Connected. Press ctrl+¨ to disconnect.");

                            while (run)
                            {
                                if (stream.DataAvailable)                                // data received from device?
                                {
                                    var length  = stream.Read(buffer, 0, buffer.Length); // read data into buffer
                                    var message = encoding.GetString(buffer, 0, length); // convert to text
                                    Console.Write(message);
                                }

                                if (Console.KeyAvailable)        // user input?
                                {
                                    while (Console.KeyAvailable) // read all user input
                                    {
                                        var key = Console.ReadKey(true);
                                        if (key.KeyChar == 0x1d) // terminate
                                        {
                                            run = false;
                                            Console.WriteLine();
                                            Console.WriteLine("Disconnecting...");
                                        }
                                        else if (key.Key == ConsoleKey.Enter)
                                        {
                                            stringBuilder.Append(Environment.NewLine);
                                        }
                                        else
                                        {
                                            stringBuilder.Append(key.KeyChar); // gather all characters from user
                                        }
                                    }

                                    if (stringBuilder.Length > 0)
                                    {
                                        var s = stringBuilder.ToString(); // text from user
                                        stringBuilder.Clear();

                                        var b = encoding.GetBytes(s); // convert to byte array
                                        stream.Write(b, 0, b.Length); // ...and send it to the device

                                        if (localEcho)
                                        {
                                            Console.Write(s);
                                        }
                                    }
                                }

                                Thread.Sleep(1);
                            }
                        }
                    }
                }

                Console.WriteLine("Disconnected.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }