Exemplo n.º 1
0
 private static SensorData[] GetParse(ushort[] dataSensors)
 {
     SensorData[] resultParse = new SensorData[dataSensors.Length];
     uint firstMask = 0x1;
     uint secondMask = 0x1FFE;
     for (int i = 0; i < dataSensors.Length; i++)
     {
         int counter = 0;
         int dataResult = dataSensors[i];
         while (dataResult > 0)
         {
             dataResult = dataResult >> 1;
             counter++;
         }
         int amountOfBits = counter - 1;
         int cod = dataSensors[i] >> 13;
         uint controlBit = dataSensors[i] & firstMask;
         uint val = (dataSensors[i] & secondMask) >> 1;
         if ((amountOfBits % 2 == 0 && controlBit == 0) || (amountOfBits % 2 != 0 && controlBit == 1))
         {
             resultParse[i] = new SensorData(Convert.ToUInt16(cod), Convert.ToUInt16(val), Convert.ToUInt16(controlBit));
         }
         else
         {
             Console.WriteLine("Данные {0} со счетчика {1} повреждены", dataSensors[i], cod);
         }
     }
     return resultParse;
 }
Exemplo n.º 2
0
 private static double[] GetAverageBySensor(SensorData[] resultParse)
 {
     int counterFirstSensor = 0;
     int counterSecondSensor = 0;
     int counterThirdSensor = 0;
     int sumFirstSensor = 0;
     int sumSecondSensor = 0;
     int sumThirdSensor = 0;
     for (int i = 0; i < resultParse.Length; i++)
     {
         switch (resultParse[i].codeSensor)
         {
             case 1:
                 counterFirstSensor++;
                 sumFirstSensor += resultParse[i].valueSensor;
                 break;
             case 2:
                 counterSecondSensor++;
                 sumSecondSensor += resultParse[i].valueSensor;
                 break;
             case 3:
                 counterThirdSensor++;
                 sumThirdSensor += resultParse[i].valueSensor;
                 break;
             default:
                 break;
         }
     }
     double[] AverageBySensor = { (sumFirstSensor / counterFirstSensor), (sumSecondSensor / counterSecondSensor), (sumThirdSensor / counterThirdSensor) };
     return AverageBySensor;
 }
Exemplo n.º 3
0
 public SensorClientData(SensorInfo ci, SensorData sd)
 {
     this.SensorId = ci.SensorId.ToString();
     this.Lat = ci.Lat;
     this.Lng = ci.Lng;
     this.Name = ci.Name;
     this.Organization = ci.Organization;
     this.Humidity = sd.Humidity;
     this.Temperature = sd.Temperature;
 }
Exemplo n.º 4
0
        public override double SquaredDistanceFrom(SensorData other)
        {
            other.GetType();
            var otherSensor = other as WlanSensorData;

            if (!BusinessEquals(otherSensor, false))
                return 1d;

            Debug.Assert(otherSensor != null, "otherSensor != null");
            return Math.Pow(SignalStrength - otherSensor.SignalStrength, 2);
        }
Exemplo n.º 5
0
 private void getMessage()
 {
     while (true) {
         NetworkStream stream = _clientSocket.GetStream ();
         BinaryFormatter formatter = new BinaryFormatter ();
         object obj = formatter.Deserialize (stream);
         SensorData data = (SensorData)obj;
         //Console.WriteLine (data.BottomLeft + " - " + data.BottomoRight + " - " + data.TopLeft + " - " + data.TopRight);
         _data = (SensorData)obj;
     }
 }
Exemplo n.º 6
0
        private void UpdateUI(SensorData.Vector reading)
        {
            ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.X);
            ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.Y);
            ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.Z);

            // Show the values graphically
            xLine.X2 = xLine.X1 + reading.X * 100;
            yLine.Y2 = yLine.Y1 - reading.Y * 100;
            zLine.X2 = zLine.X1 - reading.Z * 50;
            zLine.Y2 = zLine.Y1 + reading.Z * 50;
        }
