예제 #1
0
        private void ReadDataFromSerialPort()
        {
            lock (buffer)
            {
                int amount = serialPort.Read(staticBuffer, 0, MAXIMUM_BUFFER_SIZE);

                //Console.WriteLine($"Data amount: {amount}");

                if (amount > 0)
                {
                    for (var index = 0; index < amount; index++)
                    {
                        buffer += (char)staticBuffer[index];
                    }
                }
                var eolMarkerPosition = buffer.IndexOf(LINE_END);

                while (eolMarkerPosition >= 0)
                {
                    var line = buffer.Substring(0, eolMarkerPosition);
                    buffer            = buffer.Substring(eolMarkerPosition + 2);
                    eolMarkerPosition = buffer.IndexOf(LINE_END);

                    // Console.WriteLine($"Line: {line}");

                    OnLineReceived?.Invoke(this, line);
                }
            }
        }
예제 #2
0
        public int ReadSerial()
        {
            var len = serialPort.BytesToRead;

            if (len == 0)
            {
                Console.WriteLine("No data");
                return(0);
            }

            var data = new byte[len];

            serialPort.Read(data, 0, len);

            for (int i = 0; i < data.Length - 3; i++)
            {
                if (data[i] == 'R')
                {
                    Console.WriteLine($"i:{i} -- {(char)data[i + 1]}, {(char)data[i + 2]}, {(char) data[i + 3]}");
                }
            }

            Console.WriteLine($"Byte array: {string.Join(" ", data)}");

            Console.WriteLine($"Length: {len}");

            return(0);
        }
예제 #3
0
        private bool TrySendReceive()
        {
            //Console.WriteLine("Trying with {0}", _port.BaudRate);
            _internalOp = true;
            _port.Write(Encoding.ASCII.GetBytes("AT"));

            if (!_signal.WaitOne(2000))
            {
                _internalOp = false;
                //Console.WriteLine("timeout");
                return(false);
            }

            byte[] buffer = new byte[_port.BytesToRead];
            _port.Read(buffer, 0, buffer.Length);

            string response = Encoding.ASCII.GetString(buffer);

            //Console.WriteLine(response);
            return(response == "OK");
        }
예제 #4
0
        protected int ReadFrameSegment(int segmentLength, byte[] frameBuffer, int frameAddress)
        {
            RunCommand(Command.READ_FBUF,
                       new byte[] { 0x0, 0x0A,
                                    (byte)((frameAddress >> 24) & 0xFF), (byte)((frameAddress >> 16) & 0xFF), (byte)((frameAddress >> 8) & 0xFF), (byte)(frameAddress & 0xFF),
                                    (byte)((segmentLength >> 24) & 0xFF), (byte)((segmentLength >> 16) & 0xFF), (byte)((segmentLength >> 8) & 0xFF), (byte)(segmentLength & 0xFF),
                                    (byte)((CameraDelayMilliSec >> 8) & 0xFF), (byte)(CameraDelayMilliSec & 0xFF) }, 5);

            var totalBytesRead = 0;

            while (segmentLength > 0)
            {
                if (WaitForIncomingData(GetTimeoutMilliSec(segmentLength)) == false)
                {
                    throw new ApplicationException("Timeout");
                }
                var bytesToRead = System.Math.Min(_serialPort.BytesToRead, segmentLength);
                var bytesRead   = _serialPort.Read(frameBuffer, 0, bytesToRead);
                segmentLength  -= bytesRead;
                totalBytesRead += bytesRead;
            }

            return(totalBytesRead);
        }
예제 #5
0
        // anonymous method declaration so we can unwire later.
        void ProcessData(object sender, SerialDataReceivedEventArgs e)
        {
            Console.WriteLine("Serial Data Received");
            byte[] buffer      = new byte[512];
            int    bytesToRead = classicSerialPort.BytesToRead > buffer.Length
                                ? buffer.Length
                                : classicSerialPort.BytesToRead;

            while (true)
            {
                int readCount = classicSerialPort.Read(buffer, 0, bytesToRead);
                Console.Write(ParseToString(buffer, readCount, currentTestEncoding));
                // if we got all the data, break the while loop, otherwise, keep going.
                if (readCount < 512)
                {
                    break;
                }
            }
            Console.Write("\n");
        }
