Example #1
0
 public async void SetAnswer(DeviceCommands obj, string childPath)
 {
     var firebase = new FirebaseClient(Maps.LunaUrl);
     await firebase
     .Child(childPath)
     .PutAsync(obj);
 }
Example #2
0
        //private static string bright = "10001000";
        //private static string dim = "10011000";

        public static string GetMessage(int deviceNumber, DeviceCommands command)
        {
            if (deviceNumber < 1 || deviceNumber > 8)
            {
                throw new ArgumentException("Invalid Device Requested");
            }

            string message = header + codeA;

            switch (command)
            {
            case DeviceCommands.On:
                message += onCommands[deviceNumber];
                break;

            case DeviceCommands.Off:
                message += offCommands[deviceNumber];
                break;

            default:
                throw new ArgumentException("Invalid Command Requested");
            }

            message += footer;
            return(message);
        }
Example #3
0
        public Device(PhysicalDevice physicalDevice, DeviceCreateInfo info)
        {
            if (physicalDevice == null)
            {
                throw new ArgumentNullException(nameof(physicalDevice));
            }
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            PhysicalDevice = physicalDevice;
            Instance       = physicalDevice.Instance;
            queues         = new Dictionary <QueueID, Queue>();

            if (info.extensions == null)
            {
                Extensions = new List <string>();
            }
            else
            {
                Extensions = new List <string>(info.extensions);
            }

            ValidateExtensions();

            CreateDevice(info);

            Vulkan.Load(ref getDeviceProcAddr, Instance);
            Commands = new DeviceCommands(this);
        }
Example #4
0
        public byte ExecuteCommand(DeviceCommands deviceCommand)
        {
            return(ExceptionExtensions.ExecuteFunction(_logger, () =>
            {
                CanExecuteCommand(deviceCommand);

                byte[] sendBuffer = new byte[1],
                receiveBuffer = new byte[1];
                sendBuffer[0] = (byte)deviceCommand;
                if (_logger.IsTraceEnabled)
                {
                    _logger.TraceFormat("ExecuteCommand {0} BufferData: {1}", deviceCommand,
                                        sendBuffer.Aggregate("", (current, part) => current + part.ToString("X").PadLeft(2, '0')));
                }
                lock (SyncRoot)
                {
                    _spiDevice.TransferFullDuplex(sendBuffer, receiveBuffer);
                }
                if (_logger.IsTraceEnabled)
                {
                    _logger.TraceFormat("ExecuteCommand result Status Register: {0}", receiveBuffer[0]);
                }
                return receiveBuffer[0];
            }));
        }
Example #5
0
        public void SendCommand(int device, DeviceCommands command)
        {
            var message = MessageGenerator.GetMessage(device, command);

            Commander.SendCommand(message);
            Console.WriteLine("{0} - Device: {1}, Command: {2}",
                              DateTime.Now.ToString("G"), device.ToString(), command.ToString());
        }
Example #6
0
    void Start()
    {
        Command lockCommand = new Command("Lock");

        lockCommand.OnProcessCommand += Lock;
        Command unlockCommand = new Command("Unlock");

        unlockCommand.OnProcessCommand += Unlock;

        DeviceCommands.Add(lockCommand);
        DeviceCommands.Add(unlockCommand);
    }
Example #7
0
 public void NewCommand(DeviceCommands obj, string path)
 {
     if (obj.Answer == "0")
     {
         //its a new command
         if (AliasBox.InvokeRequired)
         {
             AliasBox.Invoke(new MethodInvoker(delegate { AliasBox.Text += "Command: " + obj.CommandText + " FROM: " + obj.From; }));
         }
         obj.Answer = commands.ExecuteCommand(obj.CommandName);
         SetAnswer(obj, path);
     }
 }
Example #8
0
 private void CanExecuteCommand(DeviceCommands deviceCommand)
 {
     ExceptionExtensions.ExecuteFunction(_logger, () =>
     {
         OperatingModes?operatingMode = GetOperatingMode?.Invoke();
         if (CheckOperatingMode && operatingMode.HasValue &&
             (deviceCommand == DeviceCommands.W_REGISTER &&
              !(operatingMode == OperatingModes.StandBy || operatingMode == OperatingModes.PowerDown)))
         {
             throw new InvalidOperationException(
                 "Writing to registers should only happen in Standby or PowerDown mode");
         }
     });
 }