Exemplo n.º 7
0
        public async Task OnWeatherData(SensorData data)
        {
            if (this.SensorInfo == null) return;
            var o = new SensorClientData(this.SensorInfo, data);

            //Tell monitors about the new data (not the sensors)
            await this.InvokeTo<Monitor>(p => p.ClientType == ClientType.Monitor && p.TempThreshold < o.Temperature, o, "wd");

            await this.ScaleOut(o, "swd");

            //Store data on Azure Storage
            await this.StorageSet(o.SensorId, o);
        }
        private void UpdateUI(SensorData.Vector reading)
        {
            statusTextBlock.Text = "Receiving data from accelerometer...";

            // Show the numeric values
            xTextBlock.Text = "X: " + reading.X.ToString("0.00");
            yTextBlock.Text = "Y: " + reading.Y.ToString("0.00");
            zTextBlock.Text = "Z: " + reading.Z.ToString("0.00");

            // Show the values graphically
            xLine.X2 = xLine.X1 + reading.X * 100;
            yLine.Y2 = yLine.Y1 - reading.Y * 100;
            zLine.X2 = zLine.X1 - reading.Z * 50;
            zLine.Y2 = zLine.Y1 + reading.Z * 50;            
        }
        public void ShowSensorData(string args)
        {
            SensorData sensorData = SomneoApiClient.GetSensorData();

            if (sensorData == null)
            {
                Console.WriteLine("Unable to retrieve the sensor data.");
                return;
            }

            Console.WriteLine(
                $@"Sensor data:
  Temperature: {sensorData.CurrentTemperature} °C (avg: {sensorData.AverageTemperature} °C)
  Light: {sensorData.CurrentLight} lux (avg: {sensorData.AverageLight} lux)
  Sound: {sensorData.CurrentSound} dB (avg: {sensorData.AverageSound} dB)
  Humidity: {sensorData.CurrentHumidity} % (avg: {sensorData.AverageHumidity} %)");
        }
Exemplo n.º 10
0
        private async Task <SensorData> movementChangedProc(byte[] bArray, bool doCallback)
        {
            SensorData values = null;

            if (bArray.Length == DataLength[(int)this.SensorIndex])
            {
                Int16 dataGyroX = (Int16)(((UInt16)bArray[1] << 8) + (UInt16)bArray[0]);
                Int16 dataGyroY = (Int16)(((UInt16)bArray[3] << 8) + (UInt16)bArray[2]);
                Int16 dataGyroZ = (Int16)(((UInt16)bArray[5] << 8) + (UInt16)bArray[4]);

                Int16 dataAccX = (Int16)(((UInt16)bArray[7] << 8) + (UInt16)bArray[6]);
                Int16 dataAccY = (Int16)(((UInt16)bArray[9] << 8) + (UInt16)bArray[8]);
                Int16 dataAccZ = (Int16)(((UInt16)bArray[11] << 8) + (UInt16)bArray[10]);


                Int16 dataMagX = (Int16)(256 * ((UInt16)bArray[13]) + (UInt16)bArray[12]);
                Int16 dataMagY = (Int16)(256 * ((UInt16)bArray[15]) + (UInt16)bArray[14]);
                Int16 dataMagZ = (Int16)(256 * ((UInt16)bArray[17]) + (UInt16)bArray[16]);


                values = new SensorData
                {
                    Sensor_Index = SensorIndex,
                    Values       = new double[] {
                        sensorMpu9250GyroConvert(dataGyroX),
                        sensorMpu9250GyroConvert(dataGyroY),
                        sensorMpu9250GyroConvert(dataGyroZ),
                        sensorMpu9250AccConvert(dataAccX),
                        sensorMpu9250AccConvert(dataAccY),
                        sensorMpu9250AccConvert(dataAccZ),
                        sensorMpu9250MagConvert(dataMagX),
                        sensorMpu9250MagConvert(dataMagY),
                        sensorMpu9250MagConvert(dataMagZ)
                    },
                    Raw = bArray
                };
                if (doCallback)
                {
                    if (CallMeBack != null)
                    {
                        CallMeBack(values);
                    }
                }
            }
            return(values);
        }
Exemplo n.º 11
0
        public override void Append(SensorData data)
        {
            // Add to the internal array
            _data.Add(data);

            // Save to disk
            using (var f = File.Open(_filename, FileMode.Append)) {
                using (var b = new BinaryWriter(f)) {
                    WriteRecord(b, data);
                    b.Close();
                }
                f.Close();
            }

            // We're good
            _dirty = false;
        }
Exemplo n.º 12
0
        private void DisplayValue(string sVal)
        {
            try
            {
                ushort v = ushort.Parse(sVal);
                if (v < 0 || v > maxPhotoVal)
                {
                    return;
                }

                SensorData data = new SensorData(DateTime.Now, v);
                photoDatas.Add(data);
                TxtSensorCount.Text    = photoDatas.Count.ToString();
                PgbPhotoRegistor.Value = v;
                LblPhotoRegistor.Text  = v.ToString();

                string item = $"{photoDatas.Count} {DateTime.Now.ToString("yy-MM-dd hh:mm:ss")}\t{v}";


                RtbLog.AppendText($"{item}\n");
                RtbLog.ScrollToEnd();



                vs.Add(v);
                Time.Add(time);

                linegraph.PlotY(vs);


                if (IsSimulation == false)
                {
                    BtnPortValue.Content = $"{serial.PortName}\n{sVal}";
                    InsertDataToDB(data);
                }
                else
                {
                    BtnPortValue.Content = $"{sVal}";
                }
            }
            catch (Exception ex)
            {
                RtbLog.AppendText($"Error : {ex.Message}\n");
                RtbLog.ScrollToEnd();
            }
        }
Exemplo n.º 13
0
        public IHttpActionResult GetLocationReadings(int locationId, string startDate = null, string endDate = null)
        {
            Location location = Location.GetById(locationId);

            if (location == null)
            {
                return(NotFound());
            }

            DateTime            _startDateTime, _endDateTime;
            Nullable <DateTime> startDateTime = null, endDateTime = null;

            if (startDate != null)
            {
                startDateTime = DateTime.TryParse(startDate, out _startDateTime) ? _startDateTime : (DateTime?)null;
            }
            if (startDate != null && startDateTime == null)
            {
                return(this.Content(HttpStatusCode.BadRequest, new ApiError("Invalid start date")));
            }
            if (startDateTime != null && (startDateTime < DateTime.MinValue || startDateTime > DateTime.MaxValue))
            {
                return(this.Content(HttpStatusCode.BadRequest, new ApiError("Invalid start date")));
            }

            if (endDate != null)
            {
                endDateTime = DateTime.TryParse(endDate, out _endDateTime) ? _endDateTime : (DateTime?)null;
            }
            if (endDate != null && endDateTime == null)
            {
                return(this.Content(HttpStatusCode.BadRequest, new ApiError("Invalid end date")));
            }
            if (endDateTime != null && (endDateTime < DateTime.MinValue || endDateTime > DateTime.MaxValue))
            {
                return(this.Content(HttpStatusCode.BadRequest, new ApiError("Invalid end date")));
            }

            if ((startDateTime != null && endDateTime != null) && endDateTime < startDateTime)
            {
                return(this.Content(HttpStatusCode.BadRequest, new ApiError("Invalid date range; endDate must be greater than or equal to startDate")));
            }

            return(Ok(SensorData.GetAllByLocationId(locationId, startDateTime, endDateTime)));
        }
Exemplo n.º 14
0
        // Key press change handler
        // Algorithm taken from http://processors.wiki.ti.com/index.php/SensorTag_User_Guide#Simple_Key_Service
        public async void keyChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
        {
            byte[] bArray = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(bArray);
            if (bArray.Length == DataLength[(int)this.SensorIndex])
            {
                byte data = bArray[0];

                double left;
                double right;
                double reed;

                if ((data & 0x01) == 0x01)
                {
                    right = 1;
                }
                else
                {
                    right = 0;
                }

                if ((data & 0x02) == 0x02)
                {
                    left = 1;
                }
                else
                {
                    left = 0;
                }

                if ((data & 0x04) == 0x04)
                {
                    reed = 1;
                }
                else
                {
                    reed = 0;
                }

                var values = new SensorData {
                    Sensor_Index = SensorIndex, Values = new double[] { right, left, reed }, Raw = bArray
                };
                CallMeBack(values);
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            Post postData = new Post();
            //Vi sætter her den port vi skal bruge til at modtage data fra raspberry pi'en.
            UdpClient  receiveUdp      = new UdpClient(9001);
            IPEndPoint receiveEndPoint = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                while (true)
                {
                    //Her modtager vi data som bytes fra vores raspberry pi og konverterer det til en string
                    Byte[] receiveBytes = receiveUdp.Receive(ref receiveEndPoint);
                    string receivedData = Encoding.ASCII.GetString(receiveBytes);

                    Console.WriteLine("This message was sent from " +
                                      receiveEndPoint.Address.ToString() +
                                      " on their port number " +
                                      receiveEndPoint.Port.ToString());

                    Console.WriteLine(receivedData);

                    //Vi splitter vores string op i bidder så man kan bruge dem til at lave et objekt.
                    string[] txtSplit = receivedData.Split(" ");

                    for (int i = 0; i < txtSplit.Length; i++)
                    {
                        Console.WriteLine(txtSplit[i]);
                    }

                    //Her laver vi et objekt af det modtaget data, hvor vi konverterer de forskellige txtsplit til den ønskede data type.
                    SensorData sensorData = new SensorData(Convert.ToInt16(txtSplit[0]), Convert.ToInt16(txtSplit[1]),
                                                           Convert.ToInt32(txtSplit[2]), Convert.ToBoolean(txtSplit[3]), Convert.ToString(txtSplit[4]));

                    //Vi laver her en PostRequest til at sende objektet til vores database.
                    postData.PostItemHttpTask(sensorData);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 16
0
    // Polls for new skeleton data
    /// <summary>
    /// 轮询新的骨架数据
    /// </summary>
    /// <param name="sensorData">传感器数据</param>
    /// <param name="bodyFrame">身体帧</param>
    /// <param name="kinectToWorld">Kinect世界矩阵</param>
    /// <returns></returns>
    public static bool PollBodyFrame(SensorData sensorData, ref BodyFrameData bodyFrame, ref Matrix4x4 kinectToWorld)
    {
        bool bNewFrame = false;

        if (sensorData.sensorInterface != null)
        {
            //获取新的身体帧
            bNewFrame = sensorData.sensorInterface.PollBodyFrame(sensorData, ref bodyFrame, ref kinectToWorld);

            if (bNewFrame)
            {
                for (int i = 0; i < sensorData.bodyCount; i++)
                {
                    if (bodyFrame.bodyData[i].bIsTracked != 0)
                    {
                        // calculate joint directions
                        //计算关节方向
                        for (int j = 0; j < sensorData.jointCount; j++)
                        {
                            if (j == 0)
                            {
                                bodyFrame.bodyData[i].joint[j].direction = Vector3.zero;
                            }
                            else
                            {
                                //获取关节的父节点
                                int jParent = (int)sensorData.sensorInterface.GetParentJoint(bodyFrame.bodyData[i].joint[j].jointType);

                                //当前关节和父关节都不是未跟踪时,则进行处理
                                if (bodyFrame.bodyData[i].joint[j].trackingState != TrackingState.NotTracked &&
                                    bodyFrame.bodyData[i].joint[jParent].trackingState != TrackingState.NotTracked)
                                {
                                    //设置身体数据关节方向
                                    bodyFrame.bodyData[i].joint[j].direction =
                                        bodyFrame.bodyData[i].joint[j].position - bodyFrame.bodyData[i].joint[jParent].position;
                                }
                            }
                        }
                    }
                }
            }
        }

        return(bNewFrame);
    }
Exemplo n.º 17
0
        /// <summary>
        ///     处理并计算统计数据
        /// </summary>
        /// <param name="sd"></param>
        /// <param name="period"></param>
        /// <returns></returns>
        private async Task<bool> ProcessStatistics(SensorData sd, int period)
        {
            var key = StatisticsProcessor.GetStatisticsKey(sd.Time, period, sd.DeviceCode);
            var sts = _redisClient.HashGet<DeviceTimeSharingStatisticsDto>(RedisKeyString.DeviceTimeSharingStatistics,
                key, RedisSerializeType.DataType);
            if (sts == null)
            {
                sts = new DeviceTimeSharingStatisticsDto
                {
                    DeviceSerialnum = sd.DeviceCode,
                    Serialnum = key,
                    TimeSharing = period
                };
                sts.MaxValue = sts.MinValue = sts.StartValue = sts.EndValue = sts.AvgValue = sd.Value;
                sts.CreateTime = DateTime.Now;
            }
            else
            {
                if (sd.Value > sts.MaxValue)
                    sts.MaxValue = sd.Value;
                if (sd.Value < sts.MinValue)
                    sts.MinValue = sd.Value;

                sts.EndValue = sd.Value;
                sts.AvgValue = (sts.AvgValue + sd.Value) / 2;
            }
            sts.Count++;
            sts.UpdateTime = sd.Time;
            //取上下限
            var deviceExceptionSetService = AhnqIotContainer.Container.Resolve<IDeviceExceptionSetService>();
            var set = await deviceExceptionSetService.GetDeviceExceptionSetByDeviceIdAsny(sd.DeviceCode);
            if (set == null)
                return
                    _redisClient.HashSetFieldValue(RedisKeyString.DeviceTimeSharingStatistics, key, sts, RedisSerializeType.DataType) >
                    0;
            sts.Max = set.Max;
            sts.Min = set.Min;
            if (sd.Value > set.Max || sd.Value < set.Min)
            {
                sts.ExceptionCount++;
            }

            return
                _redisClient.HashSetFieldValue(RedisKeyString.DeviceTimeSharingStatistics, key, sts, RedisSerializeType.DataType) > 0;
        }
Exemplo n.º 18
0
        public void AddSensorData(SensorData message)
        {
            lock (_accessLock)
            {
                foreach (var pair in _currentSessions)
                {
                    if (UserRoleHelper.IsAllSensorsAllowed(pair.Key))
                    {
                        pair.Value.AddUpdate(message);
                    }

                    else if (pair.Key.IsSensorAvailable(message.Key))
                    {
                        pair.Value.AddUpdate(message);
                    }
                }
            }
        }
Exemplo n.º 19
0
        public async Task <ActionResult <SensorData> > PostSensorData(SensorData sensorData)
        {
            var sensor = await _context.Sensor.Include(sd => sd.Data).FirstOrDefaultAsync(s => s.Id == sensorData.SensorId);

            if (sensor == null)
            {
                return(NotFound());
            }

            if (sensor.Data == null)
            {
                sensor.Data = new List <SensorData>();
            }
            sensor.Data.Add(sensorData);
            await _context.SaveChangesAsync();

            return(NoContent());
        }
Exemplo n.º 20
0
        public IActionResult GetUpdate()
        {
            var update = deviceService.GetUpdate();

            if (int.TryParse(update.Humidity.Split('.')[0], out int h) && int.TryParse(update.Temperature.Split('.')[0], out int t))
            {
                var data = new SensorData
                {
                    Humidity    = h,
                    Temperature = t,
                    Timestamp   = update.TimeStamp,
                    LedOn       = update.LedOn
                };
                return(base.Json(data));
            }

            return(base.BadRequest());
        }
Exemplo n.º 21
0
        /// <summary>
        /// This function adds a sensor with the data from the fields to the collection of sensors
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            SensorData data = new SensorData
            {
                Name            = txtName.Text,
                Description     = txtDesc.Text,
                Location        = new Location((double)numLat.Value, (double)numLong.Value),
                Type            = sensorTypeChooser.Text,
                PollingInterval = (int)numPoll.Value
            };

            RangeBoundaries <string> boundaries = new RangeBoundaries <string>(numMinVal.Text, numMaxVal.Text);

            if (logic.AddSensor(data, boundaries))
            {
                logic.SaveState();
            }
        }
        public void WriteSensorData(SensorDataMessage message)
        {
            var sensor = context.Sensors.FirstOrDefault(x => x.Id == message.SensorId && x.Device.Token == message.Token);

            if (sensor == null)
            {
                throw new SensorIdOrTokenNotFoundException();
            }
            var data = new SensorData
            {
                EventDateTime = DateTime.Now,
                SensorId      = sensor.Id,
                Value         = message.Value
            };

            context.SensorData.Add(data);
            context.SaveChanges();
        }
Exemplo n.º 23
0
 private async void OnDataReceived(MqttApplicationMessageReceivedEventArgs arg)
 {
     try
     {
         var json_data = Encoding.UTF8.GetString(arg.ApplicationMessage.Payload);
         Console.WriteLine(json_data);
         SensorData sensorData = JsonConvert.DeserializeObject <SensorData>(json_data);
         if (_mqttService.IsConnected())
         {
             await _mqttService.Publish(sensorData, "data-analytics/data");
         }
         this.saveData(sensorData);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
Exemplo n.º 24
0
        public async void SendToRest(SensorData obj)
        {
            // http client - PostAsync
            using (HttpClient client = new HttpClient())
            {
                StringContent content = new StringContent(
                    JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");

                HttpResponseMessage resp = await client.PostAsync(URI, content);

                //if (resp.IsSuccessStatusCode)
                //{
                //    return;
                //}

                //throw new ArgumentException("opret fejlede");
            }
        }
Exemplo n.º 25
0
        public Identifier AddSensorData(PointerDeviceType deviceType, List <PointerData> pointerDataList)
        {
            Identifier    inputContextId = mDeviceTypeMap[deviceType];
            InputContext  inputContext   = mInputContexts[inputContextId];
            SensorContext sensorContext  = mSensorContexts[inputContext.SensorContextId];

            // Create sensor data using the input context
            SensorData sensorData = new SensorData(
                Identifier.FromNewGuid(),
                inputContext.Id,
                InkState.Plane);

            PopulateSensorData(sensorData, sensorContext, pointerDataList);

            mSensorDataMap.TryAdd(sensorData.Id, sensorData);

            return(sensorData.Id);
        }
Exemplo n.º 26
0
        public void AddUpdate(SensorData message)
        {
            lock (_lockObj)
            {
                _monitoringQueue.Enqueue(message);
                ++_elementsCount;
            }

            if (_elementsCount >= ErrorCapacity)
            {
                OnQueueOverflow();
            }

            if (_elementsCount >= WarningCapacity)
            {
                OnQueueOverflowWarning();
            }
        }
Exemplo n.º 27
0
        public async void Start()
        {
            UdpClient proxyClient = new UdpClient(10100);

            while (true)
            {
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                var        buffer         = proxyClient.Receive(ref remoteEndPoint);
                string     receivedString = Encoding.UTF8.GetString(buffer);
                Console.WriteLine(receivedString);

                SensorData sd = JsonSerializer.Deserialize <SensorData>(receivedString);
                Console.WriteLine(sd);
                Console.WriteLine(await PostToRestAsync(JsonSerializer.Serialize(sd)));

                Thread.Sleep(5000);
            }
        }
        private static SensorData LoadSensorData(SqlDataReader reader)
        {
            SensorData sensorData = new SensorData();

            sensorData.Id        = (int)reader["Id"];
            sensorData.SensorId  = (int)reader["SensorId"];
            sensorData.TimeStamp = (reader["TimeStamp"] == DBNull.Value) ? new DateTime(0, 0, 0) : (DateTime)reader["TimeStamp"];
            if (reader["Temperature"] != DBNull.Value)
            {
                sensorData.Temperature = (double)reader["Temperature"];
            }
            if (reader["Humidity"] != DBNull.Value)
            {
                sensorData.Humidity = (double)reader["Humidity"];
            }

            return(sensorData);
        }
Exemplo n.º 29
0
        private void EncodeCurrentStrokeCommon(string pointerDeviceType, InkBuilder inkBuilder, Style style)
        {
            // Create the ink input provider using the pointer device type
            InkInputProvider inkInputProvider = CreateAndAddInkProvider(pointerDeviceType);

            // Create the input device using EasClientDeviceInformation or any other class providing relevant info
            InputDevice inputDevice = CreateAndAddInputDevice();


            // Create the sensor context
            SensorContext sensorContext = CreateAndAddSensorContext(inkInputProvider, inputDevice);

            // Create the input context using the environment and the sensor context
            Identifier inputContextId = CreateAndAddInputContext(sensorContext.Id);

            // Create sensor data using the input context
            SensorData sensorData = new SensorData(
                Identifier.FromNewGuid(),
                inputContextId,
                Wacom.Ink.Serialization.InkState.Plane);

            // Get the sensor data from the ink builders
            List <PointerData> pointerDataList = inkBuilder.GetPointerDataList();

            // Fill the default channels with the sensor data
            FillDefaultChannels(sensorData, sensorContext, pointerDataList);

            InkDocument.SensorData.Add(sensorData);

            Spline spline = inkBuilder.SplineProducer.AllData;

            PathPointLayout layout = inkBuilder.Layout;

            Stroke stroke = new Stroke(
                Identifier.FromNewGuid(),
                spline.Clone(),
                style,
                layout,
                sensorData.Id);

            StrokeNode strokeNode = new StrokeNode(Identifier.FromNewGuid(), stroke);

            InkDocument.InkTree.Root.Add(strokeNode);
        }
Exemplo n.º 30
0
        public int AddSensor(SensorData sd)
        {
            string sql = "insert into Sensor (node,sensor,v1,v2,datetime) values (@node,@sensor,@v1,@v2,@datetime)";

            SqlParameter[] pars =
            {
                new SqlParameter("@node",     SqlDbType.VarChar, 20),
                new SqlParameter("@sensor",   SqlDbType.VarChar, 20),
                new SqlParameter("@v1",       SqlDbType.VarChar, 20),
                new SqlParameter("@v2",       SqlDbType.VarChar, 20),
                new SqlParameter("@datetime", SqlDbType.DateTime)
            };
            pars[0].Value = sd.Node;
            pars[1].Value = sd.Sensor;
            pars[2].Value = sd.V1;
            pars[3].Value = sd.V2;
            pars[4].Value = sd.DTTime;
            return(SqlHelper.ExecuteNonQuery(sql, CommandType.Text, pars));
        }
Exemplo n.º 31
0
        public Watering CheckWatering(string mac)
        {
            // make sensor obj
            Sensor sensor = sensorController.GetSensor(mac);
            // make sensorData obj
            SensorData sensorData = sensorDataController.GetSensorData(mac);
            // Get User
            User user = userController.GetUserGeo(sensor.FK_UserId);

            Watering wat = new Watering();

            wat.Port = sensorController.GetPort(mac).Port;

            if (sensorData.Humidity < sensor.LimitLow)
            {
                userController.UpdateWaterCount(user.Id);
                wat.Water = 1;
                return(wat);
                //return true;
            }
            else if (sensorData.Humidity < sensor.LimitUp)
            {
                // Generate Weathermodels
                weatherAPI = new WeatherAPI(user.Lat, user.Lon);
                WeatherModel weatherModel = weatherAPI.GetForecast();

                double incommingRain = 0;
                for (int i = 0; i < threeHourIntervals; i++)
                {
                    incommingRain += weatherModel.list[i].rain._3h;
                }

                if (incommingRain <= rainRequirementInMM)
                {
                    userController.UpdateWaterCount(user.Id);
                    wat.Water = 1;
                    return(wat);
                }
            }

            wat.Water = 0;
            return(wat);
        }
Exemplo n.º 32
0
    private void JSONToOrientation(string json)
    {
        // float deltaTime = Time.time - lastTime;
        // lastTime = Time.time;
        SensorData data = JsonUtility.FromJson <SensorData>(json); // deserialize JSON data

        if (data != null)                                          // if serialization successful => pipe to AHRS algorithm
        {
            ahrs.accelerometer = data.accelerometer.ToVector();
            ahrs.magnetsensor  = data.magnetometer.ToVector();
            ahrs.gyroscope     = new Vector3(
                data.gyroscope.x * Mathf.Deg2Rad,
                data.gyroscope.y * Mathf.Deg2Rad,
                data.gyroscope.z * Mathf.Deg2Rad
                );

            //ahrs.samplePeriod = deltaTime; // time components could be used to adapt the sample rate
        }
    }
Exemplo n.º 33
0
 public void importData(SensorData sensorData)
 {
     _sensorData = new SensorData();
     Debug.Log(sensorData);
     try
     {
         _sensorData._id       = sensorData._id;
         _sensorData.attrNames = sensorData.attrNames;
         _sensorData.attrs     = sensorData.attrs;
         _sensorData.credate   = sensorData.credate;
         _sensorData.modDate   = sensorData.modDate;
         _sensorData.location  = sensorData.location;
     }
     catch
     {
         Debug.Log("Device importData failed");
     }
     populateServices();
 }
Exemplo n.º 34
0
        public void AddValue(string productName, SensorData sensorData)
        {
            lock (_syncRoot)
            {
                SortedList <string, SensorData> list;

                if (!_productSensorDictionary.ContainsKey(productName))
                {
                    list = new SortedList <string, SensorData>();
                    _productSensorDictionary[productName] = list;
                }
                else
                {
                    list = _productSensorDictionary[productName];
                }

                list[sensorData.Path] = sensorData.Clone();
            }
        }
Exemplo n.º 35
0
        public void SetupServer()
        {
            LoggerSingleton.Instance.Log("Setting up server...");

            try
            {
                _sensorData = new SensorData();
                _serverSocket.Bind(new IPEndPoint(_ip, _port));
                // place the socket in a listen state. Max queue of 5 connections at a time
                _serverSocket.Listen(5);
                _serverSocket.BeginAccept(AcceptCallback, null);
                LoggerSingleton.Instance.Log("Socket server started");
            }
            catch (Exception ex)
            {
                LoggerSingleton.Instance.Log("The following error occurred on setupserver", ex);
                throw;
            }
        }
Exemplo n.º 36
0
    IEnumerator WaitForRequest(WWW www)
    {
        yield return(www);

        // check for errors
        if (www.error == null)
        {
            data = JsonUtility.FromJson <SensorData>(www.text);
            //Debug.Log(JsonUtility.ToJson(data));
            foodManager.temperature = data.temperature;
            foodManager.co2         = data.carboneDioxide;
            string[] s = data.lastMovement.Split(':');
            foodManager.timeStir = 60 * float.Parse(s[1]) + float.Parse(s[2]);
        }
        else
        {
            Debug.Log("WWW Error: " + www.error);
        }
    }
Exemplo n.º 37
0
        /// <summary>
        /// Adds sensor with the given "data" to the Sensors List
        /// </summary>
        /// <param name="data"></param>
        /// <param name="rangeBoundaries"></param>
        /// <returns>True if the sensor is added successfully, False otherwise</returns>
        public bool AddSensor(SensorData data, RangeBoundaries <string> rangeBoundaries)
        {
            bool   success = true;
            Sensor sensor  = null;

            try
            {
                switch (data.Type)
                {
                case "DoorSensor":
                    sensor = new DoorSensor(data);
                    break;

                case "ElPowerSensor":
                    sensor = new ElPowerSensor(data, new RangeBoundaries <int>(int.Parse(rangeBoundaries.Min), int.Parse(rangeBoundaries.Max)));
                    break;

                case "NoiseSensor":
                    sensor = new NoiseSensor(data, new RangeBoundaries <int>(int.Parse(rangeBoundaries.Min), int.Parse(rangeBoundaries.Max)));
                    break;

                case "HumiditySensor":
                    sensor = new HumiditySensor(data, new RangeBoundaries <float>(float.Parse(rangeBoundaries.Min), float.Parse(rangeBoundaries.Max)));
                    break;

                case "TemperatureSensor":
                    sensor = new TemperatureSensor(data, new RangeBoundaries <double>(double.Parse(rangeBoundaries.Min), double.Parse(rangeBoundaries.Max)));
                    break;

                default:
                    break;
                }
                Sensors.Add(sensor);
                SaveState();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed to add the sensor!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                success = false;
            }

            return(success);
        }
Exemplo n.º 38
0
        public void HandleEvent(object sender, EventArgs args)
        {
            CustomEventArgs eventArgs = (CustomEventArgs)args;
            int             indicator = eventArgs.getIndicator();

            switch (indicator)
            {
            case (int)ShimmerBluetooth.ShimmerIdentifier.MSG_IDENTIFIER_STATE_CHANGE:
                System.Diagnostics.Debug.Write(((ShimmerBluetooth)sender).GetDeviceName() + " State = " + ((ShimmerBluetooth)sender).GetStateString() + System.Environment.NewLine);
                int state = (int)eventArgs.getObject();
                if (state == (int)ShimmerBluetooth.SHIMMER_STATE_CONNECTED)
                {
                    System.Console.WriteLine("Connected");
                }
                else if (state == (int)ShimmerBluetooth.SHIMMER_STATE_CONNECTING)
                {
                    System.Console.WriteLine("Connecting");
                }
                else if (state == (int)ShimmerBluetooth.SHIMMER_STATE_NONE)
                {
                    System.Console.WriteLine("Disconnected");
                }
                else if (state == (int)ShimmerBluetooth.SHIMMER_STATE_STREAMING)
                {
                    System.Console.WriteLine("Streaming");
                    System.Console.WriteLine("Data being written to ecg.csv");
                }
                break;

            case (int)ShimmerBluetooth.ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE:
                break;

            case (int)ShimmerBluetooth.ShimmerIdentifier.MSG_IDENTIFIER_DATA_PACKET:
                ObjectCluster objectCluster = (ObjectCluster)eventArgs.getObject();
                SensorData    data          = objectCluster.GetData(Shimmer3Configuration.SignalNames.ECG_LA_RA, "CAL");
                if (data != null)
                {
                    System.Console.Write(data.Data + ",");
                }
                logging.WriteData(objectCluster);
                break;
            }
        }
        /// <summary>
        /// Tests for the lineparser format. Additionally it looks for the header row and 
        /// trys to determine the third value seperated by semicolom.
        /// </summary>
        /// <param name="line">The line to parse</param>
        /// <returns>True is successful</returns>
        /// <exception cref="LineparserException">If no linematcher is set</exception>
        public override bool test(string line)
        {
            // Is header line?
            if (line.IndexOf("Date;Time;") != -1)
            {
                // Split header line by semicolom.
                String[] splits = line.Split(';');
                if (splits.Length != 3)
                {
                    return false;
                }

                // set additional value
                SensorData tValue = (SensorData)Enum.Parse(typeof(SensorData), splits[splits.Length - 1]);
                this.extraValue = tValue;

                // set supported values
                SensorData[] t = { SensorData.Date, tValue };
                this.SupportedValues = t;
            }

            // run the actual test
            return base.test(line);
        }
Exemplo n.º 40
0
        // closes opened readers and closes the sensor
        public static void CloseSensor(SensorData sensorData)
        {
            if (sensorData != null && sensorData.sensorInterface != null)
            {
                sensorData.sensorInterface.CloseSensor(sensorData);
            }

            if (sensorData.bodyIndexBuffer != null)
            {
                sensorData.bodyIndexBuffer.Release();
                sensorData.bodyIndexBuffer = null;
            }

            if (sensorData.depthImageBuffer != null)
            {
                sensorData.depthImageBuffer.Release();
                sensorData.depthImageBuffer = null;
            }

            if (sensorData.depthHistBuffer != null)
            {
                sensorData.depthHistBuffer.Release();
                sensorData.depthHistBuffer = null;
            }

            if (sensorData.depth2ColorBuffer != null)
            {
                sensorData.depth2ColorBuffer.Release();
                sensorData.depth2ColorBuffer = null;
            }
        }
Exemplo n.º 41
0
        public static void FinishBackgroundRemoval(SensorData sensorData)
        {
            if (sensorData.alphaBodyTexture != null)
            {
                sensorData.alphaBodyTexture.Release();
                sensorData.alphaBodyTexture = null;
            }

            sensorData.erodeBodyMaterial = null;
            sensorData.dilateBodyMaterial = null;
            sensorData.blurBodyMaterial = null;

            if (sensorData.color2DepthBuffer != null)
            {
                sensorData.color2DepthBuffer.Release();
                sensorData.color2DepthBuffer = null;
            }

            if (sensorData.color2DepthTexture != null)
            {
                sensorData.color2DepthTexture.Release();
                sensorData.color2DepthTexture = null;
            }

            sensorData.color2DepthMaterial = null;
            sensorData.color2DepthCoords = null;
        }
Exemplo n.º 42
0
 //    public static EventHandler<SensorData> MeasurementComplete;
 /// <summary>
 /// Raises the <see cref="MeasurementComplete"/> event.
 /// </summary>
 /// <param name="sender">The object that raised the event.</param>
 /// <param name="sensorData">The <see cref="SensorData"/> object that contains the results of the measurement.</param>
 public void OnMeasurementCompleteEvent(Accelaccelerometer sender, SensorData sensorData)
 {
     if (_OnMeasurementComplete == null)
         _OnMeasurementComplete = OnMeasurementCompleteEvent;
 }
 public FilteredDatabaseDataSet(SensorData[] SupportedValues)
 {
     this.SupportedValues = SupportedValues;
 }
	// Polls for new skeleton data
	public static bool PollBodyFrame(SensorData sensorData, ref BodyFrameData bodyFrame, ref Matrix4x4 kinectToWorld)
	{
		bool bNewFrame = false;

		if(sensorData.sensorInterface != null)
		{
			bNewFrame = sensorData.sensorInterface.PollBodyFrame(sensorData, ref bodyFrame, ref kinectToWorld);

			if(bNewFrame)
			{
				for(int i = 0; i < sensorData.bodyCount; i++)
				{
					if(bodyFrame.bodyData[i].bIsTracked != 0)
					{
						// calculate joint directions
						for(int j = 0; j < sensorData.jointCount; j++)
						{
							if(j == 0)
							{
								bodyFrame.bodyData[i].joint[j].direction = Vector3.zero;
							}
							else
							{
								int jParent = (int)sensorData.sensorInterface.GetParentJoint(bodyFrame.bodyData[i].joint[j].jointType);
								
								if(bodyFrame.bodyData[i].joint[j].trackingState != TrackingState.NotTracked && 
								   bodyFrame.bodyData[i].joint[jParent].trackingState != TrackingState.NotTracked)
								{
									bodyFrame.bodyData[i].joint[j].direction = 
										bodyFrame.bodyData[i].joint[j].position - bodyFrame.bodyData[i].joint[jParent].position;
								}
							}
						}
					}

				}
			}
		}
		
		return bNewFrame;
	}
	// frees last multi source frame
	public static void FreeMultiSourceFrame(SensorData sensorData)
	{
		if(sensorData.sensorInterface != null)
		{
			sensorData.sensorInterface.FreeMultiSourceFrame(sensorData);
		}
	}
	// gets new multi source frame
	public static bool GetMultiSourceFrame(SensorData sensorData)
	{
		bool bResult = false;

		if(sensorData.sensorInterface != null)
		{
			bResult = sensorData.sensorInterface.GetMultiSourceFrame(sensorData);
		}

		return bResult;
	}
	// invoked periodically to update sensor data, if needed
	public static bool UpdateSensorData(SensorData sensorData)
	{
		bool bResult = false;

		if(sensorData.sensorInterface != null)
		{
			bResult = sensorData.sensorInterface.UpdateSensorData(sensorData);
		}

		return bResult;
	}
	// closes opened readers and closes the sensor
	public static void CloseSensor(SensorData sensorData)
	{
		if(sensorData != null && sensorData.sensorInterface != null)
		{
			sensorData.sensorInterface.CloseSensor(sensorData);
		}
	}
Exemplo n.º 49
0
        // returns the foregound frame rectangle, as to the required resolution
        public static Rect GetForegroundFrameRect(SensorData sensorData, bool isHiResPrefered)
        {
            if (isHiResPrefered && sensorData != null && sensorData.sensorInterface != null)
            {
                if (sensorData.sensorInterface.IsBRHiResSupported() && sensorData.colorImage != null)
                {
                    return new Rect(0f, 0f, sensorData.colorImageWidth, sensorData.colorImageHeight);
                }
            }

            return sensorData != null ? new Rect(0f, 0f, sensorData.depthImageWidth, sensorData.depthImageHeight) : new Rect();
        }
Exemplo n.º 50
0
        private static bool GetForegroundAlphaFrame(SensorData sensorData, bool bLimitedUsers, ICollection<int> alTrackedIndexes, ref byte[] fgAlphaFrame)
        {
            if (sensorData == null || sensorData.bodyIndexImage == null)
                return false;

            CvMat cvAlphaMap = new CvMat(sensorData.depthImageHeight, sensorData.depthImageWidth, MatrixType.U8C1);

            System.IntPtr rawPtrAlpha;
            cvAlphaMap.GetRawData(out rawPtrAlpha);

            if (sensorData.selectedBodyIndex != 255 || bLimitedUsers)
            {
                // copy body-index selectively
                byte btSelBI = sensorData.selectedBodyIndex;
                int iBodyIndexLength = sensorData.bodyIndexImage.Length;

                for (int i = 0; i < iBodyIndexLength; i++)
                {
                    byte btBufBI = sensorData.bodyIndexImage[i];

                    bool bUserTracked = btSelBI != 255 ? btSelBI == btBufBI :
                        (btBufBI != 255 ? alTrackedIndexes.Contains((int)btBufBI) : false);

                    if (bUserTracked)
                    {
                        cvAlphaMap.Set1D(i, btBufBI);
                    }
                    else
                    {
                        cvAlphaMap.Set1D(i, 255);
                    }
                }
            }
            else
            {
                // copy the entire body-index buffer
                Marshal.Copy(sensorData.bodyIndexImage, 0, rawPtrAlpha, sensorData.bodyIndexImage.Length);
            }

            // make the image b&w
            cvAlphaMap.Threshold(cvAlphaMap, 254, 255, ThresholdType.BinaryInv);

            // apply erode, dilate and blur
            cvAlphaMap.Erode(cvAlphaMap);
            cvAlphaMap.Dilate(cvAlphaMap);
            cvAlphaMap.Smooth(cvAlphaMap, SmoothType.Blur, 5, 5);
            //cvAlphaMap.Smooth(cvAlphaMap, SmoothType.Median, 7);

            // get the foreground image
            Marshal.Copy(rawPtrAlpha, fgAlphaFrame, 0, fgAlphaFrame.Length);

            return true;
        }
 public override object getValue(SensorData target)
 {
     switch (target)
     {
         case SensorData.Activity:
             return this.data.ToArray()[currentRow].Activity;
         case SensorData.ActivityY:
             return this.data.ToArray()[currentRow].ActivityY;
         case SensorData.ActivityZ:
             return this.data.ToArray()[currentRow].ActivityZ;
         case SensorData.CaloriesActivity:
             return this.data.ToArray()[currentRow].CaloriesActivity;
         case SensorData.CaloriesTotal:
             return this.data.ToArray()[currentRow].CaloriesTotal;
         case SensorData.Date:
             return this.data.ToArray()[currentRow].Date;
         case SensorData.Inclinometer:
             return this.data.ToArray()[currentRow].Inclinometer;
         case SensorData.Steps:
             return this.data.ToArray()[currentRow].Steps;
         case SensorData.Vmu:
             return this.data.ToArray()[currentRow].Vmu;
         default:
             return null;
     }
 }
	// Polls for new infrared frame data
	public static bool PollInfraredFrame(SensorData sensorData)
	{
		bool bNewFrame = false;

		if(sensorData.sensorInterface != null)
		{
			bNewFrame = sensorData.sensorInterface.PollInfraredFrame(sensorData);
		}

		return bNewFrame;
	}
 public override object getNextValue(SensorData target)
 {
     read();
     return getValue(target);
 }
	// returns depth frame coordinates for the given 3d Kinect-space point
	public static Vector2 MapSpacePointToDepthCoords(SensorData sensorData, Vector3 kinectPos)
	{
		Vector2 vPoint = Vector2.zero;

		if(sensorData.sensorInterface != null)
		{
			vPoint = sensorData.sensorInterface.MapSpacePointToDepthCoords(sensorData, kinectPos);
		}

		return vPoint;
	}
Exemplo n.º 55
0
 //    public static EventHandler<SensorData> MeasurementComplete;
 /// <summary>
 /// Raises the <see cref="MeasurementComplete"/> event.
 /// </summary>
 /// <param name="sender">The object that raised the event.</param>
 /// <param name="sensorData">The <see cref="SensorData"/> object that contains the results of the measurement.</param>
 public void OnMeasurementCompleteEvent(Magnetometer sender, SensorData sensorData)
 {
     if (_OnMeasurementComplete == null)
         _OnMeasurementComplete = OnMeasurementCompleteEvent;
 }
	// returns color-map coordinates for the given depth point
	public static Vector2 MapDepthPointToColorCoords(SensorData sensorData, Vector2 depthPos, ushort depthVal)
	{
		Vector2 vPoint = Vector2.zero;

		if(sensorData.sensorInterface != null)
		{
			vPoint = sensorData.sensorInterface.MapDepthPointToColorCoords(sensorData, depthPos, depthVal);
		}

		return vPoint;
	}
	// estimates color-map coordinates for the current depth frame
	public static bool MapDepthFrameToColorCoords(SensorData sensorData, ref Vector2[] vColorCoords)
	{
		bool bResult = false;

		if(sensorData.sensorInterface != null)
		{
			bResult = sensorData.sensorInterface.MapDepthFrameToColorCoords(sensorData, ref vColorCoords);
		}

		return bResult;
	}
Exemplo n.º 58
0
        // returns the foregound frame length, as to the required resolution
        public static int GetForegroundFrameLength(SensorData sensorData, bool isHiResPrefered)
        {
            if (isHiResPrefered && sensorData != null && sensorData.sensorInterface != null)
            {
                if (sensorData.sensorInterface.IsBRHiResSupported() && sensorData.colorImage != null)
                {
                    return sensorData.colorImage.Length;
                }
            }

            return (sensorData != null && sensorData.bodyIndexImage != null) ? sensorData.bodyIndexImage.Length * 4 : 0;
        }
Exemplo n.º 59
0
        // converts current body frame to a single csv line. returns empty string if there is no new data
        public static string GetBodyFrameAsCsv(SensorData sensorData, ref BodyFrameData bodyFrame, ref long liRelTime, ref float fUnityTime)
        {
            // check for invalid sensor data and if the frame is still the same
            if (sensorData == null)
                return string.Empty;
            if (bodyFrame.liRelativeTime == liRelTime)
                return string.Empty;

            // create the output string
            StringBuilder sbBuf = new StringBuilder();
            const char delimiter = ',';

            sbBuf.Append("kb").Append(delimiter);
            sbBuf.Append(bodyFrame.liRelativeTime).Append(delimiter);

            liRelTime = bodyFrame.liRelativeTime;
            fUnityTime = Time.time;

            sbBuf.Append(sensorData.bodyCount).Append(delimiter);
            sbBuf.Append(sensorData.jointCount).Append(delimiter);

            // add information for all bodies
            for (int i = 0; i < sensorData.bodyCount; i++)
            {
                sbBuf.Append(bodyFrame.bodyData[i].bIsTracked).Append(delimiter);

                if (bodyFrame.bodyData[i].bIsTracked != 0)
                {
                    // add information for the tracked body - body-id and joints
                    sbBuf.Append(bodyFrame.bodyData[i].liTrackingID).Append(delimiter);

                    for (int j = 0; j < sensorData.jointCount; j++)
                    {
                        KinectInterop.JointData jointData = bodyFrame.bodyData[i].joint[j];

                        sbBuf.Append((int)jointData.trackingState).Append(delimiter);

                        if (jointData.trackingState != TrackingState.NotTracked)
                        {
                            sbBuf.AppendFormat("{0:F3}", jointData.kinectPos.x).Append(delimiter);
                            sbBuf.AppendFormat("{0:F3}", jointData.kinectPos.y).Append(delimiter);
                            sbBuf.AppendFormat("{0:F3}", jointData.kinectPos.z).Append(delimiter);
                        }
                    }
                }
            }

            // remove the last delimiter
            if (sbBuf.Length > 0 && sbBuf[sbBuf.Length - 1] == delimiter)
            {
                sbBuf.Remove(sbBuf.Length - 1, 1);
            }

            return sbBuf.ToString();
        }
Exemplo n.º 60
0
        public static bool InitBackgroundRemoval(SensorData sensorData, bool isHiResPrefered)
        {
            if (sensorData != null && sensorData.bodyIndexImage != null && sensorData.colorImage != null
               && IsDirectX11Available())
            {
                sensorData.alphaBodyTexture = new RenderTexture(sensorData.depthImageWidth, sensorData.depthImageHeight, 0);
                sensorData.alphaBodyTexture.wrapMode = TextureWrapMode.Clamp;
                //sensorData.alphaBodyTexture.filterMode = FilterMode.Point;

                Shader erodeBodyShader = Shader.Find("Custom/Erode");
                sensorData.erodeBodyMaterial = new Material(erodeBodyShader);
                sensorData.erodeBodyMaterial.SetFloat("_TexResX", (float)sensorData.depthImageWidth);
                sensorData.erodeBodyMaterial.SetFloat("_TexResY", (float)sensorData.depthImageHeight);
                //sensorData.erodeBodyMaterial.SetTexture("_MainTex", sensorData.bodyIndexTexture);

                Shader dilateBodyShader = Shader.Find("Custom/Dilate");
                sensorData.dilateBodyMaterial = new Material(dilateBodyShader);
                sensorData.dilateBodyMaterial.SetFloat("_TexResX", (float)sensorData.depthImageWidth);
                sensorData.dilateBodyMaterial.SetFloat("_TexResY", (float)sensorData.depthImageHeight);
                //sensorData.dilateBodyMaterial.SetTexture("_MainTex", sensorData.bodyIndexTexture);

                Shader blurBodyShader = Shader.Find("Custom/BlurShader");
                sensorData.blurBodyMaterial = new Material(blurBodyShader);
                sensorData.blurBodyMaterial.SetFloat("_Amount", 1.5f);

                if (isHiResPrefered)
                {
                    Shader color2DepthShader = Shader.Find("Kinect/Color2DepthShader");

                    if (color2DepthShader)
                    {
                        sensorData.color2DepthTexture = new RenderTexture(sensorData.colorImageWidth, sensorData.colorImageHeight, 0);
                        sensorData.color2DepthTexture.wrapMode = TextureWrapMode.Clamp;
                        //sensorData.color2DepthTexture.filterMode = FilterMode.Point;

                        sensorData.color2DepthMaterial = new Material(color2DepthShader);

                        sensorData.color2DepthMaterial.SetFloat("_ColorResX", (float)sensorData.colorImageWidth);
                        sensorData.color2DepthMaterial.SetFloat("_ColorResY", (float)sensorData.colorImageHeight);
                        sensorData.color2DepthMaterial.SetFloat("_DepthResX", (float)sensorData.depthImageWidth);
                        sensorData.color2DepthMaterial.SetFloat("_DepthResY", (float)sensorData.depthImageHeight);

                        sensorData.color2DepthBuffer = new ComputeBuffer(sensorData.colorImageWidth * sensorData.colorImageHeight, sizeof(float) * 2);
                        sensorData.color2DepthMaterial.SetBuffer("_DepthCoords", sensorData.color2DepthBuffer);
                    }
                }
            }

            if (isHiResPrefered && sensorData != null && sensorData.bodyIndexImage != null && sensorData.colorImage != null)
            {
                sensorData.color2DepthCoords = new Vector2[sensorData.colorImageWidth * sensorData.colorImageHeight];
            }

            return true;
        }