public override async Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument) { var miCommand = command.CustomData1; var zone = command.CustomData2; var ip = (from d in device.Values where d.Name == "IPAddress" select d.Value).FirstOrDefault(); decimal level; decimal.TryParse(argument, out level); await _controller.Send(ip, miCommand, zone, level); await Log.ReportInfoAsync(string.Format("{0} Command Sent Command:{1}, Zone:{2}, IP:{3}, Level:{4}", Name, miCommand, zone, ip, level), CancellationToken); }
public async Task<Result> RegisterAsync(DeviceValue deviceValue, Device device, CancellationToken cancellationToken) { if (deviceValue == null) return Result.ReportError("You must send a device value when registering a device value!"); if (device == null) return Result.ReportError("You must send a device when registering a device value!"); using (var context = new ZvsContext(EntityContextConnection)) { var existingDv = await context.DeviceValues.FirstOrDefaultAsync(o => o.UniqueIdentifier == deviceValue.UniqueIdentifier && o.DeviceId == device.Id, cancellationToken); if (existingDv == null) { //NEW VALUE context.DeviceValues.Add(deviceValue); return await context.TrySaveChangesAsync(cancellationToken); } var hasChanged = false; PropertyChangedEventHandler action = (s, a) => hasChanged = true; existingDv.PropertyChanged += action; existingDv.CommandClass = deviceValue.CommandClass; existingDv.CustomData1 = deviceValue.CustomData1; existingDv.CustomData2 = deviceValue.CustomData2; existingDv.Genre = deviceValue.Genre; existingDv.Index = deviceValue.Index; existingDv.IsReadOnly = deviceValue.IsReadOnly; existingDv.Description = deviceValue.Description; existingDv.Name = deviceValue.Name; existingDv.ValueType = deviceValue.ValueType; existingDv.Value = deviceValue.Value; existingDv.IsReadOnly = deviceValue.IsReadOnly; existingDv.PropertyChanged -= action; if (hasChanged) { return await context.TrySaveChangesAsync(cancellationToken); } return Result.ReportSuccess("Nothing to update"); } }
public static async Task<string> GetDevicePropertyValueAsync(ZvsContext context, Device device, string settingName) { var d2 = await context.Devices .Include(o=> o.DeviceSettingValues) .FirstOrDefaultAsync(o => o.Id == device.Id); if (d2 == null) return string.Empty; //See if the custom value is set. var dpv = d2.DeviceSettingValues.FirstOrDefault(o => o.DeviceSetting.UniqueIdentifier == settingName); if (dpv != null) return dpv.Value; //default value from property var dp = await context.DeviceSettings.FirstOrDefaultAsync(o => o.UniqueIdentifier == settingName); return dp != null ? dp.Value : string.Empty; }
private async void UserControl_Loaded_1(object sender, RoutedEventArgs e) { Device = await _context.Devices .Include(o => o.Values) .FirstOrDefaultAsync(dv => dv.Id == DeviceId); if (Device == null) { MessageBox.Show("Device not found", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } // Do not load your data at design time. if (DesignerProperties.GetIsInDesignMode(this)) return; //Load your data here and assign the result to the CollectionViewSource. var myCollectionViewSource = (CollectionViewSource)Resources["DeviceValueViewSource"]; myCollectionViewSource.Source = Device.Values.OrderBy(dv => dv.Id); ; }
private Task Publish(DeviceType deviceType, Device device, DeviceTypeCommand deviceTypeCommand, DeviceCommand deviceCommand, string argument) { JavaScriptSerializer js = new JavaScriptSerializer(); var o = new { DeviceName = device.Name, DeviceCommandName = (deviceCommand == null ? null : deviceCommand.Name), DeviceTypeCommandName = (deviceTypeCommand == null ? null : deviceTypeCommand.Name), DeviceTypeCommandValue = (deviceTypeCommand == null ? null : deviceTypeCommand.Value), Argument = argument, DeviceTypeName = (device == null || device.Type == null ? null : device.Type.Name), device.CurrentLevelInt, device.CurrentLevelText }; var str = js.Serialize(o); client.Publish(SystemTopic, Encoding.UTF8.GetBytes(str)); return Task.FromResult(0); }
private async Task AddSensor(MqttMsgPublishEventArgs e) { var name = e.Topic; var value = System.Text.UTF8Encoding.UTF8.GetString(e.Message); using (ZvsContext context = new ZvsContext()) { context.Devices .FirstOrDefaultAsync( d => d.Type.Adapter.AdapterGuid == this.AdapterGuid && d.Name == name).ContinueWith(t => { Device dev = t.Result; if (dev == null) { log.Info("New MQTT device found, registering:" + name); dev = new Device { ////NodeNumber = //// rnd.Next((int) byte.MinValue + 100, (int) byte.MaxValue), DeviceTypeId = SensorTypeId, Name = name, CurrentLevelInt = 0, CurrentLevelText = value }; //dev.Commands.Add(motionCommand); context.Devices.Add(dev); context.TrySaveChangesAsync().ContinueWith(tt => { if (tt.Result.HasError) ZvsEngine.log.Error(tt.Result.Message); }).Wait(); } AddOrUpdateValue(name, System.DateTime.Now.ToString(), dev.Id, DataType.STRING, "Date", "Audit", context); AddOrUpdateValue(name, value, dev.Id, DataType.STRING, "Value", "MQTT", context); AddOrUpdateValue(name, e.QosLevel.ToString(), dev.Id, DataType.BYTE, "QosLevel", "MQTT", context); AddOrUpdateValue(name, e.Topic, dev.Id, DataType.STRING, "Topic", "MQTT", context); AddOrUpdateValue(name, e.Retain.ToString(), dev.Id, DataType.BOOL, "Retain", "MQTT", context); }).Wait(); } }
private async Task AddMQTTAdDevice() { using(ZvsContext context = new ZvsContext()) { context.Devices.FirstOrDefaultAsync( d => d.Type.Adapter.AdapterGuid == this.AdapterGuid && d.Name == SystemTopic).ContinueWith(t => { if (t.Result == null) { log.Info("MQTT broker not found, registering."); Device dev = new Device { //NodeNumber = rnd.Next((int) byte.MinValue + 100, (int) byte.MaxValue), DeviceTypeId = SensorTypeId, Name = SystemTopic, }; //dev.Commands.Add(motionCommand); context.Devices.Add(dev); context.TrySaveChangesAsync().ContinueWith(tt => { if (tt.Result.HasError) ZvsEngine.log.Error(tt.Result.Message); AddCommand(dev.Id, "Publish to Broker", context); }).Wait(); } }).Wait(); } }
public override Task RepollAsync(Device device, ZvsContext context) { //m_manager.RequestNodeState(m_homeId, nodeNumber); return Task.FromResult(0); }
public override Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument) { throw new System.NotImplementedException(); }
public abstract Task RepollAsync(Device device);
private void OpenDeviceDetails(Device d) { var app = (App)Application.Current; var deviceDetailsWindow = new DeviceDetailsWindow(d.Id) { Owner = app.ZvsWindow }; deviceDetailsWindow.Show(); }
public override async Task ProcessDeviceCommandAsync(Device device, DeviceCommand command, string argument, string argument2) { if (!command.UniqueIdentifier.Contains("DYNAMIC_CMD_")) return; var nodeNumber = Convert.ToByte(device.NodeNumber); //Get more info from this Node from OpenZWave var node = GetNode(MHomeId, nodeNumber); if (!IsNodeReady(nodeNumber)) { await Log.ReportInfoFormatAsync(CancellationToken, "Failed to issue command on {0}, node {1}. Node not ready.", device.Name, nodeNumber); return; } switch (command.ArgumentType) { case DataType.BYTE: { byte b; byte.TryParse(argument, out b); var value = node.Values.FirstOrDefault(o => o.ValueID.GetId().ToString(CultureInfo.InvariantCulture).Equals(command.CustomData2)); if (value != null) MManager.SetValue(value.ValueID, b); break; } case DataType.BOOL: { bool b; bool.TryParse(argument, out b); var value = node.Values.FirstOrDefault(o => o.ValueID.GetId().ToString(CultureInfo.InvariantCulture).Equals(command.CustomData2)); if (value != null) MManager.SetValue(value.ValueID, b); break; } case DataType.DECIMAL: { var f = Convert.ToSingle(argument); var value = node.Values.FirstOrDefault(o => o.ValueID.GetId().ToString(CultureInfo.InvariantCulture).Equals(command.CustomData2)); if (value != null) MManager.SetValue(value.ValueID, f); break; } case DataType.LIST: case DataType.STRING: { var value = node.Values.FirstOrDefault(o => o.ValueID.GetId().ToString(CultureInfo.InvariantCulture).Equals(command.CustomData2)); if (value != null) MManager.SetValue(value.ValueID, argument); break; } case DataType.INTEGER: { int i; int.TryParse(argument, out i); var value = node.Values.FirstOrDefault(o => o.ValueID.GetId().ToString(CultureInfo.InvariantCulture).Equals(command.CustomData2)); if (value != null) MManager.SetValue(value.ValueID, i); break; } } }
public override Task ProcessDeviceCommandAsync(Device device, DeviceCommand command, string argument, string argument2) { throw new NotImplementedException(); }
private async Task AddNewWifiControllerToDatabase(string ipAddress) { if (!string.IsNullOrEmpty(ipAddress)) { using (var context = new ZvsContext(EntityContextConnection)) { var devices = from d in context.Devices where d.Type.Adapter.AdapterGuid == AdapterGuid select d; Device existing = null; foreach (var d in devices) { var value = (from v in d.Values where v.Name == "IPAddress" && v.Value == ipAddress select v).FirstOrDefault(); if (value != null) { existing = d; break; } } //If already have the device, don't install a duplicate if (existing != null) return; existing = new Device { DeviceTypeId = DimmerTypeId, Name = string.Format("MiLight WiFi Controller - {0}", ipAddress), Location = string.Format("MiLight WiFi Controller - {0}", ipAddress), CurrentLevelInt = 0, CurrentLevelText = "", }; existing.Values.Add(new DeviceValue() { Name = "IPAddress", Value = ipAddress, }); context.Devices.Add(existing); var result = await context.TrySaveChangesAsync(CancellationToken); if (result.HasError) await Log.ReportErrorFormatAsync(CancellationToken, "Failed to save new device. {0}", result.Message); await Log.ReportInfoAsync(string.Format("{0} New Controller added to the database, IP:{1}", Name, ipAddress), CancellationToken); } } }
private async Task AddNewDeviceToDatabase(byte nodeId) { #region Add device to database using (var context = new ZvsContext(EntityContextConnection)) { var ozwDevice = await context.Devices .FirstOrDefaultAsync(d => d.Type.Adapter.AdapterGuid == AdapterGuid && d.NodeNumber == nodeId); //If already have the device, don't install a duplicate if (ozwDevice != null) return; ozwDevice = new Device { NodeNumber = nodeId, DeviceTypeId = UnknownTypeId, Name = "Unknown OpenZwave Device", CurrentLevelInt = 0, CurrentLevelText = "" }; context.Devices.Add(ozwDevice); var result = await context.TrySaveChangesAsync(CancellationToken); if (result.HasError) await Log.ReportErrorFormatAsync(CancellationToken, "Failed to save new device. {0}", result.Message); } #endregion }
public override async Task RepollAsync(Device device) { var nodeNumber = Convert.ToByte(device.NodeNumber); if (!IsNodeReady(nodeNumber)) { await Log.ReportInfoFormatAsync(CancellationToken, "Re-poll node {0} failed, node not ready.", nodeNumber); return; } MManager.RequestNodeState(MHomeId, nodeNumber); }
private async void ButtonRemoveDevice_OnClick(object sender, RoutedEventArgs e) { var selectedGroup = GroupsDataGrid.SelectedItem as Group; if (selectedGroup == null || GroupsDevicesLstVw.SelectedItems.Count <= 0) return; if (MessageBox.Show( string.Format("Are you sure you want to remove the {0} selected devices from this group?", GroupsDevicesLstVw.SelectedItems.Count), "Remove Devices?", MessageBoxButton.YesNo, MessageBoxImage.Error) != MessageBoxResult.Yes) return; var devicesToRemove = new Device[GroupsDevicesLstVw.SelectedItems.Count]; GroupsDevicesLstVw.SelectedItems.CopyTo(devicesToRemove, 0); foreach (var gd in devicesToRemove) selectedGroup.Devices.Remove(gd); await SaveChangesAsync(); }
public override Task ProcessDeviceCommandAsync(Device device, DeviceCommand command, string argument, string argument2) { return Publish(device.Type, device, null, command, argument); }
public override async Task ProcessDeviceTypeCommandAsync(DeviceType deviceType, Device device, DeviceTypeCommand command, string argument) { var nodeNumber = Convert.ToByte(device.NodeNumber); if (!IsNodeReady(nodeNumber)) { await Log.ReportInfoFormatAsync(CancellationToken, "Failed to issue command on {0}, node {1}. Node not ready.", device.Name, nodeNumber); return; } if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Controller.ToString()) { #region Controller Commands switch (command.UniqueIdentifier) { case "RESET": { MManager.ResetController(MHomeId); break; } case "ADDDEVICE": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.AddDevice, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "CreateNewPrimary": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.CreateNewPrimary, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "ReceiveConfiguration": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.ReceiveConfiguration, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "RemoveDevice": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.RemoveDevice, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "TransferPrimaryRole": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.TransferPrimaryRole, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "HasNodeFailed": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.HasNodeFailed, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "RemoveFailedNode": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.RemoveFailedNode, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } case "ReplaceFailedNode": { var dlg = new ControllerCommandDlg(MManager, MHomeId, ZWControllerCommand.ReplaceFailedNode, (byte)device.NodeNumber); dlg.ShowDialog(); dlg.Dispose(); break; } } #endregion } else if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Switch.ToString()) { #region Switch command handeling switch (command.UniqueIdentifier) { case "MOMENTARY": { int delay; int.TryParse(argument, out delay); var nodeId = (byte)device.NodeNumber; MManager.SetNodeOn(MHomeId, nodeId); await Task.Delay(delay); MManager.SetNodeOff(MHomeId, nodeId); break; } case "TURNON": { MManager.SetNodeOn(MHomeId, (byte)device.NodeNumber); break; } case "TURNOFF": { MManager.SetNodeOff(MHomeId, (byte)device.NodeNumber); break; } } #endregion } else if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Dimmer.ToString()) { #region Dimmer command handling switch (command.UniqueIdentifier) { case "TURNON": { using (var context = new ZvsContext(EntityContextConnection)) { var value = await device.GetDeviceTypeValueAsync(OpenzWaveDeviceTypeSettings.DefaultDimmerOnLevel.ToString(), context); if (value != null) { byte bValue = byte.TryParse(value, out bValue) ? bValue : (byte)99; MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, bValue); break; } } MManager.SetNodeOn(MHomeId, (byte)device.NodeNumber); break; } case "TURNOFF": { MManager.SetNodeOff(MHomeId, (byte)device.NodeNumber); break; } case "SETPRESETLEVEL": { switch (argument) { case "0%": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(0)); break; case "20%": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(20)); break; case "40%": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(40)); break; case "60%": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(60)); break; case "80%": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(80)); break; case "100%": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(100)); break; case "255": MManager.SetNodeLevel(MHomeId, (byte)device.NodeNumber, Convert.ToByte(255)); break; } break; } } #endregion } else if (deviceType.UniqueIdentifier == OpenzWaveDeviceTypes.Thermostat.ToString()) { #region Thermostat Command Handling switch (command.UniqueIdentifier) { case "SETENERGYMODE": { MManager.SetNodeOff(MHomeId, (byte)device.NodeNumber); break; } case "SETCONFORTMODE": { MManager.SetNodeOn(MHomeId, (byte)device.NodeNumber); break; } } #endregion } }
public override Task RepollAsync(Device device) { throw new NotImplementedException(); }
public override Task ProcessDeviceCommandAsync(Device device, DeviceCommand command, string argument, string argument2) { return Task.FromResult(0); }
////User Events private async Task DeleteSelectedItemsAsync() { if (DeviceGrid.SelectedItems.Count > 0) { var selectedItemsCopy = new Device[DeviceGrid.SelectedItems.Count]; DeviceGrid.SelectedItems.CopyTo(selectedItemsCopy, 0); foreach (var selectedDevice in selectedItemsCopy) { var device = selectedDevice; var d = await Context.Devices.FirstOrDefaultAsync(o => o.Id == device.Id); if (d == null) continue; //Check for device dependencies foreach (var dvt in await Context.DeviceValueTriggers.Where(t => t.DeviceValue.Device.Id == d.Id).ToListAsync()) { var windowResult = MessageBox.Show( string.Format("Deleting device '{0}' will delete trigger '{1}', would you like continue?", d.Name, dvt.Name), "Device Delete Warning", MessageBoxButton.YesNo); if (windowResult == MessageBoxResult.Yes) { Context.DeviceValueTriggers.Local.Remove(dvt); var result = await Context.TrySaveChangesAsync(_app.Cts.Token); if (result.HasError) await Log.ReportErrorFormatAsync(_app.Cts.Token, "Error deleting device triggers. {0}", result.Message); } else return; } Context.Devices.Local.Remove(d); var r2 = await Context.TrySaveChangesAsync(_app.Cts.Token); if (r2.HasError) await Log.ReportErrorFormatAsync(_app.Cts.Token, "Error deleting device. {0}", r2.Message); } } }
public override Task RepollAsync(Device device) { return Task.FromResult(0); }
private async Task LoadDeviceAsync() { using (var context = new ZvsContext(App.EntityContextConnection)) { var d = await context.Devices .Include(o => o.Type) .FirstOrDefaultAsync(dv => dv.Id == DeviceId); if (d == null) { MessageBox.Show("Device not found", "Error", MessageBoxButton.OK, MessageBoxImage.Error); Close(); return; } Device = d; } }
public abstract Task ProcessDeviceCommandAsync(Device device, DeviceCommand command, string argument, string argument2);