Example #9
0
    void Start()
    {
        animator = GetComponent <Animator>();
        OnPowerConnectionLost();

        if (powerGrid)
        {
            powerGrid.ConnectRecieverToGrid(this);
        }

        Command unlock = new Command("Unlock");

        unlock.OnProcessCommand += UnlockDoor;
        DeviceCommands.Add(unlock);
    }
Example #10
0
        public DeviceAdapter(IDevice device)
        {
            _device = device.ThrowIfNull(nameof(device));
            _device.ConnectionError += Device_ConnectionError;

            _commands = new DeviceCommands(this);

            Calibration = (device as ICalibrate) ?? NullDeviceCalibration.Instance;

            Configurator = CreateConfigurator(device);

            Observables = DeviceObservables.CreateForDevice(this, _device);

            _states = CreateStateMachine();
        }
        public byte[] ExecuteCommand(DeviceCommands deviceCommand, byte address, byte[] value, bool autoRevert = true)
        {
            return ExceptionExtensions.ExecuteFunction(_logger, () =>
            {
                CanExecuteCommand(deviceCommand);

                // Create send and receive buffers
                int resultLength = value.Length,
                    bufferLength = resultLength + 1;
                byte[] result = new byte[resultLength];
                byte[] sendBuffer = new byte[bufferLength],
                    receiveBuffer = new byte[bufferLength];

                // Populate send buffer with command and value to write
                sendBuffer[0] = (byte) ((byte) deviceCommand | address);
                if (value.Length > 1 && autoRevert && _revertBytes)
                    for (int i = 0; i < resultLength; i++)
                        sendBuffer[resultLength - i] = value[i];
                else
                    Array.Copy(value, 0, sendBuffer, 1, resultLength);

                // Send and Receive
                if (_logger.IsTraceEnabled) _logger.TraceFormat("ExecuteCommand: {0} Address: {1} Value: {2} BufferData: {3}", deviceCommand,
                    address,
                    value.Aggregate("", (current, part) => current + part.ToString("X").PadLeft(2, '0')),
                    sendBuffer.Aggregate("", (current, part) => current + part.ToString("X").PadLeft(2, '0')));
                lock (SyncRoot)
                {
                    _spiDevice.TransferFullDuplex(sendBuffer, receiveBuffer);
                }
                Task.Delay(1).Wait();
                if (_logger.IsTraceEnabled) _logger.TraceFormat("ExecuteCommand result Status Register: {0}", receiveBuffer[0]);

                // The STATUS register value is returned at first byte on each SPI call
                LoadStatusRegister?.Invoke(new[] {receiveBuffer[0]});

                // Populate result with the rest of the receive buffer
                if (value.Length > 1 && autoRevert && _revertBytes)
                    for (int i = 0; i < result.Length; i++)
                        result[i] = receiveBuffer[bufferLength - (i + 1)];
                else
                    Array.Copy(receiveBuffer, 1, result, 0, bufferLength - 1);

                return result;
            });
        }
