private void CheckForUsage([NotNull] DeviceAction action, [NotNull] Simulator sim) { if (!PerformCleanupChecks) { return; } var usedIns = action.CalculateUsedIns(sim); if (usedIns.Count == 0) { throw new DataIntegrityException( "It seems the device action " + action.Name + " is not used in a single affordance. Please fix or delete.", action); } }
// Invoke the direct method on the device, passing the payload public Task InvokeMethod(string DeviceId, string ActionName = "PlaySound", params string[] Params) { Console.WriteLine($"Do Action -> {ActionName}"); return(Task.Factory.StartNew(() => { var action = new DeviceAction() { ActionName = ActionName, Params = Params }; SendCommand(JsonConvert.SerializeObject(action)); })); //Console.WriteLine("Response status: {0}, payload:", response.Status); //Console.WriteLine(response.GetPayloadAsJson()); }
public static DeviceCommand SetAction(this DeviceCommand device, DeviceAction action) { if (device == null) { throw new ArgumentNullException(nameof(device)); } if (action == DeviceAction.None) { throw new InvalidOperationException($"{action} cannot be set as device action"); } device.Action = action; return(device); }
public void IsAffordanceAvailableTestCheckDeviceActionGroupInDeviceActionGroup() { // Location: device action group // affordance: device Action Group Config.IsInUnitTesting = true; var col = new ColorRGB(255, 0, 0); var deviceActions = new ObservableCollection <DeviceAction>(); var aff = new Affordance("bla", null, null, false, PermittedGender.All, 1, col, string.Empty, null, string.Empty, string.Empty, true, true, 0, 100, false, ActionAfterInterruption.GoBackToOld, false, Guid.NewGuid().ToStrGuid(), BodilyActivityLevel.Low); var rd1 = new RealDevice("rd1", 1, string.Empty, null, string.Empty, false, false, string.Empty, Guid.NewGuid().ToStrGuid()); var dg = new DeviceActionGroup("group", string.Empty, string.Empty, Guid.NewGuid().ToStrGuid()); var da = new DeviceAction("device action 1", null, "blub", string.Empty, dg, rd1, Guid.NewGuid().ToStrGuid()); deviceActions.Add(da); var devices = new ObservableCollection <RealDevice> { rd1 }; // check if it works with a device category that has the device var dc1 = new DeviceCategory("dc1", 0, string.Empty, false, devices, Guid.NewGuid().ToStrGuid(), null, true); rd1.DeviceCategory = dc1; dc1.RefreshSubDevices(); (dc1.SubDevices.Count).Should().Be(1); var connectionString = string.Empty; var lt = new VLoadType("lt", string.Empty, "bla", "blub", 1, 1, new TimeSpan(0, 1, 0), 1, connectionString, LoadTypePriority.Mandatory, true, Guid.NewGuid().ToStrGuid()); var tbp = new TimeBasedProfile("name", 1, connectionString, TimeProfileType.Absolute, "data source", Guid.NewGuid().ToStrGuid()); aff.AffordanceDevices.Add(new AffordanceDevice(dg, tbp, null, 0, null, new ObservableCollection <RealDevice>(), new ObservableCollection <DeviceCategory>(), "name", lt, string.Empty, 1, Guid.NewGuid().ToStrGuid())); var allDevices3 = new List <IAssignableDevice> { dg }; if (da.DeviceActionGroup == null) { throw new LPGException("device action group was null"); } var relevantDeviceActionGroup = da.DeviceActionGroup.GetDeviceActions(deviceActions); (relevantDeviceActionGroup.Count).Should().Be(1); (aff.IsAffordanceAvailable(allDevices3, deviceActions)).Should().BeTrue(); }
CentralConnectServiceResponse ICentralConnectService.RetrieveRegisterDeviceMessageByEnvironmentAndDeviceNameAndDomain(CentralConnectServiceRequest centralConnectServiceRequest) { if (centralConnectServiceRequest.RegisterDeviceMessage == null) { return(new CentralConnectServiceResponse() { Code = 400, Message = "RegisterDeviceMessage should not null" }); } if (string.IsNullOrEmpty(centralConnectServiceRequest.RegisterDeviceMessage.Environment) || string.IsNullOrEmpty(centralConnectServiceRequest.RegisterDeviceMessage.DeviceName) || string.IsNullOrEmpty(centralConnectServiceRequest.RegisterDeviceMessage.Domain)) { return(new CentralConnectServiceResponse() { Code = 400, Message = "Environment DeviceName Domain should not null" }); } if (string.IsNullOrEmpty(centralConnectServiceRequest.Id) || string.IsNullOrEmpty(centralConnectServiceRequest.Token) || string.IsNullOrEmpty(centralConnectServiceRequest.Type)) { return(new CentralConnectServiceResponse() { Code = 400, Message = "Id Type and Token should not null" }); } string message = string.Empty; if (HP.TS.Devops.Security.SecurityCode.Success != HP.TS.Devops.Security.SecurityAction.CheckAccess(this.ConnectString, centralConnectServiceRequest, out message)) { return(new CentralConnectServiceResponse() { Code = 403, Message = centralConnectServiceRequest.Id + " of type " + centralConnectServiceRequest.Type + " have no access of " + message }); } DeviceAction deviceAction = new DeviceAction(this.ConnectString); List <RegisterDeviceMessage> registerDeviceMessages = deviceAction.RetrieveRegisterDeviceMessageByEnvironmentAndDeviceNameAndDomain(centralConnectServiceRequest.RegisterDeviceMessage.Environment, centralConnectServiceRequest.RegisterDeviceMessage.DeviceName, centralConnectServiceRequest.RegisterDeviceMessage.Domain); return(new CentralConnectServiceResponse() { Code = 0, Message = "Success", RegisterDeviceMessages = registerDeviceMessages }); }
public void When_no_raw_keys_and_no_time_are_included_it_must_raise_event_without_keys_and_time() { // Arrange var deviceAction = new DeviceAction(Source, null, NullTime); var tracker = new RemoteKeyTracker(); // Act using (var listener = new TrackerEventListener(tracker)) { tracker.ProcessDeviceAction(deviceAction); // Assert listener.EventsCollected.Should().HaveCount(1); listener.EventsCollected[0].ShouldBeMissingKeyFor(Source, NullTime); } }
public virtual async Task <CreateResponse <ApiDeviceActionServerResponseModel> > Create( ApiDeviceActionServerRequestModel model) { CreateResponse <ApiDeviceActionServerResponseModel> response = ValidationResponseFactory <ApiDeviceActionServerResponseModel> .CreateResponse(await this.DeviceActionModelValidator.ValidateCreateAsync(model)); if (response.Success) { DeviceAction record = this.DalDeviceActionMapper.MapModelToEntity(default(int), model); record = await this.DeviceActionRepository.Create(record); response.SetRecord(this.DalDeviceActionMapper.MapEntityToModel(record)); await this.mediator.Publish(new DeviceActionCreatedNotification(response.Record)); } return(response); }
private void DeviceActionToConfig(DeviceAction action) { try { int devAddr = IndexForHostDevice(); if (devAddr != -1) { foreach (var param in action.RequiredParameters) { SetConfigForActionParameterAtDevice(param, site.siteCfg.deviceConfigs[devAddr]); } } } catch (Exception e) { } }
public bool PerformDeviceAction(DeviceAction act) { try { CommDeviceProtocolManager man = new CommDeviceProtocolManager(act.Device); //Task actTask = man.PerformActionAsync(act); //actTask.ContinueWith( t => { DeviceUpdateEventService.SendDeviceUpdate(act.Device); }); man.PerformAction(act); DeviceUpdateEventService.SendDeviceUpdate(act.Device); return(true); } catch (Exception e) { nlogger.ErrorException(e.Message, e); return(false); } }
public async void Get_ShouldReturnRecords() { var mock = new ServiceMockFacade <IDeviceActionService, IDeviceActionRepository>(); var record = new DeviceAction(); mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult(record)); var service = new DeviceActionService(mock.LoggerMock.Object, mock.MediatorMock.Object, mock.RepositoryMock.Object, mock.ModelValidatorMockFactory.DeviceActionModelValidatorMock.Object, mock.DALMapperMockFactory.DALDeviceActionMapperMock); ApiDeviceActionServerResponseModel response = await service.Get(default(int)); response.Should().NotBeNull(); mock.RepositoryMock.Verify(x => x.Get(It.IsAny <int>())); }
private static void CheckForDuplicateTimeProfiles([NotNull] DeviceAction action) { foreach (var profile1 in action.Profiles) { foreach (var profile2 in action.Profiles) { if (profile1 != profile2) { if (profile1.VLoadType == profile2.VLoadType && profile1.TimeOffset == profile2.TimeOffset) { throw new DataIntegrityException( "The device action " + action.Name + " has the same load type twice with the same time offset. Please fix.", action); } } } } }
public DeviceAction DeviceActionWithId(int ActionId) { try { iotSharedEntityContext <DeviceAction> devCont = new iotSharedEntityContext <DeviceAction>(); DeviceAction dev = devCont.GetById(ActionId); if (dev != null) { return(dev); } return(null); } catch (Exception e) { nlogger.ErrorException(e.Message, e); return(new DeviceAction()); } }
// Invoke the direct method on the device, passing the payload public async Task InvokeMethod(string DeviceId, string ActionName = "PlaySound", params string[] Params) { var methodInvocation = new CloudToDeviceMethod("DoAction") { ResponseTimeout = TimeSpan.FromSeconds(30) }; var action = new DeviceAction() { ActionName = ActionName, Params = Params }; methodInvocation.SetPayloadJson(JsonConvert.SerializeObject(action)); // Invoke the direct method asynchronously and get the response from the simulated device. var response = await s_serviceClient.InvokeDeviceMethodAsync(DeviceId, methodInvocation); Console.WriteLine("Response status: {0}, payload:", response.Status); Console.WriteLine(response.GetPayloadAsJson()); }
public static void LoadActionsFromDB() { DataTable rules = ActionsTableMgr.GetActions(); if (rules != null) { foreach (DataRow row in rules.Rows) { var action = new DeviceAction(); action.DeviceName = row["DeviceName"].ToString(); action.Category = row["Category"].ToString(); action.Label = row["Label"].ToString(); action.ActionText = row["ActionText"].ToString(); action.Tooltip = row["Tooltip"].ToString(); Actions.Add(action); } Logger.AddLogEntry(LogCategory.INFO, "Actions Inventory Loaded"); } }
public HttpResponseMessage CheckStatus(string deviceSerial) { try { var deviceAction = new DeviceAction { Action = "STATUS", DeviceSerial = deviceSerial }; var deviceSession = DeviceSessionPool.GetDeviceSession(deviceSerial); deviceSession.Send((new JavaScriptSerializer().Serialize(deviceAction))); return(Request.CreateResponse(HttpStatusCode.OK, DeviceSessionPool.deviceStatus[deviceSerial])); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public void CalculateMaximumInternalTimeResolutionTestForDeviceAction() { using (var db = new DatabaseSetup(Utili.GetCurrentMethodAndClass())) { Config.IsInUnitTesting = true; var col = new ColorRGB(255, 0, 0); var devices = new ObservableCollection <RealDevice>(); var rd2 = new RealDevice("rd2", 1, string.Empty, null, string.Empty, false, false, db.ConnectionString, Guid.NewGuid().ToStrGuid()); rd2.SaveToDB(); devices.Add(rd2); var deviceCategories = new ObservableCollection <DeviceCategory>(); var aff = new Affordance("bla", null, null, false, PermittedGender.All, 1, col, string.Empty, null, string.Empty, db.ConnectionString, true, true, 0, 100, false, ActionAfterInterruption.GoBackToOld, false, Guid.NewGuid().ToStrGuid(), BodilyActivityLevel.Low); aff.SaveToDB(); var tp = new TimeBasedProfile("tp", null, db.ConnectionString, TimeProfileType.Relative, "fake", Guid.NewGuid().ToStrGuid()); tp.SaveToDB(); tp.AddNewTimepoint(new TimeSpan(0, 0, 0), 1, false); tp.AddNewTimepoint(new TimeSpan(0, 1, 0), 1, false); tp.AddNewTimepoint(new TimeSpan(0, 10, 0), 1, false); var lt = new VLoadType("lt", string.Empty, "bla", "blub", 1, 1, new TimeSpan(0, 1, 0), 1, db.ConnectionString, LoadTypePriority.Mandatory, true, Guid.NewGuid().ToStrGuid()); lt.SaveToDB(); var dag = new DeviceActionGroup("dag", db.ConnectionString, string.Empty, Guid.NewGuid().ToStrGuid()); dag.SaveToDB(); var da = new DeviceAction("da", null, string.Empty, db.ConnectionString, dag, rd2, Guid.NewGuid().ToStrGuid()); da.SaveToDB(); da.AddDeviceProfile(tp, 0, lt, 1); new ObservableCollection <DeviceAction>().Add(da); var tbp = new TimeBasedProfile("name", 1, db.ConnectionString, TimeProfileType.Absolute, "data source", Guid.NewGuid().ToStrGuid()); aff.AddDeviceProfile(da, tbp, 0, devices, deviceCategories, lt, 1); var ts = aff.CalculateMaximumInternalTimeResolution(); (ts.TotalSeconds).Should().Be(60); Logger.Info(ts.ToString()); db.Cleanup(); } }
public Task PerformActionAsync(DeviceAction action) { try { CommProtocolType protType = GetDeviceQueryProtcol(); ICommProtocol protocol = GetProtocolDelegateForType(protType); if (protocol.ProtocolDeviceQueryAble()) { return(protocol.PerformActionAsync(action)); } else { return(null); } } catch (Exception e) { return(null); } }
public Task PerformActionAsync(DeviceAction action) { try { Task t = Task.Factory.StartNew(() => { LoadDevice(action.Device); UpdateSite(); DeviceActionToConfig(action); WriteSiteConfig(); LoadDeviceActions(action.Device); //load site config after change }); return(t); } catch (Exception e) { nlogger.ErrorException(e.Message, e); return(null); } }
internal static bool AddRule(DeviceAction action) { lock (DBAdmin.padlock) { int updatedRows = 0; using (SQLiteConnection dbConnection = DBAdmin.GetSQLConnection()) { dbConnection.Open(); using (SQLiteCommand cmd = new SQLiteCommand(dbConnection)) { SQLiteTransaction trans = dbConnection.BeginTransaction(); cmd.CommandText = "INSERT INTO [ACTIONS] " + "([DeviceName], [Category], [Label], [ActionText], [Tooltip]) " + "VALUES(@deviceName, @category, @label, @actionText, @tooltip);"; cmd.Parameters.Add(new SQLiteParameter("@deviceName", DbType.String) { Value = action.DeviceName }); cmd.Parameters.Add(new SQLiteParameter("@category", DbType.String) { Value = action.Category }); cmd.Parameters.Add(new SQLiteParameter("@label", DbType.String) { Value = action.Label }); cmd.Parameters.Add(new SQLiteParameter("@actionText", DbType.String) { Value = action.ActionText }); cmd.Parameters.Add(new SQLiteParameter("@tooltip", DbType.String) { Value = action.Tooltip }); updatedRows = cmd.ExecuteNonQuery(); trans.Commit(); } } return(updatedRows == 1); } }
private void AddActionForMapperAndDevice(sconnConfigMapper maper, Device edited, int DevNo) { try { DeviceAction action = new DeviceAction(); action.ActionName = "Output" + maper.SeqNumber; //TODO read from name cfg action.Device = edited; action.LastActivationTime = DateTime.Now; var qry = connector.ActionAdd(action); //copy maper for action sconnConfigMapper actionMaper = new sconnConfigMapper(); actionMaper.ConfigType = maper.ConfigType; actionMaper.SeqNumber = maper.SeqNumber; ParameterType paramtype = ParamTypeForSconnMapper(actionMaper); ActionParameter inparam = new ActionParameter(); inparam.Value = sconnConfigToStringVal(actionMaper, site.siteCfg.deviceConfigs[DevNo]); inparam.Type = paramtype; inparam.Action = action; actionMaper.ActionParam = inparam; qry = connector.ActionParamAdd(inparam); //create parameter and bind mapper to it DeviceParameter param = new DeviceParameter(); param.Value = sconnConfigToStringVal(maper, site.siteCfg.deviceConfigs[DevNo]); param.Type = paramtype; param.Action = action; qry = connector.ParameterAdd(param); maper.Parameter = param; qry = connector.MapperAdd(maper); } catch (Exception e) { } }
public bool SwitchOnOff(DeviceAction deviceAction) { Models.AuthResponse token = JsonConvert.DeserializeObject <Models.AuthResponse>(Preferences.Get("Token", "")); using (HttpClient client = new HttpClient()) { string url = Constants.baseUrl + "api/Device/Control"; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("Authorization", token.Token); client.DefaultRequestHeaders.Add("AcceptEncoding", "application/json"); var response = client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(deviceAction), Encoding.UTF8, "application/json")).Result; var responseBody = response.Content.ReadAsStringAsync().Result; if (response.IsSuccessStatusCode) { return(true); } } return(false); }
public async Task <CommandResult> ExecuteActionAsync(DeviceAction action, CancellationToken cancellationToken) { var result = CommandResult.NotApplied; IDeviceCommand command; if (_commands.TryGet(c => c.Action == action, out command) && CanApplyCommand(command)) { var execution = ApplyCommandsAsync(new[] { command }, cancellationToken); if (execution != null) { RecentCommandExecution = new DeviceCommandExecution(execution, command.TargetState); result = await execution; } } return(result); }
private static void CheckforAllPlaceholders([NotNull] DeviceAction action) { var areAllPlaceholder = true; foreach (var profile in action.Profiles) { if (profile.Timeprofile?.Name.ToUpperInvariant().Contains("PLACEHOLDER") == false) { areAllPlaceholder = false; } } if (areAllPlaceholder) { if (!action.Description.Contains("Place holder profile on purpose")) { throw new DataIntegrityException( "The device action " + action.Name + " has only placeholder profiles. This is pointless. Please fix.", action); } } }
public OnOffDevice(bool useOpenCloseActions) { this.DeviceType = BO.DeviceType.OnOff; this.DisplayType = BO.DisplayType.Boolean; if (useOpenCloseActions) { this.Actions = new List <DeviceAction>() { DeviceAction.Get <OpenAction>(), DeviceAction.Get <CloseAction>() }; } else { this.Actions = new List <DeviceAction>() { DeviceAction.Get <OnAction>(), DeviceAction.Get <OffAction>() }; } }
private void DeviceActionToConfig(DeviceAction action) { try { int devAddr = 0; //IndexForHostDevice(); if (site.siteCfg.deviceNo == 0) { return; } if (devAddr != -1) { foreach (var param in action.RequiredParameters) { SetConfigForActionParameterAtDevice(param, site.siteCfg.deviceConfigs[devAddr]); } } } catch (Exception e) { nlogger.ErrorException(e.Message, e); } }
/******************* Public ************************/ public bool PerformAction(DeviceAction action) { try { Stopwatch watch = new Stopwatch(); LoadDevice(action.Device); watch.Start(); UpdateSite(); watch.Stop(); Debug.WriteLine("Execution time : " + watch.ElapsedMilliseconds + " ms"); watch.Reset(); DeviceActionToConfig(action); watch.Start(); WriteSiteConfig(); watch.Stop(); Debug.WriteLine("Execution time : " + watch.ElapsedMilliseconds + " ms"); watch.Reset(); watch.Start(); LoadDeviceActions(action.Device); //load site config after change watch.Stop(); Debug.WriteLine("Execution time : " + watch.ElapsedMilliseconds + " ms"); watch.Reset(); return(true); } catch (Exception e) { nlogger.ErrorException(e.Message, e); return(false); } }
//设备打开消息,同步给重连Socket public void SendDeviceStatusRelink(int status, UInt16 stationIndex, DeviceType deviceType, int deviceId, PlayerActor u3dPlayerActor) { if (u3dPlayerActor == null) { return; } Agent agent = u3dPlayerActor.Agent; DeviceAction deviceAction = new DeviceAction() { m_deviceId = deviceId, m_deviceType = (int)deviceType, m_stationIndex = stationIndex, m_deviceStatus = (byte)status, }; byte[] bytes = deviceAction.Packet2Bytes(); UInt16 sendId = TDFramework.SingletonMgr.GameGlobalInfo.ServerInfo.Id; UInt16 u3dId = 0; UInt16 msgLen = (UInt16)bytes.Length; Packet packet = new Packet(sendId, u3dId, TDFramework.SingletonMgr.MessageIDMgr.DeviceActionMessageId, msgLen, bytes); agent.SendPacket(packet.Packet2Bytes()); }
public virtual async Task <UpdateResponse <ApiDeviceActionServerResponseModel> > Update( int id, ApiDeviceActionServerRequestModel model) { var validationResult = await this.DeviceActionModelValidator.ValidateUpdateAsync(id, model); if (validationResult.IsValid) { DeviceAction record = this.DalDeviceActionMapper.MapModelToEntity(id, model); await this.DeviceActionRepository.Update(record); record = await this.DeviceActionRepository.Get(id); ApiDeviceActionServerResponseModel apiModel = this.DalDeviceActionMapper.MapEntityToModel(record); await this.mediator.Publish(new DeviceActionUpdatedNotification(apiModel)); return(ValidationResponseFactory <ApiDeviceActionServerResponseModel> .UpdateResponse(apiModel)); } else { return(ValidationResponseFactory <ApiDeviceActionServerResponseModel> .UpdateResponse(validationResult)); } }
public void DeviceCategoryPickerDeviceActionGroupAutoDev() { Random r = new Random(2); DeviceSelection ds = new DeviceSelection("ds", 1, string.Empty, string.Empty, Guid.NewGuid().ToStrGuid()); DeviceCategoryPicker picker = new DeviceCategoryPicker(r, ds); // device stuff ObservableCollection <RealDevice> allDevices = new ObservableCollection <RealDevice>(); DeviceCategory dc = new DeviceCategory("dc", -1, "bla", false, allDevices, Guid.NewGuid().ToStrGuid()); RealDevice rd1 = new RealDevice("device1", 0, string.Empty, dc, "desc", false, true, string.Empty, Guid.NewGuid().ToStrGuid(), -1); RealDevice rd2 = new RealDevice("device2", 0, string.Empty, dc, "desc", false, true, string.Empty, Guid.NewGuid().ToStrGuid(), -1); DeviceActionGroup dag = new DeviceActionGroup("Dag1", string.Empty, "blub", Guid.NewGuid().ToStrGuid(), -1); DeviceAction da1 = new DeviceAction("da1", -1, "blub", string.Empty, dag, rd1, Guid.NewGuid().ToStrGuid()); DeviceAction da2 = new DeviceAction("da2", -1, "blub", string.Empty, dag, rd2, Guid.NewGuid().ToStrGuid()); ObservableCollection <DeviceAction> deviceActions = new ObservableCollection <DeviceAction> { da1, da2 }; allDevices.Add(rd1); List <IAssignableDevice> otherDevicesAtLocation = new List <IAssignableDevice> { dag }; DeviceAction pickedDeviceAction = picker.GetAutoDeviceActionFromGroup(dag, otherDevicesAtLocation, EnergyIntensityType.Random, deviceActions, 5); Logger.Info("Device Action 1 " + pickedDeviceAction); for (int i = 0; i < 50; i++) { DeviceAction deviceAction2 = picker.GetAutoDeviceActionFromGroup(dag, otherDevicesAtLocation, EnergyIntensityType.Random, deviceActions, 5); Logger.Info("Device Action " + i + " " + deviceAction2); pickedDeviceAction.Should().Be(deviceAction2); } }
public byte[] MessageBuilder(DeviceAction deviceAction) { byte[] dataMessage = new byte[5]; dataMessage[0] = 0xBE; dataMessage[1] = (byte)deviceAction.ActionTime.Hour; dataMessage[2] = (byte)deviceAction.ActionTime.Minute; //dataMessage[1] = (byte) deviceAction.Hour; //dataMessage[2] = (byte)deviceAction.Minute; dataMessage[3] = (byte)deviceAction.ActionDayOfWeek; byte camAndConnect = 0; if (deviceAction.IsCamera1PhotoNeed) { camAndConnect += 1; } if (deviceAction.IsCamera2PhotoNeed) { camAndConnect += 2; } if (deviceAction.IsCamera3PhotoNeed) { camAndConnect += 4; } if (deviceAction.IsCamera4PhotoNeed) { camAndConnect += 8; } if (deviceAction.IsSensorDataNeed) { camAndConnect += 16; } dataMessage[4] = camAndConnect; dataMessage[5] = 0xBE; return(dataMessage); }
public virtual ApiDeviceActionServerResponseModel MapEntityToModel( DeviceAction item) { var model = new ApiDeviceActionServerResponseModel(); model.SetProperties(item.Id, item.Action, item.DeviceId, item.Name); if (item.DeviceIdNavigation != null) { var deviceIdModel = new ApiDeviceServerResponseModel(); deviceIdModel.SetProperties( item.DeviceIdNavigation.Id, item.DeviceIdNavigation.DateOfLastPing, item.DeviceIdNavigation.IsActive, item.DeviceIdNavigation.Name, item.DeviceIdNavigation.PublicId); model.SetDeviceIdNavigation(deviceIdModel); } return(model); }
private bool ActionOnDevice(string deviceName, DeviceAction action) { bool bFound = false; Guid myGUID = System.Guid.Empty; IntPtr hDevInfo = Native.SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, Native.DIGCF_ALLCLASSES | Native.DIGCF_PRESENT); if (hDevInfo.ToInt32() == Native.INVALID_HANDLE_VALUE) { throw new Exception("Failed to open the device manager"); return false; } Native.SP_DEVINFO_DATA DeviceInfoData; DeviceInfoData = new Native.SP_DEVINFO_DATA(); DeviceInfoData.cbSize = Marshal.SizeOf(DeviceInfoData); // JDA 28; //is devices exist for class DeviceInfoData.devInst = 0; DeviceInfoData.classGuid = System.Guid.Empty; DeviceInfoData.reserved = 0; UInt32 i; StringBuilder DeviceName = new StringBuilder(""); DeviceName.Capacity = Native.MAX_DEV_LEN; for (i = 0; Native.SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData); i++) { //Declare vars while (!Native.SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, Native.SPDRP_DEVICEDESC, 0, DeviceName, Native.MAX_DEV_LEN, IntPtr.Zero)) { //Skip } if (DeviceName.ToString().ToLower().Contains(deviceName.ToLower())) { bFound = true; switch (action) { case DeviceAction.Disable : if (!EnableOrDisableDevice(hDevInfo, DeviceInfoData, false)) throw new Exception("Failed to disable the device"); break; case DeviceAction.Enable : if (!EnableOrDisableDevice(hDevInfo, DeviceInfoData, true)) throw new Exception("Failed to enable the device"); break; case DeviceAction.Reset : if (!RestartDevice(hDevInfo, DeviceInfoData)) throw new Exception("Failed to reset the device"); break; default : throw new Exception("Invalid action."); } break; } } Native.SetupDiDestroyDeviceInfoList(hDevInfo); if (!bFound) throw new Exception("Device not found"); return true; }
public abstract bool ExecuteAction(Device device, DeviceAction action);
private void SignalButton_Click([CanBeNull] object sender, [NotNull] EventArgs e) { var deviceAction = new DeviceAction(settings.DeviceAddressNotNull, null, hardwareStatus.ClockValue); sessionManager.Value.NotifyAction(deviceAction); }
public DriveEventArgs(string driveName,int listPosition, DeviceAction action) { DriveName = driveName; ListPosition = listPosition; Action = action; }
public override bool ExecuteAction(Device device, DeviceAction action) { return true; }