Exemplo n.º 1
0
        public IActionResult Put([FromBody] SensorViewModel model)
        {
            if (model == null)
            {
                return(StatusCode(500, new InternalServerError()));
            }
            if (!ModelState.IsValid)
            {
                return(StatusCode(500, new InternalServerError("Incorrect data!")));
            }

            var user = User.GetUser(_context);

            var userHasController = _context
                                    .UserHasControllers
                                    .Where(p => p.UserId == user.Id)
                                    .Where(p => p.ControllerId == model.ControllerId)
                                    .Where(p => p.IsAdmin);

            if (userHasController == null)
            {
                return(Unauthorized(new UnauthorizedError()));
            }

            var sensors = _context.Sensors
                          .Where(p => p.ControllerId == model.ControllerId)
                          .Where(p => p.Pin == model.Pin);

            //Перевіряємо чи до цього піну підключені інші сенсори
            if (sensors.Any())
            {
                return(StatusCode(500, new InternalServerError("Pin is already taken!")));
            }
            //Додаємо сенсор
            var sensor = new Sensor
            {
                Name         = model.Name,
                Pin          = model.Pin,
                SensorTypeId = model.SensorTypeId,
                ControllerId = model.ControllerId,
                Value        = 0,
                Status       = model.Status
            };

            _context.Sensors.Add(sensor);
            _context.SaveChanges();
            sensor.SensorType = _context.SensorTypes.Find(sensor.SensorTypeId);
            return(Json(sensor.Adapt <SensorViewModel>()));
        }