Ejemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ISmartHouseCreator shc = Manufacture.GetManufacture(modelAssembly);

            if (!IsPostBack)
            {
                CreateDeviceTypeDropDownList();
                Session["showAddDevice"] = null;
            }

            if (Session["SmartHouse"] == null)
            {
                ISmartDevice    dev;
                IBrightable     ibri;
                IHaveThermostat iterm;

                sh = shc.CreateSmartHouse();

                dev = shc.CreateDevice("SmartLamp", "l1");

                ibri = dev as IBrightable;
                ibri.BrightnessMax  = 100;
                ibri.BrightnessMin  = 10;
                ibri.BrightnessStep = 10;
                ibri.Brightness     = ibri.BrightnessMax;
                sh.AddDevice(dev);

                dev = shc.CreateDevice("SmartLamp", "l2");

                ibri = dev as IBrightable;
                ibri.BrightnessMax  = 100;
                ibri.BrightnessMin  = 10;
                ibri.BrightnessStep = 15;
                ibri.Brightness     = ibri.BrightnessMax;
                sh.AddDevice(dev);

                dev = shc.CreateDevice("Fridge", "fr1");

                iterm          = dev as IHaveThermostat;
                iterm.TempMax  = 0;
                iterm.TempMin  = -5;
                iterm.TempStep = 1;
                dev.On();
                iterm.DecreaseTemperature();
                sh.AddDevice(dev);

                dev = shc.CreateDevice("Clock", "clk1");

                dev.On();
                sh.AddDevice(dev);

                Session.Add("SmartHouse", sh);
            }
            else
            {
                sh = Session["SmartHouse"] as ISmartHouse;
            }

            RefreshControls();
        }
Ejemplo n.º 2
0
        private ISmartHouse LoadFromStorage()
        {
            ISmartHouse result = null;

            SmartHouseConfig shConfig    = GetConfig();
            string           storagePath = Path.Combine(shConfig.StorageFilePath, shConfig.StorageFileName);

            storagePath = HostingEnvironment.MapPath(storagePath);
            FileInfo fi = null;

            try
            {
                fi = new FileInfo(storagePath);
            }
            catch { }

            if (fi != null && fi.Exists)
            {
                using (FileStream fs = fi.Open(FileMode.Open))
                {
                    try
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        result = bf.Deserialize(fs) as ISmartHouse;
                    }
                    catch { }
                }
            }

            return(result);
        }
Ejemplo n.º 3
0
        // PUT api/Door/5
        public IHttpActionResult Put(string id, [FromBody] bool value)
        {
            ISmartHouse       sh  = LoadSmartHouse();
            ISmartDevice      dev = sh[id];
            IHttpActionResult result;

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                if (dev is IOpenCloseable)
                {
                    (dev as IOpenCloseable).IsOpened = value;

                    result = Ok((dev as IOpenCloseable).IsOpened);
                    SaveSmartHouse(sh);
                }
                else
                {
                    result = BadRequest(string.Format("Устройство {0} не поддерживает интерфейс IOpenClosable", dev.Name));
                }
            }

            return(result);
        }
Ejemplo n.º 4
0
        private bool SaveToStorage(ISmartHouse sh)
        {
            bool saved = false;

            SmartHouseConfig shConfig    = GetConfig();
            string           storagePath = Path.Combine(shConfig.StorageFilePath, shConfig.StorageFileName);

            storagePath = HostingEnvironment.MapPath(storagePath);
            FileInfo fi = null;

            try
            {
                fi = new FileInfo(storagePath);
            }
            catch { }

            if (fi != null)
            {
                using (FileStream fs = fi.Open(FileMode.Create))
                {
                    try
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(fs, sh);
                        saved = true;
                    }
                    catch { }
                }
            }

            return(saved);
        }
