コード例 #1
0
        public async Task <string> GetDeviceTypeCode()
        {
            var response = await DeviceStream.SendCommand(new GetDeviceTypeCommand(DeviceId));

            DeviceId = response.DeviceID;
            return(Bytes.GetAsciiString(response.DATA));
        }
コード例 #2
0
ファイル: SmartDeviceV2.cs プロジェクト: nicolasdeory/NzxtRGB
        /// <summary>
        /// Send color array in RGB format
        /// </summary>
        public void SendRGB(byte channel, byte[] colors)
        {
            if (channel != 1 && channel != 2)
            {
                throw new ArgumentException("Channel must be 1 or 2");
            }

            if (colors.Length % 3 != 0)
            {
                throw new ArgumentException("Color array length must be multiple of 3");
            }

            byte[] buffer = null;
            using (MemoryStream strm = new MemoryStream(4 + colors.Length * 3))
            {
                strm.Write(new byte[] { 0x22, 0x10, channel, 0x00 }, 0, 4);
                for (int i = 0; i < colors.Length / 3; i += 1)
                {
                    strm.Write(new byte[] { colors[i * 3 + 1], colors[i * 3], colors[i * 3 + 2] }, 0, 3);
                }
                buffer = strm.ToArray();
            }
            DeviceStream.Write(buffer);
            DeviceStream.Write(new byte[] { 0x22, 0x11, channel });
            //0x22,0xA0,0x02,0x00,0x01,0x00,0x00,0x10,0x00,0x00,0x80,0x00,0x32,0x00,0x00,0x01
            DeviceStream.Write(new byte[] { 0x22, 0xA0, channel, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x80, 0x00, 0x32, 0x00, 0x00, 0x01 });
        }
コード例 #3
0
 public async Task SetEmployeesData(List <UserInfo> users)
 {
     while (users.Count > 0)
     {
         await DeviceStream.SendCommand(new SetStaffDataCommand(DeviceId, users));
     }
 }
コード例 #4
0
        /// <summary>
        /// Refreshes the logical device.
        /// </summary>
        public void Refresh()
        {
            bootSector = null;
            data       = new UInt16[0];

            // Jump to FAT partition
            DeviceStream.Seek(partition.RelativeSector * PhysicalDevice.SectorSize, SeekOrigin.Begin);
            if (!partition.IsFAT)
            {
                return;
            }

            // Boot sector
            bootSector = (BootSector)StreamActivator.CreateInstance(typeof(BootSector), DeviceStream);
            DeviceStream.Seek(448, SeekOrigin.Current);

            // Failsafe .. be sure FAT partition table is valid
            if ((DeviceStream.ReadByte() != 0x55) || (DeviceStream.ReadByte() != 0xAA))
            {
                bootSector = null;
                return;
            }

            // Get FAT sector
            BinaryReader br = new BinaryReader(DeviceStream);

            data = new UInt16[bootSector.NumberOfFATs * ((bootSector.SectorsPerFAT * PhysicalDevice.SectorSize) / 2)];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = br.ReadUInt16();
            }
        }
コード例 #5
0
        public async Task <DateTime> GetDateTime()
        {
            var cmd      = new GetDateTimeCommand(DeviceId);
            var response = await DeviceStream.SendCommand(cmd);

            return(DateConversions.ByteArrayToDateTime(response.DATA));
        }
コード例 #6
0
        public async Task <ulong> GetDeviceID()
        {
            var response = await DeviceStream.SendCommand(new GetDeviceIDCommand(DeviceId));

            DeviceId = Bytes.Read(response.DATA);
            return(DeviceId);
        }
コード例 #7
0
        protected override Stream GetStreamInternal(Uri uri, FileMode mode, FileAccess access)
        {
            string path = GetPath(uri);

            long offset;

            if (!String.IsNullOrEmpty(uri.Fragment) && Int64.TryParse(HttpUtility.UrlDecode(uri.Fragment.Substring(1)), out offset))
            {
                DeviceStream stream;
                switch (mode)
                {
                case FileMode.Create:
                    stream = new DeviceStream(path, FileMode.OpenOrCreate, access);
                    stream.SetLength(offset);
                    break;

                case FileMode.Truncate:
                    stream = new DeviceStream(path, FileMode.Open, access);
                    stream.SetLength(offset);
                    break;

                default:
                    stream = new DeviceStream(path, mode, access);
                    break;
                }
                stream.Seek(offset, SeekOrigin.Begin);
                return(stream);
            }
            else
            {
                return(new DeviceStream(path, mode, access));
            }
        }
コード例 #8
0
ファイル: SmartDeviceV2.cs プロジェクト: nicolasdeory/NzxtRGB
        /// <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;
            });
        }
コード例 #9
0
        public async Task <byte[]> EnrollFingerprint(ulong employeeID)
        {
            await DeviceStream.SendCommand(new EnrollFingerprintCommand(DeviceId, employeeID, true));

            await DeviceStream.SendCommand(new EnrollFingerprintCommand(DeviceId, employeeID, false));

            return(await GetFingerprintTemplate(employeeID, 0));
        }
