示例#1
0
        public LampService(ServiceCreationInfo info)
            : base(info)
        {
            uint port = uint.Parse(info.Configuration["port"]);

            mSerialHelper = SerialRepository.OpenPort("arduino", port, 115200);
        }
示例#2
0
        private void CreateServices(List <dynamic> configs)
        {
            foreach (var serviceConfig in configs)
            {
                ServiceBase service;
                try
                {
                    ServiceCreationInfo info = new ServiceCreationInfo(serviceConfig, mServiceManager, mDeviceManager);

                    service = ServiceFactory.CreateService(info);
                    mServiceManager.AddService(service);
                }
                catch (Exception e)
                {
                    Log.Error("Failed creating service for node: " + serviceConfig.Name);
                    if (e.InnerException != null)
                    {
                        Log.Error("Inner Exception: {0}\nCallstack:\n{1}", e.InnerException.Message, e.InnerException.StackTrace);
                    }
                    else
                    {
                        Log.Error("Exception: {0}\nCallstack:\n{1}", e.Message, e.StackTrace);
                    }

                    continue;
                }

                Log.Info("Created service: {0} of type: {1}", service.Name, service.GetType().ToString());
            }
        }
示例#3
0
        private void CreateSystemService()
        {
            ServiceCreationInfo info = new ServiceCreationInfo(null, mServiceManager, mDeviceManager);
            var service = new SystemControlService(info);

            mServiceManager.AddService(service);
        }
示例#4
0
        public ServiceBase(string name, ServiceCreationInfo info)
        {
            if (name == null || name.Length == 0)
                throw new ArgumentException("Missing name on service");

            mName = name;
        }
示例#5
0
        public LampService(ServiceCreationInfo info)
            : base(info)
        {
            uint port = uint.Parse(info.Configuration["port"]);

            mSerialHelper = SerialRepository.OpenPort("arduino", port, 115200);
        }
示例#6
0
        public static ServiceBase CreateService(ServiceCreationInfo info)
        {
            string typeName;

            try
            {
                typeName = info.Configuration.type;
            }
            catch (RuntimeBinderException)
            {
                throw new ArgumentException("Missing type of service");
            }

            Type serviceType = Type.GetType(typeName);

            if (serviceType == null)
            {
                throw new ArgumentException("Invalid service type name: " + typeName);
            }

            if (!serviceType.IsSubclassOf(typeof(ServiceBase)))
            {
                throw new ArgumentException("Service type is not a subclass of ServiceBase. Type: " + serviceType.Name);
            }

            Object[] arguments = new Object[] { info };

            return((ServiceBase)Activator.CreateInstance(serviceType, arguments));
        }
