Esempio n. 1
0
        /// <summary>
        /// Called when data is received.
        /// </summary>
        /// <param name="data">The data that was received.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="count">The count.</param>
        protected async Task OnDataReceivedAsync(byte[] data, int offset, int count)
        {
            Logger.Debug($"Session {Id} read {count} bytes:");
            Logger.Debug(Environment.NewLine + Utils.HexDump(data, offset, count));

            // save it to the session read buffer
            await SessionReceiveBuffer.LockAsync().ConfigureAwait(false);

            try {
                await SessionReceiveBuffer.WriteAsync(data, offset, count).ConfigureAwait(false);

                // ensure we don't overflow our max buffer
                if (SessionReceiveBuffer.Length > MaxSessionReceiveBufferSize)
                {
                    await ErrorAsync("Session buffer overflow!").ConfigureAwait(false);

                    return;
                }
            } finally {
                SessionReceiveBuffer.Release();
            }

            LastRecvTime = DateTime.Now;

            // push out a copy in the event
            byte[] dataCopy = new byte[count];
            Array.Copy(data, offset, dataCopy, 0, count);
            DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs
            {
                Count = count,
                Data  = dataCopy,
            }
                                      );
        }
 void Start()
 {
     gameObject.SetActive(true);
     handleConstraintsAction = new UnityAction <JObject>(handleConstraints);
     handleConstraintsEvent  = new DataReceivedEvent();
     handleConstraintsEvent.AddListener(handleConstraintsAction);
 }
        private void sendResponseToMainThread(string message, string clazz, string clientRequestId)
        {
            JSONNode jsonNode = JSONNode.Parse(message);

            if (clazz.Equals(".OfflineChatMessageListResponse"))
            {
                List <string> deliveryIdList = getDeliveryIdList(jsonNode);
                if (deliveryIdList.Count > 0)
                {
                    backtoryApi.SendDeliveryList(deliveryIdList);
                }
            }

            string requestId = jsonNode ["requestId"];

            if (requestId != null && !requestId.Equals(""))
            {
                MatchmakingRequestIdList.Add(requestId);
            }

            DataReceivedEvent receivedEvent = pendingRequests [clientRequestId];

            if (receivedEvent != null)
            {
                receivedEvent.data = message;
                // TODO CHECK
                receivedEvent.latch.Signal();
            }
            else
            {
                Debug.Log(TAG + "No data found for request id: " + clientRequestId);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Raised by the socket wrapper when byte data is received from the server
        /// </summary>
        private void ClientInstance_DataReceivedEvent(object sender, DataReceivedEventArgs e)
        {
            try
            {
                Logger.Log(Logger.Level.Info, "A packet was received from the server");

                // Make sure the packet is valid
                if (e.Data == null || e.Data.Length == 0)
                {
                    throw new Exception("A null packet was received.  Skipping");
                }

                Logger.Log(Logger.Level.Debug, $"\tSerialized Packet Length: {e.Data.Length}");

                // Using the overridden method (hopefully), deserialize
                var deserialized = DeserializePacket(e.Data)
                                   ?? throw new Exception("Deserializing the packet resulted in a null value.  Skipping");

                Logger.Log(Logger.Level.Debug, $"\tDeserialized Packet Length: {deserialized.Length}");
                Logger.Log(Logger.Level.Debug, $"Raising the {nameof(DataReceivedEvent)} event");

                // Pass the data on
                var args = new object[] { sender, new DataReceivedEventArgs(deserialized) };
                DataReceivedEvent.RaiseEventSafe(ref args);
            }
            catch (Exception ex)
            {
                Logger.Log(Logger.Level.Error, $"An error occurred while handling the data received.\n\n{ex.Message}");
            }
        }
        // Event: Receiving Transponder data. Creates a list of tracks from it
        private void ReceiverOnTransponderDataReady(object sender, RawTransponderDataEventArgs e)
        {
            var tracks = new List <Track>();

            // Add all tracks to list
            foreach (var data in e.TransponderData)
            {
                // Split data into separate strings
                string[] trackInfo = data.Split(';');

                // Create DateTime object from trackInfo.
                int    timeIndex  = 4;
                string timeString = trackInfo[timeIndex].Substring(0, 4) + "-" +  // 'yyyy'
                                    trackInfo[timeIndex].Substring(4, 2) + "-" +  // 'mm'
                                    trackInfo[timeIndex].Substring(6, 2) + " " +  // 'dd
                                    trackInfo[timeIndex].Substring(8, 2) + ":" +  // 'hh'
                                    trackInfo[timeIndex].Substring(10, 2) + ":" + // 'mm'
                                    trackInfo[timeIndex].Substring(12, 2) + "," + // 'ss'
                                    trackInfo[timeIndex].Substring(14, 3);        // 'fff'
                DateTime time = DateTime.ParseExact(timeString, "yyyy-MM-dd HH:mm:ss,fff",
                                                    System.Globalization.CultureInfo.InvariantCulture);

                // Create track from split data
                var t = new Track(trackInfo[0], int.Parse(trackInfo[1]),
                                  int.Parse(trackInfo[2]), int.Parse(trackInfo[3]),
                                  time, 0
                                  , 0);
                //Velocity and compassCourse will be calculated in  ATM
                // Add track to list
                tracks.Add(t);
            }

            DataReceivedEvent?.Invoke(this, new DataEventArgs(tracks));
        }
Esempio n. 6
0
 // Use this for initialization
 void Start()
 {
     gameObject.SetActive(true);
     dataReceivedAction = new UnityAction <JObject>(reloadBoard);
     dataReceivedEvent  = new DataReceivedEvent();
     dataReceivedEvent.AddListener(dataReceivedAction);
 }
        private void ParseFrame(NetworkDataEventArgs e)
        {
            var data = new List <byte>();
            var payloadStartIndex = 2 + _parser.PayloadLenLenght + _parser.MaskingKeyLenght;

            switch ((WebSocketOpcode)_parser.Opcode)
            {
            case WebSocketOpcode.Ping:
                //Ping frame. Sent Pong Frame.
                _parser.PollReceived = true;
                data.AddRange(_parser.DataBuffer);
                data[0] = (byte)(data[0] & 0xF0);
                data[0] = (byte)(data[0] | (byte)WebSocketOpcode.Pong);
                Write(data.ToArray());
                break;

            case WebSocketOpcode.Pong:
                _parser.PollReceived = true;
                break;

            case WebSocketOpcode.ConnectionClose:
                //Close frame. Sent Close back.
                var connectionCloseReason = (_parser.DataBuffer[payloadStartIndex] << 8) + ((int)_parser.DataBuffer[payloadStartIndex + 1] << 0);
                ConnectionCloseEvent?.Invoke(this, new ConnectionCloseEventArgs((ConnectionCloseReason)connectionCloseReason));
                SendClose((ConnectionCloseReason)connectionCloseReason);
                break;

            case WebSocketOpcode.BinaryFrame:
            case WebSocketOpcode.TextFrame:
                DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs(e.LocalEndPoint, e.RemoteEndPoint, (WebSocketOpcode)_parser.Opcode, _parser.DataBuffer.GetRange(payloadStartIndex, _parser.PayloadLen).ToArray()));
                break;
            }
        }
Esempio n. 8
0
 private void HandleDataReceivedEvent(DataReceivedEvent aciEvent)
 {
     if (DataReceived != null)
     {
         DataReceived(aciEvent);
     }
 }
        private void ReadIncomingData(byte[] data)
        {
            var remainingDataLength = _buffer.Length - _receivedData;

            // we need to know if the incoming data is smaller than the needed data or not, if so we will read it all.
            int length = Math.Min(remainingDataLength, data.Length);

            // this mainly used to skip the header
            if (length != remainingDataLength)
            {
                length -= _readingOffset;
            }

            InternalRead(data, _buffer, length);

            _receivedData += length;

            if (_receivedData == _buffer.Length)
            {
                DataReceivedEvent?.Invoke(_buffer);
                if (CheckIfThereIsAnotherPacket(data))
                {
                    Reset();
                    _readingOffset += length;
                    Read(data);
                }
                else
                {
                    Reset();
                }
            }

            // we don't want to reset the offset until we read the rest of the data * another packet *
            _readingOffset = 0;
        }
Esempio n. 10
0
        private void ProcessEvent(byte[] content)
        {
            var      eventType = (AciEventType)content[0];
            AciEvent aciEvent  = null;

            switch (eventType)
            {
            case AciEventType.BondStatus:
                aciEvent = new BondStatusEvent(content);
                HandleBondStatusEvent((BondStatusEvent)aciEvent);
                break;

            case AciEventType.CommandResponse:
                aciEvent = new CommandResponseEvent(content);
                HandleCommandResponseEvent((CommandResponseEvent)aciEvent);
                break;

            case AciEventType.Connected:
                aciEvent = new AciEvent(content);
                State    = Nrf8001State.Connected;
                break;

            case AciEventType.DataCredit:
                aciEvent = new DataCreditEvent(content);
                HandleDataCreditEvent((DataCreditEvent)aciEvent);
                break;

            case AciEventType.DataReceived:
                aciEvent = new DataReceivedEvent(content);
                HandleDataReceivedEvent((DataReceivedEvent)aciEvent);
                break;

            case AciEventType.DeviceStarted:
                aciEvent = new DeviceStartedEvent(content);
                HandleDeviceStartedEvent((DeviceStartedEvent)aciEvent);
                break;

            case AciEventType.Disconnected:
                aciEvent = new AciEvent(content);
                State    = Nrf8001State.Standby;
                break;

            case AciEventType.PipeStatus:
                aciEvent          = new AciEvent(content);
                OpenPipesBitmap   = aciEvent.Content.ToUnsignedLong(1);
                ClosedPipesBitmap = aciEvent.Content.ToUnsignedLong(9);
                break;

            default:
                aciEvent = new AciEvent(content);
                break;
            }

            Debug.Print("Event: " + eventType.GetName());

            if (AciEventReceived != null)
            {
                AciEventReceived(aciEvent);
            }
        }
Esempio n. 11
0
 private void OnDataReceived(DataReceivedEvent dataReceivedEvent)
 {
     if (dataReceivedEvent.ServicePipeId == RedDotSightPowerPipeId)
     {
         _led.Write(dataReceivedEvent.Data[0] == 1);
     }
 }
Esempio n. 12
0
 private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         List <byte> listBuffer = new List <byte>();
         ReadBuffer(ref listBuffer);
         Thread.Sleep(50);
         //再次读取
         ReadBuffer(ref listBuffer);
         if (listBuffer.Any())
         {
             LogD.Info($"收到的原始报文:{ByteHelper.ToHexString(listBuffer.ToArray())}");
             var requestInfo = SubstatonFilter.Filter(listBuffer);
             if (requestInfo == null)
             {
                 IsBitError = true;
             }
             else
             {
                 IsBitError = false;
                 //触发事件
             }
             _sendCommand.IsReceiveResponse = true;
             DataReceivedEvent?.Invoke(this, new ChannelDataEventArgs(_sendCommand, requestInfo));
         }
     }
     catch (Exception ex)
     {
         _sendCommand.IsReceiveResponse = false;
         LogD.Error($"SerialPort_DataReceived:{ex}");
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Loop that listens for data and raises events when data is received.
        /// </summary>
        private async Task DataReceiver(CancellationToken token)
        {
            Logger.Log(Logger.Level.Debug, $"Currently monitoring socket for incoming data");

            try
            {
                // Loop forever.  That's a long time
                while (true)
                {
                    // Determine if we can loop
                    if (token.IsCancellationRequested || Client == null || !Client.Connected)
                    {
                        Logger.Log(Logger.Level.Debug, $"Halting socket monitoring...");
                        break;
                    }

                    // Read data.  This should not return until data is received
                    byte[] data = await DataReadAsync(token);

                    // Obviously, if there's no data, there's an issue
                    if (data == null)
                    {
                        Logger.Log(Logger.Level.Warning, $"Read null bytes from the socket.  Skipping...");
                        // Wait for a bit and try again
                        await Task.Delay(30);

                        continue;
                    }

                    Logger.Log(Logger.Level.Debug, $"Read {data.Length} bytes from the socket.  Raising events.");

                    // Raise the event unawaited so that we can keep looping in case more data comes in
                    _ = Task.Run(() =>
                    {
                        var args = new object[] { this, new DataReceivedEventArgs(data) };
                        DataReceivedEvent.RaiseEventSafe(ref args);
                    });
                }
            }
            catch (TaskCanceledException)
            {
                // We don't really care if the task was cancelled.
            }
            catch (OperationCanceledException)
            {
                // We don't really care if the task was cancelled.
            }
            catch (Exception ex)
            {
                Logger.Log(Logger.Level.Error, $"An error occurred monitoring the socket for data.\n\n{ex.Message}");
            }

            Logger.Log(Logger.Level.Debug, $"Raising the {nameof(DisconnectedEvent)} event");
            _ = Task.Run(() =>
            {
                var args = new object[] { this, EventArgs.Empty };
                DisconnectedEvent.RaiseEventSafe(ref args);
            });
        }
Esempio n. 14
0
 private void ProcessIncomingData()
 {
     while (_listeningAtcive)
     {
         var strChunk = _blockingCollection.Take();
         DataReceivedEvent?.Invoke(this, new SerialDataEventArgs(strChunk));
     }
 }
Esempio n. 15
0
        /// <summary>
        /// 事件传递函数
        /// </summary>
        /// <param name="data"></param>
        protected virtual void OnDataReceived(TData data)
        {
            if (!Enable)
            {
                return;
            }

            DataReceivedEvent?.Invoke(data);
        }
    public override void OnData(DataReceivedEvent e)
    {
        base.OnData(e);
        var message = e.Read <NetworkTestMessage>();

        if (message != null)
        {
            _.Log("Incoming message: {0}", message.Message);
        }
    }
Esempio n. 17
0
    // Use this for initialization
    void Start()
    {
        status = true;
        //gameObject.SetActive(true);
        dataReceivedAction = new UnityAction <JObject>(done);
        dataReceivedEvent  = new DataReceivedEvent();
        dataReceivedEvent.AddListener(dataReceivedAction);

        dataWaitingAction = new UnityAction <string>(wait);
        dataWaitingEvent  = new SendDataEvent();
        dataWaitingEvent.AddListener(dataWaitingAction);
    }
 private void waitForResponseFromServer(DataReceivedEvent dataReceivedEvent)
 {
     try {
         dataReceivedEvent.latch.Wait(TIMEOUT_IN_SECONDS * 1000);
     } catch (Exception e) {
         // TODO
         Debug.Log(TAG + e.Data);
     } finally {
         // TODO don't pass new object as second parameters
         DataReceivedEvent temp = new DataReceivedEvent("");
         pendingRequests.TryRemove(dataReceivedEvent.requestId, out temp);
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Called when the NIC causes an interrupt.
        /// </summary>
        /// <param name="sender">A reference to the object that caused the event.</param>
        /// <param name="e">The event arguments.</param>
        void OnInterrupt(object sender, EventArgs e)
        {
            // Figure out the reason for the interrupt.
            switch (Nic.InterruptReason)
            {
            case Interrupt.DataReceived:
                DataReceivedEvent.RaiseEvent(this, e as DataReceivedEventArgs);
                break;

            case Interrupt.SendFifoEmpty:
                SendFifoEmptyEvent.RaiseEvent(this, e);
                break;
            }
        }
Esempio n. 20
0
        public BaseService(DataReceivedEvent dr, int port)
        {
            DataReceived += dr;

            // Establish the local endpoint
            // for the socket. Dns.GetHostName
            // returns the name of the host
            // running the application.
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddr = IPAddress.Any;

            _localEndPoint = new IPEndPoint(ipAddr, port);

            // Creation TCP/IP Socket using
            // Socket Class Costructor
            _listener = new Socket(ipAddr.AddressFamily,
                                   SocketType.Stream, ProtocolType.Tcp);
        }
 private void TryBundleAccruedFrames()
 {
     if (accruedFrames.Count == 0)
     {
         return;
     }
     if (accruedFrames[0].Fin)
     {
         DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs {
             Opcode = accruedFrames[0].Opcode, UnmaskedApplicationData = accruedFrames[0].UnmaskedApplicationData
         });
         accruedFrames.RemoveAt(0);
         if (accruedFrames.Count != 0)
         {
             TryBundleAccruedFrames();
         }
     }
     else
     {
         var indexOfFinFrame = accruedFrames.FindIndex(frame => frame.Fin);
         if (indexOfFinFrame != -1)
         {
             var opcode = accruedFrames[0].Opcode; //CHECK: are these all the same
             var unmaskedApplicationData = new List <byte>();
             for (var i = 0; i < indexOfFinFrame; i++)
             {
                 unmaskedApplicationData.AddRange(accruedFrames[0].UnmaskedApplicationData);
             }
             for (var i = 0; i < indexOfFinFrame; i++)
             {
                 accruedFrames.RemoveAt(0);
             }
             DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs {
                 Opcode = opcode, UnmaskedApplicationData = unmaskedApplicationData
             });
             if (accruedFrames.Count != 0)
             {
                 TryBundleAccruedFrames();
             }
         }
     }
 }
Esempio n. 22
0
 private void OnDataReceived(DataReceivedEventArgs eventArgs)
 {
     if (DataReceivedEvent != null)
     {
         //DataReceivedEvent(this, e);
         ////System.Diagnostics.Debug.Assert();
         Delegate[] delArray = DataReceivedEvent.GetInvocationList();
         foreach (Delegate del in delArray)
         {
             try
             {
                 EventHandler <DataReceivedEventArgs> method = (EventHandler <DataReceivedEventArgs>)del;
                 method.BeginInvoke(this, eventArgs, OnDataReceivedProcessComplete, null);
             }
             catch (Exception e)
             {
                 throw e;
             }
         }
     }
 }
Esempio n. 23
0
    public IEnumerator getDataRequest(string _email, string _password, DataReceivedEvent onUserData)
    {
        // Create a form object
        WWWForm form = new WWWForm();

        form.AddField("email", _email);
        form.AddField("password", _password);
        form.AddField("action", "login");

        // Create a download object
        WWW returned = new WWW(account_api, form);

        // Wait until the download is done
        yield return(returned);

        if (!string.IsNullOrEmpty(returned.error))
        {
            Debug.Log("Error downloading: " + returned.error);
            yield break;
        }
        //  Debug.Log(returned.text);
        NetworkResponse             response = JsonUtility.FromJson <NetworkResponse>(returned.text);
        Dictionary <string, string> results  = response.ToDictionary();

        if (results["success"] == "true" && response.user != null)
        {
            Dictionary <string, string> userData = new Dictionary <string, string>();
            int kills  = 0;
            int deaths = 0;
            if (response.user.userdata.Length > 0)
            {
                UserInfo _userData = JsonUtility.FromJson <UserInfo>(response.user.userdata);
                kills  = _userData.getKills();
                deaths = _userData.getDeaths();
            }
            userData["kills"]  = kills.ToString();
            userData["deaths"] = deaths.ToString();
            onUserData.Invoke(userData);
        }
    }
        public string Send(string destination, Dictionary <string, object> jsonData, Dictionary <string, string> extraHeader)
        {
            if (!isConnected())
            {
                throw new Exception("WS is not connected");
            }

            try {
                DateTime Jan1st1970      = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                string   clientRequestId = ((long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds).ToString();
                jsonData.Add("clientRequestId", clientRequestId);
                DataReceivedEvent dataReceivedEvent = new DataReceivedEvent(clientRequestId);
                pendingRequests.TryAdd(clientRequestId, dataReceivedEvent);
                sendNoWait(destination, jsonData, extraHeader);
                waitForResponseFromServer(dataReceivedEvent);

                return(dataReceivedEvent.data);
            } catch (Exception) {
                // TODO uncomment up lines
                return(null);
            }
        }
Esempio n. 25
0
 protected virtual void OnDataReceivedEvent(AirplaneArgs e)
 {
     DataReceivedEvent?.Invoke(this, e);
 }
Esempio n. 26
0
        private void InsertXmlString(List <DataToCollect> dataList, string filePath)
        {
            //create the xml
            XmlDocument fieldXmlDoc = new XmlDocument();

            fieldXmlDoc.Load(filePath); //open the xml file

            foreach (DataToCollect myReading in dataList)
            {
                //build then data structure in xml
                XmlNode fieldDataNode = fieldXmlDoc.SelectSingleNode("FieldData");

                XmlNode newDataNode = fieldXmlDoc.CreateNode(XmlNodeType.Element, "DataNode", null);

                XmlNode newFieldName = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Field", null);
                newDataNode.AppendChild(newFieldName);
                XmlText newFieldNameData = fieldXmlDoc.CreateTextNode(myReading.savedFieldName);
                newFieldName.AppendChild(newFieldNameData);

                XmlNode newLatReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Latitude", null);
                newDataNode.AppendChild(newLatReading);
                XmlText newLatData = fieldXmlDoc.CreateTextNode(myReading.savedLat.ToString());
                newLatReading.AppendChild(newLatData);

                XmlNode newLongReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Longitude", null);
                newDataNode.AppendChild(newLongReading);
                XmlText newLongData = fieldXmlDoc.CreateTextNode(myReading.savedLon.ToString());
                newLongReading.AppendChild(newLongData);

                XmlNode newAltReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Altitude", null);
                newDataNode.AppendChild(newAltReading);
                XmlText newAltData = fieldXmlDoc.CreateTextNode(myReading.savedAlt.ToString());
                newAltReading.AppendChild(newAltData);

                XmlNode newSpeedReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Speed", null);
                newDataNode.AppendChild(newSpeedReading);
                XmlText newSpeedData = fieldXmlDoc.CreateTextNode(myReading.savedSpeedKph.ToString());
                newSpeedReading.AppendChild(newSpeedData);

                XmlNode newYieldReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Yield", null);
                newDataNode.AppendChild(newYieldReading);
                XmlText newYieldData = fieldXmlDoc.CreateTextNode(myReading.savedYieldTime.ToString());
                newYieldReading.AppendChild(newYieldData);

                XmlNode newPaddleReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Paddle", null);
                newDataNode.AppendChild(newPaddleReading);
                XmlText newPaddleData = fieldXmlDoc.CreateTextNode(myReading.savedPaddleTime.ToString());
                newPaddleReading.AppendChild(newPaddleData);

                XmlNode newDate = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Date", null);
                newDataNode.AppendChild(newDate);
                XmlText newDateData = fieldXmlDoc.CreateTextNode(myReading.savedDate.ToString());
                newDate.AppendChild(newDateData);

                XmlNode newTimeReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Time", null);
                newDataNode.AppendChild(newTimeReading);
                XmlText newTimeData = fieldXmlDoc.CreateTextNode(myReading.savedTime.ToString());
                newTimeReading.AppendChild(newTimeData);

                fieldDataNode.AppendChild(newDataNode);
            }

            fieldXmlDoc.Save(filePath);    //save record to xml file

            if (DataReceivedEvent != null) //do we have subscribers
            {
                SendDataStoredArgs args = new SendDataStoredArgs()
                {
                    dataSaved = true
                };
                DataReceivedEvent.Invoke(null, args);
            }
        }
Esempio n. 27
0
    /// <summary>
    ///     ''' Polling is started in Initialize
    ///     ''' </summary>
    private static void PollSerialPort()
    {
        try
        {
            byte[] Buffer;

            while (true)
            {
                if (Port.BytesToRead > 1)
                {
                    Thread.Sleep(20);

                    Buffer = new byte[Port.BytesToRead + 1];

                    Port.Read(Buffer, 0, Buffer.Length);

                    char[] Chars = System.Text.Encoding.UTF8.GetChars(Buffer);

                    for (var i = 0; i <= Chars.Length - 1; i++)
                    {
                        Data += Chars[i];
                    }


                    switch (CurrentMode)
                    {
                    case (int)Mode.Connect:
                    {
                        // Get IP
                        if (InString(Data, "+CIFSR:STAIP,"))
                        {
                            IPAddress = ParseIPAddres(Data);
                        }
                        break;
                    }

                    case (int)Mode.TCPServer:
                    case (int)Mode.AP:
                    {
                        if (InString(Data, "+IPD"))
                        {
                            ServerRequest = Data;

                            // Get the current connection linked ID
                            // Used to send the requested data in SendServerRequest
                            LinkedID = GetLinkID(ServerRequest);

                            if (CurrentMode == (int)Mode.TCPServer)
                            {
                                ServerRequestEvent.Invoke();
                            }

                            if (CurrentMode == (int)Mode.AP)
                            {
                                APServerRequestEvent.Invoke();
                            }
                        }

                        break;
                    }

                    case (int)Mode.TCPClient:
                    {
                        // Returned request from Google
                        if (InString(Data, "+IPD"))
                        {
                            GetTimeFromString(Data);
                        }
                        break;
                    }
                    }

                    DataReceivedEvent.Invoke();

                    Data = string.Empty;
                }

                Thread.Sleep(100);
            }
        }
        catch (Exception ex)
        {
            PrintData("Error: PollSerialPort: " + ex.ToString());
        }
    }
Esempio n. 28
0
		/// <summary>
		/// Starts a process without showing a console.
		/// </summary>
		public static Process ExecuteSilentlyAsync(string Executable, string Arguments, string StartDirectory,
			DataReceivedEvent OnOutput, DataReceivedEvent OnError, ProcessExitedEvent OnExit)
		{
			if (GlobalProperties.Instance.VerboseBuildOutput)
				ErrorLogger.Log(Executable + " " + Arguments,ErrorType.Message,ErrorOrigin.Build);

			if (!File.Exists(Executable))
			{
				ErrorLogger.Log(Executable + " not found!",ErrorType.Error,ErrorOrigin.Build);
				return null;
			}

			var psi = new ProcessStartInfo(Executable, Arguments) { 
				WorkingDirectory=StartDirectory,
				CreateNoWindow=true,
				UseShellExecute=false,
				//RedirectStandardInput=true,
				RedirectStandardError=true,
				RedirectStandardOutput=true,
                StandardErrorEncoding= Encoding.UTF8,
                StandardOutputEncoding=Encoding.UTF8
			};

			var prc = new Process() { StartInfo=psi, EnableRaisingEvents=true};

			prc.ErrorDataReceived += delegate(object s, DataReceivedEventArgs e) {
				if (!string.IsNullOrEmpty(e.Data))
				{ 
					if(GlobalProperties.Instance.VerboseBuildOutput)
						ErrorLogger.Log(e.Data,ErrorType.Warning,ErrorOrigin.Build);

					if(OnError != null)
						OnError(e.Data);
				}
			};
			prc.OutputDataReceived += delegate(object s, DataReceivedEventArgs e)
			{
				if (!string.IsNullOrEmpty(e.Data))
				{
					if(GlobalProperties.Instance.VerboseBuildOutput)
						ErrorLogger.Log(e.Data,ErrorType.Message,ErrorOrigin.Build);

					if(OnOutput != null)
						OnOutput(e.Data);
				}
			};
			prc.Exited +=new EventHandler( delegate(object s, EventArgs e) { if (OnExit != null) OnExit(); });

			try
			{
				prc.Start();
				prc.BeginErrorReadLine();
				prc.BeginOutputReadLine();
			}
			catch (Exception ex)
			{
				ErrorLogger.Log(ex, ErrorType.Error, ErrorOrigin.Build);
				return null;
			}
			return prc;
		}
Esempio n. 29
0
 private void RaiseReceivedEvent(byte[] data, EndPoint source)
 {
     Logger.Log(LogLevel.Information, "Received data from {0}.", source.ToString());
     DataReceivedEvent?.Invoke(this, data, source);
 }
Esempio n. 30
0
 private static void DataReceivedEventHandler(DataReceivedEvent dataReceivedEvent)
 {
     WriteObject(dataReceivedEvent);
 }
 /// <summary>
 /// Event delegate to notify state change events.
 /// </summary>
 /// <param name="args">Device event data.</param>
 protected void OnDataReceived(SesnsorReadEventArgs args)
 {
     DataReceivedEvent?.Invoke(this, args);
 }