コード例 #10
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);
        }
コード例 #11
0
        internal void Register(DeviceStream deviceStream)
        {
            lock (deviceStreams)
            {
                Log.Write("DeviceConnnection.Register<NabtoStream>()");

                deviceStreams.Add(deviceStream);
            }
        }
コード例 #12
0
ファイル: SetDeviceIDCommand.cs プロジェクト: xiltoos/Anviz
        public async Task SetDeviceID(ulong newDeviceId)
        {
            await DeviceStream.SendCommand(new SetDeviceIDCommand(DeviceId, newDeviceId));

            if (DeviceId != 0)
            {
                DeviceId = newDeviceId;
            }
        }
コード例 #13
0
        internal void Unregister(DeviceStream deviceStream)
        {
            lock (deviceStreams)
            {
                Log.Write("DeviceConnnection.Unregister<NabtoStream>()");

                deviceStreams.Remove(deviceStream);

                CheckForImplicitDispose();
            }
        }
コード例 #14
0
        protected override void GivenThat()
        {
            base.GivenThat();

            Stream = GenerateMock <IStream>();

            // Make seek return a non-zero position
            Stream.Stub(stream => stream.Seek(0, 0, IntPtr.Zero))
            .IgnoreArguments()
            .WhenCalled(invocation => Marshal.WriteInt64((IntPtr)invocation.Arguments[2], 1234));

            DeviceStream = new DeviceStream(Stream);
        }
コード例 #15
0
        public async Task <List <ScheduledBell> > GetScheduledBells()
        {
            var response = await DeviceStream.SendCommand(new GetScheduledBellsCommand(DeviceId));

            var bells   = new List <ScheduledBell>(ScheduledBell.MAX_SCHEDULED_BELL_SLOT);
            var counter = 0;

            while (counter < response.DATA.Length)
            {
                bells.Add(new ScheduledBell(response.DATA, counter));
                counter += ScheduledBell.RECORD_LENGTH;
            }
            return(bells);
        }
コード例 #16
0
        public async Task <byte[]> EnrollFingerprint(ulong employeeID, int verifyCount = 2)
        {
            if (verifyCount < 1)
            {
                throw new ArgumentException("verifyCount should be at least 1");
            }
            var first = true;

            while (verifyCount-- > 0)
            {
                await DeviceStream.SendCommand(new EnrollFingerprintCommand(DeviceId, employeeID, first));

                first = false;
            }
            return(await GetFingerprintTemplate(employeeID, 0));
        }
コード例 #17
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));
        }
コード例 #18
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);
        }
コード例 #19
0
        public async Task <ActionResult> ConnectSSH([FromBody] SshRequest request)
        {
            // return Bad request
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                // Create SSH streaming. This will run in separate thread, so that it won't block the main process
                DeviceStream deviceStream = new DeviceStream();
                await Task.Factory.StartNew(() => deviceStream.StartAsync(request));

                return(Ok("Connected"));
            }
            catch (Exception ex)
            {
                throw new ApiException(ex.Message);
            }
        }
コード例 #20
0
ファイル: GetRecordsCommand.cs プロジェクト: xiltoos/Anviz
        public async Task <List <Record> > DownloadRecords(bool onlyNew = false)
        {
            var statistics = await GetDownloadInformation();

            var recordAmount = onlyNew ? statistics.NewRecordAmount : statistics.AllRecordAmount;
            var records      = new List <Record>((int)recordAmount);
            var isFirst      = true;

            while (recordAmount > 0)
            {
                var response = await DeviceStream.SendCommand(new GetRecordsCommand(DeviceId, isFirst, onlyNew, recordAmount));

                var counter = response.DATA[0];
                recordAmount -= counter;
                for (var i = 0; i < counter; i++)
                {
                    records.Add(new Record(response.DATA, 1 + i * Record.RECORD_LENGTH));
                }
                isFirst = false;
            }
            return(records);
        }
コード例 #21
0
ファイル: GetStaffDataCommand.cs プロジェクト: xiltoos/Anviz
        public async Task <List <UserInfo> > GetEmployeesData()
        {
            var statistics = await GetDownloadInformation();

            var userAmount = statistics.UserAmount;
            var users      = new List <UserInfo>((int)userAmount);
            var isFirst    = true;

            while (userAmount > 0)
            {
                var response = await DeviceStream.SendCommand(new GetStaffDataCommand(DeviceId, isFirst, userAmount));

                var counter = response.DATA[0];
                userAmount -= counter;
                for (var i = 0; i < counter; i++)
                {
                    users.Add(new UserInfo(response.DATA, 1 + i * UserInfo.RECORD_LENGTH));
                }
                isFirst = false;
            }
            return(users);
        }
