Exemplo n.º 1
0
    void Update()
    {
        // ---- process commands and send them out if time threshold has been reached ----

        sendNextUpdates += Time.deltaTime;

        if (sendNextUpdates >= messageSendRateMs / 1000)
        {
            // for each module first check if there are new values, if so send them a command over serial
            foreach (KeyValuePair <int, Command> entry in commandsById)
            {
                Command command  = entry.Value;
                int     moduleId = entry.Key;

                int[] newValues = null;

                switch (modulesById[moduleId].actuatorType)
                {
                case ActuatorType.Haptic:
                    newValues = MaxStackValues(queuedActuatorValuesById[moduleId]);
                    break;

                case ActuatorType.Temperature:
                    newValues = MaxStackValues(queuedActuatorValuesById[moduleId]);
                    //newValues = AverageStackValues(queuedActuatorValuesById[moduleId]);
                    break;

                case ActuatorType.EMS:
                    newValues = MaxStackValues(queuedActuatorValuesById[moduleId]);
                    //newValues = AverageStackValues(queuedActuatorValuesById[moduleId]);
                    break;
                }

                if (newValues != null)
                {
                    command.values = newValues;
                    commandsToSendNext.Push(command);
                    SetColor(moduleId, command.values);
                }
            }

            SendCommands();
            sendNextUpdates = 0.0f;
        }

        // ---- process incomming messages ----

        string message = ReceiveMessage();

        if (message == null)
        {
            return;
        }

        // Check if the message is plain data or a connect/disconnect event.
        if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_CONNECTED))
        {
            Debug.Log("Connection established");
        }
        else if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_DISCONNECTED))
        {
            Debug.Log("Connection attempt failed or disconnection detected");
        }
        else
        {
            if (ShowInMessages == true)
            {
                Debug.Log("Received message: " + message);
            }

            // parse json
            try
            {
                Summary summary = Summary.CreateFromJSON(message);

                foreach (ModuleInformation item in summary.modules)
                {
                    modulesById[item.id].setReadValues(item.values.ToArray());

                    modulesById[item.id].setMeasuredValues(item.measurements.ToArray());
                }
            }
            catch (ArgumentException e)
            {
                Debug.Log("Not valid JSON: " + message);
            }
        }
    }