Exemple #1
0
        public CameraInput()
        {
            string assemblyFolder = MigService.GetAssemblyDirectory(this.GetType().Assembly);

            // video 4 linux interop, try to detect Raspbian/Ubuntu
            if (Directory.Exists("/lib/arm-linux-gnueabi") || Directory.Exists("/lib/arm-linux-gnueabihf"))
            {
                MigService.ShellCommand("cp", " -f \"" + Path.Combine(assemblyFolder, "v4l/raspbian_libCameraCaptureV4L.so") + "\" \"" + Path.Combine(assemblyFolder, "libCameraCaptureV4L.so") + "\"");
                //
                //if (File.Exists("/usr/lib/libgdiplus.so") && !File.Exists("/usr/local/lib/libgdiplus.so"))
                //{
                //    ShellCommand("ln", " -s \"/usr/lib/libgdiplus.so\" \"/usr/local/lib/libgdiplus.so\"");
                //}
            }
            else // fallback (ubuntu and other 64bit debians)
            {
                string v4lfile = "v4l/debian64_libCameraCaptureV4L.so.gd3";
                if (!File.Exists("/usr/lib/x86_64-linux-gnu/libgd.so.3"))
                {
                    v4lfile = "v4l/debian64_libCameraCaptureV4L.so";
                }
                MigService.ShellCommand(
                    "cp",
                    " -f \"" + Path.Combine(
                        assemblyFolder,
                        v4lfile
                        ) + "\" \"" + Path.Combine(
                        assemblyFolder,
                        "libCameraCaptureV4L.so"
                        ) + "\""
                    );
            }
        }
Exemple #2
0
        private void SaveConfig()
        {
            string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lircconfig.xml");

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            var settings = new System.Xml.XmlWriterSettings();

            settings.Indent = true;
            var serializer = new System.Xml.Serialization.XmlSerializer(remotesConfig.GetType());
            var writer     = System.Xml.XmlWriter.Create(fileName, settings);

            serializer.Serialize(writer, remotesConfig);
            writer.Close();
            //
            try
            {
                string lircConfiguration = "";
                foreach (var remote in remotesConfig)
                {
                    lircConfiguration += GetString(remote.Configuration) + "\n";
                }
                File.WriteAllText("/etc/lirc/lircd.conf", lircConfiguration);
                MigService.ShellCommand("/etc/init.d/lirc", " force-reload");
            }
            catch
            {
            }
        }
 private void SendResponseObject(HttpListenerContext context, object responseObject)
 {
     if (responseObject != null && responseObject.GetType().Equals(typeof(byte[])) == false)
     {
         string responseText = "";
         if (responseObject is string)
         {
             responseText = responseObject.ToString();
         }
         else
         {
             responseText = MigService.JsonSerialize(responseObject);
         }
         // simple automatic json response type detection
         if (responseText.StartsWith("[") && responseText.EndsWith("]") ||
             responseText.StartsWith("{") && responseText.EndsWith("}"))
         {
             // send as JSON
             context.Response.ContentType     = "application/json";
             context.Response.ContentEncoding = defaultWebFileEncoding;
         }
         WebServiceUtility.WriteStringToContext(context, responseText);
     }
     else
     {
         // Send as binary data
         WebServiceUtility.WriteBytesToContext(context, (byte[])responseObject);
     }
 }
Exemple #4
0
        /// <summary>
        /// Main Program
        /// </summary>
        /// <param name="args">command line arguments</param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Mig Interface test APP");

            var migService = new MigService();

            // Load the configuration from systemconfig.xml file
            MigServiceConfiguration configuration;

            // Construct an instance of the XmlSerializer with the type
            // of object that is being deserialized.
            XmlSerializer mySerializer = new XmlSerializer(typeof(MigServiceConfiguration));

            // To read the file, create a FileStream.
            FileStream myFileStream = new FileStream("systemconfig.xml", FileMode.Open);

            // Call the Deserialize method and cast to the object type.
            configuration = (MigServiceConfiguration)mySerializer.Deserialize(myFileStream);

            // Set the configuration and start MIG Service
            migService.Configuration = configuration;
            migService.StartService();

            // Get a reference to the test interface
            var interfaceDomain = "HomeAutomation.TradfriInterface";
            var migInterface    = migService.GetInterface(interfaceDomain);

            migInterface.Connect();
            Console.WriteLine("Get Modules");
            var interfacemodules = migInterface.GetModules();

            foreach (MIG.InterfaceModule mod in interfacemodules)
            {
                Console.WriteLine($"Module Address: {mod.Address} Module Type: {mod.ModuleType}");
                if (mod.ModuleType.ToString() != "Dimmer")
                {
                    ResponseText resp;
                    resp = (ResponseText)migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + $"/{mod.Address}/Battery.Get"));
                    Console.WriteLine(resp.ResponseValue);
                }

                // var response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + $"/{mod.Address}/Control.On"));
                // System.Threading.Thread.Sleep(1000);
                // response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + $"/{mod.Address}/Control.Colour/eaf6fb"));
                // System.Threading.Thread.Sleep(2000);
                // response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + $"/{mod.Address}/Control.Colour/ebb63e"));
                // System.Threading.Thread.Sleep(2000);
                // response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + $"/{mod.Address}/Control.Colour/f5faf6"));
                // System.Threading.Thread.Sleep(2000);
                // response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + $"/{mod.Address}/Control.Off"));
            }

            Console.WriteLine("\n[Press Enter to Quit]\n");
            Console.ReadLine();
        }
Exemple #5
0
        public LircRemote()
        {
            // lirc client lib symlink
            string assemblyFolder = MigService.GetAssemblyDirectory(this.GetType().Assembly);
            var    liblirclink    = Path.Combine(assemblyFolder, "liblirc_client.so");

            if (File.Exists("/usr/lib/liblirc_client.so") && !File.Exists(liblirclink))
            {
                MigService.ShellCommand("ln", " -s \"/usr/lib/liblirc_client.so\" \"" + liblirclink + "\"");
            }
            else if (File.Exists("/usr/lib/liblirc_client.so.0") && !File.Exists(liblirclink))
            {
                MigService.ShellCommand("ln", " -s \"/usr/lib/liblirc_client.so.0\" \"" + liblirclink + "\"");
            }
            // create .lircrc file
            var lircrcFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".lircrc");

            if (!File.Exists(lircrcFile))
            {
                var lircrc = "begin\n" +
                             "        prog = homegenie\n" +
                             "        button = KEY_1\n" +
                             "        repeat = 3\n" +
                             "        config = KEY_1\n" +
                             "end\n";
                try
                {
                    File.WriteAllText(lircrcFile, lircrc);
                }
                catch { }
            }
            //
            remotesConfig = new List <LircRemoteData>();
            string configfile = Path.Combine(assemblyFolder, "lircconfig.xml");

            if (File.Exists(configfile))
            {
                var serializer = new XmlSerializer(typeof(List <LircRemoteData>));
                var reader     = new StreamReader(configfile);
                remotesConfig = (List <LircRemoteData>)serializer.Deserialize(reader);
                reader.Close();
            }
            //
            string remotesdb = Path.Combine(assemblyFolder, "lircremotes.xml");

            if (File.Exists(remotesdb))
            {
                var serializer = new XmlSerializer(typeof(List <LircRemoteData>));
                var reader     = new StreamReader(remotesdb);
                remotesData = (List <LircRemoteData>)serializer.Deserialize(reader);
                reader.Close();
            }
        }