示例#7
0
        public ServiceBase CreateService(dynamic configuration)
        {
            var info    = new ServiceCreationInfo(configuration, ServiceManager, DeviceManager);
            var service = ServiceFactory.CreateService(info);

            ServiceManager.AddService(service);

            return(service);
        }
        public SystemControlService(ServiceCreationInfo info)
            : base("system", info)
        {
            RefreshStatus();

            Log.Info("Application is running version: " + mStatus.CurrentVersion);
            if (mStatus.UpdateAvailable)
                Log.Info("There is an update available");
        }
        internal static void InstallFabricInstallerService(string fabricPackageRoot, string machineName)
        {
            if (string.IsNullOrEmpty(machineName))
            {
                machineName = Helpers.GetMachine();
            }
            DeployerTrace.WriteInfo(StringResources.Info_CheckIfFabricInstallerServiceAlreadyExists, machineName);
            var fabricInstallerService = GetService(Constants.FabricInstallerServiceName, machineName);

            if (fabricInstallerService == null)
            {
                DeployerTrace.WriteInfo(StringResources.Info_InstallFabricInstallerServiceOnMachine, machineName);
                string servicePath = Path.Combine(fabricPackageRoot, Constants.FabricInstallerServiceRelativePathFromRoot);
                var    remotePath  = Helpers.GetRemotePath(servicePath, machineName);
                if (!File.Exists(remotePath))
                {
                    string errorMessage = string.Format(CultureInfo.InvariantCulture, StringResources.Error_UnableToInstallFabricInstallerSvcFNF, remotePath);
                    DeployerTrace.WriteError(errorMessage);
                    throw new FileNotFoundException(errorMessage);
                }

                var serviceCreationinfo = new ServiceCreationInfo()
                {
                    ServicePath = string.Format("\"{0}\"", servicePath),
                    DisplayName = Constants.FabricInstallerDisplayName
                };

                IntPtr svcHandle = GetServiceHandle(machineName, Constants.FabricInstallerServiceName, serviceCreationinfo);
                if (svcHandle == IntPtr.Zero)
                {
                    string errorMessage = string.Format(CultureInfo.InvariantCulture,
                                                        StringResources.Error_OpenSCManagerReturnsErrorWhileCreating, machineName, Utility.GetWin32ErrorMessage(Marshal.GetLastWin32Error()));
                    DeployerTrace.WriteError(errorMessage);
                    throw new InvalidOperationException(errorMessage);
                }
                else
                {
                    try
                    {
                        SetServiceDescription(svcHandle, Constants.FabricInstallerServiceDescription);
                        SetStartupTypeDelayedAuto(svcHandle);
                        SetServiceFailureActionsForRestart(svcHandle,
                                                           Constants.FabricInstallerServiceDelayInSecondsBeforeRestart,
                                                           Constants.FabricUpgradeFailureCountResetPeriodInDays);
                    }
                    finally
                    {
                        NativeMethods.CloseServiceHandle(svcHandle);
                    }
                }
            }
            else
            {
                DeployerTrace.WriteInfo(StringResources.Info_FabricInstallerSvcAlreadyInstalled, machineName);
            }
        }
示例#10
0
        public CurtainService(ServiceCreationInfo info)
            : base("curtain", info)
        {
            uint port = uint.Parse(info.Configuration.port);

            mSerialHelper = SerialRepository.OpenPort("arduino", port, 115200);
            mRadioLock    = RadioLock.Instance;

            mLock = new Object();
        }
示例#11
0
        public CurtainService(ServiceCreationInfo info)
            : base("curtain", info)
        {
            uint port = uint.Parse(info.Configuration.port);

            mSerialHelper = SerialRepository.OpenPort("arduino", port, 115200);
            mRadioLock = RadioLock.Instance;

            mLock = new Object();
        }
示例#12
0
        public SystemControlService(ServiceCreationInfo info)
            : base("system", info)
        {
            RefreshStatus();

            Log.Info("Application is running version: " + mStatus.CurrentVersion);
            if (mStatus.UpdateAvailable)
            {
                Log.Info("There is an update available");
            }
        }
示例#13
0
        public RfxComService(ServiceCreationInfo info)
            : base("rfxcom", info)
        {
            mDeviceManager = info.DeviceManager;

            int port = int.Parse(info.Configuration["port"]);

            mSerialHelper = new SerialHelper("rfxcom", (uint)port, 38400);
            mRadioLock    = RadioLock.Instance;
            mEvents       = new EventWaitHandle[] { mActionEvent, mSerialEvent, mStopEvent };

            mRfxThread = new Thread(Tick);
            mRfxThread.Start();
        }
示例#14
0
        public RfxComService(ServiceCreationInfo info)
            : base("rfxcom", info)
        {
            mDeviceManager = info.DeviceManager;

            int port = int.Parse(info.Configuration["port"]);

            mSerialHelper = new SerialHelper("rfxcom", (uint)port, 38400);
            mRadioLock = RadioLock.Instance;
            mEvents = new EventWaitHandle[] { mActionEvent, mSerialEvent, mStopEvent };

            mRfxThread = new Thread(Tick);
            mRfxThread.Start();
        }