Ejemplo n.º 5
0
        // PUT api/PowerState/5
        public IHttpActionResult Put(string id, [FromBody] string value)
        {
            ISmartHouse       sh  = LoadSmartHouse();
            ISmartDevice      dev = sh[id];
            IHttpActionResult result;

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                switch (value)
                {
                case "on":
                    dev.State = EPowerState.On;
                    break;

                default:
                    dev.State = EPowerState.Off;
                    break;
                }

                result = Ok(dev.State.ToString().ToLower());
                SaveSmartHouse(sh);
            }

            return(result);
        }
Ejemplo n.º 6
0
        protected ISmartHouse LoadSmartHouse()
        {
            ISmartHouse        sh       = null;
            SmartHouseConfig   shConfig = GetConfig();
            ISmartHouseCreator shc      = Manufacture.GetManufacture(modelAssembly);
            Type smartHouseType         = shc.SmartHouseType;

            if (smartHouseType.IsSubclassOf(typeof(DbContext)))
            {
                sh = shc.CreateSmartHouse();
            }
            else
            {
                if (shConfig.UseSession)
                {
                    var Session = HttpContext.Current.Session;
                    sh = Session["SmartHouse"] as ISmartHouse;
                }
                else
                {
                    sh = LoadFromStorage();
                }
            }
            return(sh);
        }
Ejemplo n.º 7
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;
			ISmartDevice dev;
			string action;

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					dev = sh[args[i]];

					if (dev != null)
					{
						dev.Break();
						action = "издало хлопок и задымилось";
					}
					else
					{
						action = DEV_NOT_FOUND;
					}

					output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
				}
			}
			else
			{
				output = MISSING_ARGS + Name;
				result = false;
			}

			return result;
		}
Ejemplo n.º 8
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;
			ISmartDevice dev;
			IRepareable devOK;
			string action;
			string devtype = "Устройство";

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					dev = sh[args[i]];

					if (dev != null)
					{
						devtype = dev.DeviceType.ToUpperFirstLetter();
						
						if (dev.State == EPowerState.Broken)
						{
							if (dev is IRepareable)
							{
								devOK = dev as IRepareable;
								devOK.Repare();
								action = ": Вы подёргали какие-то проводки и протёрли всё тряпкой";
							}
							else
							{
								action = "проще выкинуть";
							}
						}
						else
						{
							action = "неплохо себя чувствует и без вас";
						}
					}
					else
					{
						action = DEV_NOT_FOUND;
					}

					output = string.Format("{2} {3} {0} {1}", args[i], action, (output != null ? output + "\n" : ""), devtype);
				}
			}
			else
			{
				output = MISSING_ARGS + Name;
				result = false;
			}

			return result;
		}
Ejemplo n.º 9
0
        public ActionResult GetDeviceView(string id)
        {
            ISmartHouse  sh  = LoadSmartHouse();
            ISmartDevice dev = sh[id];

            if (dev == null)
            {
                return(HttpNotFound(string.Format("Устройство с id == \"{0}\" не найдено", id)));
            }

            return(PartialView("Parts/Device/GeneralDevice", dev as object));
        }
Ejemplo n.º 10
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			int value;
			string action;
			ISmartDevice dev;
			IHaveThermostat devOK;

			output = null;

			if (args == null || args.Length % 2 != 0)
			{
				output = string.Format("Количество аргументов {0} должно быть чётным и больше нуля", Name);
				result = false;
			}

			if (result)
			{
				for (int i = 0; i < args.Length; i += 2)
				{
					if (int.TryParse(args[i + 1], out value))
					{
						dev = sh[args[i]];
						if (dev != null)
						{
							if (dev is IHaveThermostat)
							{
								devOK = dev as IHaveThermostat;
								devOK.Temperature = value;
								action = string.Format("- температура установлена в {1}", dev.Name, devOK.Temperature);
							}
							else
							{
								action = "не имеет настроек температуры";
							}
						}
						else
						{
							action = DEV_NOT_FOUND;
						}
						output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
					}
					else
					{
						output = string.Format("{2} Аргумент \"{1}\" не является целым числом", i + 1, args[i + 1], (output != null ? output + "\n" : ""));
					}
				}
			}

			return result;
		}