Exemple #6
0
        /// <summary>
        /// Main Program
        /// </summary>
        /// <param name="args">command line arguments</param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Mig Interface Hikvision test APP");

            var migService = new MigService();

            // Load the configuration from systemconfig.xml file
            MigServiceConfiguration configuration;

            // Construct an instance of the XmlSerializer with the type
            // of object that is being deserialized.
            var mySerializer = new XmlSerializer(typeof(MigServiceConfiguration));

            // To read the file, create a FileStream.
            var myFileStream = new FileStream("systemconfig.xml", FileMode.Open);

            // Call the Deserialize method and cast to the object type.
            configuration = (MigServiceConfiguration)mySerializer.Deserialize(myFileStream);

            // Set the configuration and start MIG Service
            migService.Configuration = configuration;
            migService.StartService();

            // Get a reference to the test interface
            var interfaceDomain = "Hikvision.InterfaceHikvision";
            var migInterface    = migService.GetInterface(interfaceDomain);

            // Test an interface API command programmatically <module_domain>/<module_address>/<command>[/<option_0>[/../<option_n>]]
            var response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/3/Greet.Hello/Username"));

            // <module_domain> ::= "Hikvision.InterfaceHikvision"
            // <module_address> ::= "3"
            // <command> ::= "Greet.Hello"
            // <option_0> ::= "Username"
            // For more infos about MIG API see:
            //    http://genielabs.github.io/HomeGenie-BE/api/mig/overview.html
            //    http://genielabs.github.io/HomeGenie-BE/api/mig/mig_api_interfaces.html

            // The same command can be invoked though the WebGateway
            // http://<server_address>:8080/api/Hikvision.InterfaceHikvision/1/Greet.Hello/Username

            // Test some other interface API command
            response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/1/Control.On"));
            MigService.Log.Debug(response);
            response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/1/Control.Off"));
            MigService.Log.Debug(response);
            response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/2/Temperature.Get"));
            MigService.Log.Debug(response);

            Console.WriteLine("\n[Press Enter to Quit]\n");
            Console.ReadLine();
        }
 public void OnInterfacePropertyChanged(object sender, InterfacePropertyChangedEventArgs args)
 {
     if (webSocketServer != null && webSocketServer.IsListening)
     {
         WebSocketServiceHost host;
         webSocketServer.WebSocketServices.TryGetServiceHost("/events", out host);
         if (host == null)
         {
             return;
         }
         host.Sessions.BroadcastAsync(MigService.JsonSerialize(args.EventData), () => {});
     }
 }
Exemple #8
0
        public X10()
        {
            if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
            {
                // Fix libusb symbolic link
                string assemblyFolder = MigService.GetAssemblyDirectory(this.GetType().Assembly);
                var    libUsbLink     = Path.Combine(assemblyFolder, "libusb-1.0.so");
                if (File.Exists(libUsbLink))
                {
                    File.Delete(libUsbLink);
                }
                // RaspBerry Pi arm-hf (hard-float) dependency check and needed symlink
                if (File.Exists("/lib/arm-linux-gnueabihf/libusb-1.0.so.0.1.0"))
                {
                    MigService.ShellCommand("ln", " -s \"/lib/arm-linux-gnueabihf/libusb-1.0.so.0.1.0\" \"" + libUsbLink + "\"");
                }
                // RaspBerry Pi arm-el dependency check and needed symlink
                else if (File.Exists("/lib/arm-linux-gnueabi/libusb-1.0.so.0.1.0"))
                {
                    MigService.ShellCommand("ln", " -s \"/lib/arm-linux-gnueabi/libusb-1.0.so.0.1.0\" \"" + libUsbLink + "\"");
                }
                // Debian/Ubuntu 64bit dependency and needed symlink check
                else if (File.Exists("/lib/x86_64-linux-gnu/libusb-1.0.so.0"))
                {
                    MigService.ShellCommand("ln", " -s \"/lib/x86_64-linux-gnu/libusb-1.0.so.0\" \"" + libUsbLink + "\"");
                }
                // Remove CM19 kernel drivers to allow access to the device
                MigService.ShellCommand("rmmod", " lirc_atiusb");
                MigService.ShellCommand("rmmod", " ati_remote");
                MigService.ShellCommand("rmmod", " rc_ati_x10");
            }

            // CM19 Transceiver driver
            // TODO: should "rmmod" CM19 kernel modules for CM19Lib to work (Linux)
            cm19Lib = new Cm19Manager();
            cm19Lib.RfCameraReceived   += Cm19LibOnRfCameraReceived;
            cm19Lib.RfDataReceived     += Cm19LibOnRfDataReceived;
            cm19Lib.RfCommandReceived  += Cm19LibOnRfCommandReceived;
            cm19Lib.RfSecurityReceived += Cm19LibOnRfSecurityReceived;

            // CM11 and CM15 PLC driver
            x10Lib = new XTenManager();
            x10Lib.ModuleChanged      += X10lib_ModuleChanged;
            x10Lib.RfDataReceived     += X10lib_RfDataReceived;
            x10Lib.RfSecurityReceived += X10lib_RfSecurityReceived;

            securityModules = new List <InterfaceModule>();
            // try loading cached security modules list
            DeserializeModules(SecurityModulesDb, securityModules);
            standardModules = new List <InterfaceModule>();
        }
Exemple #9
0
        public X10()
        {
            string assemblyFolder = MigService.GetAssemblyDirectory(this.GetType().Assembly);
            var    libusblink     = Path.Combine(assemblyFolder, "libusb-1.0.so");

            // RaspBerry Pi armel dependency check and needed symlink
            if ((File.Exists("/lib/arm-linux-gnueabi/libusb-1.0.so.0.1.0") || File.Exists("/lib/arm-linux-gnueabihf/libusb-1.0.so.0.1.0")) && !File.Exists(libusblink))
            {
                MigService.ShellCommand("ln", " -s \"/lib/arm-linux-gnueabi/libusb-1.0.so.0.1.0\" \"" + libusblink + "\"");
            }
            // Debian/Ubuntu 64bit dependency and needed symlink check
            if (File.Exists("/lib/x86_64-linux-gnu/libusb-1.0.so.0") && !File.Exists(libusblink))
            {
                MigService.ShellCommand("ln", " -s \"/lib/x86_64-linux-gnu/libusb-1.0.so.0\" \"" + libusblink + "\"");
            }

            x10lib = new XTenManager();
            x10lib.ModuleChanged      += X10lib_ModuleChanged;
            x10lib.RfDataReceived     += X10lib_RfDataReceived;
            x10lib.RfSecurityReceived += X10lib_RfSecurityReceived;
            securityModules            = new List <InterfaceModule>();
        }
        public static void Main(string[] args)
        {
            var migService = new MigService();

            // Construct an instance of the XmlSerializer with the type
            // of object that is being deserialized.
            var mySerializer = new XmlSerializer(typeof(MigServiceConfiguration));

            // To read the file, create a FileStream.
            var myFileStream = new FileStream("systemconfig.xml", FileMode.Open);

            // Call the Deserialize method and cast to the object type.
            var configuration = (MigServiceConfiguration)mySerializer.Deserialize(myFileStream);

            // Load the configuration Set the configuration and start MIG Service
            migService.Configuration = configuration;
            migService.StartService();


            Console.WriteLine("\n[Press Enter to Quit]\n");
            Console.ReadLine();
        }