Example #12
0
        public void ScheduleOneTimeItem(DateTime time, int device,
                                        DeviceCommands command)
        {
            var scheduleItem = new ScheduleItem()
            {
                Device  = device,
                Command = command,
                Info    = new ScheduleInfo()
                {
                    EventTime = time,
                    Type      = ScheduleType.Once,
                },
                IsEnabled   = true,
                ScheduleSet = "",
            };

            schedule.Add(scheduleItem);
        }
 public byte ExecuteCommand(DeviceCommands deviceCommand)
 {
     return ExecuteCommandReturns[0];
 }
 public byte ExecuteCommand(DeviceCommands deviceCommand, byte address)
 {
     return(ExecuteCommandReturns[0]);
 }
        private byte[] SendCommand(byte nOfParameters, DeviceID deviceId, DeviceCommands command, byte[] par)
        {
            switch (deviceId)
            {
                case DeviceID.DecAltMotor:
                case DeviceID.RaAzmMotor:
                    return this.MotorCommands(nOfParameters, command, par);
                case DeviceID.HC:

                default:
                    return "#".ToBytes();
            }
        }
 private byte[] MotorCommands(byte nOfParameters, DeviceCommands command, byte[] par)
 {
     switch (command)
     {
         case DeviceCommands.GET_VER:
             return "12#".ToBytes();
         case DeviceCommands.MC_GET_POSITION:
             return new byte[] { 0, 1, 2, 4, (byte)(char)GeneralCommands.TERMINATOR };
         case DeviceCommands.MC_GOTO_FAST:
         case DeviceCommands.MC_GOTO_SLOW:
             return "#".ToBytes();
         case DeviceCommands.MC_SET_POS_FIXED_GUIDERATE:
         case DeviceCommands.MC_SET_NEG_FIXED_GUIDERATE:
             return "#".ToBytes();
         case DeviceCommands.MC_SET_POS_VARIABLE_GUIDERATE:
         case DeviceCommands.MC_SET_NEG_VARIABLE_GUIDERATE:
             return "#".ToBytes();
         case DeviceCommands.MC_SET_POSITION:
             return "#".ToBytes();
         case DeviceCommands.MC_SET_AUTOGUIDE_RATE:
             return "#".ToBytes();
         case DeviceCommands.MC_GET_AUTOGUIDE_RATE:
             return new byte[] { 0x0, 0x1, 0x2, 0x3, (byte)(char)GeneralCommands.TERMINATOR };
         case DeviceCommands.MC_SLEW_DONE:
             return new byte[] { 0xff, (byte)(char)GeneralCommands.TERMINATOR };
         default:
             return "#".ToBytes();
     }
 }
 public byte[] ExecuteCommand(DeviceCommands deviceCommand, byte address, byte[] value, bool autoRevert = true)
 {
     return(ExecuteCommandReturns);
 }
