/// <summary>
 /// ctor
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="cache"></param>
 /// <param name="toArduino"></param>
 /// <param name="configuration"></param>
 public DigitalController(ILogger<DigitalController> logger, IMemoryCache cache, ConnectToArduino toArduino, IConfiguration configuration)
 {
     _logger = logger;
     _cache = cache;
     _toArduino = toArduino;
     _configuration = configuration;
     var expiration = _configuration.GetValue<int>("Cache:AbsoluteExpirationInSec");
     CacheEntryOptions = new MemoryCacheEntryOptions
     {
         AbsoluteExpiration = DateTime.Now.AddSeconds(expiration),
         Priority = CacheItemPriority.High,
         SlidingExpiration = TimeSpan.FromSeconds(expiration)
     };
 }
Пример #2
0
 // Use this for initialization
 void Start()
 {
     connectiontext   = GameObject.Find("ConnectionText").GetComponent <Text>();
     connectToArduino = GameObject.Find("ConnectToArduino").GetComponent <ConnectToArduino>();
     BaudRate         = connectToArduino.sanitizedBaudRate;
     PortName         = connectToArduino.sanitizedSerialPort;
     email            = connectToArduino.email;
     Comment          = connectToArduino.comment;
     pid = connectToArduino.pid;
     isLoggingStarted = false;
     hasStateChanged  = false;
     serialPort       = connectToArduino.serialport;
     isConnected      = true;
     sceneLeft        = false;
     UpdateStatus();
     _ = CheckConnectionAsync();
     LoggingManager = GameObject.Find("LoggingManager").GetComponent <LoggingManager>();
     //OpenPort(); //Open the serial port when the scene is loaded.
 }
    void Awake()
    {
        eventSystem = EventSystem.current;
        string[] ports = SerialPort.GetPortNames();
        DisplayAvailablePorts();

        // If there isn't already an instance of ConnectToArduino, set it to this.
        if (Instance == null)
        {
            Instance = this;
        }
        // If there is an existing instance, destroy it.
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
        //Setting dontdestroyonload to our soundmanager so it will keep being there when reloading the scene.
        DontDestroyOnLoad(gameObject);
        SceneManager.sceneLoaded += this.OnLoadCallback;
    }
Пример #4
0
    //Process the data we get from our Arduino (this function might be called more often than Update(), depending on the chosen polling rate)
    private void ProcessInputFromArduino(string serialInput)
    {
        if (!ParseIncomingData)
        {
            return;
        }
        // Read what is our current state
        if (receiverState == ReceiverState.Standby)
        {
            // Check for "BEGIN" string.
            if (serialInput.Contains("LOG BEGIN"))
            {
                // Parse Reported Column and Separator
                ParseDataArguments(serialInput);
                onLoggingStarted.Invoke(outputLabel);
                receiverState = ReceiverState.ReadingHeader;
            }
        }
        else if (receiverState == ReceiverState.ReadingHeader)
        {
            // Parse header
            connectToArduino = GameObject.Find("ConnectToArduino").GetComponent <ConnectToArduino>();
            // Update PID whenever we get a new header from Arduino
            // This enables us to use the reconnect button
            pid       = connectToArduino.pid;
            email     = connectToArduino.email;
            Comment   = connectToArduino.comment;
            timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff");
            //List<string> headersList = new List<string>();
            headers = serialInput.Split('\t').ToList();
            if (NewHeaderEvent != null)   //Check that someone is actually subscribed to the event
            {
                NewHeaderEvent(headers);  //Fire the event in case someone is subscribed
            }
            // Check that header contains the expected number of columns.
            if (headers.Count == numberOfColumns)
            {
                //foreach (var header in headers) {
                //    headersList.Add(header);
                //}
                LoggingManager.DeleteAllLogs();
                LoggingManager.SetEmail(email);
                LoggingManager.CreateLog(outputLabel);
                //LoggingManager.TerminateLogRow("Meta");
                receiverState = ReceiverState.ReadingData;
            }
            else
            {
                // Otherwise error out and go to Standby Mode.
                Debug.LogError("Received " + headers.Count + "columns, but Arduino reported " + numberOfColumns + "! Data Discarded..");
                receiverState = ReceiverState.Standby;
            }
        }
        else if (receiverState == ReceiverState.ReadingData)
        {
            // Check for "END" strings
            if (serialInput.Contains("LOG END"))
            {
                StopLogging();
            }
            else
            {
                // Parse data
                var bodyData = serialInput.Split('\t');

                // Check that bodyData contains the expected number of columns.
                if (bodyData.Length == numberOfColumns)
                {
                    Dictionary <string, object> currentLogs = new Dictionary <string, object>();

                    currentLogs.Add("Comment", Comment);
                    currentLogs.Add("PID", pid);

                    for (int i = 0; i < bodyData.Length; i++)
                    {
                        string header = headers[i];
                        header = header.Replace("\n", "");
                        header = header.Replace("\r", "");
                        string sanitizedValue = new string((from c in bodyData[i] where char.IsLetterOrDigit(c) || char.IsPunctuation(c) select c).ToArray());
                        if (sanitizedValue == "NA")
                        {
                            sanitizedValue = "NULL";
                        }
                        currentLogs.Add(header, sanitizedValue);
                    }
                    LoggingManager.Log(outputLabel, currentLogs);
                    // LoggingManager.TerminateLogRow(outputLabel);
                    //When ever new data arrives, the scripts fires an event to any scripts that are subscribed, to let them know there is new data available (e.g. my Arduino Logger script).
                    if (NewDataEvent != null)
                    {                                //Check that someone is actually subscribed to the event
                        NewDataEvent(logCollection); //Fire the event in case someone is subscribed
                    }
                }
                else
                {
                    // Otherwise error out and go to Standby Mode.
                    Debug.LogError("Received " + bodyData.Length + "columns, but Arduino reported " + numberOfColumns + "! Data Discarded..");
                    receiverState = ReceiverState.Standby;
                }
            }
        }

        /*  */

        // ----- INPUT FROM ARDUINO TO UNITY ----- //
        //From here you can do what ever you want with the data.
        //As an example, I parse the data into public variables that can be accessed from other classes/scripts:

        //string[] values = serialInput.Split('\t');  //Split the string between the chosen delimiter (tab)

        //ArduinoMillis = uint.Parse(values[0]);      //Pass the first value to an unsigned integer
        //RawEDA = int.Parse(values[1]);              //Pass the second value to an integer
        //int tmpIBI = int.Parse(values[2]);
        //if (tmpIBI > 0)
        //    IBI = tmpIBI;
        //RawPulse = int.Parse(values[3]);
        //rawPressure = int.Parse(values[4]);
        //testStart = int.Parse(values[5]);

        //Feel free to add new variables (both here and in the Arduino script).
    }