Exemple #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CameraInput"/> class.
        /// </summary>
        public CameraInput()
        {
            var assemblyFolder = MigService.GetAssemblyDirectory(this.GetType().Assembly);

            Log.Debug($"{this.GetDomain()} Attempting to determine OS for V4L Driver");

            // video 4 linux interop, try to detect Raspbian/Ubuntu
            if (Directory.Exists("/lib/arm-linux-gnueabi") || Directory.Exists("/lib/arm-linux-gnueabihf"))
            {
                Log.Debug($"{this.GetDomain()} /lib/arm-linux-gnueabi exists");
                var command     = "cp";
                var commandArgs = " -f \"" + Path.Combine(assemblyFolder, "v4l/raspbian_libCameraCaptureV4L.so") + "\" \"" + Path.Combine(assemblyFolder, "libCameraCaptureV4L.so") + "\"";
                Log.Debug($"{this.GetDomain()} Running: {command}{commandArgs}");
                MigService.ShellCommand(command, commandArgs);

                // if (File.Exists("/usr/lib/libgdiplus.so") && !File.Exists("/usr/local/lib/libgdiplus.so"))
                // {
                //    ShellCommand("ln", " -s \"/usr/lib/libgdiplus.so\" \"/usr/local/lib/libgdiplus.so\"");
                // }
            }
            else
            {
                Log.Debug($"{this.GetDomain()} /lib/arm-linux-gnueabi doesn't exist, using fallback");

                // fallback (ubuntu and other 64bit debians)
                var v4lfile = "v4l/debian64_libCameraCaptureV4L.so.gd3";
                if (!File.Exists("/usr/lib/x86_64-linux-gnu/libgd.so.3"))
                {
                    Log.Debug($"{this.GetDomain()} /usr/lib/x86_64-linux-gnu/libgd.so.3 doesn't exist");
                    v4lfile = "v4l/debian64_libCameraCaptureV4L.so";
                    Log.Debug($"{this.GetDomain()} v4lfile set to {v4lfile}");
                }

                var fallbackCommand = "cp";
                var fallbackArgs    = " -f \"" + Path.Combine(assemblyFolder, v4lfile) + "\" \"" + Path.Combine(assemblyFolder, "libCameraCaptureV4L.so") + "\"";
                Log.Debug($"{this.GetDomain()} Running: {fallbackCommand}{fallbackArgs}");
                MigService.ShellCommand(fallbackCommand, fallbackArgs);
            }
        }
Exemple #12
0
        public static void Main(string[] args)
        {
            var migService = new MigService();

            // Configuration can also be loaded from a file as shown below
            MigServiceConfiguration configuration;
            // Construct an instance of the XmlSerializer with the type
            // of object that is being deserialized.
            XmlSerializer mySerializer = new XmlSerializer(typeof(MigServiceConfiguration));
            // To read the file, create a FileStream.
            FileStream myFileStream = new FileStream("systemconfig.xml", FileMode.Open);

            // Call the Deserialize method and cast to the object type.
            configuration = (MigServiceConfiguration)mySerializer.Deserialize(myFileStream);
            // Set the configuration
            migService.Configuration = configuration;

            migService.StartService();

            // Enable some interfaces for testing...

            /*
             * var zwave = migService.AddInterface("HomeAutomation.ZWave", "MIG.HomeAutomation.dll");
             * zwave.SetOption("Port", "/dev/ttyUSB0");
             * migService.EnableInterface("HomeAutomation.ZWave");
             */

            /*
             * var x10 = migService.AddInterface("HomeAutomation.X10", "MIG.HomeAutomation.dll");
             * zwave.SetOption("Port", "CM19"); // "USB" for CM15 or the serial port path for CM11
             * migService.EnableInterface("HomeAutomation.X10");
             */

            while (true)
            {
                Thread.Sleep(10000);
            }
        }
Exemple #13
0
        public static void Main(string[] args)
        {
            string webPort = "8088";

            Console.WriteLine("MigService test APP");
            Console.WriteLine("URL: http://localhost:{0}", webPort);

            var migService = new MigService();

            // Add and configure the Web gateway
            var web = migService.AddGateway("WebServiceGateway");

            web.SetOption("HomePath", "html");
            web.SetOption("BaseUrl", "/pages/");
            web.SetOption("Host", "*");
            web.SetOption("Port", webPort);
            web.SetOption("Password", "");
            web.SetOption("EnableFileCaching", "False");

            /*
             * // Add and configure the Web Socket gateway
             * var ws = migService.AddGateway("WebSocketGateway");
             * ws.SetOption("Port", "8181");
             */

            migService.StartService();

            // Enable UPnP interface

            var upnp = migService.AddInterface("Protocols.UPnP", "MIG.Protocols.dll");

            migService.EnableInterface("Protocols.UPnP");

            while (true)
            {
                Thread.Sleep(10000);
            }
        }
        public LircRemote()
        {
            assemblyFolder = MigService.GetAssemblyDirectory(this.GetType().Assembly);
            // lirc client lib symlink
            var liblirclink = Path.Combine(assemblyFolder, "liblirc_client.so");

            if (File.Exists("/usr/lib/liblirc_client.so") && !File.Exists(liblirclink))
            {
                MigService.ShellCommand("ln", " -s \"/usr/lib/liblirc_client.so\" \"" + liblirclink + "\"");
            }
            else if (File.Exists("/usr/lib/liblirc_client.so.0") && !File.Exists(liblirclink))
            {
                MigService.ShellCommand("ln", " -s \"/usr/lib/liblirc_client.so.0\" \"" + liblirclink + "\"");
            }
            //
            remotesConfig = new List <LircRemoteData>();
            string configfile = Path.Combine(assemblyFolder, "lircconfig.xml");

            if (File.Exists(configfile))
            {
                var serializer = new XmlSerializer(typeof(List <LircRemoteData>));
                var reader     = new StreamReader(configfile);
                remotesConfig = (List <LircRemoteData>)serializer.Deserialize(reader);
                reader.Close();
            }
            //
            string remotesdb = Path.Combine(assemblyFolder, "lircremotes.xml");

            if (File.Exists(remotesdb))
            {
                var serializer = new XmlSerializer(typeof(List <LircRemoteData>));
                var reader     = new StreamReader(remotesdb);
                remotesData = (List <LircRemoteData>)serializer.Deserialize(reader);
                reader.Close();
            }
        }
 public void OnInterfacePropertyChanged(object sender, InterfacePropertyChangedEventArgs args)
 {
     wsocketServer.WebSocketServices.Broadcast(MigService.JsonSerialize(args.EventData));
 }
Exemple #16
0
        public void OnInterfacePropertyChanged(object sender, InterfacePropertyChangedEventArgs args)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            server.SendAll(encoding.GetBytes(MigService.JsonSerialize(args)));
        }