Ejemplo n.º 11
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;
			ISmartDevice dev;
			string action;

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					dev = sh[args[i]];

					if (dev != null)
					{
						if (dev is IOpenCloseable)
						{
							if (!(dev as IOpenCloseable).IsOpened)
							{
								action = "закрылось";
								(dev as IOpenCloseable).Close();
							}
							else
							{
								action = "\"То, что закрыто, закрыться не может\"";
							}
						}
						else
						{
							action = "не знает, что ему нужно закрыть";
						}
					}
					else
					{
						action = DEV_NOT_FOUND;
					}

					output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
				}
			}
			else
			{
				output = MISSING_ARGS + Name;
				result = false;
			}

			return result;
		}
Ejemplo n.º 12
0
        // POST: api/Device
        public IHttpActionResult Post([FromBody] string value)
        {
            IHttpActionResult           result = BadRequest();
            Dictionary <string, string> fields;
            DataContractJsonSerializer  js = new DataContractJsonSerializer(typeof(Dictionary <string, string>));

            using (Stream str = GenerateStreamFromString(value))
            {
                fields = (Dictionary <string, string>)js.ReadObject(str);
            }
            ISmartHouse sh = LoadSmartHouse();

            if (sh[fields[CreateDeviceFields.name]] == null)
            {
                Assembly           modelAssembly = Assembly.Load("SmartHouse");
                ISmartHouseCreator shc           = Manufacture.GetManufacture(modelAssembly);

                ISmartDevice dev = shc.CreateDevice(fields[CreateDeviceFields.devType], fields[CreateDeviceFields.name]);
                if (dev != null)
                {
                    if (dev is IBrightable)
                    {
                        IBrightable idev = dev as IBrightable;
                        idev.BrightnessMax  = int.Parse(fields[CreateDeviceFields.brightnessMax]);
                        idev.BrightnessMin  = int.Parse(fields[CreateDeviceFields.brightnessMin]);
                        idev.BrightnessStep = int.Parse(fields[CreateDeviceFields.brightnessStep]);
                    }

                    if (dev is IHaveThermostat)
                    {
                        IHaveThermostat idev = dev as IHaveThermostat;
                        idev.TempMax  = int.Parse(fields[CreateDeviceFields.temperatureMax]);
                        idev.TempMin  = int.Parse(fields[CreateDeviceFields.temperatureMin]);
                        idev.TempStep = int.Parse(fields[CreateDeviceFields.temperatureStep]);
                    }


                    sh.AddDevice(dev);
                    SaveSmartHouse(sh);
                    result = Ok();
                }
            }
            else
            {
                result = BadRequest(string.Format("Устройство {0} уже есть в системе", fields[CreateDeviceFields.name]));
            }
            return(result);
        }
Ejemplo n.º 13
0
        private ISmartHouse CreateTestSet()
        {
            ISmartHouseCreator shc = Manufacture.GetManufacture(modelAssembly);

            ISmartHouse sh = null;

            ISmartDevice    dev;
            IBrightable     ibri;
            IHaveThermostat iterm;

            sh = shc.CreateSmartHouse();

            dev = shc.CreateDevice("SmartLamp", "l1");

            ibri = dev as IBrightable;
            ibri.BrightnessMax  = 100;
            ibri.BrightnessMin  = 10;
            ibri.BrightnessStep = 10;
            ibri.Brightness     = ibri.BrightnessMax;
            sh.AddDevice(dev);

            dev = shc.CreateDevice("SmartLamp", "l2");

            ibri = dev as IBrightable;
            ibri.BrightnessMax  = 100;
            ibri.BrightnessMin  = 10;
            ibri.BrightnessStep = 15;
            ibri.Brightness     = ibri.BrightnessMax;
            sh.AddDevice(dev);

            dev = shc.CreateDevice("Fridge", "fr1");

            iterm          = dev as IHaveThermostat;
            iterm.TempMax  = 0;
            iterm.TempMin  = -5;
            iterm.TempStep = 1;
            dev.On();
            iterm.DecreaseTemperature();
            sh.AddDevice(dev);

            dev = shc.CreateDevice("Clock", "clk1");

            dev.On();
            sh.AddDevice(dev);

            return(sh);
        }
