Ejemplo n.º 1
0
        public LampService(ServiceCreationInfo info)
            : base(info)
        {
            uint port = uint.Parse(info.Configuration["port"]);

            mSerialHelper = SerialRepository.OpenPort("arduino", port, 115200);
        }
Ejemplo n.º 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());
            }
        }
Ejemplo n.º 3
0
        private void CreateSystemService()
        {
            ServiceCreationInfo info = new ServiceCreationInfo(null, mServiceManager, mDeviceManager);
            var service = new SystemControlService(info);

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

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

            mSerialHelper = SerialRepository.OpenPort("arduino", port, 115200);
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 7
0
        public ServiceBase CreateService(dynamic configuration)
        {
            var info    = new ServiceCreationInfo(configuration, ServiceManager, DeviceManager);
            var service = ServiceFactory.CreateService(info);

            ServiceManager.AddService(service);

            return(service);
        }
Ejemplo n.º 8
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");
        }
        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);
            }
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 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");
            }
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 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;
                }
            });
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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;
                }
            });
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 21
0
 public DeviceManagerService(ServiceCreationInfo info)
     : base("device", info)
 {
     mDeviceManager = info.DeviceManager;
 }
Ejemplo n.º 22
0
 public SceneService(ServiceCreationInfo info)
     : base("scene", info)
 {
 }
Ejemplo n.º 23
0
 public YamahaService(ServiceCreationInfo info)
     : base("yamaha", info)
 {
     mDevices = new HashSet<YamahaDevice>();
 }
Ejemplo n.º 24
0
 public LampServiceMock(ServiceCreationInfo info)
     : base(info)
 {
     SetLevelCalled = false;
     Level          = 0.0f;
 }
Ejemplo n.º 25
0
 public WakeOnLanService(ServiceCreationInfo info)
     : base("wake", info)
 {
 }
Ejemplo n.º 26
0
 public LampServiceBase(ServiceCreationInfo info)
     : base(info)
 {
 }
Ejemplo n.º 27
0
 public PowerControlService(ServiceCreationInfo info)
     : base("power", info)
 {
 }
Ejemplo n.º 28
0
 public EventService(ServiceCreationInfo info)
     : base("events", info)
 {
 }
Ejemplo n.º 29
0
 public EventService(ServiceCreationInfo info)
     : base("events", info)
 {
 }
Ejemplo n.º 30
0
 public WakeOnLanService(ServiceCreationInfo info)
     : base("wake", info)
 {
 }
Ejemplo n.º 31
0
 public SceneService(ServiceCreationInfo info)
     : base("scene", info)
 {
 }
Ejemplo n.º 32
0
 public DummyService(ServiceCreationInfo info)
     : base("dummy", info)
 {
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 35
0
 public YamahaService(ServiceCreationInfo info)
     : base("yamaha", info)
 {
     mDevices = new HashSet <YamahaDevice>();
 }
Ejemplo n.º 36
0
 public PowerControlService(ServiceCreationInfo info)
     : base("power", info)
 {
 }
Ejemplo n.º 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());
            }
        }
Ejemplo n.º 38
0
 private void CreateSystemService()
 {
     ServiceCreationInfo info = new ServiceCreationInfo(null, mServiceManager, mDeviceManager);
     var service = new SystemControlService(info);
     mServiceManager.AddService(service);
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 40
0
 public DummyService(ServiceCreationInfo info)
     : base("dummy", info)
 {
 }
Ejemplo n.º 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);
        }