Exemple #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Mig Interface Skelton test APP");

            var migService = new MigService();

            // Load the configuration from systemconfig.xml file
            MigServiceConfiguration configuration;
            // Construct an instance of the XmlSerializer with the type
            // of object that is being deserialized.
            XmlSerializer mySerializer = new XmlSerializer(typeof(MigServiceConfiguration));
            // To read the file, create a FileStream.
            FileStream myFileStream = new FileStream("systemconfig.xml", FileMode.Open);

            // Call the Deserialize method and cast to the object type.
            configuration = (MigServiceConfiguration)mySerializer.Deserialize(myFileStream);

            // Set the configuration and start MIG Service
            migService.Configuration = configuration;
            migService.StartService();

            // Get a reference to the test interface
            var interfaceDomain = "Knx.KnxInterface";
            var migInterface    = migService.GetInterface(interfaceDomain);

            migInterface.InterfacePropertyChanged += MigInterface_InterfacePropertyChanged;
            // Test an interface API command programmatically <module_domain>/<module_address>/<command>[/<option_0>[/../<option_n>]]
            // var response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/3/Greet.Hello/Username"));
            // MigService.Log.Debug(response);
            // <module_domain> ::= "Example.InterfaceSkelton"
            // <module_address> ::= "3"
            // <command> ::= "Greet.Hello"
            // <option_0> ::= "Username"
            // For more infos about MIG API see:
            //    http://genielabs.github.io/HomeGenie/api/mig/overview.html
            //    http://genielabs.github.io/HomeGenie/api/mig/mig_api_interfaces.html

            // The same command can be invoked though the WebGateway
            // http://<server_address>:8080/api/Example.InterfaceSkelton/1/Greet.Hello/Username

            // Test some other interface API command

            /*
             * var response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/1.0.0/Control.On"));
             * MigService.Log.Debug(response);
             * Thread.Sleep(3000);
             * response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/1.0.0/Control.Off"));
             * MigService.Log.Debug(response);
             */
            //response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/2/Temperature.Get"));
            //MigService.Log.Debug(response);

            //Console.WriteLine("\n[Press Enter to Quit]\n");
            Console.WriteLine("Test Commands : ");
            Console.WriteLine("Adress : Type : Command");
            Console.WriteLine("Adress Example 1.0.0");
            Console.WriteLine("Command On, Off, Up, Down");
            Console.WriteLine("Exit for End");

            while (true)
            {
                var value = Console.ReadLine();

                if (value.ToLower().Equals("exit"))
                {
                    break;
                }

                var parts = value.Split(':');
                if (parts.Length == 2)
                {
                    var address = parts[0].Trim();
                    var command = "";
                    switch (parts[1].Trim())
                    {
                    case "On":
                        command = "Control.On";
                        break;

                    case "Up":
                        command = "Dimmer.Up";
                        break;

                    case "Down":
                        command = "Dimmer.Down";
                        break;

                    default:
                        command = "Control.Off";
                        break;
                    }

                    var response = migInterface.InterfaceControl(new MigInterfaceCommand(interfaceDomain + "/" + address + "/" + command));
                    Console.WriteLine(((MIG.ResponseText)response).ResponseValue);
                    MigService.Log.Debug(response);
                }
                else
                {
                    Console.WriteLine("Wrong Command");
                }
            }
        }
        private void HandleEventsRoute(HttpListenerRequest request, HttpListenerResponse response, HttpListenerContext context,
                                       string remoteAddress)
        {
            // Server sent events
            // NOTE: no PreProcess or PostProcess events are fired in this case
            //response.KeepAlive = true;
            response.ContentEncoding = Encoding.UTF8;
            response.ContentType     = "text/event-stream";
            response.Headers.Set(HttpResponseHeader.CacheControl, "no-cache, no-store, must-revalidate");
            response.Headers.Set(HttpResponseHeader.Pragma, "no-cache");
            response.Headers.Set("Access-Control-Allow-Origin", "*");

            // 2K padding for IE
            var padding = ":" + new String(' ', 2048) + "\n";

            byte[] paddingData = Encoding.UTF8.GetBytes(padding);
            response.OutputStream.Write(paddingData, 0, paddingData.Length);
            byte[] retryData = Encoding.UTF8.GetBytes("retry: 1000\n");
            response.OutputStream.Write(retryData, 0, retryData.Length);

            DateTime lastTimeStamp = DateTime.UtcNow;
            var      lastId        = context.Request.Headers.Get("Last-Event-ID");

            if (lastId == null || lastId == "")
            {
                var queryValues = HttpUtility.ParseQueryString(context.Request.Url.Query);
                lastId = queryValues.Get("lastEventId");
            }

            if (lastId != null && lastId != "")
            {
                double unixTimestamp = 0;
                double.TryParse(lastId, NumberStyles.Float | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture,
                                out unixTimestamp);
                if (unixTimestamp != 0)
                {
                    lastTimeStamp = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    lastTimeStamp.AddSeconds(Math.Round(unixTimestamp / 1000d));
                }
            }

            bool connected    = true;
            var  timeoutWatch = Stopwatch.StartNew();

            while (connected)
            {
                // dirty work around for signaling new event and
                // avoiding locks on long socket timetout
                lock (sseEventToken)
                    Monitor.Wait(sseEventToken, 1000);
                // safely dequeue events
                List <SseEvent> bufferedData;
                do
                {
                    bufferedData = sseEventBuffer.FindAll(le => le != null && le.Timestamp.Ticks > lastTimeStamp.Ticks);
                    if (bufferedData.Count > 0)
                    {
                        foreach (SseEvent entry in bufferedData)
                        {
                            // send events
                            try
                            {
                                // The following throws an error on some mono-arm (Input string was not in the correct format)
                                // entry.Event.UnixTimestamp.ToString("R", CultureInfo.InvariantCulture)
                                byte[] data = Encoding.UTF8.GetBytes("id: " + entry.Event.UnixTimestamp.ToString().Replace(",", ".") +
                                                                     "\ndata: " + MigService.JsonSerialize(entry.Event) + "\n\n");
                                response.OutputStream.Write(data, 0, data.Length);
                                //response.OutputStream.Flush();
                                lastTimeStamp = entry.Timestamp;
                            }
                            catch (Exception e)
                            {
                                MigService.Log.Info(new MigEvent(this.GetName(), remoteAddress, "HTTP", request.HttpMethod,
                                                                 $"{response.StatusCode} {request.RawUrl} [ERROR: {e.Message}]"));
                                connected = false;
                                break;
                            }
                        }

                        Thread.Sleep(100);
                    }

                    // there might be new data after sending
                } while (connected && bufferedData.Count > 0);

                // check if the remote end point is still alive every 15 seconds or so
                if (timeoutWatch.Elapsed.TotalSeconds > 15)
                {
                    connected = connected && IsRemoteEndPointConnected(request.RemoteEndPoint);
                    timeoutWatch.Stop();
                    timeoutWatch = Stopwatch.StartNew();
                }
            }
        }
