public override void ProcessData(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, byte[] data) { int? userId = data[0]; float weight = BitConverter.ToInt16(data, 1) / 10.0f; // user not specified if (userId == 0) { userId = FindUserBasedOnHistory(ctx, weight); } if (userId == null) { _log.Error("Could not find user based on weight '" + weight + "'"); return; } _log.Info("Weight received for user [" + userId + "]: " + weight); WirelessScaleData wirelessScaleData = new WirelessScaleData { UserId = userId.Value, Value = weight, ZigBeeDevice = device, ReceivedDateTime = DateTime.Now }; ctx.DbCtx.WirelessScaleDatas.AddObject(wirelessScaleData); ctx.DbCtx.SaveChanges(); }
protected override void OnStart(string[] args) { _log.Info("BEGIN OnStart (args: " + args.JoinAsString(", ") + ")"); try { LoadConfiguration(); IocContainer.Instance.Compose(this); // verify connection with database _log.Debug("Verifing connection with database"); ZigBeeCoordinatorContext.ConnectionString = "metadata=res://*/Models.Db.ZigBeeCoordinatorModel.csdl|res://*/Models.Db.ZigBeeCoordinatorModel.ssdl|res://*/Models.Db.ZigBeeCoordinatorModel.msl;provider=System.Data.SqlClient;provider connection string=\"Data Source=fileserver;Initial Catalog=ZigBeeCoordinator;Integrated Security=True;MultipleActiveResultSets=True\""; using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { ctx.DbCtx.CoordinatorUsers.FirstOrDefault(); } _zigBeeCommunicationsController.PortName = _portName; _zigBeeCommunicationsController.BaudRate = _baudRate; _zigBeeCommunicationsController.PacketArrived += PacketArrived; _zigBeeCommunicationsController.Start(); } catch (Exception ex) { _log.Error("Could not start", ex); throw; } _log.Info("END OnStart"); base.OnStart(args); }
public ActionResult ManualInput(DateTime date, string time, double weight) { int?userId = CoordinatorUser.Finder.GetCurrentUserId(); if (userId == null) { throw new Exception("You must be logged in"); } using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { DateTime t = DateTime.Parse(date.ToString("d") + " " + time); WirelessScaleData data = new WirelessScaleData { UserId = userId.Value, ReceivedDateTime = t, Value = weight, ZigBeeDevice = null }; ctx.DbCtx.WirelessScaleDatas.AddObject(data); ctx.DbCtx.SaveChanges(); } return(RedirectToAction("Index", new { userId = userId })); }
private void LogReceivePacket(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, ZigBeeCommunicationsController.ZigBeeReceivePacket packet) { FiveVoltPacket fiveVoltPacket = FiveVoltPacket.Decode(packet.ReceiveData); if (fiveVoltPacket is InvalidFileVoltPacket) { InvalidFileVoltPacket invalidPacket = (InvalidFileVoltPacket)fiveVoltPacket; _log.Error("Invalid five volt packet. Reason \"" + invalidPacket.Reason + "\""); } else if (fiveVoltPacket is CapabilityFiveVoltPacket) { CapabilityFiveVoltPacket capabilityFiveVoltPacket = (CapabilityFiveVoltPacket)fiveVoltPacket; LogCapabilityFiveVoltPacket(ctx, device, capabilityFiveVoltPacket); } else if (fiveVoltPacket is CapabilityDataFiveVoltPacket) { CapabilityDataFiveVoltPacket capabilityDataFiveVoltPacket = (CapabilityDataFiveVoltPacket)fiveVoltPacket; LogCapabilityDataFiveVoltPacket(ctx, device, capabilityDataFiveVoltPacket); } else if (fiveVoltPacket is MessageFiveVoltPacket) { MessageFiveVoltPacket messageFiveVoltPacket = (MessageFiveVoltPacket)fiveVoltPacket; LogMessageFiveVoltPacket(ctx, device, messageFiveVoltPacket); } else { _log.Error("Unhandled five volt packet type [" + fiveVoltPacket.GetType() + "]"); } }
private IEnumerable <WirelessScaleData> GetUserHistory(ZigBeeCoordinatorContext ctx, int userId) { return(ctx.DbCtx.WirelessScaleDatas .Include(d => d.CoordinatorUser) .Where(d => d.UserId == userId) .OrderBy(d => d.ReceivedDateTime) .ToList()); }
private IEnumerable <WirelessScaleData> FindUsersMostRecentData(ZigBeeCoordinatorContext ctx) { return(ctx.DbCtx.WirelessScaleDatas .ToList() .GroupBy(q => q.UserId) .Select(userData => userData.OrderByDescending(d => d.ReceivedDateTime).FirstOrDefault()) .ToList()); }
private IEnumerable<WirelessScaleData> FindUsersMostRecentData(ZigBeeCoordinatorContext ctx) { return ctx.DbCtx.WirelessScaleDatas .ToList() .GroupBy(q => q.UserId) .Select(userData => userData.OrderByDescending(d => d.ReceivedDateTime).FirstOrDefault()) .ToList(); }
public CoordinatorUser GetCurrentUser(ZigBeeCoordinatorContext ctx) { int? userId = GetCurrentUserId(); if (userId != null) { return GetUserByUserId(ctx, userId.Value); } return null; }
// ************************************** // URL: /Account/LogOff // ************************************** public ActionResult LogOff() { using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { CoordinatorUser.Finder.SignOutCurrentUser(ctx); } return(RedirectToAction("Index", "Home")); }
public string GetSetting(ZigBeeCoordinatorContext ctx, int userId, string name) { UserSetting setting = ctx.DbCtx.UserSettings.FirstOrDefault(us => us.UserId == userId && us.Name == name); if (setting == null) { return null; } return setting.Value; }
public double GetSettingAsDouble(ZigBeeCoordinatorContext ctx, int userId, string name, double defaultValue) { string val = GetSetting(ctx, userId, name); if (string.IsNullOrEmpty(val)) { return defaultValue; } return double.Parse(val); }
public CoordinatorUser GetCurrentUser(ZigBeeCoordinatorContext ctx) { int?userId = GetCurrentUserId(); if (userId != null) { return(GetUserByUserId(ctx, userId.Value)); } return(null); }
private int? FindUserBasedOnHistory(ZigBeeCoordinatorContext ctx, float weight) { IEnumerable<WirelessScaleData> mostRecentHistory = FindUsersMostRecentData(ctx); WirelessScaleData closestData = mostRecentHistory.Smallest(d => Math.Abs(d.Value - weight)); if (Math.Abs(closestData.Value - weight) > 20) { return null; } return closestData.UserId; }
public double GetSettingAsDouble(ZigBeeCoordinatorContext ctx, int userId, string name, double defaultValue) { string val = GetSetting(ctx, userId, name); if (string.IsNullOrEmpty(val)) { return(defaultValue); } return(double.Parse(val)); }
public string GetSetting(ZigBeeCoordinatorContext ctx, int userId, string name) { UserSetting setting = ctx.DbCtx.UserSettings.FirstOrDefault(us => us.UserId == userId && us.Name == name); if (setting == null) { return(null); } return(setting.Value); }
public ZigBeeDevice FindByAddressOrDefault(ZigBeeCoordinatorContext ctx, byte[] address) { List<ZigBeeDevice> devices = ctx.DbCtx.ZigBeeDevices.ToList(); ZigBeeDevice zigBeeDevice = devices.FirstOrDefault(d => address.EqualsAllItems(d.DeviceAddress)); if (zigBeeDevice != null) { return zigBeeDevice; } return null; }
public ZigBeeDevice FindByAddressOrDefault(ZigBeeCoordinatorContext ctx, byte[] address) { List <ZigBeeDevice> devices = ctx.DbCtx.ZigBeeDevices.ToList(); ZigBeeDevice zigBeeDevice = devices.FirstOrDefault(d => address.EqualsAllItems(d.DeviceAddress)); if (zigBeeDevice != null) { return(zigBeeDevice); } return(null); }
private int?FindUserBasedOnHistory(ZigBeeCoordinatorContext ctx, float weight) { IEnumerable <WirelessScaleData> mostRecentHistory = FindUsersMostRecentData(ctx); WirelessScaleData closestData = mostRecentHistory.Smallest(d => Math.Abs(d.Value - weight)); if (Math.Abs(closestData.Value - weight) > 20) { return(null); } return(closestData.UserId); }
private void LogCapabilityDataFiveVoltPacket(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, CapabilityDataFiveVoltPacket packet) { Capability capability = Capability.Finder.FindByIdOrDefault(ctx, packet.Capability); if (capability == null) { _log.Error("Could not find capability with id [" + packet.Capability + "]"); return; } capability.ProcessData(ctx, device, packet.Data); }
private void LogCapabilityFiveVoltPacket(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, CapabilityFiveVoltPacket capabilityFiveVoltPacket) { Capability capability = Capability.Finder.FindByIdOrDefault(ctx, capabilityFiveVoltPacket.Capability); if (capability == null) { _log.Error("Could not find capability with id [" + capabilityFiveVoltPacket.Capability + "]"); return; } _log.Info("New capability found [" + capability.Name + "] at address [" + device.DeviceAddressString + "]"); device.Capabilities.Add(capability); }
public CoordinatorUser ValidateUser(ZigBeeCoordinatorContext ctx, string userName, string password) { CoordinatorUser user = GetUserByUserName(ctx, userName); string hash = SecurityHelpers.GetMD5HashHexString(password); if (string.Equals(user.Password, hash, StringComparison.InvariantCultureIgnoreCase) || string.Equals(user.Password, password, StringComparison.InvariantCultureIgnoreCase)) { return(user); } return(null); }
public ActionResult Detail(int id) { using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { ZigBeeDevice device = ctx.DbCtx.ZigBeeDevices .Include(d => d.ZigBeeDeviceType) .Include(d => d.Capabilities) .FirstOrDefault(d => d.ZigBeeDeviceId == id); ctx.DbCtx.LoadProperty(device, d => d.ZigBeeDeviceLogs); return(View(device)); } }
public ActionResult Index() { ViewBag.Message = ""; using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { ViewBag.Devices = ctx.DbCtx.ZigBeeDevices .Include(d => d.ZigBeeDeviceType) .ToList(); } return(View()); }
public void ProcessData(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, byte[] data) { _log.Debug("Processing data for capability [" + CapabilityId + ": " + Name + "], from [" + device.DeviceAddressString + "], data [" + data.ToHexString() + "]"); if (CapabilityHandler == null) { _log.Error("Unknown capability id [" + CapabilityId + "]"); } else { CapabilityHandler.ProcessData(ctx, device, data); } }
private void LogMessageFiveVoltPacket(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, MessageFiveVoltPacket packet) { string message = "Message from [" + device.NetworkAddress.ToHexString() + "]: " + packet.Message; switch (packet.Level) { case MessageLevel.Debug: _log.Debug(message); break; case MessageLevel.Info: _log.Info(message); break; case MessageLevel.Warning: _log.Warn(message); break; case MessageLevel.Error: _log.Error(message); break; default: _log.Error(message + " (Invalid message level: " + packet.Level + ")"); break; } }
protected void Application_Start() { MyLogManager.ConfigureFromWebConfig(); // verify connection with database MyLogManager.GetLogger(typeof(MvcApplication)).Debug("Verifing connection with database"); using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { ctx.DbCtx.CoordinatorUsers.FirstOrDefault(); } AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }
public ActionResult UserSettings(double goalWeight) { int?userId = CoordinatorUser.Finder.GetCurrentUserId(); if (userId == null) { throw new Exception("You must be logged in"); } using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { UserSetting.Finder.SetSetting(ctx, userId.Value, GoalWeightSettingKey, goalWeight.ToString()); ctx.DbCtx.SaveChanges(); } return(RedirectToAction("Index", new { userId = userId })); }
public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { if (CoordinatorUser.Finder.GetCurrentUser(ctx).ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return(RedirectToAction("ChangePasswordSuccess")); } } ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } // If we got this far, something failed, redisplay form ViewBag.PasswordLength = CoordinatorUser.MinPasswordLength; return(View(model)); }
private void PacketArrived(ZigBeeCommunicationsController source, ZigBeeCommunicationsController.Packet packet) { try { if (_log.IsDebugEnabled) { _log.Debug("Packet received [length: " + packet.PacketData.Length + "]\n" + packet.PacketData.ToHexStringWithAscii(16)); } using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { ZigBeeDeviceLog.Finder.LogPacket(ctx, packet); } } catch (Exception ex) { _log.Error("Could not process packet [length: " + packet.PacketData.Length + "]\n" + packet.PacketData.ToHexStringWithAscii(16), ex); } }
public void SetSetting(ZigBeeCoordinatorContext ctx, int userId, string name, string val) { _log.Debug("Setting user setting \"" + name + "\" = \"" + val + "\" (user id: " + userId + ")"); UserSetting setting = ctx.DbCtx.UserSettings.FirstOrDefault(us => us.UserId == userId && us.Name == name); if (setting == null) { setting = new UserSetting { UserId = userId, Name = name, Value = val }; ctx.DbCtx.UserSettings.AddObject(setting); } else { setting.Value = val; } }
public ActionResult DeleteValue(int wirelessScaleDataId) { int?userId = CoordinatorUser.Finder.GetCurrentUserId(); if (userId == null) { throw new Exception("You must be logged in"); } using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { WirelessScaleData data = ctx.DbCtx.WirelessScaleDatas .FirstOrDefault(d => d.WirelessScaleDataId == wirelessScaleDataId); ctx.DbCtx.WirelessScaleDatas.DeleteObject(data); ctx.DbCtx.SaveChanges(); } return(RedirectToAction("Index", new { userId = userId })); }
public void LogPacket(ZigBeeCoordinatorContext ctx, ZigBeeCommunicationsController.Packet packet) { ZigBeeDevice device = ZigBeeDevice.Finder.FindAddOrUpdate(ctx, packet.Address, packet.NetworkAddress); device.LastPacketDateTime = DateTime.Now; ZigBeeDeviceLog log = new ZigBeeDeviceLog { DateTime = packet.ReceivedDataTime, PacketData = packet.PacketData, ZigBeeDevice = device }; ctx.DbCtx.ZigBeeDeviceLogs.AddObject(log); ctx.DbCtx.SaveChanges(); if (packet is ZigBeeCommunicationsController.ZigBeeReceivePacket) { LogReceivePacket(ctx, device, (ZigBeeCommunicationsController.ZigBeeReceivePacket)packet); } }
public ActionResult HistoryChart(int userId, int?width, int?height, HistoryChartType?chartType) { using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { double minX = UserSetting.Finder.GetSettingAsDouble(ctx, userId, GoalWeightSettingKey, 100.0); string title = "History"; IEnumerable <WirelessScaleData> datas = GetUserHistory(ctx, userId); if (chartType == null || chartType.Value == HistoryChartType.All) { title = "History - All"; } else if (chartType.Value == HistoryChartType.Month) { title = "History - 30-days"; DateTime start = DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0)); datas = datas.Where(d => d.ReceivedDateTime > start); WirelessScaleData smallest = datas.Smallest(d => d.Value); if (smallest != null) { minX = smallest.Value; } } else if (chartType.Value == HistoryChartType.Week) { title = "History - 7-days"; DateTime start = DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)); datas = datas.Where(d => d.ReceivedDateTime > start); WirelessScaleData smallest = datas.Smallest(d => d.Value); if (smallest != null) { minX = smallest.Value; } } ViewBag.Chart = BuildHistoryChart(datas, minX, width ?? 400, height ?? 300, title); return(View()); } }
public int? GetCurrentUserId() { object userIdObj = HttpContext.Current.Session["UserId"]; if (userIdObj is int) { return (int)userIdObj; } if (HttpContext.Current.Request.IsAuthenticated) { string userName = HttpContext.Current.User.Identity.Name; using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { CoordinatorUser user = GetUserByUserName(ctx, userName); if (user != null) { user.UpdateSession(); return user.UserId; } } } return null; }
public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { CoordinatorUser user; using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { if ((user = CoordinatorUser.Finder.ValidateUser(ctx, model.UserName, model.Password)) != null) { user.SignIn(model.RememberMe); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Home")); } } ModelState.AddModelError("", "The user name or password provided is incorrect."); } // If we got this far, something failed, redisplay form return(View(model)); }
public ZigBeeDevice FindAddOrUpdate(ZigBeeCoordinatorContext ctx, byte[] address, byte[] networkAddress) { ZigBeeDevice zigBeeDevice = FindByAddressOrDefault(ctx, address); if (zigBeeDevice != null) { if (!zigBeeDevice.NetworkAddress.EqualsAllItems(networkAddress)) { zigBeeDevice.NetworkAddress = networkAddress; } } else { zigBeeDevice = new ZigBeeDevice { CreatedDateTime = DateTime.Now, DeviceAddress = address, NetworkAddress = networkAddress }; ctx.DbCtx.ZigBeeDevices.AddObject(zigBeeDevice); ctx.DbCtx.SaveChanges(); } return zigBeeDevice; }
public ActionResult Index(int userId, string extension) { ViewBag.Message = ""; using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { IEnumerable <WirelessScaleData> datas = GetUserHistory(ctx, userId); ViewBag.WirelessScaleDatas = datas; ViewBag.GoalWeight = UserSetting.Finder.GetSetting(ctx, userId, GoalWeightSettingKey); if (extension == "json") { object jsonData = datas .Select(d => new { ReceivedDateTime = d.ReceivedDateTime, Weight = d.Value }) .ToList(); return(Json(jsonData, JsonRequestBehavior.AllowGet)); } return(View()); } }
public int?GetCurrentUserId() { object userIdObj = HttpContext.Current.Session["UserId"]; if (userIdObj is int) { return((int)userIdObj); } if (HttpContext.Current.Request.IsAuthenticated) { string userName = HttpContext.Current.User.Identity.Name; using (ZigBeeCoordinatorContext ctx = new ZigBeeCoordinatorContext()) { CoordinatorUser user = GetUserByUserName(ctx, userName); if (user != null) { user.UpdateSession(); return(user.UserId); } } } return(null); }
public CoordinatorUser GetUserByUserId(ZigBeeCoordinatorContext ctx, int userId) { return ctx.DbCtx.CoordinatorUsers.FirstOrDefault(u => u.UserId == userId); }
public Capability FindByIdOrDefault(ZigBeeCoordinatorContext ctx, UInt16 capabilityId) { return ctx.DbCtx.Capabilities.FirstOrDefault(c => c.CapabilityId == capabilityId); }
public abstract void ProcessData(ZigBeeCoordinatorContext ctx, ZigBeeDevice device, byte[] data);
public CoordinatorUser GetUserByUserName(ZigBeeCoordinatorContext ctx, string userName) { return ctx.DbCtx.CoordinatorUsers.FirstOrDefault(u => u.UserName == userName); }
public void SignOutCurrentUser(ZigBeeCoordinatorContext ctx) { FormsAuthentication.SignOut(); HttpContext.Current.Session.Remove("UserId"); }
public CoordinatorUser ValidateUser(ZigBeeCoordinatorContext ctx, string userName, string password) { CoordinatorUser user = GetUserByUserName(ctx, userName); string hash = SecurityHelpers.GetMD5HashHexString(password); if (string.Equals(user.Password, hash, StringComparison.InvariantCultureIgnoreCase) || string.Equals(user.Password, password, StringComparison.InvariantCultureIgnoreCase)) { return user; } return null; }