示例#15
0
        private TimeSpan SCAN_INTERVAL_PRESENT = new TimeSpan(0, 30, 1); // Keep a multiple of this slightly longer than AWAY_TIMEOUT to prevent evaulating 1sec before the timeout.

        #endregion Fields

        #region Constructors

        public BluetoothService(ServiceCreationInfo info)
            : base("bluetooth", info)
        {
            mBluetooth = new BluetoothHelper();

            // Refresh available devices
            mBluetooth.RefreshDevices();
            mDeviceNames = mBluetooth.GetDevices();
            Log.Info("Bluetooth devices: {0}", mDeviceNames);

            // Set up scan thread.
            mEvents = new EventWaitHandle[] { mStopEvent, mDeviceEvent };
            mThread = new Thread(_searchThread);
            mThread.Start();
        }
示例#16
0
        public ModeService(ServiceCreationInfo info)
            : base("mode", info)
        {
            mCurrentMode = new Mode("<none>");
            mChangeQueue = new List <ModeChange>();
            mQueueEvent  = new AsyncEvent();

            Task.Run(async() =>
            {
                while (true)
                {
                    // Retry once we have something in the queue.
                    if (mChangeQueue.Count == 0)
                    {
                        await mQueueEvent.Wait();
                        continue;
                    }

                    ModeChange change;
                    var delay = TimeSpan.Zero;

                    lock (mChangeQueue)
                    {
                        change = mChangeQueue[0];
                        delay  = change.ActivationTime - DateTime.Now;
                        mQueueEvent.Reset();

                        if (delay <= TimeSpan.Zero)
                        {
                            mChangeQueue.RemoveAt(0);
                        }
                    }

                    if (delay > TimeSpan.Zero)
                    {
                        using (var delayTokenSource = new CancellationTokenSource())
                        {
                            var tasks = new Task[] { mQueueEvent.Wait(), Task.Delay(delay, delayTokenSource.Token) };
                            await Task.WhenAny(tasks);
                        }
                        continue;
                    }

                    CurrentMode = change.Mode;
                }
            });
        }
示例#17
0
        public ServiceBase(ServiceCreationInfo info)
        {
            string name;
            try
            {
                name = info.Configuration.Name;
            }
            catch (RuntimeBinderException)
            {
                throw new ArgumentException("Missing name of service");
            }

            if (name.Length == 0)
                throw new ArgumentException("Missing name on service");

            mName = name;
        }
示例#18
0
        public ModeService(ServiceCreationInfo info)
            : base("mode", info)
        {
            mCurrentMode = new Mode("<none>");
            mChangeQueue = new List<ModeChange>();
            mQueueEvent = new AsyncEvent();

            Task.Run(async () =>
            {
                while (true)
                {
                    // Retry once we have something in the queue.
                    if (mChangeQueue.Count == 0)
                    {
                        await mQueueEvent.Wait();
                        continue;
                    }

                    ModeChange change;
                    var delay = TimeSpan.Zero;

                    lock (mChangeQueue)
                    {
                        change = mChangeQueue[0];
                        delay = change.ActivationTime - DateTime.Now;
                        mQueueEvent.Reset();

                        if (delay <= TimeSpan.Zero)
                            mChangeQueue.RemoveAt(0);
                    }

                    if (delay > TimeSpan.Zero)
                    {
                        using (var delayTokenSource = new CancellationTokenSource())
                        {
                            var tasks = new Task[] { mQueueEvent.Wait(), Task.Delay(delay, delayTokenSource.Token) };
                            await Task.WhenAny(tasks);
                        }
                        continue;
                    }

                    CurrentMode = change.Mode;
                }
            });
        }
示例#19
0
        public BluetoothService(ServiceCreationInfo info)
            : base("bluetooth", info)
        {
            mBluetooth = new BluetoothHelper();

            // Refresh available devices
            mBluetooth.RefreshDevices();
            mDeviceNames = mBluetooth.GetDevices();
            if (mDeviceNames != null)
            {
                Log.Info("Bluetooth devices: {0}", mDeviceNames);
            }

            // Set up scan thread.
            mEvents = new EventWaitHandle[] { mStopEvent, mDeviceEvent };
            mThread = new Thread(_searchThread);
            mThread.Start();
        }