Exemple #19
0
        public static void Main(string[] args)
        {
            var    Log            = MigService.Log;
            string webServicePort = "8088";
            string webSocketPort  = "8181";

            string authUser  = "******";
            string authPass  = "******";
            string authRealm = "MIG Secure Zone";

            Log.Info("MigService test APP");
            Log.Info("URL: http://localhost:{0}", webServicePort);

            var migService = new MigService();

            // Add and configure the WebService gateway
            var web = (WebServiceGateway)migService.AddGateway(Gateways.WebServiceGateway);

            web.SetOption(WebServiceGatewayOptions.HomePath, "html");
            web.SetOption(WebServiceGatewayOptions.BaseUrl, "/pages/");
            // for deploying modern web app (eg. Angular 2 apps)
            web.SetOption(WebServiceGatewayOptions.UrlAliasPrefix, "app/*:app/index.html");
            web.SetOption(WebServiceGatewayOptions.Host, "*");
            web.SetOption(WebServiceGatewayOptions.Port, webServicePort);
            if (!String.IsNullOrEmpty(authUser) && !String.IsNullOrEmpty(authPass))
            {
                //web.SetOption(WebServiceGatewayOptions.Authentication, WebAuthenticationSchema.Basic);
                web.SetOption(WebServiceGatewayOptions.Authentication, WebAuthenticationSchema.Digest);
                web.SetOption(WebServiceGatewayOptions.AuthenticationRealm, authRealm);
                web.UserAuthenticationHandler += (sender, eventArgs) =>
                {
                    if (eventArgs.Username == authUser)
                    {
                        // WebServiceGateway requires password to be encrypted using the `Digest.CreatePassword(..)` method.
                        // This applies both to 'Digest' and 'Basic' authentication methods.
                        string password = Digest.CreatePassword(authUser, authRealm, authPass);
                        return(new User(authUser, authRealm, password));
                    }
                    return(null);
                };
            }
            web.SetOption(WebServiceGatewayOptions.EnableFileCaching, "False");

            // Add and configure the WebSocket gateway
            var ws = (WebSocketGateway)migService.AddGateway(Gateways.WebSocketGateway);

            ws.SetOption(WebSocketGatewayOptions.Port, webSocketPort);
            // WebSocketGateway access via authorization token
            ws.SetOption(WebSocketGatewayOptions.Authentication, WebAuthenticationSchema.Token);

            /*
             * if (!String.IsNullOrEmpty(authUser) && !String.IsNullOrEmpty(authPass))
             * {
             *  //ws.SetOption(WebSocketGatewayOptions.Authentication, WebAuthenticationSchema.Basic);
             *  ws.SetOption(WebSocketGatewayOptions.Authentication, WebAuthenticationSchema.Digest);
             *  ws.SetOption(WebSocketGatewayOptions.AuthenticationRealm, authRealm);
             *  ((WebSocketGateway) ws).UserAuthenticationHandler += (sender, eventArgs) =>
             *  {
             *      if (eventArgs.Username == authUser)
             *      {
             *          return new User(authUser, authRealm, authPass);
             *      }
             *      return null;
             *  };
             * }
             */

            migService.StartService();

            // API commands and events are exposed to all active gateways (WebService and WebSocket in this example)
            migService.RegisterApi("myapp/demo", (request) =>
            {
                Log.Debug("Received API call over {0}\n", request.Context.Source);
                Log.Debug("[Context data]\n{0}\n", request.Context.Data);
                Log.Debug("[Mig Command]\n{0}\n", MigService.JsonSerialize(request.Command, true));

                var cmd = request.Command;

                // cmd.Domain is the first element in the API URL (myapp)
                // cmd.Address is the second element in the API URL (demo)
                // cmd.Command is the third element in the API URL (greet | echo | ping)
                // cmd.GetOption(<n>) will give all the subsequent elements in the API URL (0...n)

                switch (cmd.Command)
                {
                case ApiCommands.Token:
                    // authorization token will expire in 5 seconds
                    var token = ws.GetAuthorizationToken(5);
                    return(new ResponseText(token.Value));

                case ApiCommands.Greet:
                    var name = cmd.GetOption(0);
                    migService.RaiseEvent(
                        typeof(MainClass),
                        cmd.Domain,
                        cmd.Address,
                        "Reply to Greet",
                        "Greet.User",
                        name
                        );
                    break;

                case ApiCommands.Echo:
                    string fullRequestPath = cmd.OriginalRequest;
                    migService.RaiseEvent(
                        typeof(MainClass),
                        cmd.Domain,
                        cmd.Address,
                        "Reply to Echo",
                        "Echo.Data",
                        fullRequestPath
                        );
                    break;

                case ApiCommands.Ping:
                    migService.RaiseEvent(
                        typeof(MainClass),
                        cmd.Domain,
                        cmd.Address,
                        "Reply to Ping",
                        "Ping.Reply",
                        "PONG"
                        );
                    break;
                }

                return(new ResponseStatus(Status.Ok));
            });

            while (true)
            {
                Thread.Sleep(5000);
            }
        }
Exemple #20
0
        public static void Main(string[] args)
        {
            string webPort = "8088";

            Console.WriteLine("MigService test APP");
            Console.WriteLine("URL: http://localhost:{0}", webPort);

            var migService = new MigService();

            // Add and configure the Web gateway
            var web = migService.AddGateway("WebServiceGateway");

            web.SetOption("HomePath", "html");
            web.SetOption("BaseUrl", "/pages/");
            web.SetOption("Host", "*");
            web.SetOption("Port", webPort);
            web.SetOption("Password", "");
            web.SetOption("EnableFileCaching", "False");

            // Add and configure the Web Socket gateway
            var ws = migService.AddGateway("WebSocketGateway");

            ws.SetOption("Port", "8181");

            migService.StartService();

            migService.RegisterApi("myapp/demo", (request) =>
            {
                Console.WriteLine("Received API call from source {0}\n", request.Context.Source);
                Console.WriteLine("[Context data]\n{0}\n", MigService.JsonSerialize(request.Context.Data, true));
                Console.WriteLine("[Mig Command]\n{0}\n", MigService.JsonSerialize(request.Command, true));

                var cmd = request.Command;

                // cmd.Domain is the first element in the API URL (myapp)
                // cmd.Address is the second element in the API URL (demo)
                // cmd.Command is the third element in the API URL (greet | echo | ping)
                // cmd.GetOption(<n>) will give all the subsequent elements in the API URL (0...n)

                switch (cmd.Command)
                {
                case "greet":
                    var name = cmd.GetOption(0);
                    migService.RaiseEvent(typeof(MainClass), cmd.Domain, cmd.Address, "Reply to Greet", "Greet.User", name);
                    break;

                case "echo":
                    string fullRequestPath = cmd.OriginalRequest;
                    migService.RaiseEvent(typeof(MainClass), cmd.Domain, cmd.Address, "Reply to Echo", "Echo.Data", fullRequestPath);
                    break;

                case "ping":
                    migService.RaiseEvent(typeof(MainClass), cmd.Domain, cmd.Address, "Reply to Ping", "Ping.Reply", "PONG");
                    break;
                }

                return(new ResponseStatus(Status.Ok));
            });

            while (true)
            {
                Thread.Sleep(10000);
            }
        }
Exemple #21
0
        public object InterfaceControl(MigInterfaceCommand request)
        {
            string response = ""; //default success value

            Commands command;

            Enum.TryParse <Commands>(request.Command.Replace(".", "_"), out command);

            switch (command)
            {
            case Commands.Remotes_Search:
                response = MigService.JsonSerialize(SearchRemotes(request.GetOption(0)));
                break;

            case Commands.Remotes_Add:
            {
                var remote = remotesData.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
                if (remote != null && remotesConfig.Find(r => r.Model.ToLower() == remote.Model.ToLower() && r.Manufacturer.ToLower() == remote.Manufacturer.ToLower()) == null)
                {
                    var    webClient = new WebClient();
                    string config    = webClient.DownloadString("http://lirc.sourceforge.net/remotes/" + remote.Manufacturer + "/" + remote.Model);
                    remote.Configuration = GetBytes(config);
                    remotesConfig.Add(remote);
                    SaveConfig();
                }
            }
            break;

            case Commands.Remotes_Remove:
            {
                var remote = remotesConfig.Find(r => r.Manufacturer.ToLower() == request.GetOption(0).ToLower() && r.Model.ToLower() == request.GetOption(1).ToLower());
                if (remote != null)
                {
                    remotesConfig.Remove(remote);
                    SaveConfig();
                }
            }
            break;

            case Commands.Remotes_List:
                response = MigService.JsonSerialize(remotesConfig);
                break;

            case Commands.Control_IrSend:
                string commands = "";
                int    c        = 0;
                while (request.GetOption(c) != "")
                {
                    var options = request.GetOption(c).Split('/');
                    foreach (string o in options)
                    {
                        commands += "\"" + o + "\" ";
                    }
                    c++;
                }
                MigService.ShellCommand("irsend", "SEND_ONCE " + commands);
                break;
            }

            return(response);
        }