예제 #6
0
        private void ReadAll()
        {
            byte[] buf       = new byte[0];
            int    bytesRead = 0;

            try
            {
                if (_port.BytesToRead > 0 && _shouldRun)
                {
                    int bytes = Math.Min(_port.BytesToRead, 8);
                    buf       = new byte[bytes];
                    bytesRead = _port.Read(buf, 0, bytes);
                }
            } catch (IOException)
            {
                Console.WriteLine("While reading an IOException occured");
                StopConnection();
                return;
            }
            _protocol.Add(buf);
        }
        /// <summary>
        /// just a diagnostic method that polls the serial and outputs anything
        /// in the buffer.
        /// </summary>
        void ListenToSerial()
        {
            byte[] buffer = new byte[1024];
            int    bytesToRead;

            while (true)
            {
                bytesToRead = classicSerialPort.BytesToRead;
                if (bytesToRead > buffer.Length)
                {
                    bytesToRead = buffer.Length;
                }
                int dataLength = classicSerialPort.Read(buffer, 0, bytesToRead);

                if (dataLength > 0)
                {
                    Console.WriteLine(ParseToString(buffer, dataLength, Encoding.ASCII));
                }
                Thread.Sleep(500);
            }
        }
예제 #8
0
        public void Test_CSerialPort_Read()
        {
            SetupPort();
            try
            {
                Stopwatch timer          = new Stopwatch();
                bool      bGotData       = false;
                bool      bRightEncoding = false; // C# serial port encoding incoming data with UTF8,UTF16, etc thus makes data sent different from ones received at application
                timer.Start();
                while (timer.Elapsed.TotalSeconds < 5)
                {
                    string data = hlPort.Read();
                    if (data == null)
                    {
                        continue;
                    }

                    bGotData = true;
                    Byte[] DataAsByte = Encoding.Default.GetBytes(data);
                    foreach (Byte b in DataAsByte)
                    {
                        if (b == (Byte)(0xCC))
                        {
                            bRightEncoding = true;
                            goto FINISH;
                        }
                    }
                }

FINISH:
                Assert.IsTrue(bGotData);
                Assert.IsTrue(bRightEncoding);
            }
            finally
            {
                Clean();
            }
        }
예제 #9
0
        private void ReceivedCallBack(IAsyncResult ar)
        {
            int    errorCode = 0;
            string errorMsg  = "接收成功";

            //若SerialPort已经打开
            if (ISerialPort != null && ISerialPort.IsOpen)
            {
                try
                {
                    #region 接收数据

                    int    nBytesRec   = ISerialPort.BytesToRead;
                    byte[] _dataBuffer = new byte[nBytesRec];
                    ISerialPort.Read(_dataBuffer, 0, nBytesRec);

                    if (nBytesRec > 0)
                    {
                        errorMsg = string.Format("串口:[{0}]{1}", ISerialPort.PortName, errorMsg);

                        ReceivedData.Clear();
                        string strtemp = Encoding.Default.GetString(_dataBuffer, 0, nBytesRec);
                        ReceivedData.Append(strtemp);

                        if (ReceivedEvt != null)
                        {
                            System.Windows.Forms.Control target = ReceivedEvt.Target as System.Windows.Forms.Control;
                            if (target != null && target.InvokeRequired)
                            {
                                //非创建控件线程同步调用事件:SerialPortConnected
                                target.Invoke(ReceivedEvt, new object[] { ReceivedData.ToString(),
                                                                          ProCommon.Communal.ToolFunctions.GetSubData(_dataBuffer, 0, nBytesRec) });
                            }
                            else
                            {
                                //创建控件线程调用事件
                                ReceivedEvt(Property, ReceivedData.ToString(),
                                            ProCommon.Communal.ToolFunctions.GetSubData(_dataBuffer, 0, nBytesRec));
                            }
                        }
                    }
                    else
                    {
                        errorCode = 1; errorMsg = "接收数据为空";
                        //Common.SocketClosedEventHandler d=new Common.SocketClosedEventHandler();
                        if (ClosedEvt != null)
                        {
                            System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control;
                            if (target != null && target.InvokeRequired)
                            {
                                //非创建控件线程同步调用事件:SocketClosed
                                target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg });
                            }
                            else
                            {
                                //创建控件线程调用事件
                                ClosedEvt(Property, errorCode, errorMsg);
                            }
                        }
                    }
                    #endregion
                }
                catch
                {
                    try
                    {
                        if (ClosedEvt != null)
                        {
                            System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control;
                            if (target != null && target.InvokeRequired)
                            {
                                //非创建控件线程同步调用事件:SocketClosed
                                target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg });
                            }
                            else
                            {
                                //创建控件线程调用事件
                                ClosedEvt(Property, errorCode, errorMsg);
                            }
                        }
                    }
                    catch { }
                }
            }
            else
            {
                Property.IsConnected = false; //改变连接属性
            }
        }
