static void Main(string[] args) { Fridge f = new Fridge("холодко"); //Console.WriteLine("холодильник {0} с температурой {1}",f.Name,f.IncreaceTemperature(-6)); string cd = String.Empty; PrintMenu(cd); while (true) { Console.Write("{0}>", cd); string cmd = Console.ReadLine().Trim().ToLower(); switch (cmd) { case "q": return; case "": PrintMenu(cd); continue; default: break; } ; PrintMenu(cd); string resCmd = DeviceCommand.Run(cmd); if (resCmd != String.Empty) { Console.WriteLine(resCmd); } } }
private bool ToggleDeviceSwitch() { var deviceCurrentStatus = new Dictionary <string, AttributeState>(); if (this.smartThingsClient.TryGetDeviceCapabilityStatus(this.device.DeviceId, this.device.Components[0].Id, "switch", out deviceCurrentStatus) && deviceCurrentStatus.Count > 0) { string state = deviceCurrentStatus["switch"].Value.ToString().ToLower(); string newState = state == "on" ? "off" : "on"; DeviceCommandsRequest commandsRequest = new DeviceCommandsRequest() { Commands = new List <DeviceCommand>() }; DeviceCommand command = new DeviceCommand(capability: "switch", command: newState); commandsRequest.Commands.Add(command); this.smartThingsClient.ExecuteDevicecommand(this.device.DeviceId, commandsRequest); return(true); } else { return(false); } }
/// <summary> /// Creates a new <see cref="CommandFrame"/> from specified parameters. /// </summary> /// <param name="idCode">The ID code of this <see cref="CommandFrame"/>.</param> /// <param name="command">The <see cref="DeviceCommand"/> for this <see cref="CommandFrame"/>.</param> /// <param name="version">IEEE C37.118 revision number.</param> /// <remarks> /// This constructor is used by a consumer to generate an IEEE C37.118 command frame. /// </remarks> public CommandFrame(ushort idCode, DeviceCommand command, byte version) : base(new CommandCellCollection(Common.MaximumExtendedDataLength), command) { base.IDCode = idCode; base.Timestamp = DateTime.UtcNow.Ticks; this.Version = version; }
public PartialViewResult DeletePV(long id) { DeviceCommand Command = UnitOfWork_Repositories.repoDeviceCommands.Find(id); ViewBag.DeviceID = new SelectList(UnitOfWork_Repositories.repoEndpoints.GetList(), "ID", "Title", Command.DeviceID); return(PartialView("_Delete", Command)); }
/// <summary> /// Writes out the commands to the device and handles exceptions as /// appropriate. /// </summary> /// <param name="command">The command to be sent to the device</param> /// <param name="write">whether it is a write command</param> /// <param name="data">Data to be sent, if it is a write.</param> private async void SendData_Click(DeviceCommand command, int write, byte[] data) { try { if (streamSocket.OutputStream != null) { // Create the DataWriter object and attach to OutputStream dataWriterObject = new DataWriter(streamSocket.OutputStream); // send off the data and wait await WriteAsync(command, write, data); } else { dateStampOutput(); outputTextBox.Text += "Bluetooth did not connect correctly. " + System.Environment.NewLine; } } catch (Exception ex) { dateStampOutput(); outputTextBox.Text += "SEND ERROR: " + ex.Message + System.Environment.NewLine; } finally { // Cleanup once complete if (dataWriterObject != null) { dataWriterObject.DetachStream(); dataWriterObject = null; } } }
public PartialViewResult EditPV(long id) { DeviceCommand Command = uof_repos.repoDeviceCommands.Find(id); ViewBag.DeviceID = new SelectList(uof_repos.repoDevices.GetList(), "ID", "Title", Command.DeviceID); return(PartialView("_Edit", Command)); }
private void Notify(WebSocketConnectionBase connection, Guid subscriptionId, DeviceCommand command, Device device, bool isInitialCommand = false) { if (!isInitialCommand) { var initialCommandList = GetInitialCommandList(connection, subscriptionId); lock (initialCommandList) // wait until all initial commands are sent { if (initialCommandList.Contains(command.ID)) { return; } } if (!IsDeviceAccessible(connection, device, "GetDeviceCommand")) { return; } } connection.SendResponse("command/insert", new JProperty("subscriptionId", subscriptionId), new JProperty("deviceGuid", device.GUID), new JProperty("command", GetMapper <DeviceCommand>().Map(command))); }
private void SendDeviceCommand(DeviceCommand aDeviceCommand, bool aSecondPS2Port, byte?aByte = null) { mDebugger.SendInternal("(PS/2 Controller) Sending device command:"); mDebugger.SendInternal("Device command:"); mDebugger.SendInternal((byte)aDeviceCommand); if (aSecondPS2Port) { SendCommand(Command.WriteNextByteToSecondPS2PortInputBuffer); } WaitToWrite(); IO.Data.Byte = (byte)aDeviceCommand; WaitForAck(); mDebugger.SendInternal("Device command sent."); if (aByte.HasValue) { mDebugger.SendInternal("(PS/2 Controller) Sending byte after device command:"); mDebugger.SendInternal("Byte value:"); mDebugger.SendInternal(aByte.Value); if (aSecondPS2Port) { SendCommand(Command.WriteNextByteToSecondPS2PortInputBuffer); } WaitToWrite(); IO.Data.Byte = aByte.Value; WaitForAck(); } }
/// <summary> /// Notifies the user about new device command. /// </summary> /// <action>command/insert</action> /// <response> /// <parameter name="subscriptionId" type="guid">Identifier of the associated subscription.</parameter> /// <parameter name="deviceGuid" type="string">Device unique identifier.</parameter> /// <parameter name="command" cref="DeviceCommand">A <see cref="DeviceCommand"/> resource representing the command.</parameter> /// </response> public void HandleDeviceCommand(int deviceId, int commandId, string name) { var subscriptions = _deviceSubscriptionManagerForCommands.GetSubscriptions(deviceId); if (subscriptions.Any()) { Device device = null; DeviceCommand command = null; foreach (var subscription in subscriptions) { var names = (string[])subscription.Data; if (names != null && !names.Contains(name)) { continue; } if (command == null) { command = DataContext.DeviceCommand.Get(commandId); } if (device == null) { device = DataContext.Device.Get(deviceId); } Notify(subscription.Connection, subscription.Id, command, device); } } }
public async Task RunDeviceCommandTest() { //Arrange var dbConnection = new UnitTestDbConnection(); Database.SetInitializer(new CreateFreshDbInitializer()); int?commandIdRan = 0; var arg1Ran = ""; var arg2Ran = ""; var commandProcessor = new StubICommandProcessor { RunCommandAsyncNullableOfInt32StringStringCancellationToken = (commandId, argument, argument2, cancellationToken) => { commandIdRan = commandId; arg1Ran = argument; arg2Ran = argument2; return(Task.FromResult(Result.ReportSuccess())); } }; var log = new StubIFeedback <LogEntry> { ReportAsyncT0CancellationToken = (e, c) => { Console.WriteLine(e); return(Task.FromResult(0)); } }; var cts = new CancellationTokenSource(); var runner = new JavaScriptRunner(log, commandProcessor, dbConnection); const string script = @" function f1() { var result = runDeviceNameCommandName('Light Switch','Turn On', '99'); logInfo(result.Message); }; f1();"; var device = UnitTesting.CreateFakeDevice(); using (var context = new ZvsContext(dbConnection)) { var deviceCommand = new DeviceCommand { Name = "Turn On" }; device.Commands.Add(deviceCommand); context.Devices.Add(device); await context.SaveChangesAsync(CancellationToken.None); //Act var result = await runner.ExecuteScriptAsync(script, cts.Token); //Assert Assert.IsFalse(result.HasError, result.Message); Assert.IsTrue(deviceCommand.Id == commandIdRan, "Wrong command ran!"); Assert.IsTrue("99" == arg1Ran, "command arguments not passed in correctly."); Assert.IsTrue(string.Empty == arg2Ran, "command arguments not passed in correctly."); } }
private bool ToggleDeviceSwitchLevel() { var deviceCurrentStatus = new Dictionary <string, AttributeState>(); if (this.smartThingsClient.TryGetDeviceCapabilityStatus(this.device.DeviceId, this.device.Components[0].Id, "switchLevel", out deviceCurrentStatus) && deviceCurrentStatus.Count > 0) { string currentLevel = deviceCurrentStatus["level"].Value.ToString(); var commandArgs = new List <object>() { { currentLevel == "0" ? 100 : 0 } }; var command = new DeviceCommand(capability: "switchLevel", command: "setLevel", arguments: commandArgs); var commandsRequest = new DeviceCommandsRequest() { Commands = new List <DeviceCommand>() }; commandsRequest.Commands.Add(command); this.smartThingsClient.ExecuteDevicecommand(this.device.DeviceId, commandsRequest); return(true); } else { return(false); } }
private void AddCommand(int deviceID, string name, ZvsContext context) { context.DeviceCommands.FirstOrDefaultAsync(d => d.Name == name && d.DeviceId == deviceID).ContinueWith( t => { if (motionCommand != null) { return; } motionCommand = context.DeviceCommands.Add(new DeviceCommand() { DeviceId = deviceID, Description = name, Name = name, UniqueIdentifier = Guid.NewGuid().ToString(), ArgumentType = DataType.STRING, Help = name, CustomData1 = "Value", CustomData2 = name, SortOrder = 0 }); context.TrySaveChangesAsync().ContinueWith(tt => { if (tt.Result.HasError) { ZvsEngine.log.Error(tt.Result.Message); } }).Wait(); }).Wait(); }
public ExecuteCommandCacheEntry(DeviceCommand deviceCommand) { if (deviceCommand != null) { Status = deviceCommand.Status; Timestamp = DateTime.Now; } }
public async Task ExecuteCommand(Guid id, DeviceCommand command) { var client = ServiceClient.CreateFromConnectionString(_connectionString); var json = JsonConvert.SerializeObject(command); var jsonBInary = Encoding.ASCII.GetBytes(json); var message = new Message(jsonBInary); await client.SendAsync(id.ToString(), message); }
protected override bool CanHandleDeviceCommand(DeviceCommand command) { try { SafeUri uri = new SafeUri(command.DeviceId); return(IpodDevice.MountPoint.StartsWith(uri.LocalPath)); } catch { return(false); } }
protected override void Dispose(bool disposing) { lock (_lockObj) { _tlAutoDeviceSerialPort.DataReceived -= TLAutoDeviceSerialPortDataReceived; _tlAutoDeviceSerialPort = null; _deviceCommand = null; } }
/// <summary> /// Parses the binary body image. /// </summary> /// <param name="buffer">Binary image to parse.</param> /// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param> /// <param name="length">Length of valid data within <paramref name="buffer"/>.</param> /// <returns>The length of the data that was parsed.</returns> protected override int ParseBodyImage(byte[] buffer, int startIndex, int length) { int parsedLength = 2; m_command = (DeviceCommand)BigEndian.ToInt16(buffer, startIndex); parsedLength += base.ParseBodyImage(buffer, startIndex + 2, length); return(parsedLength); }
private static string getDevicePropForUser(DeviceCommand deviceid) { string istrue = "0"; #if ANDROID_DEVICE Pvr_UnitySDKAPI.System.UPvr_CallStaticMethod <string>(ref istrue, Pvr_UnitySDKRender.javaVrActivityClass, "getDevicePropForUser", (int)deviceid); #endif return(istrue); }
private void Property_StatusChanged(object sender, DeviceCommand e) { if (!_updating) { _client.SendCommand(new List <DeviceCommand> { e }); } }
private static bool setDevicePropForUser(DeviceCommand deviceid, string number) { bool istrue = false; #if ANDROID_DEVICE Pvr_UnitySDKAPI.System.UPvr_CallStaticMethod <bool>(ref istrue, Pvr_UnitySDKRender.javaVrActivityClass, "setDevicePropForUser", (int)deviceid, number); #endif return(istrue); }
public void SetCommandInformation(DeviceCommand commandInformation) { this.commandInformation = commandInformation; this.btnAction.Content = commandInformation.ShortLabel; this.btnAction.ToolTip = commandInformation.Description; this.LoadVariables(); }
public override DeviceCommand GenerateJsonPayload() { DeviceCommand command = new DeviceCommand() { Type = CommandType.None }; return(command); }
protected override bool CanHandleDeviceCommand(DeviceCommand command) { try { SafeUri uri = new SafeUri(command.DeviceId); return(BaseDirectory.StartsWith(uri.LocalPath)); } catch { return(false); } }
public async Task RegisterAsyncRemovedCommandOptionsTest() { //arrange var dbConnection = new UnitTestDbConnection(); Database.SetInitializer(new CreateFreshDbInitializer()); var dvb = new DeviceCommandBuilder(dbConnection); var device = UnitTesting.CreateFakeDevice(); var deviceCommand = new DeviceCommand { Name = "Unit Testing Command", }; var option1 = new CommandOption { Name = "Option 1" }; var option2 = new CommandOption { Name = "Option 2" }; deviceCommand.Options.Add(option1); deviceCommand.Options.Add(option2); using (var context = new ZvsContext(dbConnection)) { device.Commands.Add(deviceCommand); context.Devices.Add(device); await context.SaveChangesAsync(); } deviceCommand.Options.Remove(option1); //act var result = await dvb.RegisterAsync(device.Id, deviceCommand, CancellationToken.None); Console.WriteLine(result.Message); List <DeviceCommand> deviceCommands; using (var context = new ZvsContext(dbConnection)) { deviceCommands = await context.DeviceCommands .Include(o => o.Options) .Include(o => o.Device) .Where(o => o.Id == deviceCommand.Id) .ToListAsync(); } //assert Assert.IsFalse(result.HasError, result.Message); Assert.IsTrue(deviceCommands.Count == 1, "Device has an unexpected number of commands"); Assert.IsTrue(deviceCommands[0].Options.Count == 1, "Option not removed as expected"); Assert.IsTrue(deviceCommands[0].Options[0].Name == option2.Name, "Option mismatch"); }
public ActionResult EditPV([Bind(Include = "ID,Title,Description,DeviceID,CommandCode")] DeviceCommand Command) { ResultInfo.Result res = ResultInfo.GetResultByID(1); if (ModelState.IsValid) { res = uof_repos.repoDeviceCommands.Edit(Command.ID, Command.Title, Command.Description, long.Parse(Command.DeviceID.ToString()), Command.CommandCode); return(Json(res)); } return(Json(res)); }
public ActionResult DeletePV([Bind(Include = "ID,Title,Description,DeviceID")] DeviceCommand Command) { ResultInfo.Result res = ResultInfo.GetResultByID(1); if (ModelState.IsValid) { res = uof_repos.repoDeviceCommands.Detele(Command.ID); return(Json(res)); } return(Json(res)); }
public ActionResult Details(long id) { if (ValidateUserPermissions(true, false) == false) { return(RedirectToAction("Login", "Account")); } DeviceCommand cmd = uof_repos.repoDeviceCommands.Find(id); return(View(cmd)); }
public ActionResult AddPV([Bind(Include = "Title,DeviceID,Description,CommandCode")] DeviceCommand command) { ResultInfo.Result res = ResultInfo.GetResultByID(1); if (ModelState.IsValid) { long cmd = long.Parse(command.DeviceID.ToString()); res = uof_repos.repoDeviceCommands.Add(command.Title, long.Parse(command.DeviceID.ToString()), command.Description, command.CommandCode, "1"); } return(Json(res)); }
public static DeviceCommand SetName(this DeviceCommand device, string name) { if (device == null) { throw new ArgumentNullException(nameof(device)); } device.Name = name; return(device); }
public static DeviceCommand SetLedMode(this DeviceCommand device, bool enable) { if (device == null) { throw new ArgumentNullException(nameof(device)); } device.LedMode = enable ? 1 : 0; return(device); }
/// <summary> /// Sets switch value according to input command /// </summary> /// <param name="cmd">Input command</param> /// <returns>True if successful; false - otherwise</returns> public override bool OnCommand(DeviceCommand cmd) { try { string val = cmd.parameters[StateParameter].ToString(); int NewState = int.Parse(val); SetValue(NewState, cmd); return true; } catch (Exception) { return false; } }
protected override bool DeviceCommandMatchesSource(DiscSource source, DeviceCommand command) { DvdSource dvdSource = source as DvdSource; if (dvdSource != null && command.DeviceId.StartsWith ("dvd:")) { try { Uri uri = new Uri (command.DeviceId); string match_device_node = String.Format ("{0}{1}", uri.Host, uri.AbsolutePath).TrimEnd ('/', '\\'); string device_node = source.DiscModel.Volume.DeviceNode; return device_node.EndsWith (match_device_node); } catch { } } return false; }
//public void Command(Command<byte[]> command) //{ // if ((_setupHandle == null) || (_controlHandle == null)) // throw new ApplicationException("Unable to find a USB Missile Launcher device."); // WriteBytes(_setupHandle, SetupMessage1); // WriteBytes(_setupHandle, SetupMessage2); // byte[] bytes = new byte[65]; // command.Execute(); // WriteBytes(_controlHandle, bytes); //} public void Execute(DeviceCommand command) { if ((_setupHandle == null) || (_controlHandle == null)) throw new ApplicationException("Unable to find a USB Missile Launcher device."); WriteBytes(_setupHandle, SetupMessage1); WriteBytes(_setupHandle, SetupMessage2); byte[] bytes = new byte[65]; switch (command) { case DeviceCommand.Left: bytes[2] = 1; break; case DeviceCommand.Right: bytes[3] = 1; break; case DeviceCommand.Up: bytes[4] = 1; break; case DeviceCommand.Down: bytes[5] = 1; break; case DeviceCommand.Fire: bytes[6] = 1; break; } bytes[7] = 8; bytes[8] = 8; WriteBytes(_controlHandle, bytes); }
/// <summary> /// Sends the specified <see cref="DeviceCommand"/> to the current device connection. /// </summary> /// <param name="command"><see cref="DeviceCommand"/> to send to connected device.</param> public void SendCommand(DeviceCommand command) { if ((object)m_frameParser != null) { m_frameParser.SendDeviceCommand(command); OnStatusMessage("Sent device command \"{0}\"...", command); } else { OnStatusMessage("Failed to send device command \"{0}\", no frame parser is defined.", command); } }
public void SendCommand(DeviceCommand command) { if (m_frameParser != null) { m_frameParser.SendDeviceCommand(command); OnStatusMessage("Sent device command \"{0}\"...", command); } else { if (m_isVirtual) OnStatusMessage("Cannot send command to virtual device."); else OnStatusMessage("Failed to send device command \"{0}\", no frame parser is defined."); } }
public void addCommand(int device, DeviceCommand command, String data) { SqlConnection con = new SqlConnection(conStr); con.Open(); String qry = String.Empty; qry = @"insert into command(line_id, command , command_data, status,request_timestamp) values({0},{1},'{2}',{3},'{4}')"; qry = String.Format(qry, device, (int)command, data, 1, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); SqlCommand cmd = new SqlCommand(qry, con); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); con.Dispose(); }
public DeviceCommandEventArgs([NotNull] WirelessNetworkAddress source, DeviceCommand command) : base(source) { Command = command; }
private bool DeviceCommandMatchesSource (AudioCdSource source, DeviceCommand command) { if (command.DeviceId.StartsWith ("cdda:")) { try { Uri uri = new Uri (command.DeviceId); string match_device_node = String.Format ("{0}{1}", uri.Host, uri.AbsolutePath).TrimEnd ('/', '\\'); string device_node = source.DiscModel.Volume.DeviceNode; return device_node.EndsWith (match_device_node); } catch { } } return false; }
protected override bool CanHandleDeviceCommand (DeviceCommand command) { // Whats this for? return false; // try { // SafeUri uri = new SafeUri (command.DeviceId); // return IpodDevice.MountPoint.StartsWith (uri.LocalPath); // } catch { // return false; // } }
public void CheckCall(Action<IMissileLauncher> action, DeviceCommand cmd) { action(testLauncher); fakeDevice.AssertWasCalled(d=>d.Command(cmd)); }
/// <summary> /// Performs a device command /// </summary> /// <param name="cmd">Input command</param> /// <returns>False</returns> /// <remarks>This equipment does not support commands. It returns False regardless of input. /// </remarks> public override bool OnCommand(DeviceCommand cmd) { //float f = Sensor.GetTemperature(); //return SendNotification(f); return false; }
protected abstract bool DeviceCommandMatchesSource(DiscSource source, DeviceCommand command);
protected virtual void OnDeviceCommand(object o, DeviceCommand command) { lock (this) { // Check to see if we have an already mapped disc volume that should // handle this incoming command; if not, queue it for later discs foreach (var source in Sources.Values) { if (DeviceCommandMatchesSource (source, command)) { HandleDeviceCommand (source, command.Action); return; } } if (unhandled_device_commands == null) { unhandled_device_commands = new List<DeviceCommand> (); } unhandled_device_commands.Add (command); } }
protected internal virtual bool CanHandleDeviceCommand(DeviceCommand command) { return false; }
/// <summary> /// Creates a new <see cref="CommandFrame"/> from specified parameters. /// </summary> /// <param name="idCode">The ID code of this <see cref="CommandFrame"/>.</param> /// <param name="command">The <see cref="DeviceCommand"/> for this <see cref="CommandFrame"/>.</param> /// <param name="version">IEC 61850-90-5 revision number.</param> /// <remarks> /// This constructor is used by a consumer to generate an IEC 61850-90-5 command frame. /// </remarks> public CommandFrame(ushort idCode, DeviceCommand command, byte version) : base(new CommandCellCollection(Common.MaximumExtendedDataLength), command) { base.IDCode = idCode; base.Timestamp = DateTime.UtcNow.Ticks; this.Version = version; }
/// <summary> /// Handles incoming device command, override to implement custom logic. /// Default implementation uses reflection to execute action method with matching <see cref="DeviceCommandAttribute"/> attribute. /// </summary> /// <param name="command"><see cref="DeviceCommand"/> object to handle.</param> /// <param name="token">Thread cancellation token.</param> /// <returns><see cref="DeviceCommandResult"/> object with command execution result.</returns> public virtual DeviceCommandResult HandleCommand(DeviceCommand command, CancellationToken token) { MethodInfo method; if (_deviceCommands.TryGetValue(command.Name, out method)) { var commandType = method.GetParameters()[0].ParameterType; var parameters = commandType == typeof(DeviceCommand) ? command : (command.Parameters == null ? Activator.CreateInstance(commandType) : command.Parameters.ToObject(commandType, JsonSerializer)); return (DeviceCommandResult)method.Invoke(this, new object[] { parameters, token }); } return OnHandleUnknownCommand(command, token); }
public CommandItem(DeviceCommand command) { m_command = command; }
/// <summary> /// Handles incoming device command, override to implement custom logic. /// Default implementation uses reflection to execute action method with matching <see cref="DeviceCommandAttribute"/> attribute. /// </summary> /// <param name="command"><see cref="DeviceCommand"/> object to handle.</param> /// <param name="token">Thread cancellation token.</param> /// <returns><see cref="DeviceCommandResult"/> object with command execution result.</returns> public virtual DeviceCommandResult HandleCommand(DeviceCommand command, CancellationToken token) { MethodInfo method; if (_deviceCommands.TryGetValue(command.Name, out method)) { var commandType = method.GetParameters()[0].ParameterType; var translatedCommand = (DeviceCommand)Activator.CreateInstance(commandType, command.Name, command.Parameters); return (DeviceCommandResult)method.Invoke(this, new object[] { translatedCommand, token }); } return OnHandleUnknownCommand(command, token); }
/// <summary> /// Creates a new instance of DeviceCommandEventArgs of the /// given type with the given parameters. /// </summary> /// <param name="deviceCommand"></param> /// <param name="parameters"></param> public DeviceCommandEventArgs(DeviceCommand deviceCommand, params object[] parameters) { this.DeviceCommand = deviceCommand; this.Parameters = parameters; }
/// <summary> /// Sends the specified <see cref="DeviceCommand"/> to the remote device. /// </summary> /// <param name="command"><see cref="DeviceCommand"/> to send to the remote device.</param> /// <remarks> /// Command will only be sent if <see cref="DeviceSupportsCommands"/> is <c>true</c> and <see cref="MultiProtocolFrameParser"/>. /// </remarks> /// <returns>A <see cref="WaitHandle"/>.</returns> public WaitHandle SendDeviceCommand(DeviceCommand command) { WaitHandle handle = null; try { if (m_deviceSupportsCommands && ((object)m_dataChannel != null || (object)m_serverBasedDataChannel != null || (object)m_commandChannel != null)) { ICommandFrame commandFrame; // Only the IEEE, SEL Fast Message and Macrodyne protocols support commands switch (m_phasorProtocol) { case PhasorProtocol.IEEEC37_118V2: case PhasorProtocol.IEEEC37_118V1: case PhasorProtocol.IEEEC37_118D6: commandFrame = new IEEEC37_118.CommandFrame(m_deviceID, command, 1); break; case PhasorProtocol.IEEE1344: commandFrame = new IEEE1344.CommandFrame(m_deviceID, command); break; case PhasorProtocol.IEC61850_90_5: commandFrame = new IEC61850_90_5.CommandFrame(m_deviceID, command, 1); break; case PhasorProtocol.SelFastMessage: // Get defined message period MessagePeriod messagePeriod = MessagePeriod.DefaultRate; SelFastMessage.ConnectionParameters connectionParameters = m_connectionParameters as SelFastMessage.ConnectionParameters; if ((object)connectionParameters != null) messagePeriod = connectionParameters.MessagePeriod; commandFrame = new SelFastMessage.CommandFrame(command, messagePeriod); break; case PhasorProtocol.Macrodyne: commandFrame = new Macrodyne.CommandFrame(command); break; default: commandFrame = null; break; } if ((object)commandFrame != null) { byte[] buffer = commandFrame.BinaryImage(); // Send command over appropriate communications channel - command channel, if defined, // will take precedence over other communications channels for command traffic... if ((object)m_commandChannel != null && m_commandChannel.CurrentState == ClientState.Connected) { handle = m_commandChannel.SendAsync(buffer, 0, buffer.Length); } else if ((object)m_dataChannel != null && m_dataChannel.CurrentState == ClientState.Connected) { handle = m_dataChannel.SendAsync(buffer, 0, buffer.Length); } else if ((object)m_serverBasedDataChannel != null && m_serverBasedDataChannel.CurrentState == ServerState.Running) { WaitHandle[] handles = m_serverBasedDataChannel.MulticastAsync(buffer, 0, buffer.Length); if ((object)handles != null && handles.Length > 0) handle = handles[0]; } if ((object)SentCommandFrame != null) SentCommandFrame(this, new EventArgs<ICommandFrame>(commandFrame)); } } } catch (Exception ex) { OnParsingException(ex, "Failed to send device command \"{0}\": {1}", command, ex.Message); } return handle; }
protected override bool CanHandleDeviceCommand (DeviceCommand command) { try { SafeUri uri = new SafeUri (command.DeviceId); return BaseDirectory.StartsWith (uri.LocalPath); } catch { return false; } }
public void SendCommand(DeviceCommand command) { if ((object)m_frameParser != null) { if ((object)m_frameParser.SendDeviceCommand(command) != null) OnStatusMessage(MessageLevel.Info, $"Sent device command \"{command}\"...", "Command"); } else { OnStatusMessage(MessageLevel.Info, $"Failed to send device command \"{command}\", no frame parser is defined.", "Command"); } }
/// <summary> /// Creates a new <see cref="CommandFrame"/> from specified parameters. /// </summary> /// <param name="idCode">The ID code of this <see cref="CommandFrame"/>.</param> /// <param name="command">The <see cref="DeviceCommand"/> for this <see cref="CommandFrame"/>.</param> /// <remarks> /// This constructor is used by a consumer to generate an IEEE 1344 command frame. /// </remarks> public CommandFrame(ulong idCode, DeviceCommand command) : base(new CommandCellCollection(0), command) { m_idCode = idCode; Timestamp = DateTime.UtcNow.Ticks; }
/// <summary> /// Handles unknown device command, override to implement custom logic. /// Default implementation returns <see cref="DeviceCommandResult"/> object with "Failed" result. /// </summary> /// <param name="command"><see cref="DeviceCommand"/> object to handle.</param> /// <param name="token">Thread cancellation token.</param> /// <returns><see cref="DeviceCommandResult"/> object</returns> protected virtual DeviceCommandResult OnHandleUnknownCommand(DeviceCommand command, CancellationToken token) { return new DeviceCommandResult("Failed", "There is no handler for this command"); }
private void processCommand(int lineId, DeviceCommand cmd, String cmdData) { String msg = String.Empty; String[] cmdParams = new String[5]; try { switch (cmd) { case DeviceCommand.SET_PLANNED_QUANTITY: updateMsg("Processing Command - "+ DeviceCommand.SET_PLANNED_QUANTITY); cmdParams = separateCommandData(cmdData); int shift = Convert.ToInt32(cmdParams[0]); int session = Convert.ToInt32(cmdParams[1]); int plannedQty = int.Parse(cmdParams[2]); if( lines.getLineName(lineId) == String.Empty) { updateMsg("Line not supported"); return; } Shift s = shifts.getShift(shift); if ( s == null) { updateMsg( "Shift not supported"); return; } Session se = s.Sessions.getSession(session); if( se == null) { updateMsg("Session not supported"); return; } msg = "Setting Target Qty for Line : {0},Shift : {1} Session:{2} Qty:{3}"; msg = String.Format(msg, lines.getLineName(lineId), s.Name,se.Name, plannedQty); updateMsg(msg); dataAccess.updateTargetQuantity(lineId, shift,session ,plannedQty); break; case DeviceCommand.ISSUE: StringReader reader = new StringReader(cmdData); AndonAlertEventArgs eventArgs = (AndonAlertEventArgs)xmlSerializer.Deserialize(reader); andonManager_andonAlertEvent(this, eventArgs); break; default: break; } } catch (SqlException se) { } }
private void DispatchCommandTask(DeviceBase device, Command cCommand) { // invoke device DeviceCommandResult result; try { var command = new DeviceCommand(cCommand.Name.Trim(), cCommand.Parameters == null ? null : cCommand.Parameters.DeepClone(), cCommand.UserId); result = device.HandleCommand(command, _cancellationSource.Token); } catch (OperationCanceledException) { return; } catch (Exception ex) { // operation faulted - log the error and send failed result Logger.Error(string.Format("Exception while handling a command '{0}' by device {1} ({2})", cCommand.Name, device.ID, device.Name), ex); result = new DeviceCommandResult("Failed", "An error occurred while handling the command"); } // send command result cCommand.Status = result.Status; cCommand.Result = result.Result == null ? null : JToken.FromObject(result.Result, device.JsonSerializer); SendCommandResult(device, cCommand); }
private void OnDeviceCommand (object o, DeviceCommand command) { lock (this) { // Check to see if we have an already mapped disc volume that should // handle this incoming command; if not, queue it for later devices foreach (DapSource source in sources.Values) { if (source.CanHandleDeviceCommand (command)) { HandleDeviceCommand (source, command.Action); return; } } if (unhandled_device_commands == null) { unhandled_device_commands = new List<DeviceCommand> (); } unhandled_device_commands.Add (command); } }
public void HandleCommand(DeviceCommand command) { Log.Debug($"Entering HandleCommand for {command}."); switch (command) { case DeviceCommand.Ready: HandleReady(); break; case DeviceCommand.DecreaseRefusals: HandleChangeRefusals(false); break; case DeviceCommand.IncreaseRefusals: HandleChangeRefusals(true); break; case DeviceCommand.DecreaseFaults: HandleChangeFaults(false); break; case DeviceCommand.IncreaseFaults: HandleChangeFaults(true); break; case DeviceCommand.ToggleElimination: HandleToggleElimination(); break; case DeviceCommand.ResetRun: HandleResetRun(); break; case DeviceCommand.PlaySoundA: HandlePlaySoundA(); break; case DeviceCommand.MuteSound: HandleMuteSound(); break; default: throw ExceptionFactory.CreateNotSupportedExceptionFor(command); } }
/// <summary> /// Sets switch value /// </summary> /// <param name="i">New value</param> /// <param name="cmd">Input command</param> private void SetValue(int i, DeviceCommand cmd) { Led.Write(i != 0); SendNotification(i); if (Changed != null) { Changed(this, new CommandEventArgs(cmd)); } }
protected override bool CanHandleDeviceCommand (DeviceCommand command) { try { SafeUri uri = new SafeUri (command.DeviceId); return IpodDevice.MountPoint.StartsWith (uri.LocalPath); } catch { return false; } }