Exemplo n.º 1
0
        public void SetRtc(DateTime rtcTime)
        {
            StxEtxMemoryStream stream = new StxEtxMemoryStream();

            stream.StartPacket();
            stream.WriteByte((byte)Commands.SetRtc);
            stream.WriteByte(ConvertToBcd(rtcTime.Second));
            stream.WriteByte(ConvertToBcd(rtcTime.Minute));
            stream.WriteByte(ConvertToBcd(rtcTime.Hour));
            byte dayOfWeek = (byte)rtcTime.DayOfWeek;

            if (rtcTime.DayOfWeek == DayOfWeek.Sunday)
            {
                dayOfWeek = 7;
            }
            stream.WriteByte(dayOfWeek);
            stream.WriteByte(ConvertToBcd(rtcTime.Day));
            stream.WriteByte(ConvertToBcd(rtcTime.Month));
            stream.WriteByte(ConvertToBcd((rtcTime.Year - 2000)));
            stream.EndPacket();
            byte[]    bytes        = stream.GetBytes();
            uint      bytesWritten = 0;
            FT_STATUS status       = _Ftdi.Write(bytes, bytes.Length, ref bytesWritten);

            if (status != FT_STATUS.FT_OK)
            {
                throw new Exception("Error writing data (SetRtc)");
            }
            if (bytesWritten != bytes.Length)
            {
                throw new Exception("Wrong number of bytes written (SetRtc)");
            }
        }
        /* Function : FTDI_SendData
         * Author	: ENTTEC
         * Purpose  : Send Data (DMX or other packets) to the PRO
         * Parameters: Label, Pointer to Data Structure, Length of Data
         * Modified by Gareth Evans, Sniper Systems to convert this to c# for use
         */
        private bool FTDI_SendData(FT_HANDLE handle, int label, byte[] data, ref FT_STATUS status)
        {
            if (Connected)
            {
                int bytes_written = 0;
                //int size = 0;
                // Form Packet Header
                byte[] header = GetProHeader(label, data.Length);
                byte[] footer = new byte[1] {
                    DMX_END_CODE
                };
                byte[] packet = header.Concat(data).Concat(footer).ToArray();
                //Console.WriteLine("Write: {0}", Sniper.Common.Conversion.ToHex(true, packet));
                bytes_written = write(handle, packet, packet.Length);
                if (bytes_written != packet.Length)
                {
                    return(false);
                }

                if (status == FT_STATUS.FT_OK)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(false);
        }
Exemplo n.º 3
0
        public byte[] ReadSramPage()
        {
            Console.WriteLine("ReadSramPage");

            byte[] cmdData = new byte[] {
                (byte)Commands.SramRead
            };

            StxEtxPacket packet = new StxEtxPacket(cmdData);

            byte[]    bytes        = packet.GetBytes();
            uint      bytesWritten = 0;
            FT_STATUS status       = _Ftdi.Write(bytes, bytes.Length, ref bytesWritten);

            if (status != FT_STATUS.FT_OK)
            {
                throw new Exception("Error writing data (ReadSramPage)");
            }
            if (bytesWritten != bytes.Length)
            {
                throw new Exception("Wrong number of bytes written (ReadSramPage)");
            }

            return(ReceiveResponse());
        }
Exemplo n.º 4
0
        public unsafe bool WriteAndReadBytes(byte[] outData, out byte[] inData, UInt32 bytes)
        {
            FT_STATUS ftStatus     = FT_STATUS.FT_OTHER_ERROR;
            UInt32    inByteCount  = 0;
            UInt32    outByteCount = 0;

            inData = new byte[bytes];

            if (CheckConnect())
            {
                // Empty input buffer before trying to read
                ftStatus = FT_Purge(ftHandle, (UInt32)(FT_PURGE_FLAGS.FT_PURGE_RX | FT_PURGE_FLAGS.FT_PURGE_TX));

                if (ftStatus == FT_STATUS.FT_OK)
                {
                    fixed(byte *pbyBuffer = outData)
                    ftStatus = FT_Write(ftHandle, pbyBuffer, bytes, ref outByteCount);

                    if (ftStatus == FT_STATUS.FT_OK)
                    {
                        fixed(byte *pbyBuffer = inData)
                        ftStatus = FT_Read(ftHandle, pbyBuffer, bytes, ref inByteCount);
                    }
                }
            }
            return((ftStatus == FT_STATUS.FT_OK) && (inByteCount == bytes) && (outByteCount == bytes));
        }
Exemplo n.º 5
0
        private byte[] ReceiveResponse()
        {
            byte[]       result = null;
            StxEtxParser parser = new StxEtxParser();

            parser.PacketComplete += new StxEtxParser.PacketCompleteHandler((par, data) => {
                result = data;
            });

            while (result == null)
            {
                if (_WaitHandle.WaitOne(1000) == false)
                {
                    throw new Exception("Error reading data (ReceiveResponse)");
                }

                uint rxBytes = 0;
                _Ftdi.GetRxBytesAvailable(ref rxBytes);
                if (rxBytes > 0)
                {
                    byte[]    readBuffer = new byte[rxBytes];
                    uint      readBytes  = 0;
                    FT_STATUS status     = _Ftdi.Read(readBuffer, (uint)readBuffer.Length, ref readBytes);
                    if (status != FT_STATUS.FT_OK)
                    {
                        throw new Exception("Error reading data (ReceiveResponse)");
                    }
                    parser.Parse(readBuffer, 0, (int)readBytes);
                }
            }

            return(result);
        }
Exemplo n.º 6
0
        protected virtual void writeDMXBuffer()
        {
            while (!done)
            {
                newData = BuildBufferFromQueues();
                try
                {
                    if (Connected)
                    {
                        if (newData)
                        {
                            FT_STATUS status = FT_STATUS.FT_OK;
                            if (!FTDI_SendData(handle, SET_DMX_TX_MODE, (new byte[1]).Concat(buffer).ToArray(), ref status))
                            {
                                break;
                            }
                            newData = false;
                        }

                        System.Threading.Thread.Sleep(25);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(25);
                    }
                }
                catch (Exception)
                {
                    break;
                }
            }
            Connected = false;
            done      = false;
        }
Exemplo n.º 7
0
 static void TestStatus(FT_STATUS status)
 {
     if (status != FT_STATUS.FT_OK)
     {
         throw new DMXException(status);
     }
 }
Exemplo n.º 8
0
        public override void Start()
        {
            try
            {
                var ports = SerialPort.GetPortNames();
                foreach (string port in ports)
                {
                    SerialPort sPort = new SerialPort(port);
                    sPort.Open();
                    sPort.Close();
                    sPort.Dispose();
                }
            }
            catch
            {
            }

            handle = 0;
            status = FT_Open(0, ref handle);
            Console.WriteLine("[DRIVER STATUS] " + status.ToString());

            InitOpenDMX();

            done       = false;
            workThread = new Thread(new ThreadStart(writeData));
            workThread.Start();
        }
Exemplo n.º 9
0
        public FT_STATUS I2C_ReadByte(byte slaveAddress, uint deviceAddress, ref byte data)
        {
            FT_STATUS status          = FT_STATUS.FT_OK;
            uint      bytesToTransfer = 0;
            uint      bytesTransfered = 0;

            byte[] buffer = new byte[2];

            buffer[bytesToTransfer++] = (byte)deviceAddress;
            buffer[bytesToTransfer++] = (byte)(deviceAddress >> 8);

            status = I2C_DeviceWrite(handle, slaveAddress, bytesToTransfer, buffer, ref bytesTransfered,
                                     I2C_TRANSFER_OPTIONS_START_BIT);

            APP_CHECK_STATUS(status);

            bytesToTransfer = 1;
            bytesTransfered = 0;
            buffer          = new byte[1];
            status         |= I2C_DeviceRead(handle, slaveAddress, bytesToTransfer, buffer, ref bytesTransfered,
                                             I2C_TRANSFER_OPTIONS_START_BIT | I2C_TRANSFER_OPTIONS_NACK_LAST_BYTE);

            APP_CHECK_STATUS(status);

            data = buffer[0];
            return(status);
        }
        /// <summary>
        /// CBUSの設定を変更する
        /// </summary>
        /// <param name="configs"></param>
        public void SetCBusConfig(CBUSConfig configs)
        {
            if (!IsOpen())
            {
                throw new InvalidOperationException("Connection is not opened yet.");
            }

            // EEPROM読込み
            eeprom = new FT232R_EEPROM_STRUCTURE();
            FT_STATUS ret = ftdi.ReadFT232REEPROM(eeprom);

            if (ret != FT_STATUS.FT_OK)
            {
                throw new InvalidOperationException("Failed to read EEPROM. FT_STATUS=" + ret);
            }

            // 設定が異なる場合のみ、EEPROMに書き込み
            if (eeprom.Cbus0 != configs.cbus0 ||
                eeprom.Cbus1 != configs.cbus1 ||
                eeprom.Cbus2 != configs.cbus2 ||
                eeprom.Cbus3 != configs.cbus3)
            {
                eeprom.Cbus0 = configs.cbus0;
                eeprom.Cbus1 = configs.cbus1;
                eeprom.Cbus2 = configs.cbus2;
                eeprom.Cbus3 = configs.cbus3;
                ret          = ftdi.WriteFT232REEPROM(eeprom);
                if (ret != FT_STATUS.FT_OK)
                {
                    throw new InvalidOperationException("Failed to write EEPROM. FT_STATUS=" + ret);
                }
            }
        }
Exemplo n.º 11
0
        void OpenFtdiDeviceThenWaitAndWrite()
        {
            Console.WriteLine("Starting DMX Frame sender thread : id {0} [{1}]", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name);
            uint handle = 0;

            try
            {
                status = FtdiDevice.FT_Open(0, ref handle).CheckStatus("FT_Open()");
            }
            catch (System.DllNotFoundException dllExc)
            {
                Console.WriteLine("DllException : " + dllExc.Message);
                Console.WriteLine("OpenDMX serial chipset driver may not be installed in your system !");
                Console.WriteLine("You can download the latest version here : http://www.ftdichip.com/Drivers/D2XX.htm");
                Console.WriteLine("Your DMX interface can not be used, is not correctly installed or is not recognized.");
                return;
            }
            if (status != FT_STATUS.FT_OK)
            {
                if (status == FT_STATUS.FT_DEVICE_NOT_FOUND)
                {
                    Console.WriteLine("No OpenDMX Interface.");
                    return;
                }
                else
                {
                    Console.WriteLine($"ERROR : unknow error in FT_Open() : {status}");
                }
            }
            Console.WriteLine("OpenDMX interface found.");
            WriteDmxDataLoop(handle);
        }
Exemplo n.º 12
0
        public void WriteSram(int pageAddr, byte[] data)
        {
            if ((pageAddr % 1) != 0)
            {
                throw new ArgumentException("pageAddr must be word aligned");
            }

            StxEtxMemoryStream stream = new StxEtxMemoryStream();

            int addr = pageAddr / 2;

            stream.StartPacket();
            stream.WriteByte((byte)Commands.SetAddr);
            WriteIntBe(stream, addr);
            stream.EndPacket();

            stream.StartPacket();
            stream.WriteByte((byte)Commands.SramWrite);
            stream.Write(data, 0, data.Length);
            stream.EndPacket();

            byte[]    bytes        = stream.GetBytes();
            uint      bytesWritten = 0;
            FT_STATUS status       = _Ftdi.Write(bytes, bytes.Length, ref bytesWritten);

            if (status != FT_STATUS.FT_OK)
            {
                throw new Exception("Error writing data (WriteSram)");
            }
            if (bytesWritten != bytes.Length)
            {
                throw new Exception("Wrong number of bytes written (WriteSram)");
            }
            _PendingAck++;
        }
Exemplo n.º 13
0
        unsafe public byte[] Read(UInt32 rxCount)
        {
            UInt32    dwRet    = 0;
            FT_STATUS ftStatus = FT_STATUS.FT_OTHER_ERROR;

            byte[] cBuf = new byte[3];

            cBuf[0] = (byte)'!';
            cBuf[1] = (byte)0; // PORT A
            cBuf[2] = 0xFF;
            // write the direction to output
            fixed(byte *pBuf = cBuf)
            {
                ftStatus = FT_Write(m_hPort, pBuf, 3, ref dwRet);
                if (ftStatus != FT_STATUS.FT_OK && dwRet != 3)
                {
                    throw (new SystemException("Error WriteDirection"));
                }
            }

            fixed(byte *pBuf = cBuf)
            {
                ftStatus = FT_Read(m_hPort, pBuf, rxCount, ref dwRet);
            }

            if (ftStatus != FT_STATUS.FT_OK)
            {
                return(null);
            }

            return(cBuf);
        }
Exemplo n.º 14
0
        unsafe public byte[] ReadValue_SPI(UInt32 rxCount)
        {
            UInt32    dwRet    = 0;
            FT_STATUS ftStatus = FT_STATUS.FT_OTHER_ERROR;

            byte[] cBuf = new byte[rxCount];

            dwRet = 0;
            long timeout;

            timeout = 0;

            do
            {
                ftStatus = FT_GetQueueStatus(m_hPort, ref dwRet);
                timeout++;
            } while ((dwRet < rxCount) && (timeout < 100000));

            if (timeout == 100000)
            {
                return(null);
            }

            fixed(byte *pBuf = cBuf)
            {
                ftStatus = FT_Read(m_hPort, pBuf, rxCount, ref dwRet);
            }

            if (ftStatus != FT_STATUS.FT_OK)
            {
                return(null);
            }

            return(cBuf);
        }
Exemplo n.º 15
0
 static void APP_CHECK_STATUS(FT_STATUS status)
 {
     if (status != FT_STATUS.FT_OK)
     {
         Console.WriteLine("Error: {0}", status.ToString());
     }
 }
Exemplo n.º 16
0
        public void start()
        {
            handle = 0;
            status = FT_Open(0, ref handle);
            if (status != FT_STATUS.FT_OK)
            {
                string message = "Failed to open FTDI device" + status.ToString();
                //failure
                throw new Exception(message);
            }
            else
            {
                //worked

                //Configure the device for DMX data
                initOpenDMX();

                //Initialize the universe and start code to all 0s
                for (int i = 0; i < 513; i++)
                {
                    setDmxValue(i, 0);
                }

                //Create and start the thread that sends the output data to the driver
                Thread thread = new Thread(new ThreadStart(writeData));
                thread.Start();
            }
        }
        private void writeDMXBuffer()
        {
            while (!done)
            {
                try
                {
                    newData = MoveNextBufferToThread();

                    if (Connected)
                    {
                        if (newData)
                        {
                            FT_STATUS status = FT_STATUS.FT_OK;
                            if (!FTDI_SendData(handle, SET_DMX_TX_MODE, (new byte[1]).Concat(bufferToUsb).ToArray(), ref status))
                            {
                                break;
                            }
                            newData = false;
                        }

                        System.Threading.Thread.Sleep(25);
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                    break;
                }
            }
            Connected = false;
            done      = false;
        }
Exemplo n.º 18
0
        public void SetFlashSelect(FlashType flashType)
        {
            byte flashSel;

            if (flashType == FlashType.Rom)
            {
                flashSel = 0;
            }
            else
            {
                flashSel = 1;
            }
            Console.WriteLine(String.Format("Set FlashSel: {0}", flashSel));

            StxEtxMemoryStream stream = new StxEtxMemoryStream();

            stream.StartPacket();
            stream.WriteByte((byte)Commands.FlashSelect);
            stream.WriteByte(flashSel);
            stream.EndPacket();

            byte[]    bytes        = stream.GetBytes();
            uint      bytesWritten = 0;
            FT_STATUS status       = _Ftdi.Write(bytes, bytes.Length, ref bytesWritten);

            if (status != FT_STATUS.FT_OK)
            {
                throw new Exception("Error writing data (SetFlashSelect)");
            }
            if (bytesWritten != bytes.Length)
            {
                throw new Exception("Wrong number of bytes written (SetFlashSelect)");
            }
        }
Exemplo n.º 19
0
        unsafe protected virtual void WriteDirection(char port, byte value)
        {
            UInt32    dwRet    = 0;
            FT_STATUS ftStatus = FT_STATUS.FT_OTHER_ERROR;

            byte[] cBuf = new byte[5];

            cBuf[0] = (byte)'!';
            cBuf[1] = (byte)port;
            cBuf[2] = value;

            switch (port)
            {
            case 'A':
                m_direction[0] = value;
                break;

            case 'B':
                m_direction[1] = value;
                break;

            case 'C':
                m_direction[2] = value;
                break;
            }

            fixed(byte *pBuf = cBuf)
            {
                ftStatus = FT_Write(m_hPort, pBuf, 3, ref dwRet);
                if (ftStatus != FT_STATUS.FT_OK && dwRet != 3)
                {
                    throw (new SystemException("Error WriteDirection"));
                }
            }
        }
Exemplo n.º 20
0
        public void EraseSector(int sectorAddr)
        {
            Console.WriteLine(String.Format("Erase sector: 0x{0:X8}", sectorAddr));

            StxEtxMemoryStream stream = new StxEtxMemoryStream();

            int addr = sectorAddr / 4;

            stream.StartPacket();
            stream.WriteByte((byte)Commands.SetAddr);
            WriteIntBe(stream, addr);
            stream.EndPacket();

            stream.StartPacket();
            stream.WriteByte((byte)Commands.FlashErase);
            stream.EndPacket();

            byte[]    bytes        = stream.GetBytes();
            uint      bytesWritten = 0;
            FT_STATUS status       = _Ftdi.Write(bytes, bytes.Length, ref bytesWritten);

            if (status != FT_STATUS.FT_OK)
            {
                throw new Exception("Error writing data (EraseSector)");
            }
            if (bytesWritten != bytes.Length)
            {
                throw new Exception("Wrong number of bytes written (EraseSector)");
            }
            _PendingAck++;
        }
        public override void Close()
        {
            isInitialized = false;
            if (ftdi != null && ftdi.IsOpen)
            {
                // バッファをクリア
                ClearBuffer();

                // ポートを閉じる
                FT_STATUS ret = ftdi.ResetPort();
                if (ret == FT_STATUS.FT_OK)
                {
                    ret = ftdi.Close();
                    if (ret != FT_STATUS.FT_OK)
                    {
                        throw new InvalidOperationException("close failure.");
                    }
                }
                else
                {
                    throw new InvalidOperationException("reset failure.");
                }
                ftdi = null;
            }
        }
Exemplo n.º 22
0
        // Flush drivers receive buffer - Get queue status and read everything available and discard data
        protected byte FlushBuffer()
        {
            ftStatus = GetRxBytesAvailable(ref BytesAvailable);  // Get the number of bytes in the receive buffer
            if (ftStatus != FT_STATUS.FT_OK)
            {
                return(1);
            }

            if (BytesAvailable > 0)
            {
                ftStatus = Read(InputBuffer, BytesAvailable, ref NumBytesRead);         //Read out the data from receive buffer
                if (ftStatus != FT_STATUS.FT_OK)
                {
                    return(1);       // error
                }
                else
                {
                    return(0);       // all bytes successfully read
                }
            }
            else
            {
                return(0);           // there were no bytes to read
            }
        }
Exemplo n.º 23
0
        public FirmwareIdentity ReadVersion()
        {
            byte[] cmdData = new byte[] {
                (byte)Commands.ReadVersion
            };

            StxEtxPacket packet = new StxEtxPacket(cmdData);

            byte[]    bytes        = packet.GetBytes();
            uint      bytesWritten = 0;
            FT_STATUS status       = _Ftdi.Write(bytes, bytes.Length, ref bytesWritten);

            if (status != FT_STATUS.FT_OK)
            {
                throw new Exception("Error writing data (ReadVersion)");
            }
            if (bytesWritten != bytes.Length)
            {
                throw new Exception("Wrong number of bytes written (ReadVersion)");
            }

            byte[] result = ReceiveResponse();

            _FirmwareIdentity.Id    = result[0];
            _FirmwareIdentity.Major = result[1];
            _FirmwareIdentity.Minor = result[2];
            _FirmwareIdentity.Debug = result[3];

            return(_FirmwareIdentity);
        }
Exemplo n.º 24
0
        // Read a specified number of bytes from the driver receive buffer
        protected byte Receive_Data(uint BytesToRead)
        {
            uint NumBytesInQueue  = 0;
            uint QueueTimeOut     = 0;
            uint Buffer1Index     = 0;
            uint Buffer2Index     = 0;
            uint TotalBytesRead   = 0;
            bool QueueTimeoutFlag = false;
            uint NumBytesRxd      = 0;

            // Keep looping until all requested bytes are received or we've tried 5000 times (value can be chosen as required)
            while ((TotalBytesRead < BytesToRead) && (QueueTimeoutFlag == false))
            {
                ftStatus = GetRxBytesAvailable(ref NumBytesInQueue);       // Check bytes available

                if ((NumBytesInQueue > 0) && (ftStatus == FT_STATUS.FT_OK))
                {
                    ftStatus = Read(InputBuffer, NumBytesInQueue, ref NumBytesRxd);  // if any available read them

                    if ((NumBytesInQueue == NumBytesRxd) && (ftStatus == FT_STATUS.FT_OK))
                    {
                        Buffer1Index = 0;

                        while (Buffer1Index < NumBytesRxd)
                        {
                            InputBuffer2[Buffer2Index] = InputBuffer[Buffer1Index];     // copy into main overall application buffer
                            Buffer1Index++;
                            Buffer2Index++;
                        }
                        TotalBytesRead = TotalBytesRead + NumBytesRxd;                  // Keep track of total
                    }
                    else
                    {
                        return(1);
                    }

                    QueueTimeOut++;
                    if (QueueTimeOut == 5000)
                    {
                        QueueTimeoutFlag = true;
                    }
                    else
                    {
                        Thread.Sleep(0);                                                // Avoids running Queue status checks back to back
                    }
                }
            }
            // returning globals NumBytesRead and the buffer InputBuffer2
            NumBytesRead = TotalBytesRead;

            if (QueueTimeoutFlag == true)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Exemplo n.º 25
0
 public static void start()
 {
     handle  = 0;
     status  = FT_Open(0, ref handle);
     runtime = new Thread(new ThreadStart(writeData));
     runtime.Start();
     setDmxValue(0, 0);  //Set DMX Start Code
 }
Exemplo n.º 26
0
 public override void Stop()
 {
     this.done = true;
     this.workThread.Abort();
     this.workThread = null;
     status          = FT_ResetDevice(handle);
     status          = FT_Close(handle);
 }
Exemplo n.º 27
0
 private static bool Ok(FT_STATUS status)
 {
     if (status == FT_STATUS.FT_OK)
     {
         return(true);
     }
     throw new ApplicationException($"[{nameof(FT232HDetector)}]Last operation failed code:{status}");
 }
Exemplo n.º 28
0
            public static void start()
            {
                handle = 0;
                status = FT_Open(0, ref handle);
                Thread thread = new Thread(new ThreadStart(writeData));

                thread.Start();
            }
Exemplo n.º 29
0
        public void Initialize()
        {
            Console.WriteLine(">>Initialize");
#if LINUXBUILD
            FT_STATUS ftstatus = FT_SetVIDPID(0x0403, 0x7cb0);
            Console.WriteLine("FT_STATUS = {0}", ftstatus.ToString());
#endif
            Console.WriteLine("<<Initialize");
        }
Exemplo n.º 30
0
        public static void Read(FT_HANDLE handle, byte[] buffer)
        {
            FT_STATUS status = FT_Read(handle, buffer, (uint)buffer.Length, out uint bytesReturned);

            if (status != FT_STATUS.FT_OK || bytesReturned != buffer.Length)
            {
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 31
0
Arquivo: FTDI.cs Projeto: stewmc/vixen
		public void start()
		{
			handle = 0;
			status = FT_Open(0, ref handle);
			if (status != FT_STATUS.FT_OK) {
				string message = "Failed to open FTDI device" + status.ToString();
				//failure
				throw new Exception(message);
			}
			else {
				//worked

				//Configure the device for DMX data
				initOpenDMX();

				//Initialize the universe and start code to all 0s
				for (int i = 0; i < 513; i++)
					setDmxValue(i, 0);

				//Create and start the thread that sends the output data to the driver
				Thread thread = new Thread(new ThreadStart(writeData));
				thread.Start();
			}
		}
Exemplo n.º 32
0
        //**************************************************************************
        //**************************************************************************
        //
        // HELPER METHODS
        //
        //**************************************************************************
        //**************************************************************************
        //**************************************************************************
        // ErrorHandler
        //**************************************************************************
        /// <summary>
        /// Method to check ftStatus and ftErrorCondition values for error conditions and throw exceptions accordingly.
        /// </summary>
        private void ErrorHandler(FT_STATUS ftStatus, FT_ERROR ftErrorCondition)
        {
            if (ftStatus != FT_STATUS.FT_OK)
            {
                // Check FT_STATUS values returned from FTD2XX DLL calls
                switch (ftStatus)
                {
                    case FT_STATUS.FT_DEVICE_NOT_FOUND:
                        {
                            throw new FT_EXCEPTION("FTDI device not found.");
                        }
                    case FT_STATUS.FT_DEVICE_NOT_OPENED:
                        {
                            throw new FT_EXCEPTION("FTDI device not opened.");
                        }
                    case FT_STATUS.FT_DEVICE_NOT_OPENED_FOR_ERASE:
                        {
                            throw new FT_EXCEPTION("FTDI device not opened for erase.");
                        }
                    case FT_STATUS.FT_DEVICE_NOT_OPENED_FOR_WRITE:
                        {
                            throw new FT_EXCEPTION("FTDI device not opened for write.");
                        }
                    case FT_STATUS.FT_EEPROM_ERASE_FAILED:
                        {
                            throw new FT_EXCEPTION("Failed to erase FTDI device EEPROM.");
                        }
                    case FT_STATUS.FT_EEPROM_NOT_PRESENT:
                        {
                            throw new FT_EXCEPTION("No EEPROM fitted to FTDI device.");
                        }
                    case FT_STATUS.FT_EEPROM_NOT_PROGRAMMED:
                        {
                            throw new FT_EXCEPTION("FTDI device EEPROM not programmed.");
                        }
                    case FT_STATUS.FT_EEPROM_READ_FAILED:
                        {
                            throw new FT_EXCEPTION("Failed to read FTDI device EEPROM.");
                        }
                    case FT_STATUS.FT_EEPROM_WRITE_FAILED:
                        {
                            throw new FT_EXCEPTION("Failed to write FTDI device EEPROM.");
                        }
                    case FT_STATUS.FT_FAILED_TO_WRITE_DEVICE:
                        {
                            throw new FT_EXCEPTION("Failed to write to FTDI device.");
                        }
                    case FT_STATUS.FT_INSUFFICIENT_RESOURCES:
                        {
                            throw new FT_EXCEPTION("Insufficient resources.");
                        }
                    case FT_STATUS.FT_INVALID_ARGS:
                        {
                            throw new FT_EXCEPTION("Invalid arguments for FTD2XX function call.");
                        }
                    case FT_STATUS.FT_INVALID_BAUD_RATE:
                        {
                            throw new FT_EXCEPTION("Invalid Baud rate for FTDI device.");
                        }
                    case FT_STATUS.FT_INVALID_HANDLE:
                        {
                            throw new FT_EXCEPTION("Invalid handle for FTDI device.");
                        }
                    case FT_STATUS.FT_INVALID_PARAMETER:
                        {
                            throw new FT_EXCEPTION("Invalid parameter for FTD2XX function call.");
                        }
                    case FT_STATUS.FT_IO_ERROR:
                        {
                            throw new FT_EXCEPTION("FTDI device IO error.");
                        }
                    case FT_STATUS.FT_OTHER_ERROR:
                        {
                            throw new FT_EXCEPTION("An unexpected error has occurred when trying to communicate with the FTDI device.");
                        }
                    default:
                        break;
                }
            }
            if (ftErrorCondition != FT_ERROR.FT_NO_ERROR)
            {
                // Check for other error conditions not handled by FTD2XX DLL
                switch (ftErrorCondition)
                {
                    case FT_ERROR.FT_INCORRECT_DEVICE:
                        {
                            throw new FT_EXCEPTION("The current device type does not match the EEPROM structure.");
                        }
                    case FT_ERROR.FT_INVALID_BITMODE:
                        {
                            throw new FT_EXCEPTION("The requested bit mode is not valid for the current device.");
                        }
                    case FT_ERROR.FT_BUFFER_SIZE:
                        {
                            throw new FT_EXCEPTION("The supplied buffer is not big enough.");
                        }

                    default:
                        break;
                }

            }

            return;
        }
Exemplo n.º 33
0
 //modified removing static
 public void start()
 {
     handle = 0;
     status = FT_Open(0, ref handle);
     if (status != FT_STATUS.FT_OK)
     {
         string message = "Failed to open FTDI device" + status.ToString();
         //failure
         throw new Exception(message);
     }
     else
     {
         //worked
         setDmxValue(0, 0);  //Set DMX Start Code
     }
 }
Exemplo n.º 34
0
            public byte[] ReadData()
            {
                uint BytesRead = 0;
                uint RxBytes = 0;
                uint EventDWord = 0;
                uint TxBytes = 0;
                CurExStatus = FT_GetStatus(curFtHandle, ref RxBytes, ref TxBytes, ref EventDWord);

                if (CurExStatus != FT_STATUS.FT_OK)
                    return null;

                if (RxBytes == 0) return null;

                var RecBuf = new byte[RxBytes];

                int IndexBuf = 0;
                while (RxBytes > 0)
                {
                    fixed (byte* rb = &RecBuf[IndexBuf])
                    {
                        CurExStatus = FT_Read(curFtHandle, rb, RxBytes < 256 ? RxBytes : 256, ref BytesRead);
                        if (CurExStatus != FT_STATUS.FT_OK)
                        {
                            return null;
                        }
                    }
                    IndexBuf += (int)BytesRead;
                    //  RxChar(RecBuf,BytesRead);
                    RxBytes -= BytesRead;
                }
                return RecBuf;
            }
Exemplo n.º 35
0
 //Added stop()
 public void stop()
 {
     //this.thread.Abort();
     status = FT_Close(handle);
 }
Exemplo n.º 36
0
 public static void initOpenDMX()
 {
     status = FT_ResetDevice(handle);
     status = FT_SetDivisor(handle, (char)12);  // set baud rate
     status = FT_SetDataCharacteristics(handle, BITS_8, STOP_BITS_2, PARITY_NONE);
     status = FT_SetFlowControl(handle, (char)FLOW_NONE, 0, 0);
     status = FT_ClrRts(handle);
     status = FT_Purge(handle, PURGE_TX);
     status = FT_Purge(handle, PURGE_RX);
 }
Exemplo n.º 37
0
 public static int write(uint handle, byte[] data, int length)
 {
     IntPtr ptr = Marshal.AllocHGlobal((int)length);
     Marshal.Copy(data, 0, ptr, (int)length);
     uint bytesWritten = 0;
     status = FT_Write(handle, ptr, (uint)length, ref bytesWritten);
     return (int)bytesWritten;
 }
Exemplo n.º 38
0
 public static void start()
 {
     handle = 0;
     status = FT_Open(0, ref handle);
     Thread thread = new Thread(new ThreadStart(writeData));
     thread.Start();
     setDmxValue(0, 0);  //Set DMX Start Code
 }
Exemplo n.º 39
0
Arquivo: FTDI.cs Projeto: stewmc/vixen
		//Added stop()
		public void stop()
		{
			done = true;
			status = FT_Close(handle);
		}
Exemplo n.º 40
0
        public static void writeData()
        {
            try
            {
                initOpenDMX();
                if (OpenDMX.status == FT_STATUS.FT_OK)
                {
                    status = FT_SetBreakOn(handle);
                    status = FT_SetBreakOff(handle);
                    bytesWritten = write(handle, buffer, buffer.Length);

                    Thread.Sleep(25);      //give the system time to send the data before sending more

                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
            }
        }
Exemplo n.º 41
0
 public int write(uint handle, byte[] data, int length)
 {
     Marshal.Copy(data, 0, ptr, (int)length);
     uint bytesWritten = 0;
     status = FT_Write(handle, ptr, (uint)length, ref bytesWritten);
     return (int)bytesWritten;
 }
Exemplo n.º 42
0
        private string OpenDevice(out ControllerStatus status, out string info)
        {
            status = ControllerStatus.DeviceError;
            info = "";

            //Get number of devices
            _ftStatus = _myFtdiDevice.GetNumberOfDevices(ref _ftdiDeviceCount);
            if (_ftStatus != FT_STATUS.FT_OK)
                return string.Format("Failed to get number of devices (error {0})", _ftStatus);
            if (_ftdiDeviceCount == 0)
            {
                status = ControllerStatus.DeviceAbsent;
                return "No connected devices";
            }

            //Get list of devices
            _ftdiDeviceList = new FT_DEVICE_INFO_NODE[_ftdiDeviceCount];
            _ftStatus = _myFtdiDevice.GetDeviceList(_ftdiDeviceList);
            if (_ftStatus != FT_STATUS.FT_OK)
                return string.Format("Failed to get list of devices (error {0})", _ftStatus);
            int ourDeviceIndex = -1;
            StringBuilder list = new StringBuilder();
            for (int i = 0; i < _ftdiDeviceCount; i++)
            {
                if (_ftdiDeviceList[i].Description.IndexOf(_description) != -1)
                    ourDeviceIndex = i;
                list.Append(string.Format("flags:{0},type:{1},ID:{2},loc.ID:{3},SN:{4},desc:'{5}'; ",
                    string.Format("{0:x}", _ftdiDeviceList[i].Flags),
                    _ftdiDeviceList[i].Type,
                    string.Format("{0:x}", _ftdiDeviceList[i].ID),
                    string.Format("{0:x}", _ftdiDeviceList[i].LocId),
                    _ftdiDeviceList[i].SerialNumber,
                    _ftdiDeviceList[i].Description));
            }
            string devices = list.ToString();
            if (ourDeviceIndex == -1)
            {
                status = ControllerStatus.DeviceAbsent;
                return string.Format("Device '{0}' is absent", _description + (devices != "" ? " (" + devices + ")" : ""));
            }

            //Open device
            _ftStatus = _myFtdiDevice.OpenByIndex(ourDeviceIndex);
            if (_ftStatus != FT_STATUS.FT_OK)
            {
                status = ControllerStatus.Error;
                return string.Format("Failed to open device (error {0})", _ftStatus);
            }
            else
                info = string.Format("Device '{0}' was opened", _description);

            //Set baud rate
            _ftStatus = _myFtdiDevice.SetBaudRate(_speed);
            if (_ftStatus != FT_STATUS.FT_OK)
            {
                status = ControllerStatus.Error;
                return string.Format("Failed to set Baud rate (error {0})", _ftStatus);
            }

            //Set timeout
            _ftStatus = _myFtdiDevice.SetTimeouts(_readTimeout, _writeTimeout);
            if (_ftStatus != FT_STATUS.FT_OK)
            {
                status = ControllerStatus.Error;
                return string.Format("Failed to set timeouts (error {0})", _ftStatus);
            }

            //Set flow control
            _ftStatus = _myFtdiDevice.SetFlowControl(FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0);
            if (_ftStatus != FT_STATUS.FT_OK)
            {
                status = ControllerStatus.Error;
                return string.Format("Failed to set flow control (error {0})", _ftStatus);
            }

            //Device ready
            status = ControllerStatus.DeviceOpened;
            return "";
        }
Exemplo n.º 43
0
Arquivo: FTDI.cs Projeto: stewmc/vixen
		public int write(uint handle, byte[] data, int length)
		{
			//Free the memory from the last call to write()
			Marshal.FreeHGlobal(transmitPtr);

			//Copy the buffer to a stream of bytes
			transmitPtr = Marshal.AllocHGlobal((int) length);
			Marshal.Copy(data, 0, transmitPtr, (int) length);

			uint bytesWritten = 0;

			//Write the data to the serial buffer
			status = FT_Write(handle, transmitPtr, (uint) length, ref bytesWritten);

			return (int) bytesWritten;
		}
Exemplo n.º 44
0
 public static void start()
 {
     handle = 0;
     status = FT_Open(0, ref handle);
     //setting up the WriteData method to be on it's own thread. This will also turn all channels off
     //this unrequested change of state can be managed by getting the current state of all channels
     //into the write buffer before calling this function.
     Thread thread = new Thread(new ThreadStart(writeData));
     thread.Start();
 }
Exemplo n.º 45
0
 public static int write(uint handle, byte[] data, int length)
 {
     try
     {
         IntPtr ptr = Marshal.AllocHGlobal((int)length);
         Marshal.Copy(data, 0, ptr, (int)length);
         uint bytesWritten = 0;
         status = FT_Write(handle, ptr, (uint)length, ref bytesWritten);
         return (int)bytesWritten;
     }
     catch (Exception exp)
     {
         Console.WriteLine(exp);
         return 0;
     }
 }