示例#20
0
        public static ServiceBase CreateService(ServiceCreationInfo info)
        {
            string typeName;
            try
            {
                typeName = info.Configuration.type;
            }
            catch (RuntimeBinderException)
            {
                throw new ArgumentException("Missing type of service");
            }

            Type serviceType = Type.GetType(typeName);
            if (serviceType == null)
                throw new ArgumentException("Invalid service type name: " + typeName);

            if (!serviceType.IsSubclassOf(typeof(ServiceBase)))
                throw new ArgumentException("Service type is not a subclass of ServiceBase. Type: " + serviceType.Name);

            Object[] arguments = new Object[] { info };

            return (ServiceBase)Activator.CreateInstance(serviceType, arguments);
        }
示例#21
0
 public DeviceManagerService(ServiceCreationInfo info)
     : base("device", info)
 {
     mDeviceManager = info.DeviceManager;
 }
示例#22
0
 public SceneService(ServiceCreationInfo info)
     : base("scene", info)
 {
 }
示例#23
0
 public YamahaService(ServiceCreationInfo info)
     : base("yamaha", info)
 {
     mDevices = new HashSet<YamahaDevice>();
 }
示例#24
0
 public LampServiceMock(ServiceCreationInfo info)
     : base(info)
 {
     SetLevelCalled = false;
     Level          = 0.0f;
 }
示例#25
0
 public WakeOnLanService(ServiceCreationInfo info)
     : base("wake", info)
 {
 }
示例#26
0
 public LampServiceBase(ServiceCreationInfo info)
     : base(info)
 {
 }
示例#27
0
 public PowerControlService(ServiceCreationInfo info)
     : base("power", info)
 {
 }
示例#28
0
 public EventService(ServiceCreationInfo info)
     : base("events", info)
 {
 }
示例#29
0
 public EventService(ServiceCreationInfo info)
     : base("events", info)
 {
 }
示例#30
0
 public WakeOnLanService(ServiceCreationInfo info)
     : base("wake", info)
 {
 }
示例#31
0
 public SceneService(ServiceCreationInfo info)
     : base("scene", info)
 {
 }
示例#32
0
 public DummyService(ServiceCreationInfo info)
     : base("dummy", info)
 {
 }
