На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Страницы: (3) 1 [2] 3  все  ( Перейти к последнему сообщению )  
> Не могу достучаться до считывателя. , Не могу достучаться до считывателя.
    Я как к ком порту достучатся не могу, но использую usb библиотеку я его хоть увидел.
      Проблемы при программировании считывателя.

      http://www.cyberforum.ru/csharp-beginners/thread1945239.html

      http://www.sql.ru/forum/1254609/ne-polucha...ya-s-komputerom

      Dmitriy78781 = dodik78781 = AlexNon = son456 :fool:

      Интересная формула получается :popcorn:
      Сообщение отредактировано: Кракозя -
        Достучался к usb и приходят данные:
        ExpandedWrap disabled
          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using LibUsbDotNet;
          using LibUsbDotNet.DeviceNotify;
          using LibUsbDotNet.Main;
           
          namespace HidUsb
          {
              class Program
              {
                  public static UsbDevice MyUsbDevice;
           
                  #region SET YOUR USB Vendor and Product ID!
           
           
                  public static UsbDeviceFinder MyUsbFinder;
           
                  #endregion
           
                  static void Main(string[] args)
                  {
           
           
                      ErrorCode ec = ErrorCode.None;
           
                      try
                      {
                          MyUsbFinder = new UsbDeviceFinder(Int32.Parse("0403", System.Globalization.NumberStyles.AllowHexSpecifier), Int32.Parse("6001", System.Globalization.NumberStyles.AllowHexSpecifier));
                          // Find and open the usb device.
                          MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
           
                          // If the device is open and ready
                          if (MyUsbDevice == null) throw new Exception("Device Not Found.");
           
                          //Console.WriteLine(MyUsbDevice.Info.ProductString);
                          //Console.ReadKey();
                          // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                          // it exposes an IUsbDevice interface. If not (WinUSB) the
                          // 'wholeUsbDevice' variable will be null indicating this is
                          // an interface of a device; it does not require or support
                          // configuration and interface selection.
                          IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                          if (!ReferenceEquals(wholeUsbDevice, null))
                          {
                              // This is a "whole" USB device. Before it can be used,
                              // the desired configuration and interface must be selected.
           
                              // Select config #1
                              wholeUsbDevice.SetConfiguration(1);
           
                              // Claim interface #0.
                              wholeUsbDevice.ClaimInterface(0);
                          }
                        
                          
           
                          // open write endpoint
                          UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
           
                          // write data, read data
                          int bytesWritten;
                          ec = writer.Write(new byte[] { 0x10, 0x02, 0xC1, 0x05, 0x00, 0x02, 0x03, 0x0A, 0x00, 0x11, 0xf3 }, 2000, out bytesWritten); // specify data to send
           
                          if (ec != ErrorCode.None)
                              throw new Exception(UsbDevice.LastErrorString);
           
                          // open read endpoint
                          UsbEndpointReader reader =
                          MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
           
                          byte[] readBuffer = new byte[1024];
                          while (ec == ErrorCode.None)
                          {
                              int bytesRead;
           
                              // If the device hasn't sent data in the last 100 milliseconds,
                              // a timeout error (ec = IoTimedOut) will occur.
                              ec = reader.Read(readBuffer, 250, out bytesRead);
           
                              if (bytesRead == 0)
                                  throw new Exception("No more bytes!");
           
                              // Write that output to the console.
                              Console.WriteLine(BitConverter.ToString(readBuffer, 0, bytesRead));
                          }
                          
                      }
                      catch (Exception ex)
                      {
                          Console.WriteLine();
                          Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
                      }
                      finally
                      {
                          if (MyUsbDevice != null)
                          {
                              if (MyUsbDevice.IsOpen)
                              {
                                  // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                                  // it exposes an IUsbDevice interface. If not (WinUSB) the
                                  // 'wholeUsbDevice' variable will be null indicating this is
                                  // an interface of a device; it does not require or support
                                  // configuration and interface selection.
                                  IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                                  if (!ReferenceEquals(wholeUsbDevice, null))
                                  {
                                      // Release interface #0.
                                      wholeUsbDevice.ReleaseInterface(0);
                                  }
           
                                  MyUsbDevice.Close();
                              }
                              MyUsbDevice = null;
           
                              // Free usb resources
                              UsbDevice.Exit();
           
                          }
           
                          // Wait for user input..
                          Console.ReadKey();
                      }
                  }
           
           
              }
          }


        Добавлено
        Данные 01-60
          Dmitriy78781 А самому слабо что-нибудь сделать? Только тонны говнокодов постить по форумам?
          Скрытый текст
          user posted image
            Кракозя, у нас запрещено оскорблять участников. Если не можешь сказать что то по существу, не разводи флейм в тематических ветках.

            Цитата Кракозя @
            Данные 01-60

            Это не ответ вашего устройства. Ещё раз гляньте протокол, оно ответит либо 7 байт (ошибка), либо 12 (операция завершена успешно). Про два байта там информации нет.

            Добавлено
            В общем, попытайтесь определить, работает устройство или нет. Такое ощущение, что так упорно молчит оно не с проста...
              Дело в том что это устройство я открыть могу и даже послать данные, но получить не получается.
              Такая же ситуация с программой Terminal. Там я устанавливаю настройки, открываю порт, вижу что данные передаются(в строке состояния написано порт открыт, Тх постоянно меняется, но Rx постоянно ноль). Такая же ситуация если установить DTR, RTS.
                VisualProg, а где Вы, уважаемый, увидели оскорбление? Излагаются только факты просто космических :sarcasm: способностей данного субьекта, с целью показать бесполезность всех побуждений помочь. :popcorn:
                  Дело в том что это устройство я открыть могу и даже послать данные, но получить не получается.
                  Такая же ситуация с программой Terminal. Там я устанавливаю настройки, открываю порт, вижу что данные передаются(в строке состояния написано порт открыт, Тх постоянно меняется, но Rx постоянно ноль). Такая же ситуация если установить DTR, RTS.
                    Возможно что под windows7 x64 где-то стоит запрет на прием и передачу?
                      Цитата Dmitriy78781 @
                      Возможно что под windows7 x64 где-то стоит запрет на прием и передачу?

                      Переустанови винду, может поможет.
                        Цитата Dmitriy78781 @
                        Возможно что под windows7 x64 где-то стоит запрет на прием и передачу?

                        Вряд ли... обычно, ОС не рулит драйверами. (отключать их может, но, тогда бы вы не видели это устройство в диспетчере, даже не устройство, а то к чему оно подключено - будь то виртуальный USB/COM порт, или реальный). Сами посудите, это как блокировать один из пинов USB порта - не то что бессмысленно, даже, в некотором роде, потенциально опасно для компьютера. Проще заблокировать порт целиком, с его интерфейсом и забыть как с ним общаться - что и реализовано в ОС. Из двух вариантов - работает/не работает - в вашем случае, ОС даёт полноценную работу с устройством.

                        Цитата
                        Тх постоянно меняется, но Rx постоянно ноль


                        ИМХО, на стороне компьютера всё в рабочем состоянии. Тем более, если вы пользовались терминалом - сомнений остаться не должно. (Не доверять терминалу не вижу смысла)
                        Либо устройство не посылает ответ, либо что то ему мешает это сделать.

                        С подобным не сталкивался, поэтому сказать конкретно в чём дело не могу - тут всё зависит от вашего устройства.
                        Сообщение отредактировано: VisualProg -
                          Так как это устройство имеет драйвер FTDI, то я стал работать с ним, но тоже ничего не выдает.
                          ExpandedWrap disabled
                            using System;
                            using System.Collections.Generic;
                            using System.Linq;
                            using System.Text;
                            using System.Threading;
                             
                            using FTD2XX_NET;
                             
                            namespace ComPortConsole
                            {
                                class Program
                                {
                                    
                                    static void Main(string[] args)
                                    {
                                        UInt32 ftdiDeviceCount = 0;
                                        FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
                             
                                        // Create new instance of the FTDI device class
                                        FTDI myFtdiDevice = new FTDI();
                             
                                        // Determine the number of FTDI devices connected to the machine
                                        ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
                                        // Check status
                                        if (ftStatus == FTDI.FT_STATUS.FT_OK)
                                        {
                                            //Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString());
                                            //Console.WriteLine("");
                                        }
                                        else
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                             
                                        // If no devices available, return
                                        if (ftdiDeviceCount == 0)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                             
                                        // Allocate storage for device info list
                                        FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
                             
                                        // Populate our device list
                                        ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);
                             
                                        /*if (ftStatus == FTDI.FT_STATUS.FT_OK)
                                        {
                                            for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                                            {
                                                Console.WriteLine("Device Index: " + i.ToString());
                                                Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                                                Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString());
                                                Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                                                Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                                                Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                                                Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString());
                                                Console.WriteLine("");
                                            }
                                        }*/
                             
                             
                                        // Open first device in our list by serial number
                                        ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                             
                                        // Set up device data parameters
                                        // Set Baud rate to 9600
                                        ftStatus = myFtdiDevice.SetBaudRate(9600);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to set Baud rate (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                             
                                        // Set data characteristics - Data bits, Stop bits, Parity
                                        ftStatus = myFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_EVEN);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                                      
                                        // Set flow control - set RTS/CTS flow control
                                        ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, 0x13);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to set flow control (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                                        
                                        // Set read timeout to 5 seconds, write timeout to infinite
                                        ftStatus = myFtdiDevice.SetTimeouts(25, 25);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to set timeouts (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                                        // Сбросим входные и выходные буфера.
                                        ftStatus = myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_TX);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                                        ftStatus = myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                                        // Perform loop back - make sure loop back connector is fitted to the device
                                        // Write string data to the device
                                        //string dataToWrite = "Hello world!";
                                        // ,0x10, 0x02, 0xC1, 0x05, 0x00, 0x02, 0x03, 0x0A, 0x00, 0x11, 0xf3
                                        //,     0x10,0x02,0xc3,0x00,0x11,0xe6
                                        byte[] dataToWrite = new byte[] { 0x10, 0x02, 0xc3, 0x00, 0x11, 0xe6 };
                             
                                        UInt32 numBytesWritten = 0;
                                        // Note that the Write method is overloaded, so can write string or byte array data
                                        ftStatus = myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to write to device (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                             
                             
                                        // Check the amount of data available to read
                                        // In this case we know how much data we are expecting,
                                        // so wait until we have all of the bytes we have sent.
                                        /*UInt32 numBytesAvailable = 0;
                                        do
                                        {
                                            ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);
                                            if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                            {
                                                // Wait for a key press
                                                Console.WriteLine("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                                                Console.ReadKey();
                                                return;
                                            }
                                            Thread.Sleep(10);
                                        } while (numBytesAvailable < dataToWrite.Length);
                             
                                        // Now that we have the amount of data we want available, read it
                                        string readData;
                                        UInt32 numBytesRead = 0;
                                        // Note that the Read method is overloaded, so can read string or byte array data
                                        ftStatus = myFtdiDevice.Read(out readData, numBytesAvailable, ref numBytesRead);
                                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                        {
                                            // Wait for a key press
                                            Console.WriteLine("Failed to read data (error " + ftStatus.ToString() + ")");
                                            Console.ReadKey();
                                            return;
                                        }
                                        Console.WriteLine(String.Format("{0:X}", readData));*/
                             
                             
                             
                             
                                        UInt32 numBytesAvailable = 0;
                                        string readData = "";
                                        while (true)
                                        {
                             
                                            
                                            UInt32 numBytesRead = 0;
                                            ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);
                                            if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                            {
                                                Console.WriteLine("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                                                Console.ReadKey();
                                                break;
                                            }
                             
                                            readData = "";
                                            
                                            
                                            // Note that the Read method is overloaded, so can read string or byte array data
                                            ftStatus = myFtdiDevice.Read(out readData, numBytesAvailable, ref numBytesRead);
                             
                                            Console.WriteLine(String.Format("{0:X}", readData.ToString()));
                                            Console.ReadKey();
                                            Thread.Sleep(25); // Sleep 10 seconds.
                                            
                                        }
                                        
                                        
                                        
                             
                             
                             
                             
                                        // Close our device
                                        ftStatus = myFtdiDevice.Close();
                             
                                        // Wait for a key press
                                        Console.WriteLine("Press any key to continue.");
                                        Console.ReadKey();
                                        return;
                                    }
                                }
                            }
                            Цитата
                            using FTD2XX_NET;


                            Начиная с этой строчки, Ваш код уже "бесполезен" для читающего) Вряд ли кто то вкурсе что там у вас подключено...
                              Компания FTDI предоставляет на платформе Windows управляемый класс-обертку (managed .NET wrapper class) для функций FTD2XX DLL.
                              ExpandedWrap disabled
                                using FTD2XX_NET;

                              Здесь все есть:
                              http://microsin.net/programming/pc/ftdi-de...rom-csharp.html
                                Считаю свой вопрос в #15 всё ещё актуальным.

                                Устройство видно как компорт - вот с портом и разбираться надо, протокол в точности реализовать, адрес опять же правильный использовать. Постараться добыть родную программу.
                                0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
                                0 пользователей:
                                Страницы: (3) 1 [2] 3  все


                                Рейтинг@Mail.ru
                                [ Script execution time: 0,0543 ]   [ 17 queries used ]   [ Generated: 19.04.24, 21:11 GMT ]