コード例 #22
0
        public static void WriteBootLoaderToDisk(string DiskId, IDeviceProfile deviceProfile)
        {
            var          chunkSize = 131072;
            DeviceStream ds        = new DeviceStream(DiskId, FileAccess.ReadWrite);

            ds.Seek(0, SeekOrigin.Begin);
            byte[] bootloader = File.ReadAllBytes(deviceProfile.Bootloader());

            var sectors = bootloader.Count() / chunkSize;

            DateTime startTime = DateTime.Now;

            using (BinaryReader br = new BinaryReader(new MemoryStream(bootloader)))
                for (int i = 0; i < sectors; i++)
                {
                    var buff = br.ReadBytes(chunkSize);
                    ds.Write(buff, 0, chunkSize);
                    Logging.ShowProgress((UInt64)bootloader.Count(), startTime, (UInt64)((i + 1) * chunkSize), (UInt64)((i + 1) * chunkSize), false);
                }
            Logging.Log("");

            ds.Dispose();
        }
コード例 #23
0
ファイル: ErosTek232.cs プロジェクト: culturespy/ZapU
        private void TransmitCommand()
        {
            ET232Command command = null;

            lock (_thread_interlock)
            {
                if (CommandQueue.Count > 0)
                {
                    command = CommandQueue.First();
                    CommandQueue.RemoveAt(0);
                }
            }

            if (command != null)
            {
                if (command.IsWrite())
                {
                    if (command.Address == AddressByte.Pot_A)
                    {
                        lock (_thread_interlock) command.Data = Governor.RegulateA(command.Data);
                    }
                    if (command.Address == AddressByte.Pot_B)
                    {
                        lock (_thread_interlock) command.Data = Governor.RegulateB(command.Data);
                    }
                }

                byte[] data = command.Format();
                last_command      = command;
                last_command_time = UnixTime.Current();
                lock (_thread_interlock)
                {
                    DeviceStream.Write(data, 0, data.Length);
                    _state = State.command;
                }
            }
        }
コード例 #24
0
ファイル: NANDService.cs プロジェクト: SIMOMEGA/HACGUI
 private static void Refresh()
 {
     foreach (DiskInfo info in CreateDiskInfos(GetDisks()))
     {
         if (info.Model == "Linux UMS disk 0 USB Device" && info.Partitions > 1) // probably a bad way of filtering?
         {
             try
             {
                 IEnumerable <PartitionInfo> partitions =
                     CreatePartitionInfos(GetPartitions())
                     .Where((p) => info.Index == p.DiskIndex)
                     .OrderBy((p) => p.Index);
                 if (!partitions.Any())
                 {
                     continue; // obv the NAND should have *some* partitions
                 }
                 PartitionInfo lastPartition = partitions.Last();
                 long          length        = (long)(lastPartition.Size + lastPartition.StartingOffset);
                 // thx windows for ignoring the GPT backup AND reporting the size of the disk incorrectly...
                 long missingLength = (0x747BFFE00 - 0x727800000) + 0x200; // (start of GPT backup - end of USER) + length of GPT backup
                 length += missingLength;
                 DeviceStream stream      = new DeviceStream(info.PhysicalName, length);
                 IStorage     diskStorage = new CachedStorage(stream.AsStorage().AsReadOnly(), info.SectorSize * 100, 4, true);
                 if (InsertNAND(diskStorage, true))
                 {
                     CurrentDisk = info;
                     break;
                 }
             }
             catch (UnauthorizedAccessException)
             {
                 MessageBox.Show("Cannot get direct access drive due to lack of permissions.\nReopen HACGUI as administrator to use the plugged in NAND.");
             }
         }
     }
 }
コード例 #25
0
 public async Task DeleteAllRecords()
 {
     await DeviceStream.SendCommand(new ClearRecordsCommand(DeviceId, ClearRecordsCommand.DELETE_ALL, 0));
 }
コード例 #26
0
 public async Task ClearNewRecords(ulong amount)
 {
     await DeviceStream.SendCommand(new ClearRecordsCommand(DeviceId, ClearRecordsCommand.CLEAR_AMOUNT, amount));
 }
コード例 #27
0
 public async Task ClearNewRecords()
 {
     await DeviceStream.SendCommand(new ClearRecordsCommand(DeviceId, ClearRecordsCommand.CLEAR_ALL, 0));
 }
コード例 #28
0
 public async Task SetFaceTemplate(ulong employeeID, byte[] template)
 {
     await DeviceStream.SendCommand(new SetFaceTemplateCommand(DeviceId, employeeID, template));
 }
コード例 #29
0
 public async Task SetAdvancedSettings(AdvancedSettings value)
 {
     await DeviceStream.SendCommand(new SetAdvancedSettingsCommand(DeviceId, value));
 }
コード例 #30
0
 public async Task SetTimeZoneInfo(byte number, AnvizTimeZone value)
 {
     await DeviceStream.SendCommand(new SetTimeZoneInfoCommand(DeviceId, number, value));
 }