Exemple #1
0
        private void GetValue()
        {
            try
            {
                var arduinoBytes = new byte[10];
                _device.Read(arduinoBytes);

                var sonarWidth = (ushort)(arduinoBytes[0] << 8 | arduinoBytes[1]);

                //var adcReading1 = (ushort)(arduinoBytes[2] << 8 | arduinoBytes[3]);
                //var adcReading2 = (ushort)(arduinoBytes[4] << 8 | arduinoBytes[5]);
                //var adcReading3 = (ushort)(arduinoBytes[6] << 8 | arduinoBytes[7]);
                //var adcReading4 = (ushort)(arduinoBytes[8] << 8 | arduinoBytes[9]);

                ProximityReceived?.Invoke(this, new ProximtyEventArgs
                {
                    RawValue  = sonarWidth,
                    Proximity = Math.Max(0, ((sonarWidth / 2d) / 2.91d) - 0.5d) //The sensors are about 5mm inside the casing of the device.
                });
            }
            catch (Exception ex)
            {
                SensorException?.Invoke(this, new ExceptionEventArgs
                {
                    Exception = ex,
                    Message   = "An error occurred reading values from Arduino Sensor Device"
                });
            }
        }
Exemple #2
0
        /// <summary>
        /// Append one item of data
        /// </summary>
        /// <param name="sensor"></param>
        /// <param name="data_to_save"></param>
        public void AppendData(ISensor sensor, SensorException exception_to_save)
        {
            using (var conn = new SQLiteConnection(_connstring)) {
                conn.Open();

                // Insert using raw compiled code
                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = @"INSERT INTO exceptions (sensor_id, exception_time, exception_text, stacktrace, cleared) values (@sensor_id, @exception_time, @exception_text, @stacktrace, @cleared)";

                    // Set up parameters
                    string[]      parameter_names = new[] { "@sensor_id", "@exception_time", "@exception_text", "@stacktrace", "@cleared" };
                    DbParameter[] parameters      = parameter_names.Select(pn =>
                    {
                        DbParameter parameter   = cmd.CreateParameter();
                        parameter.ParameterName = pn;
                        cmd.Parameters.Add(parameter);
                        return(parameter);
                    }).ToArray();

                    // Iterate through the objects in this list
                    parameters[0].Value = sensor.Identity;
                    parameters[1].Value = exception_to_save.ExceptionTime.Ticks;
                    parameters[2].Value = exception_to_save.Description;
                    parameters[3].Value = exception_to_save.StackTrace;
                    parameters[4].Value = exception_to_save.Cleared ? 1 : 0;
                    cmd.ExecuteNonQuery();
                }
            }
        }
Exemple #3
0
        private void RequestSensorToStartCollectingData()
        {
            try
            {
                var command = (byte)(VCNL4000_Constants.VCNL4000_MEASUREPROXIMITY.GetHashCode() | VCNL4000_Constants.VCNL4000_MEASUREAMBIENT.GetHashCode());

                WriteCommandToCommandRegister(command);
            }
            catch (Exception ex)
            {
                SensorException?.Invoke(this, new ExceptionEventArgs
                {
                    Exception = ex,
                    Message   = "An Error Occured writing the request to read the proximity."
                });
            }
        }
Exemple #4
0
 private void SetPositionAndGetReading(int position)
 {
     try
     {
         _contoller.SetPwm(PwmChannel.C0, 0, position);
         Task.Delay(50).Wait();
         if (_haveReading())
         {
             PositionFound?.Invoke(this, new PositionalDistanceEventArgs {
                 Angle = Angle(position), Proximity = _lastReading.Proximity, RawValue = _lastReading.RawValue
             });
         }
     }
     catch (Exception ex)
     {
         SensorException?.Invoke(this, new ExceptionEventArgs {
             Exception = ex, Message = "An error occured setting Angle and getting distance."
         });
     }
 }
Exemple #5
0
        private int RawAmbientLightReading()
        {
            try
            {
                var readAmbientLightCommand = new[] { (byte)VCNL4000_Constants.VCNL4000_AMBIENTDATA.GetHashCode() };
                var ambientBuffer           = new byte[2]; //Read VCNL4000_AMBIENTDATA for two bytes long, its a 16 bit value.

                _device.WriteRead(readAmbientLightCommand, ambientBuffer);
                var rawPAmbientReading = ambientBuffer[0] << 8 | ambientBuffer[1];
                return(rawPAmbientReading);
            }
            catch (Exception ex)
            {
                SensorException?.Invoke(this, new ExceptionEventArgs
                {
                    Exception = ex,
                    Message   = "An Error Occured reading the Ambient Light Results registers."
                });
            }
            return(-1);
        }
Exemple #6
0
        private int RawProximityReading()
        {
            try
            {
                var readProximityCommand = new[] { (byte)VCNL4000_Constants.VCNL4000_PROXIMITYDATA_1.GetHashCode() };
                var proximityBuffer      = new byte[2]; //Read VCNL4000_PROXIMITYDATA_1 and VCNL4000_PROXIMITYDATA_2 at the same time as they are adjacent register addresses

                _device.WriteRead(readProximityCommand, proximityBuffer);
                var rawProximityReading = proximityBuffer[0] << 8 | proximityBuffer[1];
                return(rawProximityReading);
            }
            catch (Exception ex)
            {
                SensorException?.Invoke(this, new ExceptionEventArgs
                {
                    Exception = ex,
                    Message   = "An Error Occured reading the Proximity Results registers."
                });
            }
            return(-1);
        }