Example #18
0
        public override async Task <int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            //Limit Log Table Size
            const int maxLogSize         = 2000;
            var       addedLogEntryCount = ChangeTracker.Entries <LogEntry>().Count(p => p.State == EntityState.Added);

            if (addedLogEntryCount > 0)
            {
                if (addedLogEntryCount > maxLogSize)
                {
                    var numberToRemove = addedLogEntryCount - maxLogSize;
                    var doNotAdd       = ChangeTracker.Entries <LogEntry>()
                                         .Where(p => p.State == EntityState.Added)
                                         .OrderBy(o => o.Entity.Datetime).Take(numberToRemove);

                    foreach (var entry in doNotAdd)
                    {
                        entry.State = EntityState.Detached;
                    }
                }

                var currentLogEntryCount = await LogEntries.CountAsync(cancellationToken);

                var toRemove = (currentLogEntryCount + addedLogEntryCount) - maxLogSize;
                if (toRemove > 0)
                {
                    var toBeRemoved =
                        await LogEntries.OrderBy(o => o.Datetime).Take(toRemove).ToListAsync(cancellationToken);

                    LogEntries.RemoveRange(toBeRemoved);
                }
            }

            //Update Run Scene Command Scene Name upon Scene Name update
            var sceneIdsOfUpdatedNames = ChangeTracker.Entries <Scene>().Where(p => p.State == EntityState.Modified && p.Property("Name").IsModified).Select(o => o.Entity.Id.ToString(CultureInfo.InvariantCulture)).ToList();
            Expression <Func <IStoredCommand, bool> > sceneCmdPredicate = o => o.Command.UniqueIdentifier == "RUN_SCENE" && sceneIdsOfUpdatedNames.Contains(o.Argument);

            foreach (var cmd in await SceneStoredCommands.Where(sceneCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await DeviceValueTriggers.Where(sceneCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await ScheduledTasks.Where(sceneCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            //Update Activate Group Command Scene Name upon Group Name update
            var groupIdsOfUpdatedNames = ChangeTracker.Entries <Group>().Where(p => p.State == EntityState.Modified && p.Property("Name").IsModified).Select(o => o.Entity.Id.ToString(CultureInfo.InvariantCulture)).ToList();
            Expression <Func <IStoredCommand, bool> > groupPredicate = o => (o.Command.UniqueIdentifier == "GROUP_ON" || o.Command.UniqueIdentifier == "GROUP_OFF") && groupIdsOfUpdatedNames.Contains(o.Argument);

            foreach (var cmd in await SceneStoredCommands.Where(groupPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await DeviceValueTriggers.Where(groupPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await ScheduledTasks.Where(groupPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            //Update cmd descriptions on JavaScriptCommand name changes
            var javescriptIdsOfUpdatedNameIds = ChangeTracker.Entries <JavaScriptCommand>().Where(p => p.State == EntityState.Modified && p.Property("Name").IsModified).Select(o => o.Entity.Id).ToList();
            Expression <Func <IStoredCommand, bool> > jsCmdPredicate = o => o.Command is JavaScriptCommand && javescriptIdsOfUpdatedNameIds.Contains(o.Command.Id);

            foreach (var cmd in await SceneStoredCommands.Where(jsCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await DeviceValueTriggers.Where(jsCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await ScheduledTasks.Where(jsCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            //Update trigger descriptions on device value name changes
            var deviceValueIdsOfUpdatedNames = ChangeTracker.Entries <DeviceValue>().Where(p => p.State == EntityState.Modified && p.Property("Name").IsModified).Select(o => o.Entity.Id).ToList();
            var triggers = await DeviceValueTriggers.Include(o => o.DeviceValue).Include(o => o.DeviceValue.Device).Where(o => deviceValueIdsOfUpdatedNames.Contains(o.DeviceValue.Id)).ToListAsync(cancellationToken);

            foreach (var trigger in triggers)
            {
                trigger.SetDescription();
            }

            //Update commands on device name changes
            var deviceIdsOfUpdatedNames    = ChangeTracker.Entries <Device>().Where(p => p.State == EntityState.Modified && (p.Property("Name").IsModified || p.Property("Location").IsModified)).Select(o => o.Entity.Id).ToList();
            var deviceIdsStrOfUpdatedNames = deviceIdsOfUpdatedNames.Select(o => o.ToString());
            var deviceTriggers             = await DeviceValueTriggers.Include(o => o.DeviceValue).Include(o => o.DeviceValue.Device).Where(o => deviceIdsOfUpdatedNames.Contains(o.DeviceValue.DeviceId)).ToListAsync(cancellationToken);

            foreach (var trigger in deviceTriggers)
            {
                trigger.SetDescription();
            }

            //Update repoll commands
            Expression <Func <IStoredCommand, bool> > repollCmdPredicate = o => o.Command.UniqueIdentifier == "REPOLL_ME" && deviceIdsStrOfUpdatedNames.Contains(o.Argument);

            foreach (var cmd in await SceneStoredCommands.Where(repollCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await DeviceValueTriggers.Where(repollCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await ScheduledTasks.Where(repollCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            Expression <Func <IStoredCommand, bool> > deviceTypeCmdPredicate = o => o.Command is DeviceTypeCommand && deviceIdsStrOfUpdatedNames.Contains(o.Argument2);

            foreach (var cmd in await SceneStoredCommands.Where(deviceTypeCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await DeviceValueTriggers.Where(deviceTypeCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await ScheduledTasks.Where(deviceTypeCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            var deviceCommandIds = await DeviceCommands.Where(o => deviceIdsOfUpdatedNames.Contains(o.DeviceId)).Select(o => o.Id).ToListAsync(cancellationToken);

            Expression <Func <IStoredCommand, bool> > deviceCmdPredicate = o => o.Command is DeviceCommand && deviceCommandIds.Contains(o.Command.Id);

            foreach (var cmd in await SceneStoredCommands.Where(deviceCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await DeviceValueTriggers.Where(deviceCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            foreach (var cmd in await ScheduledTasks.Where(deviceCmdPredicate).ToListAsync(cancellationToken))
            {
                await cmd.SetTargetObjectNameAsync(this);
            }

            //Automatically store history when a device value is changed.
            var history =
                ChangeTracker.Entries <DeviceValue>()
                .Where(p => p.State == EntityState.Modified && p.Property("Value").IsModified)
                .Select(
                    o => new DeviceValueHistory
            {
                DeviceValueId = o.Entity.Id,
                Value         = o.Entity.Value
            }).ToList();

            DeviceValueHistories.AddRange(history);
            return(await base.SaveChangesAsync(cancellationToken));
        }
Example #19
0
        public byte[] ExecuteCommand(DeviceCommands deviceCommand, byte address, byte[] value, bool autoRevert = true)
        {
            return(ExceptionExtensions.ExecuteFunction(_logger, () =>
            {
                CanExecuteCommand(deviceCommand);

                // Create send and receive buffers
                int resultLength = value.Length,
                bufferLength = resultLength + 1;
                byte[] result = new byte[resultLength];
                byte[] sendBuffer = new byte[bufferLength],
                receiveBuffer = new byte[bufferLength];

                // Populate send buffer with command and value to write
                sendBuffer[0] = (byte)((byte)deviceCommand | address);
                if (value.Length > 1 && autoRevert && _revertBytes)
                {
                    for (int i = 0; i < resultLength; i++)
                    {
                        sendBuffer[resultLength - i] = value[i];
                    }
                }
                else
                {
                    Array.Copy(value, 0, sendBuffer, 1, resultLength);
                }

                // Send and Receive
                if (_logger.IsTraceEnabled)
                {
                    _logger.TraceFormat("ExecuteCommand: {0} Address: {1} Value: {2} BufferData: {3}", deviceCommand,
                                        address,
                                        value.Aggregate("", (current, part) => current + part.ToString("X").PadLeft(2, '0')),
                                        sendBuffer.Aggregate("", (current, part) => current + part.ToString("X").PadLeft(2, '0')));
                }
                lock (SyncRoot)
                {
                    _spiDevice.TransferFullDuplex(sendBuffer, receiveBuffer);
                }
                Task.Delay(1).Wait();
                if (_logger.IsTraceEnabled)
                {
                    _logger.TraceFormat("ExecuteCommand result Status Register: {0}", receiveBuffer[0]);
                }

                // The STATUS register value is returned at first byte on each SPI call
                LoadStatusRegister?.Invoke(new[] { receiveBuffer[0] });

                // Populate result with the rest of the receive buffer
                if (value.Length > 1 && autoRevert && _revertBytes)
                {
                    for (int i = 0; i < result.Length; i++)
                    {
                        result[i] = receiveBuffer[bufferLength - (i + 1)];
                    }
                }
                else
                {
                    Array.Copy(receiveBuffer, 1, result, 0, bufferLength - 1);
                }

                return result;
            }));
        }
 public byte ExecuteCommand(DeviceCommands deviceCommand)
 {
     return(ExecuteCommandReturns[0]);
 }
 public byte ExecuteCommand(DeviceCommands deviceCommand, byte address)
 {
     return ExecuteCommandReturns[0];
 }
 private void CanExecuteCommand(DeviceCommands deviceCommand)
 {
     ExceptionExtensions.ExecuteFunction(_logger, () =>
     {
         OperatingModes? operatingMode = GetOperatingMode?.Invoke();
         if (CheckOperatingMode && operatingMode.HasValue &&
             (deviceCommand == DeviceCommands.W_REGISTER &&
              !(operatingMode == OperatingModes.StandBy || operatingMode == OperatingModes.PowerDown)))
             throw new InvalidOperationException(
                 "Writing to registers should only happen in Standby or PowerDown mode");
     });
 }
        public byte ExecuteCommand(DeviceCommands deviceCommand, byte address)
        {
            return ExceptionExtensions.ExecuteFunction(_logger, () =>
            {
                CanExecuteCommand(deviceCommand);

                byte[] sendBuffer = new byte[1],
                    receiveBuffer = new byte[1];
                sendBuffer[0] = (byte) ((byte) deviceCommand | address);
                if (_logger.IsTraceEnabled) _logger.TraceFormat("ExecuteCommand: {0} Address: {1} BufferData: {2}", deviceCommand, address,
                    sendBuffer.Aggregate("", (current, part) => current + part.ToString("X").PadLeft(2, '0')));
                lock (SyncRoot)
                {
                    _spiDevice.TransferFullDuplex(sendBuffer, receiveBuffer);
                }
                if (_logger.IsTraceEnabled) _logger.TraceFormat("ExecuteCommand result Status Register: {0}", receiveBuffer[0]);
                return receiveBuffer[0];
            });
        }
 public byte[] ExecuteCommand(DeviceCommands deviceCommand, byte address, byte[] value, bool autoRevert = true)
 {
     return ExecuteCommandReturns;
 }
 public DeviceCommandAttribute(DeviceCommands cmd)
 {
     command = cmd;
 }