예제 #10
0
    void ReceiveData()
    {
        byte[] rxBuffer      = new byte[kReadQueueSize];
        byte[] workingBuffer = new byte[kReadQueueSize];
        int    wbStartIdx    = 0;
        int    wbEndIdx      = 0;
        int    wbLength      = 0;

        RxLog("Creating rx log.");
        while (m_threadsActive)
        {
            try {
                // Firmware sends data ~1/sec.
                Thread.Sleep(kSecToMs);

                int numRead = m_serialPort.Read(kReadQueueSize, ref rxBuffer);
                RxLog("Read {0} byte{1}.", numRead, Text.S(numRead));

                if (numRead < 0)
                {
                    RxLog("Read error: {0}", m_serialPort.error);
                    continue;
                }

                int rxIndex = 0;
                while (numRead > 0)
                {
                    workingBuffer[wbEndIdx] = rxBuffer[rxIndex++];
                    wbEndIdx = (wbEndIdx + 1) & kReadQueueMask;
                    wbLength++;
                    numRead--;
                }
                RxLog("Buffer: {0}-{1}; {2} bytes.",
                      wbStartIdx, wbEndIdx, wbLength);

                int checksum;
                int heater0;
                int heater1;
                int bufferAvailableLow;
                int bufferAvailableHigh;
                int motorQueueLow;
                int motorQueueHigh;

                bool foundCompletePacket      = false;
                int  validHeater0             = 0;
                int  validHeater1             = 0;
                int  validBufferAvailable     = 0;
                int  validMotorQueueAvailable = 0;
                // NOTE(kevin): We only want to use the last packet's
                // information; if we have partial packets or invalid
                // packets, then we need to discard all the data
                // to ensure we don't overwrite data on the prop.
                while (wbLength >= 8)
                {
                    // Find the first #
                    while (wbLength > 0 && workingBuffer[wbStartIdx] != '#')
                    {
                        RxLog("Ignoring {0} (0x{1:x2}) at {2}",
                              (char)workingBuffer[wbStartIdx],
                              (int)workingBuffer[wbStartIdx],
                              wbStartIdx);
                        wbStartIdx = (wbStartIdx + 1) & kReadQueueMask;
                        wbLength--;
                    }

                    // Not enough data? Break out.
                    if (wbLength < 8)
                    {
                        RxLog("Working buffer of {0} too small.", wbLength);
                        foundCompletePacket = false;
                        break;
                    }

                    // We're at a #; invalidate the packet and extract its contents.
                    workingBuffer[wbStartIdx] = 0;
                    checksum            = workingBuffer[(wbStartIdx + 1) & kReadQueueMask];
                    heater0             = workingBuffer[(wbStartIdx + 2) & kReadQueueMask];
                    heater1             = workingBuffer[(wbStartIdx + 3) & kReadQueueMask];
                    bufferAvailableLow  = workingBuffer[(wbStartIdx + 4) & kReadQueueMask];
                    bufferAvailableHigh = workingBuffer[(wbStartIdx + 5) & kReadQueueMask];
                    motorQueueLow       = workingBuffer[(wbStartIdx + 6) & kReadQueueMask];
                    motorQueueHigh      = workingBuffer[(wbStartIdx + 7) & kReadQueueMask];
                    if (checksum == ((heater0 + heater1
                                      + bufferAvailableLow + bufferAvailableHigh
                                      + motorQueueLow + motorQueueHigh) & 0xFF))
                    {
                        validHeater0             = heater0;
                        validHeater1             = heater1;
                        validBufferAvailable     = bufferAvailableLow + (bufferAvailableHigh << 8);
                        validMotorQueueAvailable = motorQueueLow + ((motorQueueHigh & 0x7F) << 8);
                        foundCompletePacket      = true;

                        // NOTE(kevin): This is a safety precaution.
                        workingBuffer[(wbStartIdx + 1) & kReadQueueMask]
                                        = workingBuffer[(wbStartIdx + 2) & kReadQueueMask]
                                        = workingBuffer[(wbStartIdx + 3) & kReadQueueMask]
                                        = workingBuffer[(wbStartIdx + 4) & kReadQueueMask]
                                        = workingBuffer[(wbStartIdx + 5) & kReadQueueMask]
                                        = workingBuffer[(wbStartIdx + 6) & kReadQueueMask]
                                        = workingBuffer[(wbStartIdx + 7) & kReadQueueMask]
                                        = 0;

                        wbStartIdx = (wbStartIdx + 8) & kReadQueueMask;
                        wbLength  -= 8;
                    }
                    else
                    {
                        RxLog("Invalid packet!");
                        foundCompletePacket = false;
                        wbStartIdx          = (wbStartIdx + 1) & kReadQueueMask;
                        wbLength--;
                    }
                }

                if (foundCompletePacket)
                {
                    RxLog("H0: {0}C; H1: {1}C; Rx Buffer: {2}; Motor Queue: {3}",
                          validHeater0, validHeater1, validBufferAvailable, validMotorQueueAvailable);
                    m_dispatchSemaphore.WaitOne();
                    m_lastHeater0Temperature  = validHeater0;
                    m_lastHeater1Temperature  = validHeater1;
                    m_lastBufferAvailable     = validBufferAvailable;
                    m_lastMotorQueueAvailable = validMotorQueueAvailable;
                    m_isSeeking = false;
                    m_dispatchSemaphore.Release();
                }
                else
                {
                    // Set to safe values.
                    RxLog("Zeroing & setting IsSeeking");
                    m_dispatchSemaphore.WaitOne();
                    m_lastBufferAvailable     = 0;
                    m_lastMotorQueueAvailable = 0;
                    m_isSeeking = true;
                    m_dispatchSemaphore.Release();
                }
            }
            catch (System.Threading.ThreadAbortException) {
                break;
            }
            catch (System.Exception e) {
                RxLog(e.ToString());
            }
        }
        RxLog("Closing.");
    }