Exemple #7
0
        public SensorDataCollection RetrieveData(ISensor sensor, DateTime?start_date = null, DateTime?end_date = null, bool fetch_exceptions = false)
        {
            var data = new SensorDataCollection();

            data.StartDate  = start_date ?? DateTime.MinValue;
            data.EndDate    = end_date ?? DateTime.MaxValue;
            data.Data       = new List <SensorData>();
            data.Exceptions = new List <SensorException>();

            // Check to see if this sensor filename exists
            string fn = GetFilename(sensor);

            if (File.Exists(fn))
            {
                // Construct a new CSVReader and be careful about this
                using (var csv = new CSVReader(fn, ',', '\"', false)) {
                    foreach (string[] line in csv)
                    {
                        if (line != null && line.Length >= 2)
                        {
                            DateTime t = DateTime.MinValue;
                            Decimal  val;

                            // Load the measurement time if present
                            int ms = 0;
                            if (line.Length >= 3)
                            {
                                int.TryParse(line[2], out ms);
                            }

                            // Save values
                            if (DateTime.TryParse(line[0], out t) && Decimal.TryParse(line[1], out val))
                            {
                                // Only load the specific timeframe
                                if (t < data.StartDate || t > data.EndDate)
                                {
                                    continue;
                                }

                                // Load the exception if asked
                                if (fetch_exceptions)
                                {
                                    if (line.Length >= 3)
                                    {
                                        SensorException e = new SensorException()
                                        {
                                            Description   = line[2],
                                            ExceptionTime = t
                                        };
                                        data.Exceptions.Add(e);
                                    }
                                }

                                // Load the sensor data
                                SensorData sd = new SensorData()
                                {
                                    Time             = t,
                                    Value            = val,
                                    CollectionTimeMs = ms
                                };
                                data.Data.Add(sd);
                            }
                        }
                    }
                }
            }

            // Mark for lazy loading
            return(data);
        }
Exemple #8
0
 /// <summary>
 /// Append one item of data
 /// </summary>
 /// <param name="sensor"></param>
 /// <param name="data_to_save"></param>
 public void AppendData(ISensor sensor, SensorException exception_to_save)
 {
 }
Exemple #9
0
        /// <summary>
        /// Fetch some data for this sensor
        /// </summary>
        /// <param name="sensor"></param>
        /// <param name="start_date"></param>
        /// <param name="end_date"></param>
        /// <param name="fetch_exceptions"></param>
        /// <returns></returns>
        public SensorDataCollection RetrieveData(ISensor sensor, DateTime?start_date = null, DateTime?end_date = null, bool fetch_exceptions = false)
        {
            // Create a new sensor data collection object
            SensorDataCollection result = new SensorDataCollection();

            result.StartDate = DateTime.MinValue;
            result.EndDate   = DateTime.MaxValue;

            // Start the query process
            using (var conn = new SQLiteConnection(_connstring)) {
                conn.Open();

                // Insert using raw compiled code
                using (var cmd = conn.CreateCommand()) {
                    // Set up parameters
                    string[]      parameter_names = new[] { "@sensor_id", "@start_date", "@end_date" };
                    DbParameter[] parameters      = parameter_names.Select(pn =>
                    {
                        DbParameter parameter   = cmd.CreateParameter();
                        parameter.ParameterName = pn;
                        cmd.Parameters.Add(parameter);
                        return(parameter);
                    }).ToArray();

                    // Next set up the actual query text
                    string measurement_query = @"SELECT measurement_time, value, collection_time_ms FROM measurements WHERE sensor_id = @sensor_id";
                    string exception_query   = @"SELECT exception_time, exception_text, stacktrace, cleared FROM exceptions WHERE sensor_id = @sensor_id";
                    parameters[0].Value = sensor.Identity;
                    if (start_date != null && start_date.HasValue)
                    {
                        measurement_query  += " AND measurement_time >= @start_date";
                        exception_query    += " AND exception_time >= @start_date";
                        parameters[1].Value = start_date.Value.Ticks;
                        result.StartDate    = start_date.Value;
                    }
                    if (end_date != null && end_date.HasValue)
                    {
                        measurement_query  += " AND measurement_time <= @end_date";
                        exception_query    += " AND exception_time <= @end_date";
                        parameters[2].Value = end_date.Value.Ticks;
                        result.EndDate      = end_date.Value;
                    }

                    // Now query for measurements
                    cmd.CommandText = measurement_query;
                    using (var dr = cmd.ExecuteReader()) {
                        while (dr.Read())
                        {
                            SensorData sd = new SensorData();
                            sd.Time             = new DateTime(dr.GetInt64(0));
                            sd.Value            = dr.GetDecimal(1);
                            sd.CollectionTimeMs = dr.GetInt32(2);
                            result.Data.Add(sd);
                        }
                    }

                    // Now reset the query for the exceptions table
                    cmd.CommandText = exception_query;
                    using (var dr = cmd.ExecuteReader()) {
                        while (dr.Read())
                        {
                            SensorException se = new SensorException();
                            se.ExceptionTime = new DateTime(dr.GetInt64(0));
                            se.Description   = dr.GetString(1);
                            se.StackTrace    = dr.GetString(2);
                            se.Cleared       = (dr.GetInt32(3) == 1);
                            result.Exceptions.Add(se);
                        }
                    }
                }
            }
            return(result);
        }