Ejemplo n.º 14
0
        // GET api/PowerState/5
        public IHttpActionResult Get(string id)
        {
            ISmartHouse       sh  = LoadSmartHouse();
            ISmartDevice      dev = sh[id];
            IHttpActionResult result;

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                result = Ok(dev.State.ToString().ToLower());
            }

            return(result);
        }
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;
			bool devFound;
			string action;
			ISmartDevice dev;

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					dev = sh[args[i]];
					devFound = dev != null;

					if (devFound)
					{
						if (dev is IHaveThermostat)
						{
							(dev as IHaveThermostat).DecreaseTemperature();
							action = "стало холоднее";
						}
						else
						{
							action = "не имеет настроек температуры";
						}
					}
					else
					{
						action = DEV_NOT_FOUND;
					}

					output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
				}
			}
			else
			{
				output = MISSING_ARGS + Name;
				result = false;
			}

			return result;
		}
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;
			bool devFound;
			string action;
			ISmartDevice dev;

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					dev = sh[args[i]];
					devFound = dev != null;

					if (devFound)
					{
						if (dev is IBrightable)
						{
							(dev as IBrightable).IncreaseBrightness();
							action = "стало ярче";
						}
						else
						{
							action = "не имеет настроек яркости";
						}
					}
					else
					{
						action = DEV_NOT_FOUND;
					}

					output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
				}
			}
			else
			{
				output = MISSING_ARGS + Name;
				result = false;
			}

			return result;
		}
Ejemplo n.º 17
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			output = null;

			if (args == null || args.Length != 1)
			{
				output = MISSING_ARGS + Name;
				return false;
			}
			else if (sh[args[0]] != null)
			{
				output = string.Format("Устройство с именем \"{0}\" уже есть в системе", args[0]);
				return false;
			}

			sh.AddDevice(new Clock(args[0]));

			return true;
		}
Ejemplo n.º 18
0
        // DELETE: api/Device/5
        public IHttpActionResult Delete(string id)
        {
            IHttpActionResult result;

            ISmartHouse  sh  = LoadSmartHouse();
            ISmartDevice dev = sh[id];

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                sh.RemoveDevice(id);
                SaveSmartHouse(sh);
                result = Ok();
            }

            return(result);
        }
Ejemplo n.º 19
0
        private void SaveSmartHouse(ISmartHouse sh)
        {
            SmartHouseConfig shConfig = GetConfig();

            if (sh is DbContext)
            {
                (sh as DbContext).SaveChanges();
            }
            else
            {
                if (shConfig.UseSession)
                {
                    Session.Add("SmartHouse", sh);
                }
                else
                {
                    SaveToStorage(sh);
                }
            }
        }
Ejemplo n.º 20
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;
			ISmartDevice dev;
			string action;

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					dev = sh[args[i]];

					if (dev != null)
					{
						dev.On();
						if (dev.State == EPowerState.On)
						{
							action = "включено";
						}
						else
						{
							action = "не включается";
						}
					}
					else
					{
						action = DEV_NOT_FOUND;
					}

					output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
				}
			}
			else
			{
				output = "Недостаточно аргументов для " + Name;
				result = false;
			}

			return result;
		}
Ejemplo n.º 21
0
        protected void SaveSmartHouse(ISmartHouse sh)
        {
            SmartHouseConfig shConfig = GetConfig();

            if (sh is DbContext)
            {
                (sh as DbContext).SaveChanges();
            }
            else
            {
                if (shConfig.UseSession)
                {
                    var Session = HttpContext.Current.Session;
                    Session.Add("SmartHouse", sh);
                }
                else
                {
                    SaveToStorage(sh);
                }
            }
        }