예제 #11
0
    /// <summary>
    /// Validates version, burning the bundled firmware if needed.
    /// </summary>
    /// <returns>The version.</returns>
    /// <param name="aPort">A port.</param>
    IEnumerator CheckVersion(ISerialPort aPort)
    {
        m_portPath = m_serialPort.OpenPortPath();
#if UNITY_STANDALONE_WIN || UNITY_WP8
        int comPortNumber;
#endif
        aPort.Write(@"version? ");
        yield return(new UnityEngine.WaitForSeconds(0.05f));

        string versionString;
        aPort.Read(16, out versionString);
        versionString = versionString.Trim();

        UnityEngine.Debug.Log("Firmware Version from Propeller = \"" + versionString + "\"");
        UnityEngine.Debug.Log("Firmware Version in Li = \"" + versionAsset.text + "\"");

        if (versionString.Contains(versionAsset.text.Trim()))
        {
            Text.Log(@"Firmware version {0}.", versionString);
            m_wasProgrammingSuccessful = true;
        }
#if UNITY_STANDALONE_WIN || UNITY_WP8
        else if (int.TryParse(m_portPath.Substring(3), out comPortNumber) &&
                 comPortNumber > 9)
        {
            string message = string.Format(@"Update failed: Try removing unused/hidden com ports in Device Manager & restart Li.");
            Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message);

            Text.Log("Aborting after detecting {0} com ports.", comPortNumber);
            yield return(new WaitForSeconds(20.0f));

            enabled = false;
            Dispatcher <Panel> .Broadcast(PanelController.kEventClosePanel, Panel.Message);
        }