示例#33
0
 public LampServiceBase(ServiceCreationInfo info)
     : base(info)
 {
 }
        private static IntPtr GetServiceHandle(string machineName, string serviceName, ServiceCreationInfo serviceCreationInfo, bool throwOnMissingService = true)
        {
            if (string.IsNullOrEmpty(machineName))
            {
                machineName = Helpers.GetMachine();
            }

            IntPtr svcManagerHandle = IntPtr.Zero;
            IntPtr svcHandle        = IntPtr.Zero;

            svcManagerHandle = NativeMethods.OpenSCManager(machineName, null, NativeMethods.SC_MANAGER_ALL_ACCESS);
            if (svcManagerHandle == IntPtr.Zero)
            {
                DeployerTrace.WriteError(StringResources.Error_UnableToChangeOpenServiceManagerHandle, Marshal.GetLastWin32Error());
                string errorMessage = string.Format(CultureInfo.InvariantCulture,
                                                    StringResources.Error_OpenSCManagerReturnsErrorWhileDeleting, machineName, Marshal.GetLastWin32Error());
                DeployerTrace.WriteError(errorMessage);
                throw new InvalidOperationException(errorMessage);
            }

            try
            {
                if (serviceCreationInfo == null)
                {
                    svcHandle = NativeMethods.OpenService(svcManagerHandle, serviceName, NativeMethods.SERVICE_ACCESS.SERVICE_ALL_ACCESS);
                    if (svcHandle == IntPtr.Zero)
                    {
                        if (throwOnMissingService && Marshal.GetLastWin32Error() == NativeMethods.ERROR_SERVICE_DOES_NOT_EXIST)
                        {
                            DeployerTrace.WriteError(StringResources.Error_UnableToChangeOpenServiceHandle, Marshal.GetLastWin32Error());
                            string errorMessage = string.Format(CultureInfo.InvariantCulture,
                                                                StringResources.Error_OpenSCManagerReturnsErrorWhileDeleting, machineName, Marshal.GetLastWin32Error());
                            DeployerTrace.WriteError(errorMessage);
                            throw new InvalidOperationException(errorMessage);
                        }
                    }
                }
                else
                {
                    svcHandle = NativeMethods.CreateService(svcManagerHandle,
                                                            serviceName,
                                                            serviceCreationInfo.DisplayName,
                                                            NativeMethods.SERVICE_ACCESS.SERVICE_ALL_ACCESS,
                                                            NativeMethods.SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS,
                                                            NativeMethods.SERVICE_START.SERVICE_AUTO_START,
                                                            NativeMethods.SERVICE_ERROR.SERVICE_ERROR_NORMAL,
                                                            serviceCreationInfo.ServicePath,
                                                            null,
                                                            null,
                                                            null,
                                                            null,
                                                            null);
                    if (svcHandle == IntPtr.Zero)
                    {
                        string errorMessage = string.Format(CultureInfo.InvariantCulture,
                                                            StringResources.Error_OpenSCManagerReturnsErrorWhileCreating, machineName, Marshal.GetLastWin32Error());
                        DeployerTrace.WriteError(errorMessage);
                        throw new InvalidOperationException(errorMessage);
                    }
                }
            }
            finally
            {
                NativeMethods.CloseServiceHandle(svcManagerHandle);
            }
            return(svcHandle);
        }
示例#35
0
 public YamahaService(ServiceCreationInfo info)
     : base("yamaha", info)
 {
     mDevices = new HashSet <YamahaDevice>();
 }
示例#36
0
 public PowerControlService(ServiceCreationInfo info)
     : base("power", info)
 {
 }
示例#37
0
        private void CreateServices(List<dynamic> configs)
        {
            foreach (var serviceConfig in configs)
            {
                ServiceBase service;
                try
                {
                    ServiceCreationInfo info = new ServiceCreationInfo(serviceConfig, mServiceManager, mDeviceManager);

                    service = ServiceFactory.CreateService(info);
                    mServiceManager.AddService(service);
                }
                catch (Exception e)
                {
                    Log.Error("Failed creating service for node: " + serviceConfig.Name);
                    if (e.InnerException != null)
                        Log.Error("Inner Exception: {0}\nCallstack:\n{1}", e.InnerException.Message, e.InnerException.StackTrace);
                    else
                        Log.Error("Exception: {0}\nCallstack:\n{1}", e.Message, e.StackTrace);

                    continue;
                }

                Log.Info("Created service: {0} of type: {1}", service.Name, service.GetType().ToString());
            }
        }
示例#38
0
 private void CreateSystemService()
 {
     ServiceCreationInfo info = new ServiceCreationInfo(null, mServiceManager, mDeviceManager);
     var service = new SystemControlService(info);
     mServiceManager.AddService(service);
 }