Ejemplo n.º 22
0
        // PUT api/Brightness/5
        public IHttpActionResult Put(string id, [FromBody] string value)
        {
            ISmartHouse       sh  = LoadSmartHouse();
            ISmartDevice      dev = sh[id];
            IHttpActionResult result;

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                if (dev is IBrightable)
                {
                    switch (value)
                    {
                    case "+":
                        (dev as IBrightable).IncreaseBrightness();
                        break;

                    case "-":
                        (dev as IBrightable).DecreaseBrightness();
                        break;

                    default:
                        break;
                    }

                    result = Ok((dev as IBrightable).Brightness);
                    SaveSmartHouse(sh);
                }
                else
                {
                    result = BadRequest(string.Format("Устройство {0} не поддерживает интерфейс IHaveThermostat", dev.Name));
                }
            }

            return(result);
        }
Ejemplo n.º 23
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;

			if (args != null && args.Length > 0)
			{
				for (int i = 0; i < args.Length; i++)
				{
					string action = sh[args[i]] != null ? "выброшено в окно" : DEV_NOT_FOUND;
					sh.RemoveDevice(args[i]);

					output = string.Format("{2} Устройство {0} {1}", args[i], action, (output != null ? output + "\n" : ""));
				}
			}
			else
			{
				output = MISSING_ARGS + Name;
				result = false;
			}

			return result;
		}
Ejemplo n.º 24
0
        // GET api/Brightness/5
        public IHttpActionResult Get(string id)
        {
            ISmartHouse       sh  = LoadSmartHouse();
            ISmartDevice      dev = sh[id];
            IHttpActionResult result;

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                if (dev is IBrightable)
                {
                    result = Ok((dev as IBrightable).Brightness);
                }
                else
                {
                    result = BadRequest(string.Format("Устройство {0} не поддерживает интерфейс IHaveThermostat", dev.Name));
                }
            }

            return(result);
        }
Ejemplo n.º 25
0
        // GET api/Clock/5
        public IHttpActionResult Get(string id)
        {
            ISmartHouse       sh  = LoadSmartHouse();
            ISmartDevice      dev = sh[id];
            IHttpActionResult result;

            if (dev == null)
            {
                result = NotFound();
            }
            else
            {
                if (dev is IHaveClock)
                {
                    result = Ok(new { hour = (dev as IHaveClock).Time.Hour, minute = (dev as IHaveClock).Time.Minute });
                }
                else
                {
                    result = BadRequest(string.Format("Устройство {0} не поддерживает интерфейс IHaveClock", dev.Name));
                }
            }

            return(result);
        }
Ejemplo n.º 26
0
		public CommandMenu(ISmartHouse sh)
		{
			this.sh = sh;
		}
Ejemplo n.º 27
0
		public override bool Call(ISmartHouse sh, out string output, params string[] args)
		{
			bool result = true;
			output = null;

			int max = 100;
			int min = 0;
			int step = 0;
			int i = 0;
			string devName;

			if (args == null || args.Length == 0 || args.Length > 4)
			{
				output = MISSING_ARGS + Name;
				return false;
			}
			else if (sh[args[i]] != null)
			{
				output = string.Format("Устройство с именем \"{0}\" уже есть в системе", args[i]);
				return false;
			}

			devName = args[i];

			if (args.Length > ++i)
			{
				if (!int.TryParse(args[i], out max))
				{
					output = string.Format("Второй аргумент \"{0}\" не является целым числом", args[i]);
					return false;
				}
			}

			if (args.Length > ++i)
			{
				if (!int.TryParse(args[i], out min))
				{
					output = string.Format("Третий аргумент \"{0}\" не является целым числом", args[i]);
					return false;
				}
			}
			else
			{
				min = max / 10;
			}

			if (args.Length > ++i)
			{
				if (!int.TryParse(args[i], out step))
				{
					output = string.Format("Четвёртый аргумент \"{0}\" не является целым числом", args[i]);
					return false;
				}
			}
			else
			{
				step = max / 10;
			}

			try
			{
				IAdjustable<int> dimmer = new Dimmer(max, min, step);
				ISmartDevice dev = new SmartLamp(devName, dimmer);

				sh.AddDevice(dev);
			}
			catch (Exception e)
			{
				output = e.Message;
				return false;
			}

			return result;
		}