#endif
        else
        {
            m_serialPort.Close();

            string message = string.Format(@"Burning firmware v. {0} /", versionAsset.text.Trim());
            Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message);

            Text.Log("{0} over {1}", message, versionString);

            int timeout   = 3;
            int spinIndex = 0;
            while (timeout-- > 0)
            {
                m_programmingThread = new Thread(new ParameterizedThreadStart(ProgramEeprom));
                m_programmingThread.Start(Application.streamingAssetsPath + @"/Firmware/");                //encodedBinary);
                int programmingTimeoutSec = 60;
                while (m_programmingThread.IsAlive && programmingTimeoutSec-- > 0)
                {
                    yield return(new WaitForSeconds(1.0f));

                    message  = message.Remove(message.Length - 1);
                    message += kSpinning[++spinIndex % kSpinning.Length];
                    Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message);
                }
                if (programmingTimeoutSec < 1)
                {
                    Text.Log("Aborting programming thread; passed {0}", m_programmingError);
                    m_programmingThread.Abort();
                }
                m_programmingThread = null;

                Text.Log("Burning result: {0}", m_programmingError);
                if (m_wasProgrammingSuccessful)
                {
                    message = string.Format(@"Burning successful.");
                    Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message);

                    Text.Log(message);
                    yield return(new WaitForSeconds(1.0f));

                    Dispatcher <Panel> .Broadcast(PanelController.kEventClosePanel, Panel.Message);

                    break;
                }
                else
                {
                    message = string.Format(@"Still burning {0}", kSpinning[++spinIndex % kSpinning.Length]);
                    Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message);

                    Text.Log(message);

                    yield return(new WaitForSeconds(0.5f));
                }
            }
            if (timeout <= 0)
            {
                message = string.Format(@"Burning failed. Try closing Li, rebooting the printer, and restarting.");
                Dispatcher <string> .Broadcast(PanelController.kEventShowMessage, message);

                Text.Log(message);
                yield return(new WaitForSeconds(1.0f));

                enabled = false;
                Dispatcher <Panel> .Broadcast(PanelController.kEventClosePanel, Panel.Message);
            }
            m_serialPort.OpenPort(m_portPath, kBaudRate);
        }
    }
예제 #12
0
    /// <summary>
    /// Finds a printer using the specified serial connection.
    /// </summary>
    /// <returns>
    /// An enumerator for a coroutine.
    /// </returns>
    /// <param name='aSerialPort'>
    /// A serial port connection.
    /// </param>
    IEnumerator FindPrinter(ISerialPort aSerialPort)
    {
        m_foundPrinter = false;
        int timeout = kLoopTimeout;

        while (!aSerialPort.isConnected && timeout-- > 0)
        {
            string[] availablePorts = m_serialPort.AvailablePorts();
            Text.Log(@"Found {0} available port{1}.", availablePorts.Length,
                     Text.S(availablePorts.Length));

            foreach (string aPortPath in availablePorts)
            {
                Text.Log(@"Trying to open {0}", aPortPath);

                bool success = false;
                try {
                    success = aSerialPort.OpenPort(aPortPath, kBaudRate);
                    Text.Log("Opened {0} at {1}.", aPortPath, kBaudRate);
                }
                catch (System.Exception e) {
                    Text.Error(e);
                    continue;
                }

                if (success)
                {
                    // Unity reboots the Propeller on OSX but not on Windows.
                    yield return(StartCoroutine(ResetCoroutine()));

                    // We're in text mode upon startup, so try pinging.
                    aSerialPort.Write("ping ");
                    // Not blocking, so wait a bit.
                    yield return(new UnityEngine.WaitForSeconds(1.0f));                   //0.02f);

                    string response = "(null)";
                    int    numRead  = aSerialPort.Read(8, out response);
                    response = response.Trim();
                    Text.Log("Received {0} byte{1}: {2}", numRead, Text.S(numRead), response);

                    if (response.Contains("pong"))
                    {
                        yield return(StartCoroutine(CheckVersion(aSerialPort)));

                        m_foundPrinter = m_wasProgrammingSuccessful;
                        if (m_foundPrinter)
                        {
                            Text.Log("Connected to " + aPortPath);
                            aSerialPort.Write("data ");

                            m_threadsActive = true;
                            m_txThread      = new Thread(TransmitData);
                            m_txThread.Name = "Tx Thread";
                            m_txThread.Start();

                            m_rxThread      = new Thread(ReceiveData);
                            m_rxThread.Name = "Rx Thread";
                            m_rxThread.Start();

                            Dispatcher.Broadcast(kOnSerialConnectionEstablished);
                        }
                        yield break;
                    }
                    aSerialPort.Close();
                    yield return(null);
                }
            }
            yield return(new WaitForSeconds(1));
        }
        if (timeout <= 0)
        {
            Text.Log(@"Couldn't find printer.");
            enabled = false;
        }
    }