Exemple #22
0
        public static void Main(string[] args)
        {
            string webPort = "8088";

            Console.WriteLine("MigService test APP");
            Console.WriteLine("URL: http://localhost:{0}", webPort);

            var migService = new MigService();

            // Add and configure the Web gateway
            var web = migService.AddGateway("WebServiceGateway");

            web.SetOption("HomePath", "html");
            web.SetOption("BaseUrl", "/pages/");
            web.SetOption("Host", "*");
            web.SetOption("Port", webPort);
            web.SetOption("Password", "");
            web.SetOption("EnableFileCaching", "False");

            // Add and configure the Web Socket gateway
            var ws = migService.AddGateway("WebSocketGateway");

            ws.SetOption("Port", "8181");

            // Configuration can also be loaded from a file as shown below

            /*
             * MigServiceConfiguration configuration;
             * // Construct an instance of the XmlSerializer with the type
             * // of object that is being deserialized.
             * XmlSerializer mySerializer = new XmlSerializer(typeof(MigServiceConfiguration));
             * // To read the file, create a FileStream.
             * FileStream myFileStream = new FileStream("systemconfig.xml", FileMode.Open);
             * // Call the Deserialize method and cast to the object type.
             * configuration = (MigServiceConfiguration)mySerializer.Deserialize(myFileStream);
             * // Set the configuration
             * migService.Configuration = configuration;
             */

            migService.StartService();

            // Enable some interfaces for testing...

            /*
             * var zwave = migService.AddInterface("HomeAutomation.ZWave", "MIG.HomeAutomation.dll");
             * zwave.SetOption("Port", "/dev/ttyUSB0");
             * migService.EnableInterface("HomeAutomation.ZWave");
             */

            /*
             * var upnp = migService.AddInterface("Protocols.UPnP", "MIG.Protocols.dll");
             * migService.EnableInterface("Protocols.UPnP");
             */

            migService.RegisterApi("myapp/demo", (request) =>
            {
                Console.WriteLine("Received API call from source {0}\n", request.Context.Source);
                Console.WriteLine("[Context data]\n{0}\n", MigService.JsonSerialize(request.Context.Data, true));
                Console.WriteLine("[Mig Command]\n{0}\n", MigService.JsonSerialize(request.Command, true));

                var cmd = request.Command;

                // cmd.Domain is the first element in the API URL (myapp)
                // cmd.Address is the second element in the API URL (demo)
                // cmd.Command is the third element in the API URL (greet | echo | ping)
                // cmd.GetOption(<n>) will give all the subsequent elements in the API URL (0...n)

                switch (cmd.Command)
                {
                case "greet":
                    var name = cmd.GetOption(0);
                    migService.RaiseEvent(typeof(MainClass), cmd.Domain, cmd.Address, "Reply to Greet", "Greet.User", name);
                    break;

                case "echo":
                    string fullRequestPath = cmd.OriginalRequest;
                    migService.RaiseEvent(typeof(MainClass), cmd.Domain, cmd.Address, "Reply to Echo", "Echo.Data", fullRequestPath);
                    break;

                case "ping":
                    migService.RaiseEvent(typeof(MainClass), cmd.Domain, cmd.Address, "Reply to Ping", "Ping.Reply", "PONG");
                    break;
                }

                return(new ResponseStatus(Status.Ok));
            });

            while (true)
            {
                Thread.Sleep(10000);
            }
        }
        private void Worker(object state)
        {
            HttpListenerRequest  request  = null;
            HttpListenerResponse response = null;

            try
            {
                var context = state as HttpListenerContext;
                //
                request  = context.Request;
                response = context.Response;
                //
                if (request.UserLanguages != null && request.UserLanguages.Length > 0)
                {
                    try
                    {
                        CultureInfo culture = CultureInfo.CreateSpecificCulture(request.UserLanguages[0].ToLowerInvariant().Trim());
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;
                    }
                    catch
                    {
                    }
                }
                //
                if (request.IsSecureConnection)
                {
                    var       clientCertificate = request.GetClientCertificate();
                    X509Chain chain             = new X509Chain();
                    chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                    chain.Build(clientCertificate);
                    if (chain.ChainStatus.Length != 0)
                    {
                        // Invalid certificate
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        response.OutputStream.Close();
                        return;
                    }
                }
                //
                response.Headers.Set(HttpResponseHeader.Server, "MIG WebService Gateway");
                response.KeepAlive = false;
                //
                bool   isAuthenticated = (request.Headers["Authorization"] != null);
                string remoteAddress   = request.RemoteEndPoint.Address.ToString();
                string logExtras       = "";
                //
                if (servicePassword == "" || isAuthenticated) //request.IsAuthenticated)
                {
                    bool verified = false;
                    //
                    string authUser = "";
                    string authPass = "";
                    //
                    //NOTE: context.User.Identity and request.IsAuthenticated
                    //aren't working under MONO with this code =/
                    //so we proceed by manually parsing Authorization header
                    //
                    //HttpListenerBasicIdentity identity = null;
                    //
                    if (isAuthenticated)
                    {
                        //identity = (HttpListenerBasicIdentity)context.User.Identity;
                        // authuser = identity.Name;
                        // authpass = identity.Password;
                        byte[] encodedDataAsBytes = System.Convert.FromBase64String(request.Headers["Authorization"].Split(' ')[1]);
                        string authtoken          = System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
                        authUser = authtoken.Split(':')[0];
                        authPass = authtoken.Split(':')[1];
                    }
                    //
                    //TODO: complete authorization (for now with one fixed user 'admin', add multiuser support)
                    //
                    if (servicePassword == "" || (authUser == serviceUsername && Utility.Encryption.SHA1.GenerateHashString(authPass) == servicePassword))
                    {
                        verified = true;
                    }
                    //
                    if (verified)
                    {
                        string url = request.RawUrl.TrimStart('/').TrimStart('\\').TrimStart('.');
                        if (url.IndexOf("?") > 0)
                        {
                            url = url.Substring(0, url.IndexOf("?"));
                        }
                        // Check if this url is an alias
                        url = UrlAliasCheck(url.TrimEnd('/'));
                        //
                        // url aliasing check
                        if (url == "" || url.TrimEnd('/') == baseUrl.TrimEnd('/'))
                        {
                            // default home redirect
                            response.Redirect("/" + baseUrl.TrimEnd('/') + "/index.html");
                            //TODO: find a solution for HG homepage redirect ---> ?" + new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds + "#page_control");
                            response.Close();
                        }
                        else
                        {
                            var connectionWatch = Stopwatch.StartNew();
                            MigService.Log.Info(new MigEvent(this.GetName(), remoteAddress, "HTTP", request.HttpMethod.ToString(), String.Format("{0} {1} [OPEN]", response.StatusCode, request.RawUrl)));
                            // this url is reserved for Server Sent Event stream
                            if (url.TrimEnd('/').Equals("events"))
                            {
                                // TODO: move all of this to a separate function
                                // Server sent events
                                // NOTE: no PreProcess or PostProcess events are fired in this case
                                //response.KeepAlive = true;
                                response.ContentEncoding = Encoding.UTF8;
                                response.ContentType     = "text/event-stream";
                                response.Headers.Set(HttpResponseHeader.CacheControl, "no-cache, no-store, must-revalidate");
                                response.Headers.Set(HttpResponseHeader.Pragma, "no-cache");
                                response.Headers.Set("Access-Control-Allow-Origin", "*");

                                // 2K padding for IE
                                var    padding     = ":" + new String(' ', 2048) + "\n";
                                byte[] paddingData = System.Text.Encoding.UTF8.GetBytes(padding);
                                response.OutputStream.Write(paddingData, 0, paddingData.Length);
                                byte[] retryData = System.Text.Encoding.UTF8.GetBytes("retry: 1000\n");
                                response.OutputStream.Write(retryData, 0, retryData.Length);

                                DateTime lastTimeStamp = DateTime.UtcNow;
                                var      lastId        = context.Request.Headers.Get("Last-Event-ID");
                                if (lastId == null || lastId == "")
                                {
                                    var queryValues = HttpUtility.ParseQueryString(context.Request.Url.Query);
                                    lastId = queryValues.Get("lastEventId");
                                }

                                if (lastId != null && lastId != "")
                                {
                                    double unixTimestamp = 0;
                                    double.TryParse(lastId, NumberStyles.Float | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out unixTimestamp);
                                    if (unixTimestamp != 0)
                                    {
                                        lastTimeStamp = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                                        lastTimeStamp.AddSeconds(Math.Round(unixTimestamp / 1000d));
                                    }
                                }

                                bool connected    = true;
                                var  timeoutWatch = Stopwatch.StartNew();
                                while (connected)
                                {
                                    // dirty work around for signaling new event and
                                    // avoiding locks on long socket timetout
                                    lock (sseEventToken)
                                        Monitor.Wait(sseEventToken, 1000);
                                    // safely dequeue events
                                    List <SseEvent> bufferedData;
                                    do
                                    {
                                        bufferedData = sseEventBuffer.FindAll(le => le != null && le.Timestamp.Ticks > lastTimeStamp.Ticks);
                                        if (bufferedData.Count > 0)
                                        {
                                            foreach (SseEvent entry in bufferedData)
                                            {
                                                // send events
                                                try
                                                {
                                                    // The following throws an error on some mono-arm (Input string was not in the correct format)
                                                    // entry.Event.UnixTimestamp.ToString("R", CultureInfo.InvariantCulture)
                                                    byte[] data = System.Text.Encoding.UTF8.GetBytes("id: " + entry.Event.UnixTimestamp.ToString().Replace(",", ".") + "\ndata: " + MigService.JsonSerialize(entry.Event) + "\n\n");
                                                    response.OutputStream.Write(data, 0, data.Length);
                                                    //response.OutputStream.Flush();
                                                    lastTimeStamp = entry.Timestamp;
                                                }
                                                catch (Exception e)
                                                {
                                                    MigService.Log.Info(new MigEvent(this.GetName(), remoteAddress, "HTTP", request.HttpMethod.ToString(), String.Format("{0} {1} [ERROR: {2}]", response.StatusCode, request.RawUrl, e.Message)));
                                                    connected = false;
                                                    break;
                                                }
                                            }
                                            Thread.Sleep(100);
                                        }
                                        // there might be new data after sending
                                    } while (connected && bufferedData.Count > 0);
                                    // check if the remote end point is still alive every 15 seconds or so
                                    if (timeoutWatch.Elapsed.TotalSeconds > 15)
                                    {
                                        connected = connected && IsRemoteEndPointConnected(request.RemoteEndPoint);
                                        timeoutWatch.Stop();
                                        timeoutWatch = Stopwatch.StartNew();
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    MigClientRequest migRequest = null;
                                    if (url.StartsWith("api/"))
                                    {
                                        string message    = url.Substring(url.IndexOf('/', 1) + 1);
                                        var    migContext = new MigContext(ContextSource.WebServiceGateway, context);
                                        migRequest = new MigClientRequest(migContext, new MigInterfaceCommand(message));
                                        // Disable HTTP caching
                                        response.Headers.Set(HttpResponseHeader.CacheControl, "no-cache, no-store, must-revalidate");
                                        response.Headers.Set(HttpResponseHeader.Pragma, "no-cache");
                                        response.Headers.Set(HttpResponseHeader.Expires, "0");
                                        // Store POST data (if any) in the migRequest.RequestData field
                                        migRequest.RequestData = WebServiceUtility.ReadToEnd(request.InputStream);
                                        migRequest.RequestText = request.ContentEncoding.GetString(migRequest.RequestData);
                                    }

                                    OnPreProcessRequest(migRequest);

                                    bool requestHandled = (migRequest != null && migRequest.Handled);
                                    if (requestHandled)
                                    {
                                        SendResponseObject(context, migRequest.ResponseData);
                                    }
                                    else if (url.StartsWith(baseUrl) || baseUrl.Equals("/"))
                                    {
                                        // If request begins <base_url>, process as standard Web request
                                        string requestedFile = GetWebFilePath(url);
                                        if (!System.IO.File.Exists(requestedFile))
                                        {
                                            response.StatusCode = (int)HttpStatusCode.NotFound;
                                            WebServiceUtility.WriteStringToContext(context, "<h1>404 - Not Found</h1>");
                                        }
                                        else
                                        {
                                            bool isText = false;
                                            if (url.ToLower().EndsWith(".js")) // || requestedurl.EndsWith(".json"))
                                            {
                                                response.ContentType = "text/javascript";
                                                isText = true;
                                            }
                                            else if (url.ToLower().EndsWith(".css"))
                                            {
                                                response.ContentType = "text/css";
                                                isText = true;
                                            }
                                            else if (url.ToLower().EndsWith(".zip"))
                                            {
                                                response.ContentType = "application/zip";
                                            }
                                            else if (url.ToLower().EndsWith(".png"))
                                            {
                                                response.ContentType = "image/png";
                                            }
                                            else if (url.ToLower().EndsWith(".jpg"))
                                            {
                                                response.ContentType = "image/jpeg";
                                            }
                                            else if (url.ToLower().EndsWith(".gif"))
                                            {
                                                response.ContentType = "image/gif";
                                            }
                                            else if (url.ToLower().EndsWith(".svg"))
                                            {
                                                response.ContentType = "image/svg+xml";
                                            }
                                            else if (url.ToLower().EndsWith(".mp3"))
                                            {
                                                response.ContentType = "audio/mp3";
                                            }
                                            else if (url.ToLower().EndsWith(".wav"))
                                            {
                                                response.ContentType = "audio/x-wav";
                                            }
                                            else if (url.ToLower().EndsWith(".appcache"))
                                            {
                                                response.ContentType = "text/cache-manifest";
                                            }
                                            else if (url.ToLower().EndsWith(".otf") || url.ToLower().EndsWith(".ttf") || url.ToLower().EndsWith(".woff") || url.ToLower().EndsWith(".woff2"))
                                            {
                                                response.ContentType = "application/octet-stream";
                                            }
                                            else if (url.ToLower().EndsWith(".xml"))
                                            {
                                                response.ContentType = "text/xml";
                                                isText = true;
                                            }
                                            else
                                            {
                                                response.ContentType = "text/html";
                                                isText = true;
                                            }

                                            var file = new System.IO.FileInfo(requestedFile);
                                            response.ContentLength64 = file.Length;

                                            bool modified = true;
                                            if (request.Headers.AllKeys.Contains("If-Modified-Since"))
                                            {
                                                var modifiedSince = DateTime.MinValue;
                                                DateTime.TryParse(request.Headers["If-Modified-Since"], out modifiedSince);
                                                if (file.LastWriteTime.ToUniversalTime().Equals(modifiedSince))
                                                {
                                                    modified = false;
                                                }
                                            }
                                            bool disableCacheControl = HttpCacheIgnoreCheck(url);
                                            if (!modified && !disableCacheControl)
                                            {
                                                // TODO: !IMPORTANT! exclude from caching files that contains SSI tags!
                                                response.StatusCode = (int)HttpStatusCode.NotModified;
                                                //!!DISABLED!! - The following line was preventing browser to load file from cache
                                                //response.Headers.Set(HttpResponseHeader.Date, file.LastWriteTimeUtc.ToString().Replace(",", "."));
                                            }
                                            else
                                            {
                                                response.Headers.Set(HttpResponseHeader.LastModified, file.LastWriteTimeUtc.ToString().Replace(",", "."));
                                                if (disableCacheControl)
                                                {
                                                    response.Headers.Set(HttpResponseHeader.CacheControl, "no-cache, no-store, must-revalidate");
                                                    response.Headers.Set(HttpResponseHeader.Pragma, "no-cache");
                                                    response.Headers.Set(HttpResponseHeader.Expires, "0");
                                                }
                                                else
                                                {
                                                    response.Headers.Set(HttpResponseHeader.CacheControl, "max-age=86400");
                                                }

                                                // PRE PROCESS text output
                                                if (isText)
                                                {
                                                    try
                                                    {
                                                        WebFile webFile = GetWebFile(requestedFile);
                                                        response.ContentEncoding = webFile.Encoding;
                                                        response.ContentType    += "; charset=" + webFile.Encoding.BodyName;
                                                        // We don't need to parse the content again if it's coming from the cache
                                                        if (!webFile.IsCached)
                                                        {
                                                            string body = webFile.Content;
                                                            if (requestedFile.EndsWith(".md"))
                                                            {
                                                                // Built-in Markdown files support
                                                                body = CommonMark.CommonMarkConverter.Convert(body);
                                                                // TODO: add a way to include HTML header and footer template to be appended to the
                                                                // TODO: translated markdown text
                                                            }
                                                            else
                                                            {
                                                                // HTML file
                                                                // replace prepocessor directives with values
                                                                bool tagFound;
                                                                do
                                                                {
                                                                    tagFound = false;
                                                                    int ts = body.IndexOf("{include ");
                                                                    if (ts >= 0)
                                                                    {
                                                                        int te = body.IndexOf("}", ts);
                                                                        if (te > ts)
                                                                        {
                                                                            string rs = body.Substring(ts + (te - ts) + 1);
                                                                            string cs = body.Substring(ts, te - ts + 1);
                                                                            string ls = body.Substring(0, ts);
                                                                            //
                                                                            try
                                                                            {
                                                                                if (cs.StartsWith("{include "))
                                                                                {
                                                                                    string fileName = cs.Substring(9).TrimEnd('}').Trim();
                                                                                    fileName = GetWebFilePath(fileName);
                                                                                    //
                                                                                    Encoding fileEncoding = DetectWebFileEncoding(fileName);
                                                                                    if (fileEncoding == null)
                                                                                    {
                                                                                        fileEncoding = defaultWebFileEncoding;
                                                                                    }
                                                                                    var incFile = System.IO.File.ReadAllText(fileName, fileEncoding) + rs;
                                                                                    body = ls + incFile;
                                                                                }
                                                                            }
                                                                            catch
                                                                            {
                                                                                body = ls + "<h5 style=\"color:red\">Error processing '" + cs.Replace("{", "[").Replace("}", "]") + "'</h5>" + rs;
                                                                            }
                                                                            tagFound = true;
                                                                        }
                                                                    }
                                                                } while (tagFound); // continue if a pre processor tag was found
                                                                // {hostos}
                                                                body = body.Replace("{hostos}", Environment.OSVersion.Platform.ToString());
                                                                // {filebase}
                                                                body = body.Replace("{filebase}", Path.GetFileNameWithoutExtension(requestedFile));
                                                            }
                                                            // update the cache content with parsing results
                                                            webFile.Content = body;
                                                        }
                                                        // Store the cache item if the file cache is enabled
                                                        if (enableFileCache)
                                                        {
                                                            UpdateWebFileCache(requestedFile, webFile.Content, response.ContentEncoding);
                                                        }
                                                        //
                                                        WebServiceUtility.WriteStringToContext(context, webFile.Content);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        // TODO: report internal mig interface  error
                                                        response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                                        WebServiceUtility.WriteStringToContext(context, ex.Message + "\n" + ex.StackTrace);
                                                        MigService.Log.Error(ex);
                                                    }
                                                }
                                                else
                                                {
                                                    WebServiceUtility.WriteBytesToContext(context, System.IO.File.ReadAllBytes(requestedFile));
                                                }
                                            }
                                        }
                                        requestHandled = true;
                                    }

                                    OnPostProcessRequest(migRequest);

                                    if (!requestHandled && migRequest != null && migRequest.Handled)
                                    {
                                        SendResponseObject(context, migRequest.ResponseData);
                                    }
                                    else if (!requestHandled)
                                    {
                                        response.StatusCode = (int)HttpStatusCode.NotFound;
                                        WebServiceUtility.WriteStringToContext(context, "<h1>404 - Not Found</h1>");
                                    }
                                }
                                catch (Exception eh)
                                {
                                    // TODO: add error logging
                                    Console.Error.WriteLine(eh);
                                }
                            }
                            connectionWatch.Stop();
                            logExtras = " [CLOSED AFTER " + Math.Round(connectionWatch.Elapsed.TotalSeconds, 3) + " seconds]";
                        }
                    }
                    else
                    {
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        // this will only work in Linux (mono)
                        //response.Headers.Set(HttpResponseHeader.WwwAuthenticate, "Basic");
                        // this works both on Linux and Windows
                        //response.AddHeader("WWW-Authenticate", "Basic");
                    }
                }
                else
                {
                    response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    // this will only work in Linux (mono)
                    //response.Headers.Set(HttpResponseHeader.WwwAuthenticate, "Basic");
                    // this works both on Linux and Windows
                    //response.AddHeader("WWW-Authenticate", "Basic");
                }
                MigService.Log.Info(new MigEvent(this.GetName(), remoteAddress, "HTTP", request.HttpMethod.ToString(), String.Format("{0} {1}{2}", response.StatusCode, request.RawUrl, logExtras)));
            }
            catch (Exception ex)
            {
                MigService.Log.Error(ex);
            }
            finally
            {
                //
                // CleanUp/Dispose allocated resources
                //
                try { request.InputStream.Close(); } catch {
                    // TODO: add logging
                }
                try { response.OutputStream.Close(); } catch {
                    // TODO: add logging
                }
                try { response.Close(); } catch {
                    // TODO: add logging
                }
                try { response.Abort(); } catch {
                    // TODO: add logging
                }
            }
        }