// Class method used to Start a Real-Time acquisition (on muscleBAN): // samplingRate -> Desired sampling rate that will be used during the data acquisition stage. // The used units are in Hz (samples/s) // listChannels -> A list where there are specified the active channels. Each entry contains a port number of an active channel. // resolution -> Analog-to-Digital Converter (ADC) resolution. This parameter defines how precise are the digital sampled values when // compared with the ideal real case scenario. // freqDivisor -> Frequency divisor, i.e., acquired data will be subsampled accordingly to this parameter. If freqDivisor = 10, it means that each set of 10 acquired samples // will trigger the communication of a single sample (through the communication loop). public void StartAcquisitionMuscleBanUnity(int samplingRate, List <int> listChannels, int resolution, int freqDivisor) { // callbackPointer -> Pointer to the callback function that will be used to send/communicate the data acquired by PLUX devices, i.e., this callback // function will be invoked during the data acquisition process and through his inputs the acquired data will become accessible. // So, for receiving data on a third-party application it will only be necessary to redefine this callbackFunction. FPtr callbackPointerUnity = new FPtr(CallbackHandlerUnity); if (callbackPointerUnity == null) { return; } // Conversion of List of active channels to a string format. for (int i = 0; i < 8; i++) { if (listChannels.Contains(i + 1)) { ActiveChannelsStr += "1"; } else { ActiveChannelsStr += "0"; } } // Start of acquisition. StartAcquisitionMuscleBan(samplingRate, ActiveChannelsStr, resolution, freqDivisor, callbackPointerUnity); // Start Communication Loop. StartLoopUnity(); // Update global flag. AcquisitionStopped = false; }
public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, FPtr dwNewLong) { if (IntPtr.Size == 4) { return(SetWindowLongPtr32(hWnd, nIndex, dwNewLong)); } return(SetWindowLongPtr64(hWnd, nIndex, dwNewLong)); }
public static void Main() { FPtr cb = new FPtr(App.DoSomething); NativeMethods.TestCallBack(cb, 99); FPtr2 cb2 = new FPtr2(App.DoSomething2); NativeMethods.TestCallBack2(cb2, "abc"); }
public static void Main() { // If delagate will be used just inside one call, this syntax // is ok since platform invoke will protect delegate from GC // until call ends. If unmanaged side could store delegate and // try to use it later than caller should protect delegate until // unmanaged side is finished. FPtr cb = new FPtr(App.DoSomething); LibWrap.TestCallBack(cb, 99); FPtr2 cb2 = new FPtr2(App.DoSomething2); LibWrap.TestCallBack2(cb2, "abc"); }
// Use this for initialization void Start() { // Make sure that the render window continues to render when the game window does not have focus Application.runInBackground = true; CommandBuffer cmb = new CommandBuffer(); cmb.name = "WebRTC Encoding"; cmb.IssuePluginEvent(GetRenderEventFunc(), 0); Camera.main.AddCommandBuffer(CameraEvent.AfterEverything, cmb); FPtr cb = new FPtr(OnInputData); LogPtr logCb = new LogPtr(OnLog); SetInputDataCallback(cb); SetLogCallback(logCb); }
// Use this for initialization void Start() { // Make sure that the render window continues to render when the game window does not have focus Application.runInBackground = true; CommandBuffer cmb = new CommandBuffer(); cmb.name = "WebRTC Encoding"; cmb.IssuePluginEvent(GetRenderEventFunc(), 0); Camera.main.AddCommandBuffer(CameraEvent.AfterEverything, cmb); // note: -1 for a heartbeat tick, fully disables the heartbeat request Login("localhost", 8888, -1); FPtr cb = new FPtr(OnInputData); SetInputDataCallback(cb); }
protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x0134: //WM_CTLCOLORLISTBOX if (m_hListBox == IntPtr.Zero) { if (m.LParam != IntPtr.Zero) { m_hListBox = m.LParam; cb = new FPtr(this.ComboBoxListBoxProc); hr = new HandleRef(this, m_hListBox); m_pWndProc = GetWindowLong(hr, -4); SetWindowLong(hr, -4, cb); } } break; } base.WndProc(ref m); }
// Class method used to Start a Real-Time acquisition: // samplingRate -> Desired sampling rate that will be used during the data acquisition stage. // The used units are in Hz (samples/s) // numberOfChannels -> Number of the active channel that will be used during data acquisition. // With bitalino this value should be between 1 and 6 while for biosignalsplux it is possible to collect data // from up to 8 channels (simultaneously). // resolution -> Analog-to-Digital Converter (ADC) resolution. This parameter defines how precise are the digital sampled values when // compared with the ideal real case scenario. public void StartAcquisitionByNbrUnity(int samplingRate, int numberOfChannels, int resolution) { // callbackPointer -> Pointer to the callback function that will be used to send/communicate the data acquired by PLUX devices, i.e., this callback // function will be invoked during the data acquisition process and through his inputs the acquired data will become accessible. // So, for receiving data on a third-party application it will only be necessary to redefine this callbackFunction. FPtr callbackPointerUnity = new FPtr(CallbackHandlerUnity); if (callbackPointerUnity == null) { return; } // Start of the real-time acquisition. StartAcquisitionByNbr(samplingRate, numberOfChannels, resolution, callbackPointerUnity); // Start Communication Loop. StartLoopUnity(); // Update global flag. AcquisitionStopped = false; }
internal static extern void TestCallBack(FPtr cb, int value);
public static extern double MidFind(double[] ar, ref int size, FPtr ptr, double left, double right, double eps);
private static extern void StartAcquisitionMuscleBan(int samplingRate, string activeChannels, int resolution, int freqDivisor, FPtr callbackFunction);
private static extern void StartAcquisition(int samplingRate, string activeChannels, int resolution, FPtr callbackFunction);
private static extern void StartAcquisitionByNbr(int samplingRate, int numberOfChannel, int resolution, FPtr callbackFunction);
public Client(HttpListenerContext Client, ServerDbContext db) { HttpListenerRequest request = Client.Request; // Объявим строку, в которой будет хранится запрос клиента string Request = ""; // Буфер для хранения принятых от клиента данных List <byte> Buffer = new List <byte>(); // Переменная для хранения количества байт, принятых от клиента int nextbyte = 0;; // Читаем из потока клиента до тех пор, пока от него поступают данные while ((nextbyte = request.InputStream.ReadByte()) != -1) { Buffer.Add((byte)nextbyte); Request += Encoding.ASCII.GetString(new byte[] { (byte)nextbyte }, 0, 1); if (Request.IndexOf("\r\n\r\n") >= 0 || Request.Length > 4096) { break; } } Request += '&'; Console.WriteLine(Request); #region Get // Парсим строку запроса с использованием регулярных выражений if (request.HttpMethod == "GET") { string Response = ""; if (request.Url.AbsolutePath.EndsWith("/")) { Response += "index.html"; } string FilePath = "www/" + Response; // Если в папке www не существует данного файла, посылаем ошибку 404 if (!File.Exists(FilePath)) { SendResult(Client, 404); return; } // Открываем файл, страхуясь на случай ошибки FileStream FS; try { FS = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception) { // Если случилась ошибка, посылаем клиенту ошибку 500 SendResult(Client, 500); return; } HttpListenerResponse response = Client.Response; byte[] buffer = new byte[(int)FS.Length]; // Читаем данные из файла FS.Read(buffer, 0, (int)FS.Length); response.ContentLength64 = buffer.Length; response.ContentType = "text/html"; Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // закрываем поток output.Close(); // Закроем файл и соединение FS.Close(); Console.WriteLine("Обработка подключений завершена"); } #endregion Get #region Post if (request.HttpMethod == "POST") { Regex argument = new Regex(@"(\w*)=([^\&]*)&", RegexOptions.Compiled); MatchCollection matches = argument.Matches(Request); Dictionary <string, string> arguments = new Dictionary <string, string>(); foreach (Match item in matches) { arguments.Add(item.Groups[1].Value, item.Groups[2].Value); } switch (arguments.GetValueOrDefault("Action")) { case "Authentication": { var user = db.Users.Select(a => a).Where(a => a.Name == arguments.GetValueOrDefault("Login")).ToList <User>(); if (user.Count != 0 && user[0].Authorization(arguments.GetValueOrDefault("Password"))) { HttpServer.Server.activeUsers.Add(Client.Request.RemoteEndPoint.ToString(), user[0]); SendResult(Client, 200); } else { SendResult(Client, 400); } break; } case "Closing": { HttpServer.Server.activeUsers.Remove(Client.Request.RemoteEndPoint.ToString()); break; } case "Registration": { var user = db.Users.Select(a => a).Where(a => a.Name == arguments.GetValueOrDefault("Login")).ToList <User>(); if (user.Count != 0) { SendResult(Client, 401); } else if (Verefications.isCorrectLogin(arguments.GetValueOrDefault("Login"))) { User u = new User(arguments.GetValueOrDefault("Login"), arguments.GetValueOrDefault("Password"), arguments.GetValueOrDefault("Email")); db.SaveUser(u); SendResult(Client, 200); } else { SendResult(Client, 402); } break; } case "CalculateIntegral": { string op = "()+-*/^,"; string function = arguments.GetValueOrDefault("Func"); double left = Convert.ToDouble(arguments.GetValueOrDefault("Left").Replace($"%{Convert.ToString((int)',', 16)}", ",", ignoreCase: true, null)); double right = Convert.ToDouble(arguments.GetValueOrDefault("Right").Replace($"%{Convert.ToString((int)',', 16)}", ",", ignoreCase: true, null)); double step = Convert.ToDouble(arguments.GetValueOrDefault("Step").Replace($"%{Convert.ToString((int)',', 16)}", ",", ignoreCase: true, null)); string method = arguments.GetValueOrDefault("Method"); for (int i = 0; i < op.Length; i++) { function = function.Replace($"%{Convert.ToString((int)op[i], 16)}", op[i].ToString(), ignoreCase: true, null); } function.Replace(" ", ""); Parser.Parser parser = new Parser.Parser(function); FPtr f = new FPtr(parser.Calculate); int n = (int)((right - left) / step); double[] res = new double[1000]; double integralValue = 0; switch (method) { case "L": { integralValue = Left(res, n, f, left, right, step); break; } case "T": { integralValue = Trap(res, n, f, left, right, step); break; } case "M": { integralValue = Mid(res, n, f, left, right, step); break; } default: break; } string result = ""; int nom = 0; for (int i = 0; i < n * 4; i += 2, nom++) { result += $"X{nom}={String.Format("{0:f3}", res[i])}&Y{nom}={String.Format("{0:f3}", res[i + 1])}&"; } result += $"Value={String.Format("{0:f4}", integralValue)}&"; SendResult(Client, 200, result); break; } case "CalculateSecond": { string op = "()+-*/^,"; string function = arguments.GetValueOrDefault("Func"); double left = Convert.ToDouble(arguments.GetValueOrDefault("Left").Replace($"%{Convert.ToString((int)',', 16)}", ",", ignoreCase: true, null)); double right = Convert.ToDouble(arguments.GetValueOrDefault("Right").Replace($"%{Convert.ToString((int)',', 16)}", ",", ignoreCase: true, null)); double eps = Convert.ToDouble(arguments.GetValueOrDefault("Eps").Replace($"%{Convert.ToString((int)',', 16)}", ",", ignoreCase: true, null)); for (int i = 0; i < op.Length; i++) { function = function.Replace($"%{Convert.ToString((int)op[i], 16)}", op[i].ToString(), ignoreCase: true, null); } function.Replace(" ", ""); Parser.Parser parser = new Parser.Parser(function); FPtr f = new FPtr(parser.Calculate); int n = 0; double[] res = new double[1000]; double integralValue = 0; integralValue = MidFind(res, ref n, f, left, right, eps); string result = ""; int nom = 0; for (int i = 0; i < n; i += 2, nom++) { result += $"X{nom}={String.Format("{0:f3}", res[i])}&Y{nom}={String.Format("{0:f3}", res[i + 1])}&"; } result += $"Value={String.Format("{0:f4}", integralValue)}&"; SendResult(Client, 200, result); break; } } } #endregion Post Client.Response.Close(); }
public static extern double Mid(double[] ar, int size, FPtr ptr, double left, double right, double step);
private unsafe static extern void setCrashReciever(IntPtr ptr, FPtr t);
private unsafe static extern void setLogMessReciever(FPtr t);
public static extern void SetInputDataCallback(FPtr cb);
// Definition of the callback function responsible for managing the acquired data (which is defined on users Unity script). // callbackHandler -> A function pointer to the callback that will receive the acquired data samples on the Unity side. public bool SetCallbackHandler(FPtr callbackHandler) { callbackPointer = new CallbackManager(callbackHandler); return(true); }
public CallbackManager(FPtr callbackPointer) { callbackReference = callbackPointer; }
public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, FPtr dwNewLong);
public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, FPtr dwNewLong) { if (IntPtr.Size == 4) { return SetWindowLongPtr32(hWnd, nIndex, dwNewLong); } return SetWindowLongPtr64(hWnd, nIndex, dwNewLong); }
private unsafe static extern void setResultReciever(FPtr t);
private unsafe static extern void setCrashReciever(FPtr t);
private unsafe static extern void setResultReciever(IntPtr ptr, FPtr t);
private unsafe static extern void setLogMessReciever(IntPtr ptr, FPtr t);
private async void Button_Click(object sender, RoutedEventArgs e) { double tr = 0; if (double.TryParse(Left.Text, out tr) || double.TryParse(Eps.Text, out tr) || double.TryParse(Right.Text, out tr)) { } else { string expression = Expression.Text; Chart chart = this.FindName("MyWinformChart") as Chart; chart.Series.Clear(); chart.Series.Add(new Series("Series1")); chart.Series[0].BorderWidth = 5; chart.Series["Series1"].ChartArea = "Default"; chart.Series["Series1"].ChartType = SeriesChartType.Spline; double left = Convert.ToDouble(Left.Text); double right = Convert.ToDouble(Right.Text); double step = (right - left) / 20; Parser.Parser parser = new Parser.Parser(expression); if (MainWindow.isConnected) { var values = new Dictionary <string, string> { { "Action", "CalculateSecond" }, { "Func", expression }, { "Left", Left.Text }, { "Right", Right.Text }, { "Eps", Eps.Text } }; var response = await Sender.Sender.Send(values); var responseString = await response.Content.ReadAsStringAsync(); Regex argument = new Regex(@"([^\&]*)=([^\&]*)&", RegexOptions.Compiled); MatchCollection matches = argument.Matches(responseString); Dictionary <string, double> arguments = new Dictionary <string, double>(); foreach (Match item in matches) { arguments.Add(item.Groups[1].Value, double.Parse(item.Groups[2].Value)); } for (double i = 0; i < arguments.Count / 2 - 1; i += 2) { chart.Series.Add(new Series($"Series{2 + i}")); chart.Series[$"Series{2 + i}"].ChartArea = "Default"; chart.Series[$"Series{2 + i}"].ChartType = SeriesChartType.Spline; chart.Series[$"Series{2 + i}"].BorderWidth = 3; chart.Series[$"Series{2 + i}"].Points.AddXY(arguments[$"X{i}"], arguments[$"Y{i}"]); chart.Series[$"Series{2 + i}"].Points.AddXY(arguments[$"X{i + 1}"], arguments[$"Y{i + 1}"]); Result.Text = arguments["Value"].ToString(); } } else { FPtr f = new FPtr(parser.Calculate); int n = 0; double[] res = new double[1000]; double integralValue = 0; integralValue = MidFind(res, ref n, f, left, right, Convert.ToDouble(Eps.Text)); Result.Text = integralValue.ToString(); } for (double x = left; x < right + step / 2; x += step) { chart.Series["Series1"].Points.AddXY(x, parser.Calculate(x)); } } }