예제 #13
0
        public override async Task <List <Device> > Scan()
        {
            // TODO: Handle mid-scan disconnects
            var output = new List <Device>();

            //if (timestampSize > 0b11) {
            //    throw new ArgumentException($"timestampSize cannot be higher than {0b11}.");
            //}

            //if (timestampResolution > 0b1111) {
            //    throw new ArgumentException($"timestampResolution cannot be higher than {0b1111}.");
            //}

            Console.Write("  Scan init");
            try {
                port.Flush(); // Flush previous output
                port.WriteByte((byte)((byte)Command.Scan | timestampSize));
                port.WriteByte((byte)(timestampResolution & 0xF));
                //await Task.Delay(200);
                uint index_counter = 0;
                byte moreDevs;
                do
                {
                    Console.Write("  1111");
                    byte devClass = moreDevs = await port.ReadByte();

                    devClass &= 1;

                    if ((moreDevs & 0x80) != 0)
                    {
                        var productID = await port.Read(4);

                        var uniqueID = await port.Read(4);

                        Console.WriteLine(BitConverter.ToUInt32(productID, 0));

                        if (devClass == (byte)DeviceClass.Buffer)
                        {
                            var shlAmount = await port.ReadByte();

                            var bufferSize = await port.ReadByte() | (await port.ReadByte() << 8);

                            output.Add(new BufferDevice(
                                           this,
                                           BitConverter.ToUInt32(productID, 0),
                                           BitConverter.ToUInt32(uniqueID, 0),
                                           index_counter++,
                                           (ulong)bufferSize << shlAmount
                                           ));

                            throw new NotImplementedException("Buffer devices are not implemented yet");
                        }
                        else
                        {
                            Console.Write("  2222");
                            var fieldCount = await port.ReadByte();

                            //Console.WriteLine($"> There are {fieldCount} fields");
                            var fields = new List <FieldType>();
                            for (int i = 0; i < fieldCount; i += 4)
                            {
                                var currentFieldTypes = await port.ReadByte();

                                for (int j = i; j < Math.Min(i + 4, fieldCount); j++)
                                {
                                    //Console.WriteLine($"> New field {currentFieldTypes & 0b11}");
                                    fields.Add((FieldType)(currentFieldTypes & 0b11));
                                    currentFieldTypes >>= 2;
                                }
                            }
                            Console.Write("  3333");

                            output.Add(new PeripheralDevice(
                                           this,
                                           BitConverter.ToUInt32(productID, 0),
                                           BitConverter.ToUInt32(uniqueID, 0),
                                           index_counter++,
                                           fields
                                           ));
                        }
                    }
                } while (moreDevs != 0);
            } catch (InvalidOperationException) {
                throw new PortClosedException();
            };
            return(output);
        }
예제 #14
0
 private byte[] ReadExistingBytes()
 {
     var bytes = new byte[sp.BytesToRead];
     if (sp.BytesToRead > 1) sp.Read(bytes, 0, sp.BytesToRead);
     return bytes;
 }