示例#39
0
        public SpeechService(ServiceCreationInfo info)
            : base("speech", info)
        {
            mVoice = new SpVoice();

            // Select voice
            string voiceName = null;
            try
            {
                voiceName = info.Configuration.Voice;
            }
            catch (RuntimeBinderException) {}

            if (!string.IsNullOrEmpty(voiceName))
            {
                SpObjectToken voiceToken = null;

                CultureInfo culture = new CultureInfo("en-US");
                foreach (var voice in mVoice.GetVoices())
                {
                    var token = voice as SpObjectToken;
                    if (token == null)
                        continue;

                    if (culture.CompareInfo.IndexOf(token.Id, voiceName, CompareOptions.IgnoreCase) < 0)
                        continue;

                    voiceToken = token;
                }

                if (voiceToken != null)
                    mVoice.Voice = voiceToken;
            }

            // Select output. Why isn't this default any longer?
            var enumerator = new MMDeviceEnumerator();
            MMDevice endpoint = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
            if (endpoint != null)
            {
                foreach (var output in mVoice.GetAudioOutputs())
                {
                    var token = output as SpObjectToken;
                    if (token == null)
                        continue;

                    if (token.Id.IndexOf(endpoint.ID) < 0)
                        continue;

                    mVoice.AudioOutput = token;
                    break;
                }
            }

            mVoiceCommands = new Dictionary<string, DeviceBase.VoiceCommand>();

            mInput = new AudioInput();

            mRecognizer = new SpeechRecognitionEngine();
            mRecognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(OnSpeechRecognized);
            mRecognizer.RecognizerUpdateReached += new EventHandler<RecognizerUpdateReachedEventArgs>(OnUpdateRecognizer);
            mRecognizer.RecognizeCompleted += new EventHandler<RecognizeCompletedEventArgs>(OnRecognizeCompleted);

            var grammar = new Grammar(new GrammarBuilder(new Choices(new string[] { "computer" })));
            mRecognizer.LoadGrammar(grammar);

            var speechFormat = new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Mono);
            mRecognizer.SetInputToAudioStream(mInput.mStream, speechFormat);

            mRecognizer.RecognizeAsync(RecognizeMode.Multiple);
        }
示例#40
0
 public DummyService(ServiceCreationInfo info)
     : base("dummy", info)
 {
 }
示例#41
0
        public SpeechService(ServiceCreationInfo info)
            : base("speech", info)
        {
            mVoice = new SpVoice();

            // Select voice
            string voiceName = null;

            try
            {
                voiceName = info.Configuration.Voice;
            }
            catch (RuntimeBinderException) {}

            if (!string.IsNullOrEmpty(voiceName))
            {
                SpObjectToken voiceToken = null;

                CultureInfo culture = new CultureInfo("en-US");
                foreach (var voice in mVoice.GetVoices())
                {
                    var token = voice as SpObjectToken;
                    if (token == null)
                    {
                        continue;
                    }

                    if (culture.CompareInfo.IndexOf(token.Id, voiceName, CompareOptions.IgnoreCase) < 0)
                    {
                        continue;
                    }

                    voiceToken = token;
                }

                if (voiceToken != null)
                {
                    mVoice.Voice = voiceToken;
                }
            }

            // Select output. Why isn't this default any longer?
            var      enumerator = new MMDeviceEnumerator();
            MMDevice endpoint   = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);

            if (endpoint != null)
            {
                foreach (var output in mVoice.GetAudioOutputs())
                {
                    var token = output as SpObjectToken;
                    if (token == null)
                    {
                        continue;
                    }

                    if (token.Id.IndexOf(endpoint.ID) < 0)
                    {
                        continue;
                    }

                    mVoice.AudioOutput = token;
                    break;
                }
            }

            mVoiceCommands = new Dictionary <string, DeviceBase.VoiceCommand>();

            mInput = new AudioInput();

            mRecognizer = new SpeechRecognitionEngine();
            mRecognizer.SpeechRecognized        += new EventHandler <SpeechRecognizedEventArgs>(OnSpeechRecognized);
            mRecognizer.RecognizerUpdateReached += new EventHandler <RecognizerUpdateReachedEventArgs>(OnUpdateRecognizer);
            mRecognizer.RecognizeCompleted      += new EventHandler <RecognizeCompletedEventArgs>(OnRecognizeCompleted);

            var grammar = new Grammar(new GrammarBuilder(new Choices(new string[] { "computer" })));

            mRecognizer.LoadGrammar(grammar);

            var speechFormat = new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Mono);

            mRecognizer.SetInputToAudioStream(mInput.mStream, speechFormat);

            mRecognizer.RecognizeAsync(RecognizeMode.Multiple);
        }