public async Task Run() { UdpLaserListener.Status = true; while (UdpLaserListener.Status) { this.udpClient = new UdpClient(port); this.groupEP = new IPEndPoint(IPAddress.Loopback.Address, port); try { byte[] bytes = await Task <byte[]> .Factory.StartNew(() => { Console.WriteLine("Waiting for broadcast"); return(udpClient.Receive(ref groupEP)); }); IncomingData?.Invoke(this, bytes); } catch (SocketException er) { Console.WriteLine(er); } finally { udpClient.Close(); } } udpClient.Close(); }
public ActionResult Agrigation(IncomingData getData) { Read Read = new Read(); string[] fileContents = Directory.GetFiles(Server.MapPath(@"~/App_Data/")); if (Read.readFile(getData.Mode, fileContents)) { List <DataValue> ListData = Read.ListValue.Where(x => x.date >= DateTime.ParseExact(getData.DateStart, "yyyyMMdd", CultureInfo.GetCultureInfo("tr-TR")) & x.date <= DateTime.ParseExact(getData.DateEnd, "yyyyMMdd", CultureInfo.GetCultureInfo("tr-TR"))).ToList <DataValue>(); if (ListData.Count() > 0) { Dictionary <string, Dictionary <string, double> > dic = new Dictionary <string, Dictionary <string, double> >(); Dictionary <string, object> result = new Dictionary <string, object>(); foreach (var item in ListData.GroupBy(x => x.code).Select(x => x.First())) { dic[item.code.ToLower()] = new Dictionary <string, double>(); dic[item.code.ToLower()]["rate"] = ListData.Where(x => x.code == item.code).Average(x => x.rate); } result["rates"] = new object[] { dic }; string json = new JavaScriptSerializer().Serialize(result); ViewBag.jval = json; } } return(View()); }
/// <summary> /// This is the code that gets executed in another thread /// and parses all incoming bytes /// </summary> private void ReceiveQueueThread() { byte currentByte = 0x0; bool foundByteFlag = false; // This thread runs while we have the processQueue set while (processQueue) { // lock the incoming data so we don't have any race confitions lock (IncomingData) { // take a peek and dequeue the first byte in the queue if (IncomingData.Count > 0) { currentByte = IncomingData.Dequeue(); foundByteFlag = true; } } // If we found a byte then Handle it if (foundByteFlag) { HandleByte(currentByte); } else { Thread.Sleep(10); } // reset the flag and the byte value foundByteFlag = false; currentByte = 0x0; } }
public async Task <systemappuser> GetSystemAppUserApiKeys(IncomingData appData) { int userId = appData.systemuserid; int sysappid = appData.appid; if (userId == 0 || userId <= 0) { throw new ArgumentException("You have to pass a systemapp id.", "sysappid"); } if (sysappid == null || sysappid <= 0) { throw new ArgumentException("You have to pass a a valid username", "userId"); } return(await Task.Run <systemappuser>(() => { try { using (var systemapps = new userappsEntities()) { using (var system = new Model.exgripEntities()) { var user = system.UserProfiles.Where(u => u.UserId == userId).FirstOrDefault(); var sysApp = systemapps.systemapps.Where(app => app.id == sysappid).FirstOrDefault(); if ((user != null) && (sysApp != null)) { var systemAppUser = systemapps.systemappusers.Where(sysusr => sysusr.appid == sysappid && sysusr.systemuserid == userId).FirstOrDefault(); if (systemAppUser != null) { return new systemappuser() { apptoken = systemAppUser.apptoken, appSecret = systemAppUser.appSecret }; } else { return null; } } else { return null; } } } } catch (Exception ex) { throw new HttpResponseException(HttpStatusCode.InternalServerError); } })); }
private void ProviderDataReceived(object sender, DataReceivedEventArgs e) { // Just add the received bytes to the incoming data queue lock (IncomingData) { foreach (var b in e.BytesReceived) { IncomingData.Enqueue(b); } } }
private void _OnDataReceived(object sender, Renci.SshNet.Common.ShellDataEventArgs e) { string input = Encoding.UTF8.GetString(e.Data); if (IncomingData != null) { IncomingData.Invoke(this, new IncomingDataEventArgs { Data = input }); } }
/// <summary> /// This registers differnet data types that are supported. /// </summary> /// <param name="type">type of data that can come from server. This class must inherit from BaseDataPackage.</param> /// <param name="handler">Method to call when data shows up</param> public void RegisterHandler(Type type, IncomingData handler) { //check if type inherit from BaseDataPackage if (typeof(BaseDataPackage).IsAssignableFrom(type)) { Functions.Add(type, handler); } else { throw new ArgumentException("type must inherit from BaseDataPackage"); } }
/// <summary> /// Generates the event message. /// </summary> /// <param name="service">The <see cref="Service"/> to create event message for.</param> /// <param name="eventData">The <see cref="EventData"/> to generate event message for.</param> /// <param name="useSockJs">Indicates if SockJS should be used.</param> /// <returns>The event message as JSON string.</returns> public static string GenerateEventMessage(Service service, EventData eventData, bool useSockJs) { IncomingData incomingData = new IncomingData(service.Uuid, eventData.Event.Id, eventData.EventPriority, eventData.PublishingDate, eventData.Value, eventData.CorrelationId); if (useSockJs) { return(AddSockJsFrame($"{MessageType.EVENT} {EscapeStringValue(SerializeObject(incomingData))}")); } else { return($"{MessageType.EVENT} {SerializeObject(incomingData)}"); } }
public string RX() { var sb = new System.Text.StringBuilder(); while (!Buffer_RX.Empty) { sb.Append(Buffer_RX.Dequeue); } Console.WriteLine($"[RX] :{sb.ToString()}#"); IncomingData?.Invoke(this, EventArgs.Empty); return(sb.ToString()); }
private void ReceivedDataHandle(object sender, EventArgs e) { string[] SplitData = IncomingData.Split(','); if (SplitData[0].Equals("V")) { SetRPMSensor(SplitData[1], SplitData[2]); } else if (SplitData[0].Equals("T")) { DisableFunctionsWorking(); FunctionsAssignValues(SplitData); FunctionsShowTable(); } }
public async Task <IActionResult> Receive(string id) { string request_body = await ReadRequestBody(Request); IncomingData incoming_data = new IncomingData { ID = Guid.NewGuid(), ReferenceID = id, RawData = request_body, TimeStamp = DateTime.UtcNow, IsProcessed = false }; _incomingDataRepository.SetIncomingData(incoming_data); _incomingDataRepository.Save(); return(Ok("Done")); }
private void ShowIncomingStream(IncomingData theData) { try { if (this.IncomingStreamVisable && this.cbxRemoteIDs.Text == theData.RemoteDeviceID && this.FilterStream(theData.Stream)) { // 防止频繁刷新。 if (tvMessageSummary.Nodes.Count >= this.MaxSummaryCount && tvMessageSummary.SelectedNode != null && tvMessageSummary.SelectedNode.Index == 0) { this.tvMessageSummary.SelectedNode = null; } // 清除过期数据。 if (tvMessageSummary.Nodes.Count >= this.MaxSummaryCount) { tvMessageSummary.Nodes.RemoveAt(0); } // 如果没有指定解析器,则使用默认的解析器。 var parser = theData.Parser; if (parser == null) { parser = _inputStreamDefaultParser; } // Create a node var node = new TreeNode(); node.Tag = new TreeNodeTag(theData.Frame, theData.Stream, parser); node.Text = string.Format("{0}, {1}", theData.RemoteDeviceID, theData.CreationTime.ToString("yyyy-MM-dd HH:mm:ss.fff")); node.ImageKey = "InputStream"; node.SelectedImageKey = "InputStream_Selected"; // Add Node tvMessageSummary.Nodes.Add(node); } } catch (Exception ex) { this.txtDetail.Text = ex.ToString(); } }
public async void StartTransfer() { CancellationToken token = cts.Token; try { //PSoC.pid = Int32.Parse(PID, System.Globalisation.NumberStyles.HexNumber; //PSoC.vid = Int32.Parse(VID.. await Task.Run(() => PSoC.Transfer(), token); if (true)//(Usb.incomingData !=null) { IncomingData.Add("Usb.incomingData + timestamp"); } } catch (Exception ex) { } }
private void SendRawDataAgent() { while (!_sendRawDataEnd.WaitOne(0)) { try { DataInfo dataInfo = IncomingData.Take(_sendRawDataCancel.Token); if (dataInfo.XRayInfo.Energy == EnergyType) { int /*pixel count*/ count = dataInfo.LineData.Length; if (AppConfiguration.DiplotRemoveReferenceData) { count -= AppConfiguration.DetectorsPerBoard * (AppConfiguration.ReferenceRangeUpperDetectorNum - AppConfiguration.ReferenceRangeLowerDetectorNum + 1); /*ignore reference pixels*/ } // Detector data is bytesPerPixels size, not 4 bytes that uint contains. byte[] buffer = new byte[dataInfo.NumberOfBytesPerPixel * count]; int bufferIndex = 0; for (int ix = 0; ix < count; ix++) { PixelConverter.PixelToBytes(dataInfo.LineData, ix, ref buffer, ref bufferIndex, AppConfiguration.BytesPerPixel); } #if false Parallel.For(0, numPixels, index => { PixelConverter.PixelToBytes(dataInfo.LineData, index, ref buffer, ref bufferIndex, AppConfiguration.BytesPerPixel); }); #endif base.SendLineData(buffer); } } catch (Exception ex) { if (!_sendRawDataEnd.WaitOne(0)) { Logger.LogError(ex); } } } }
public async Task <HttpResponseMessage> AddSystemAppUser(IncomingData appData) { int userId = appData.systemuserid; int sysappid = appData.appid; if (userId == 0 || userId <= 0) { throw new ArgumentException("You have to pass a systemapp id.", "sysappid"); } if (sysappid == null || sysappid <= 0) { throw new ArgumentException("You have to pass a a valid username", "userId"); } using (var userapps = new Model.userappsEntities()) { using (var system = new Model.exgripEntities()) { if (!userapps.systemapps.Any(a => a.id == sysappid)) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "System application does not exist")); } else { userapps.ChangeTracker.DetectChanges(); var systemUser = system.UserProfiles.Where(sus => sus.UserId == userId).FirstOrDefault(); var sysAppUser = userapps.systemappusers.Where(us => us.systemuserid == systemUser.UserId).FirstOrDefault(); Model.systemappuser sysAppUserEntry = null; if (sysAppUser == null) { try { var password = Membership.GeneratePassword(10, 3); //Generate authentication data UserAppAuthenticationManager authManger = new Security.UserAppAuthenticationManager(); var user = await authManger.IssueTokenSysApp(systemUser.UserName, password, systemUser.UserId, sysappid); sysAppUserEntry = new Model.systemappuser() { systemuserid = systemUser.UserId, appSecret = user.Secret, apptoken = user.Token, appid = sysappid, securitySoup = user.SecSoup }; userapps.systemappusers.Add(sysAppUserEntry); await userapps.SaveChangesAsync(); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Format("Database error. Exception:{1}", ex.Message))); } return(Request.CreateResponse <Model.systemappuser>(sysAppUserEntry)); } else { try { var password = Membership.GeneratePassword(10, 3); //Generate authentication data UserAppAuthenticationManager authManger = new Security.UserAppAuthenticationManager(); var user = await authManger.IssueTokenSysApp(systemUser.UserName, password, systemUser.UserId, sysappid); sysAppUser.appSecret = user.Secret; sysAppUser.apptoken = user.Token; sysAppUser.securitySoup = user.SecSoup; await userapps.SaveChangesAsync(); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Format("Database error. Exception:{1}", ex.Message))); } return(Request.CreateResponse <Model.systemappuser>(sysAppUser)); } } } } }
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // If the com port has been closed, do nothing if (!comport.IsOpen) { return; } // This method will be called when there is data waiting in the port's buffer // Determain which mode (string or binary) the user is in if (CurrentDataMode == DataMode.Text) { //Handle Commands in form of text PF IncomingData.addIncomingText(comport.ReadExisting()); bool updatesMade = false; string currentCommandString = ""; IncomingData.lockMutex(); // incase we have updates, let's lock this thing down string commandString = IncomingData.getCurrentTextNotMutexed(); // this is safe because we are handling the mutex ourselves while (commandString.Contains(Command.commandEnder)) { commandString = commandString.Replace('\r', ' '); // unnecessary character // strip the command out currentCommandString = commandString.Substring(0, commandString.IndexOf(Command.commandEnder) + Command.commandEnder.Length); // remove the current command from the current command list commandString = commandString.Substring(currentCommandString.Length); updatesMade = true; terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, currentCommandString + '\n'); groundStation.CommandReceived(currentCommandString); // send the new command to the ground station AddAuditToHistory(currentCommandString, CurrentDataDirection.Incoming); } if (updatesMade) { IncomingData.setCurrentTextNotMutexed(commandString); // set our current text to whatever is left of the command string, this is safe because we are handling the mutex ourselves } IncomingData.unlockMutex(); //AddAuditToHistory(data, CurrentDataDirection.Incoming); } else if (CurrentDataMode == DataMode.Hex) { // Obtain the number of bytes waiting in the port's buffer int bytes = comport.BytesToRead; // Create a byte array buffer to hold the incoming data byte[] buffer = new byte[bytes]; // Read the data from the port and store it in our buffer comport.Read(buffer, 0, bytes); // Show the user the incoming data in hex format terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, terminalPresenter.ByteArrayToHexString(buffer)); AddAuditToHistory(terminalPresenter.ByteArrayToHexString(buffer), CurrentDataDirection.Incoming); } else if (CurrentDataMode == DataMode.TextFile) { // Obtain the number of bytes waiting in the port's buffer int bytes = comport.BytesToRead; // Create a byte array buffer to hold the incoming data byte[] buffer = new byte[bytes]; // Read the data from the port and store it in our buffer comport.Read(buffer, 0, bytes); string fileName = settings.ReceivedFilePath + "ReceivedFile_" + DateTime.Now.Minute + DateTime.Now.Second + ".txt"; File.WriteAllBytes(fileName, buffer); terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "New file received in the path:" + fileName); terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "\n"); StreamReader receivedFile = null; try { terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "Summary:"); terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "\n"); receivedFile = new System.IO.StreamReader(fileName); string summaryOfFile = receivedFile.ReadLine(); terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, summaryOfFile); terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "\n"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { receivedFile.Close(); } AddAuditToHistoryforfile("New file received in the path:" + fileName, CurrentDataDirection.Incoming); } else if (CurrentDataMode == DataMode.Image) { string data = comport.ReadExisting(); terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "New Image received in the path:" + data); AddAuditToHistoryforfile("New Image received in the path:" + data, CurrentDataDirection.Incoming); /* * Iam not reading anything from the port for now, let's see if we are able to open up the saved images in the SendBinaryFile method, * then we will write the path to the port in the SendBinaryFile method and read it below in the port_DataReceived */ } #region Commented //int bytes = Convert.ToInt32(comport.ReadExisting()); ////int bytes = comport.BytesToRead; //byte[] image = new byte[bytes]; //comport.Read(image, 0, bytes); //string fileName = settings.ReceivedFilePath + "ReceivedFile_" + DateTime.Now.Minute + DateTime.Now.Second + ".jpg"; //File.WriteAllBytes(fileName, image); //terminalPresenter.Log(rtfTerminal, LogMsgType.Incoming, "New file received in the path:" + fileName); //System.Drawing.Image newImage; //if (image != null) //{ // using (MemoryStream stream = new MemoryStream(image)) // { // try // { // stream.Position = 0; // stream.ToArray(); // newImage = System.Drawing.Image.FromStream(stream); // Bitmap b = new Bitmap(newImage); // pictureBox1.Image = b; // } // catch (Exception ex) // { // MessageBox.Show(ex.Message); // } // } //} //OpenFileDialog openFileDialogToSend = new OpenFileDialog(); //openFileDialogToSend.Multiselect = false; //if (openFileDialogToSend.ShowDialog() == DialogResult.OK) //{ // SendBinaryFile(comport, openFileDialogToSend.FileName); //} // // Obtain the number of bytes waiting in the port's buffer // int bytes = comport.BytesToRead; // // Create a byte array buffer to hold the incoming data // byte[] buffer = new byte[bytes]; // // Read the data from the port and store it in our buffer // comport.Read(buffer, 0, bytes); // try // { // MemoryStream ms = new MemoryStream(); // ms.Write(buffer, 0, buffer.Length); // ms.ToArray(); // ms.Position = 0; // Bitmap b = new Bitmap(ms); // PictureBox pictureBox = new PictureBox(); // pictureBox.Image = b; // } // catch (Exception ex) { MessageBox.Show(ex.Message); } // //Giri in most of the blogs i read we have to Reset the position of the memory stream prior to loading the image. // //string fileName = settings.ReceivedFilePath + "ReceivedImageFile_" + DateTime.Now.Minute + DateTime.Now.Second + ".txt"; // //File.WriteAllBytes(fileName, buffer); // //byte[] tempFile = File.ReadAllBytes(fileName); // //MemoryStream stream = new MemoryStream(tempFile); // //Image currentImage = Image.FromStream(stream); // try // { // MemoryStream stream = new MemoryStream(buffer); // Image image = System.Drawing.Image.FromStream(stream, true); // } // catch (Exception ex) { MessageBox.Show(ex.Message); } //} #endregion }
private void onIncomingData(object o) { IncomingData?.Invoke(this, new ObjectEventArgs(o)); }
protected virtual void OnDataReceived(DataReceived eventArgs) { IncomingData?.Invoke(this, eventArgs); }
public void SetIncomingData(IncomingData data) { _db.IncomingData.Add(data); }
public void AddDataLine(ref DataInfo dataInfo) { IncomingData.TryAdd(dataInfo, AppConfiguration.DataLineProcessTimeout); }