Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="waitTime">Time to wait in milliseconds for a frame to be available.</param>
        /// <returns></returns>
        public byte[] GetLatestImage(string id, int waitTime = 5000)
        {
            if (waitTime < 0)
            {
                waitTime = 0;
            }
            if (waitTime > 60000)
            {
                waitTime = 60000;
            }
            waitTime = waitTime / 20;
            IPCameraBase cam = GetCameraById(id);

            if (cam == null || cam.cameraSpec.type == CameraType.h264_rtsp_proxy)
            {
                return(new byte[0]);
            }
            lock (this)
            {
                if (!cam.isRunning)
                {
                    cam.Start();
                }
            }
            int timesWaited = 0;

            byte[] frame = cam.LastFrame;
            while (frame.Length == 0 && timesWaited++ < waitTime)
            {
                Thread.Sleep(20);
                frame = cam.LastFrame;
            }
            return(frame);
        }
Пример #2
0
        public int GetCameraDelayBetweenImageGrabs(string id)
        {
            IPCameraBase cam = GetCameraById(id);

            if (cam == null)
            {
                return(0);
            }
            return(cam.cameraSpec.delayBetweenImageGrabs);
        }
Пример #3
0
        /// <summary>
        /// Returns the minimum permission level required to view the specified camera (0 to 100).  Returns 101 if the camera is null.
        /// </summary>
        /// <param name="cameraId">The camera ID string.</param>
        /// <returns></returns>
        public int GetMinPermissionLevel(string cameraId)
        {
            IPCameraBase cam = GetCameraById(cameraId);

            if (cam == null)
            {
                return(101);
            }
            return(cam.cameraSpec.minPermissionLevel);
        }
Пример #4
0
        public static IPCameraBase CreateCamera(CameraSpec cs)
        {
            IPCameraBase cam = null;

            switch (cs.type)
            {
            case CameraType.jpg:
                cam = new JpegRefreshCamera();
                break;

            case CameraType.mjpg:
                cam = new MJpegCamera();
                break;

            case CameraType.h264_rtsp_proxy:
                // h264_rtsp_proxy cameras do not support jpeg output - only stream reflection via live555ProxyServer
                cam = new H264Camera();
                break;

            case CameraType.vlc_transcode:
                // VlcCamera does support jpeg output, but not stream reflection
                cam = new VlcCamera();
                break;

            case CameraType.vlc_transcode_to_html5:
                // Html5Camera does not support jpeg output - only streaming via VLC's http server.
                cam = new Html5VideoCamera();
                break;

            default:
                break;
            }
            if (cam != null)
            {
                cam.cameraSpec = cs;
                if (cs.ptzType == PtzType.Dahua)
                {
                    MJpegCameraProxy.PanTiltZoom.AdvPtz.AssignPtzObj(cs);
                }
                else if (cs.ptzType == PtzType.Hikvision)
                {
                    MJpegCameraProxy.PanTiltZoom.AdvPtz.AssignPtzObj(cs);
                }
            }
            return(cam);
        }
Пример #5
0
        private IPCameraBase GetCameraById(string id)
        {
            if (id == null)
            {
                return(null);
            }
            id = id.ToLower();

            IPCameraBase cam;

            // Try to get the camera reference.
            if (!cameras.TryGetValue(id, out cam))
            {
                // Camera object has not been created yet
                CameraSpec cs = MJpegWrapper.cfg.GetCameraSpec(id);
                if (cs != null && cs.enabled)
                {
                    // We have a definition for it.
                    cam = IPCameraBase.CreateCamera(cs);
                    if (cam == null)
                    {
                        return(null);
                    }
                    if (cameras.TryAdd(id, cam))
                    {
                        // Camera just got added
                    }
                    else
                    {
                        // Camera was added by another thread
                        if (!cameras.TryGetValue(id, out cam))
                        {
                            return(null);                            // And yet it doesn't exist. Fail.
                        }
                    }
                }
                else
                {
                    // Camera has not been created yet, and we have no definition for it.
                    return(null);
                }
            }
            return(cam);
        }
Пример #6
0
        public string GetRTSPUrl(string id, SimpleHttp.HttpProcessor p)
        {
            IPCameraBase cam = GetCameraById(id);

            if (cam == null || cam.cameraSpec.type != CameraType.h264_rtsp_proxy)
            {
                return("");
            }
            cam.ImageLastViewed = DateTime.Now;
            if (!cam.isRunning)
            {
                cam.Start();
                int timesWaited = 0;
                Thread.Sleep(50);
                while (timesWaited++ < 50)
                {
                    Thread.Sleep(20);
                }
                cam.ImageLastViewed = DateTime.Now;
            }
            H264Camera h264cam = (H264Camera)cam;

            return("rtsp://" + h264cam.access_username + ":" + h264cam.access_password + "@$$$HOST$$$:" + cam.cameraSpec.h264_port + "/proxyStream");
        }
Пример #7
0
        public static string GetHtml(string camId, IPCameraBase cam)
        {
            if (cam == null)
            {
                return("");
            }

            if (cam.cameraSpec.ptzType == PtzType.LoftekCheap)
            {
                return(LoftekCheapPTZ.GetHtml(camId));
            }
            //else if (cam.cameraSpec.ptzType == PtzType.Dahua)
            //	return DahuaPTZ.GetHtml(camId, cam);
            else if (cam.cameraSpec.ptzType == PtzType.WanscamCheap)
            {
                return(WanscamCheapPTZ.GetHtml(camId));
            }
            //else if (cam.cameraSpec.ptzType == PtzType.TrendnetIP672)
            //	return IP672SeriesPTZ.GetHtml(camId, cam);
            else
            {
                return(PanTiltZoom.PtzController.GetHtml(camId, cam));
            }
        }
Пример #8
0
        public static void RunCommand(IPCameraBase ipCam, string cam, string command)
        {
            try
            {
                int preset_number = 0;
                if (ipCam == null)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(cam))
                {
                    cam = cam.ToLower();
                }
                string      cmdEnd      = "";
                int         duration    = 500;
                CommandType commandType = CommandType.decoder_control;
                #region Commands
                if (command.StartsWith("q"))
                {
                    commandType = CommandType.camera_control;
                    if (command == "q1")
                    {
                        command = "param=0&value=2";
                    }
                    else if (command == "q1.5")
                    {
                        command = "param=0&value=4";
                    }
                    else if (command == "q2")
                    {
                        command = "param=0&value=8";
                    }
                    else if (command == "q2.5")
                    {
                        command = "param=0&value=16";
                    }
                    else if (command == "q3")
                    {
                        command = "param=0&value=32";
                    }
                    else
                    {
                        return;
                    }
                }
                else if (command == "2")                 // UP
                {
                    cmdEnd   = "1";
                    duration = 200;
                }
                else if (command == "0")                 // DOWN
                {
                    cmdEnd   = "3";
                    duration = 200;
                }
                else if (command == "6")                 // LEFT
                {
                    cmdEnd   = "5";
                    duration = 500;
                }
                else if (command == "4")                 // RIGHT
                {
                    cmdEnd   = "7";
                    duration = 500;
                }
                else if (command == "18")                 // ZOOM OUT
                {
                    commandType = CommandType.camera_control;
                    command     = "param=18&value=1";
                    cmdEnd      = "param=18&value=0";
                    duration    = 1500;
                }
                else if (command == "17")                 // ZOOM IN
                {
                    commandType = CommandType.camera_control;
                    command     = "param=17&value=1";
                    cmdEnd      = "param=17&value=0";
                    duration    = 1500;
                }
                else if (command == "116")                 // ZOOM OUT FINE
                {
                    commandType = CommandType.camera_control;
                    command     = "param=18&value=1";
                    cmdEnd      = "param=18&value=0";
                    duration    = 500;
                }
                else if (command == "118")                 // ZOOM IN FINE
                {
                    commandType = CommandType.camera_control;
                    command     = "param=17&value=1";
                    cmdEnd      = "param=17&value=0";
                    duration    = 500;
                }
                else if (command == "1116")                 // ZOOM OUT FINER
                {
                    commandType = CommandType.camera_control;
                    command     = "param=18&value=1";
                    cmdEnd      = "param=18&value=0";
                    duration    = 100;
                }
                else if (command == "1118")                 // ZOOM IN FINER
                {
                    commandType = CommandType.camera_control;
                    command     = "param=17&value=1";
                    cmdEnd      = "param=17&value=0";
                    duration    = 100;
                }
                else if (command == "30" || command == "31" ||              // Preset 1 - Mark / Recall
                         command == "32" || command == "33" ||                // 2
                         command == "34" || command == "35" ||                // 3
                         command == "36" || command == "37" ||                // 4
                         command == "38" || command == "39" ||                // 5
                         command == "40" || command == "41" ||                // 6
                         command == "42" || command == "43" ||                // 7
                         command == "44" || command == "45"                   // 8
                         )
                {
                    int cmdNum = int.Parse(command);
                    if (cmdNum % 2 == 0)
                    {
                        preset_number = (cmdNum - 28) / 2;
                    }
                }
                else
                {
                    return;                     // Invalid Command
                }
                #endregion

                string auth = "&loginuse=" + ipCam.cameraSpec.ptz_username + "&loginpas="******"http://" + ipCam.cameraSpec.ptz_hostName + "/decoder_control.cgi?command=" + command + auth);
                    if (cmdEnd != "")
                    {
                        Thread.Sleep(duration);
                        SimpleProxy.GetData("http://" + ipCam.cameraSpec.ptz_hostName + "/decoder_control.cgi?command=" + cmdEnd + auth);
                    }
                }
                else if (commandType == CommandType.camera_control)
                {
                    SimpleProxy.GetData("http://" + ipCam.cameraSpec.ptz_hostName + "/camera_control.cgi?" + command + auth);
                    if (cmdEnd != "")
                    {
                        Thread.Sleep(duration);
                        SimpleProxy.GetData("http://" + ipCam.cameraSpec.ptz_hostName + "/camera_control.cgi?" + cmdEnd + auth);
                    }
                }
                if (preset_number > 0)
                {
                    try
                    {
                        byte[] image = MJpegServer.cm.GetLatestImage(cam);
                        if (image.Length > 0)
                        {
                            Util.WriteImageThumbnailToFile(image, CameraProxyGlobals.ThumbsDirectoryBase + cam.ToLower() + preset_number + ".jpg");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
        }
Пример #9
0
        public override void handleGETRequest(HttpProcessor p)
        {
            try
            {
                string requestedPage = Uri.UnescapeDataString(p.request_url.AbsolutePath.TrimStart('/'));

                if (requestedPage == "admin")
                {
                    p.writeRedirect("admin/main");
                    return;
                }

                if (requestedPage == "login")
                {
                    LogOutUser(p, null);
                    return;
                }

                Session s = sm.GetSession(p.requestCookies.GetValue("cps"), p.requestCookies.GetValue("auth"), p.GetParam("rawauth"));
                if (s.sid != null && s.sid.Length == 16)
                {
                    p.responseCookies.Add("cps", s.sid, TimeSpan.FromMinutes(s.sessionLengthMinutes));
                }

                if (requestedPage == "logout")
                {
                    LogOutUser(p, s);
                    return;
                }


                if (requestedPage.StartsWith("admin/"))
                {
                    string adminPage = requestedPage == "admin" ? "" : requestedPage.Substring("admin/".Length);
                    if (string.IsNullOrWhiteSpace(adminPage))
                    {
                        adminPage = "main";
                    }
                    int idxQueryStringStart = adminPage.IndexOf('?');
                    if (idxQueryStringStart == -1)
                    {
                        idxQueryStringStart = adminPage.Length;
                    }
                    adminPage = adminPage.Substring(0, idxQueryStringStart);
                    Pages.Admin.AdminPage.HandleRequest(adminPage, p, s);
                    return;
                }
                else if (requestedPage.StartsWith("image/"))
                {
                    requestedPage = requestedPage.Substring("image/".Length);
                    #region image/
                    if (requestedPage.EndsWith(".jpg") || requestedPage.EndsWith(".jpeg") || requestedPage.EndsWith(".png") || requestedPage.EndsWith(".webp"))
                    {
                        int    extensionLength = requestedPage[requestedPage.Length - 4] == '.' ? 4 : 5;
                        string format          = requestedPage.Substring(requestedPage.Length - (extensionLength - 1));
                        string cameraId        = requestedPage.Substring(0, requestedPage.Length - extensionLength);
                        cameraId = cameraId.ToLower();

                        int minPermission = cm.GetCameraMinPermission(cameraId);
                        if (minPermission == 101)
                        {
                            p.writeFailure();
                            return;
                        }
                        if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission))
                        {
                            LogOutUser(p, s);
                            return;
                        }
                        int          wait        = p.GetIntParam("wait", 5000);
                        IPCameraBase cam         = cm.GetCamera(cameraId);
                        byte[]       latestImage = cm.GetLatestImage(cameraId, wait);
                        int          patience    = p.GetIntParam("patience");
                        if (patience > 0)
                        {
                            if (patience > 5000)
                            {
                                patience = 5000;
                            }

                            int timeLeft = patience;
                            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
                            timer.Start();
                            while (s.DuplicateImageSendCheck(cameraId, latestImage) && cam != null && timeLeft > 0)
                            {
                                // The latest image was already sent to the user in a previous image request.
                                // Wait for up to 5 seconds as desired by the user to get a "new" image.
                                cam.newFrameWaitHandle.WaitOne(Math.Max(50, timeLeft));                                  // This EventWaitHandle nonsense isn't perfect, so this should prevent excessively long delays in the event of a timing error.
                                latestImage = cm.GetLatestImage(cameraId);
                                timeLeft    = patience - (int)timer.ElapsedMilliseconds;
                            }
                        }
                        if (latestImage.Length == 0)
                        {
                            p.writeFailure("502 Bad Gateway");
                            return;
                        }
                        ImageFormat imgFormat = ImageFormat.Jpeg;
                        latestImage = ImageConverter.HandleRequestedConversionIfAny(latestImage, p, ref imgFormat, format);
                        p.tcpClient.SendBufferSize = latestImage.Length + 256;
                        p.writeSuccess(Util.GetMime(imgFormat), latestImage.Length);
                        p.outputStream.Flush();
                        p.rawOutputStream.Write(latestImage, 0, latestImage.Length);
                    }
                    else if (requestedPage.EndsWith(".mjpg"))
                    {
                        string cameraId = requestedPage.Substring(0, requestedPage.Length - 5);
                        cameraId = cameraId.ToLower();
                        int minPermission = cm.GetCameraMinPermission(cameraId);
                        if (minPermission == 101)
                        {
                            p.writeFailure();
                            return;
                        }
                        if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission))
                        {
                            LogOutUser(p, s);
                            return;
                        }
                        if (cm.GetLatestImage(cameraId).Length == 0)
                        {
                            return;
                        }
                        // Increasing the send buffer size here does not help streaming fluidity.
                        p.writeSuccess("multipart/x-mixed-replace;boundary=ipcamera");
                        byte[] newImage;
                        byte[] lastImage = null;
                        while (!this.stopRequested)
                        {
                            try
                            {
                                newImage = cm.GetLatestImage(cameraId);
                                while (newImage == lastImage)
                                {
                                    Thread.Sleep(1);
                                    newImage = cm.GetLatestImage(cameraId);
                                    if (this.stopRequested)
                                    {
                                        return;
                                    }
                                }
                                lastImage = newImage;

                                ImageFormat imgFormat = ImageFormat.Jpeg;
                                byte[]      sendImage = ImageConverter.HandleRequestedConversionIfAny(newImage, p, ref imgFormat);

                                p.outputStream.WriteLine("--ipcamera");
                                p.outputStream.WriteLine("Content-Type: " + Util.GetMime(imgFormat));
                                p.outputStream.WriteLine("Content-Length: " + sendImage.Length);
                                p.outputStream.WriteLine();
                                p.outputStream.Flush();
                                p.rawOutputStream.Write(sendImage, 0, sendImage.Length);
                                p.rawOutputStream.Flush();
                                p.outputStream.WriteLine();
                            }
                            catch (Exception ex)
                            {
                                if (!p.isOrdinaryDisconnectException(ex))
                                {
                                    Logger.Debug(ex);
                                }
                                break;
                            }
                        }
                    }
                    else if (requestedPage.EndsWith(".ogg"))
                    {
                        string cameraId = requestedPage.Substring(0, requestedPage.Length - 4);
                        cameraId = cameraId.ToLower();
                        int minPermission = cm.GetCameraMinPermission(cameraId);
                        if (minPermission == 101)
                        {
                            p.writeFailure();
                            return;
                        }
                        if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission))
                        {
                            LogOutUser(p, s);
                            return;
                        }
                        IPCameraBase _cam = cm.GetCamera(cameraId);
                        if (_cam is Html5VideoCamera)
                        {
                            Html5VideoCamera         cam            = (Html5VideoCamera)_cam;
                            ConcurrentQueue <byte[]> myDataListener = new ConcurrentQueue <byte[]>();
                            try
                            {
                                cam.RegisterStreamListener(myDataListener);
                                p.writeSuccess("application/octet-stream");
                                p.outputStream.Flush();
                                byte[] outputBuffer;
                                int    chunkCount = 0;
                                while (!this.stopRequested)
                                {
                                    try
                                    {
                                        chunkCount = myDataListener.Count;
                                        if (chunkCount > 100)
                                        {
                                            return;                                             // This connection is falling too far behind.  End it.
                                        }
                                        else if (chunkCount > 0)
                                        {
                                            Console.Write(chunkCount + " ");
                                            if (myDataListener.TryDequeue(out outputBuffer))
                                            {
                                                p.rawOutputStream.Write(outputBuffer, 0, outputBuffer.Length);
                                                p.rawOutputStream.Flush();
                                            }
                                        }
                                        else
                                        {
                                            Thread.Sleep(1);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        if (!p.isOrdinaryDisconnectException(ex))
                                        {
                                            Logger.Debug(ex);
                                        }
                                        break;
                                    }
                                }
                            }
                            finally
                            {
                                cam.UnregisterStreamListener(myDataListener);
                            }
                        }
                        else
                        {
                            p.writeFailure("501 Not Implemented");
                        }
                    }
                    else if (requestedPage.EndsWith(".cam"))
                    {
                        string cameraId = requestedPage.Substring(0, requestedPage.Length - 4);
                        cameraId = cameraId.ToLower();
                        int minPermission = cm.GetCameraMinPermission(cameraId);
                        if (minPermission == 101)
                        {
                            p.writeFailure();
                            return;
                        }
                        if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission))
                        {
                            LogOutUser(p, s);
                            return;
                        }
                        IPCameraBase cam = cm.GetCamera(cameraId);
                        if (cam != null && cam.cameraSpec.ptzType == MJpegCameraProxy.Configuration.PtzType.Dahua || cam.cameraSpec.ptzType == MJpegCameraProxy.Configuration.PtzType.Hikvision)
                        {
                            p.writeRedirect("../Camera.html?cam=" + cameraId);
                            return;
                        }

                        string userAgent = p.GetHeaderValue("User-Agent", "");
                        bool   isMobile  = userAgent.Contains("iPad") || userAgent.Contains("iPhone") || userAgent.Contains("Android") || userAgent.Contains("BlackBerry");

                        bool   isLanConnection = p == null ? false : p.IsLanConnection;
                        int    defaultRefresh  = isLanConnection && !isMobile ? -1 : 250;
                        string html            = CamPage.GetHtml(cameraId, !isMobile, p.GetIntParam("refresh", defaultRefresh), p.GetBoolParam("override") ? -1 : 600000, p);
                        if (string.IsNullOrEmpty(html) || html == "NO")
                        {
                            p.writeFailure();
                            return;
                        }
                        p.writeSuccess("text/html");
                        p.outputStream.Write(html);
                    }
                    else if (requestedPage == "PTZPRESETIMG")
                    {
                        string cameraId = p.GetParam("id");
                        cameraId = cameraId.ToLower();
                        IPCameraBase cam = cm.GetCamera(cameraId);
                        if (cam != null)
                        {
                            int index = p.GetIntParam("index", -1);
                            if (index > -1)
                            {
                                if (cam.cameraSpec.ptz_proxy)
                                {
                                    string auth = (!string.IsNullOrEmpty(cam.cameraSpec.ptz_username) && !string.IsNullOrEmpty(cam.cameraSpec.ptz_password)) ? "rawauth=" + HttpUtility.UrlEncode(cam.cameraSpec.ptz_username) + ":" + HttpUtility.UrlEncode(cam.cameraSpec.ptz_password) + "&" : "";
                                    byte[] data = SimpleProxy.GetData("http://" + cam.cameraSpec.ptz_hostName + "/PTZPRESETIMG?" + auth + "id=" + HttpUtility.UrlEncode(cam.cameraSpec.ptz_proxy_cameraId) + "&index=" + index);
                                    if (data.Length > 0)
                                    {
                                        p.writeSuccess("image/jpg", data.Length);
                                        p.outputStream.Flush();
                                        p.rawOutputStream.Write(data, 0, data.Length);
                                        return;
                                    }
                                }
                                else
                                {
                                    string fileName      = Globals.ThumbsDirectoryBase + cameraId + index + ".jpg";
                                    int    minPermission = cm.GetCameraMinPermission(cameraId);
                                    if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission) || minPermission == 101)
                                    {
                                    }
                                    else
                                    {
                                        if (File.Exists(fileName))
                                        {
                                            byte[] bytes = File.ReadAllBytes(fileName);
                                            p.writeSuccess("image/jpg", bytes.Length);
                                            p.outputStream.Flush();
                                            p.rawOutputStream.Write(bytes, 0, bytes.Length);
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                        {                         // Failed to get image thumbnail
                            byte[] bytes = File.ReadAllBytes(Globals.WWWPublicDirectoryBase + "Images/qmark.png");
                            p.writeSuccess("image/png", bytes.Length);
                            p.outputStream.Flush();
                            p.rawOutputStream.Write(bytes, 0, bytes.Length);
                            return;
                        }
                    }
                    else if (requestedPage.EndsWith(".wanscamstream"))
                    {
                        string       cameraId = requestedPage.Substring(0, requestedPage.Length - ".wanscamstream".Length);
                        IPCameraBase cam      = cm.GetCamera(cameraId);
                        if (cam == null)
                        {
                            return;
                        }
                        if (!cam.cameraSpec.wanscamCompatibilityMode)
                        {
                            return;
                        }
                        if (p.RemoteIPAddress != "127.0.0.1")
                        {
                            return;
                        }
                        Uri    url  = new Uri(cam.cameraSpec.imageryUrl);
                        string host = url.Host;
                        int    port = url.Port;
                        string path = url.PathAndQuery;
                        //string path = "/livestream.cgi?user=admin&pwd=nooilwell&streamid=0&audio=0&filename=";
                        //string path = "/videostream.cgi?user=admin&pwd=nooilwell&resolution=8";
                        int total = 0;
                        try
                        {
                            //Console.WriteLine("opening");
                            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            socket.Connect(host, port);
                            byte[] buffer = new byte[4096];
                            socket.Send(UTF8Encoding.UTF8.GetBytes("GET " + path + " HTTP/1.1\r\nHost: " + host + ":" + port + "\r\nConnection: close\r\n\r\n"));
                            //Console.WriteLine("open");
                            int read = socket.Receive(buffer);
                            p.writeSuccess("video/raw");
                            p.outputStream.Flush();
                            while (read > 0 && socket.Connected && p.tcpClient.Connected)
                            {
                                p.rawOutputStream.Write(buffer, 0, read);
                                total += read;
                                //Console.WriteLine(read);
                                read = socket.Receive(buffer);
                            }
                            //Console.WriteLine("close");
                        }
                        catch (Exception ex)
                        {
                            if (!p.isOrdinaryDisconnectException(ex))
                            {
                                Logger.Debug(ex);
                            }
                        }
                    }
                    #endregion
                }
                else if (requestedPage.StartsWith("control/"))
                {
                    requestedPage = requestedPage.Substring("control/".Length);
                    #region control/
                    if (requestedPage == "keepalive")
                    {
                        string cameraId = p.GetParam("id");
                        cameraId = cameraId.ToLower();
                        int minPermission = cm.GetCameraMinPermission(cameraId);
                        if (minPermission == 101)
                        {
                            p.writeFailure();
                            return;
                        }
                        if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission))
                        {
                            p.writeFailure("403 Forbidden");
                            return;
                        }
                        cm.GetRTSPUrl(cameraId, p);
                        p.writeSuccess("text/plain");
                        p.outputStream.Write("1");
                    }

                    else if (requestedPage == "PTZ")
                    {
                        string cameraId = p.GetParam("id");
                        cameraId = cameraId.ToLower();
                        int minPermission = cm.GetCameraMinPermission(cameraId);
                        if (minPermission == 101)
                        {
                            p.writeFailure();
                            return;
                        }
                        if ((s == null && minPermission > 0) || (s != null && s.permission < minPermission))
                        {
                            LogOutUser(p, s);
                            return;
                        }
                        PTZ.RunCommand(cameraId, p.GetParam("cmd"));
                        p.writeSuccess("text/plain");
                    }
                    #endregion
                }
                else
                {
                    #region www
                    int permissionRequired;
                    if (!Util.TryGetValue(requestedPage.ToLower(), MJpegWrapper.cfg.GetWwwFilesList(), out permissionRequired))
                    {
                        permissionRequired = -1;
                    }


                    string wwwDirectory = permissionRequired == -1 ? Globals.WWWPublicDirectoryBase : Globals.WWWDirectoryBase;

                    if (permissionRequired < 0)
                    {
                        permissionRequired = 0;
                    }
                    else if (permissionRequired > 100)
                    {
                        permissionRequired = 100;
                    }

                    if (permissionRequired > s.permission)
                    {
                        LogOutUser(p, s);
                        return;
                    }

                    DirectoryInfo WWWDirectory     = new DirectoryInfo(wwwDirectory);
                    string        wwwDirectoryBase = WWWDirectory.FullName.Replace('\\', '/').TrimEnd('/') + '/';
                    FileInfo      fi             = new FileInfo(wwwDirectoryBase + requestedPage);
                    string        targetFilePath = fi.FullName.Replace('\\', '/');
                    if (!targetFilePath.StartsWith(wwwDirectoryBase) || targetFilePath.Contains("../"))
                    {
                        p.writeFailure("400 Bad Request");
                        return;
                    }
                    if (!fi.Exists)
                    {
                        p.writeFailure();
                        return;
                    }

                    // && (fi.Extension == ".html" || fi.Extension == ".htm")
                    if (fi.Name.ToLower() == "camera.html" && fi.Length < 256000)
                    {
                        p.writeSuccess(Mime.GetMimeType(fi.Extension));
                        string   html = File.ReadAllText(fi.FullName);
                        CamPage2 cp   = new CamPage2(html, p);
                        html = cp.Html;
                        html = html.Replace("%ALLCAMS%", string.Join(",", MJpegServer.cm.GenerateAllCameraIdList()));
                        html = html.Replace("%ALLCAMS_IDS_NAMES_JS_ARRAY%", MJpegServer.cm.GenerateAllCameraIdNameList(s == null ? 0 : s.permission));
                        try
                        {
                            html = html.Replace("%REMOTEIP%", p.RemoteIPAddress);
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex);
                        }
                        p.outputStream.Write(html);
                        p.outputStream.Flush();
                    }
                    else if ((fi.Extension == ".html" || fi.Extension == ".htm") && fi.Length < 256000)
                    {
                        p.writeSuccess(Mime.GetMimeType(fi.Extension));
                        string html = File.ReadAllText(fi.FullName);
                        html = html.Replace("%ALLCAMS%", string.Join(",", MJpegServer.cm.GenerateAllCameraIdList()));
                        html = html.Replace("%ALLCAMS_IDS_NAMES_JS_ARRAY%", MJpegServer.cm.GenerateAllCameraIdNameList(s == null ? 0 : s.permission));
                        try
                        {
                            html = html.Replace("%REMOTEIP%", p.RemoteIPAddress);
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex);
                        }
                        p.outputStream.Write(html);
                        p.outputStream.Flush();
                    }
                    else
                    {
                        List <KeyValuePair <string, string> > additionalHeaders = new List <KeyValuePair <string, string> >();
                        additionalHeaders.Add(new KeyValuePair <string, string>("Cache-Control", "max-age=3600, public"));
                        p.writeSuccess(Mime.GetMimeType(fi.Extension), additionalHeaders: additionalHeaders);
                        p.outputStream.Flush();
                        using (FileStream fs = fi.OpenRead())
                        {
                            fs.CopyTo(p.rawOutputStream);
                        }
                        p.rawOutputStream.Flush();
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                if (!p.isOrdinaryDisconnectException(ex))
                {
                    Logger.Debug(ex);
                }
            }
        }
Пример #10
0
        public CamPage2(string html, SimpleHttp.HttpProcessor p)
        {
            // Set the parameters so the eval statements later can access them.
            cameraId = p.GetParam("cam");
            IPCameraBase cam = MJpegServer.cm.GetCameraAndGetItRunning(cameraId);

            if (cam == null)
            {
                Html = "The specified camera is not available.";
                return;
            }
            disableRefreshAfter = p.GetIntParam("override", 600000);
            string userAgent       = p.GetHeaderValue("User-Agent", "");
            bool   isMobile        = userAgent.Contains("iPad") || userAgent.Contains("iPhone") || userAgent.Contains("Android") || userAgent.Contains("BlackBerry");
            bool   isLanConnection = p == null ? false : p.IsLanConnection;
            int    defaultRefresh  = isLanConnection && !isMobile ? 0 : 250;

            refreshDelay = p.GetIntParam("refresh", defaultRefresh);
            cameraName   = cam.cameraSpec.name;
            if (cam.cameraSpec.type == CameraType.h264_rtsp_proxy)
            {
                bool sizeOverridden = cam.cameraSpec.h264_video_width > 0 && cam.cameraSpec.h264_video_height > 0;
                originWidth  = sizeOverridden ? cam.cameraSpec.h264_video_width : 640;
                originHeight = sizeOverridden ? cam.cameraSpec.h264_video_height : 360;
            }
            else
            {
                for (int i = 0; i < 50; i++)
                {
                    if (cam.ImageSize.Width != 0 && cam.ImageSize.Height != 0)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
                if (cam.ImageSize.Width == 0 || cam.ImageSize.Height == 0)
                {
                    Html = @"<!DOCTYPE HTML>
						<html>
						<head>
							<title>"                             + HttpUtility.HtmlEncode(cam.cameraSpec.name) + @"</title>
						</head>
						<body>
						This camera is starting up.<br/>
						Please <a href=""javascript:top.location.reload();"">try again in a few moments</a>.
						</body>
						</html>"                        ;
                    return;
                }
                originWidth  = cam.ImageSize.Width;
                originHeight = cam.ImageSize.Height;
            }
            webSocketUrl = "ws" + (p.secure_https ? "s" : "") + "://\" + location.hostname + \":" + (p.secure_https ? MJpegWrapper.cfg.webSocketPort_secure : MJpegWrapper.cfg.webSocketPort);

            thumbnailBoxPercentWidth  = cam.cameraSpec.ptz_panorama_selection_rectangle_width_percent;
            thumbnailBoxPercentHeight = cam.cameraSpec.ptz_panorama_selection_rectangle_height_percent;
            zoomMagnification         = cam.cameraSpec.ptz_magnification;

            // Evaluate the <%...%> expressions present in the html markup
            CSE.CsEval.EvalEnvironment = this;
            StringBuilder sb = new StringBuilder();
            int           idxCopyFrom = 0;
            int           idxStart = 0, idxEnd = 0;

            idxStart = html.IndexOf("<%");
            while (idxStart != -1)
            {
                sb.Append(html.Substring(idxCopyFrom, idxStart - idxCopyFrom));

                idxEnd = html.IndexOf("%>", idxStart + 2);
                if (idxEnd == -1)
                {
                    idxCopyFrom = idxStart;
                    break;
                }
                else
                {
                    string expression = html.Substring(idxStart + 2, idxEnd - (idxStart + 2)).Trim();
                    try
                    {
                        sb.Append(CSE.CsEval.Eval(expression));
                    }
                    catch (Exception)
                    {
                        Html = "<h1>Internal Server Errror</h1><p>The page you requested has errors and is unable to be produced.</p>";
                        return;
                    }
                    idxCopyFrom = idxEnd + 2;
                    idxStart    = html.IndexOf("<%", idxEnd + 2);
                }
            }
            if (idxCopyFrom < html.Length)
            {
                sb.Append(html.Substring(idxCopyFrom));
            }


            this.Html = sb.ToString();
        }
Пример #11
0
        public static string GetHtml(string camId, bool enableAutoResize, int refreshTime = 250, int disableRefreshAfter = 600000, HttpProcessor httpProcessor = null)
        {
            IPCameraBase cam = MJpegServer.cm.GetCameraAndGetItRunning(camId);

            if (cam == null)
            {
                return("NO");
            }
            int    width         = 0;
            int    height        = 0;
            int    patience      = (cam.cameraSpec.delayBetweenImageGrabs > 0 ? cam.cameraSpec.delayBetweenImageGrabs : 0) + 5000;
            string cameraImgLink = @"<img id=""imgFrame"" class=""CamImg"" />";
            string keepalive     = "";

            if (cam.cameraSpec.type == CameraType.h264_rtsp_proxy)
            {
                bool sizeOverridden = cam.cameraSpec.h264_video_width > 0 && cam.cameraSpec.h264_video_height > 0;
                width  = sizeOverridden ? cam.cameraSpec.h264_video_width : 640;
                height = sizeOverridden ? cam.cameraSpec.h264_video_height : 360;

                keepalive     = @"
				var keepaliveInterval;
				$(function()
				{
					sizeOverridden = "                     + (sizeOverridden ? "true" : "false") + @";
					keepaliveInterval = setInterval(keepalive, 4000);
					var vlc = document.getElementById('vlc');
					registerVLCEvent('MediaPlayerPlaying', handlePlayerPlaying);
					var url = '"                     + HttpUtility.HtmlEncode(HttpUtility.JavaScriptStringEncode(MJpegServer.cm.GetRTSPUrl(cam.cameraSpec.id, httpProcessor))) + @"';
					url = url.replace('$$$HOST$$$', location.hostname);
					vlc.playlist.add(url);
					vlc.playlist.play();
					if(sizeOverridden)
						vlc.video.aspectRatio = '"                         + width + ":" + height + @"';
				});
				function keepalive()
				{
					if(refreshDisabled)
						clearInterval(keepaliveInterval);
					else
						$.ajax('keepalive?id="                         + camId + @"');
				}
				function handlePlayerPlaying()
				{
					if(!sizeOverridden)
					{
						setTimeout(resize, 500);
						setTimeout(resize, 1000);
						setTimeout(resize, 1500);
					}
				}
				function registerVLCEvent(event, handler)
				{
					var vlc = document.getElementById('vlc');
					if (vlc)
					{
						if (vlc.attachEvent)
						{
							// Microsoft
							vlc.attachEvent(event, handler);
						} else if (vlc.addEventListener)
						{
							// Mozilla: DOM level 2
							vlc.addEventListener(event, handler, false);
						} else
						{
							// DOM level 0
							vlc['on' + event] = handler;
						}
					}
				}"                ;
                cameraImgLink = @"<div id=""vlcFrame"" style=""width:" + width + @"px;height:" + height + @"px;""><embed type=""application/x-vlc-plugin"" id=""vlc"" pluginspage=""http://www.videolan.org"" width=""" + width + @""" height=""" + height + @""" toolbar=""false"" src="""" mute=""false"" /></div>";
            }
            else
            {
                for (int i = 0; i < 50; i++)
                {
                    if (cam.ImageSize.Width != 0 && cam.ImageSize.Height != 0)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
                if (cam.ImageSize.Width == 0 || cam.ImageSize.Height == 0)
                {
                    return(@"<!DOCTYPE HTML>
						<html>
						<head>
							<title>"                             + HttpUtility.HtmlEncode(cam.cameraSpec.name) + @"</title>
						</head>
						<body>
						This camera is starting up.<br/>
						Please <a href=""javascript:top.location.reload();"">try again in a few moments</a>.
						</body>
						</html>"                        );
                }
                width  = cam.ImageSize.Width;
                height = cam.ImageSize.Height;
            }

            string minutesLabel = disableRefreshAfter < 0 ? "a very long time" : (TimeSpan.FromMilliseconds(disableRefreshAfter).TotalMinutes + " minutes");

            return(@"<!DOCTYPE HTML>
<html>
<head>
	<title>"     + HttpUtility.HtmlEncode(cam.cameraSpec.name) + @"</title>
	<script src="""     + Globals.jQueryPath + @""" type=""text/javascript""></script>
	<script type=""text/javascript"">
		var disableRefreshAfter = "         + disableRefreshAfter + @";
		var refreshDisabled = false;
		var originwidth = parseInt("         + width + @");
		var originheight = parseInt("         + height + @");
		var lastUpdate = 0;
		var clickCausesResize = true;
		var showPTH = "         + (cam.cameraSpec.ptzType == PtzType.None ? "false" : "true") + @";
		var sizeOverridden = false;
		$(function()
		{
			if(disableRefreshAfter > -1)
				setTimeout(""disableRefresh()"", disableRefreshAfter);
		});
		"         + keepalive + @"
		function myOnLoad()
		{
			$(""#imgFrame"").load(function ()
			{
" + (refreshTime < 0 ? "" : @"
				if (!this.complete || typeof this.naturalWidth == ""undefined"" || this.naturalWidth == 0)
				{
					alert('Bad image data was received.  A data transmission error may have occurred, or this camera may be offline.  Please reload this page to try again.');
				}
				else if(!refreshDisabled)
				{
					lastUpdate = new Date().getTime();
					setTimeout(""GetNewImage();"", "                     + refreshTime + @");
				}
") + @"
			});
			$(""#imgFrame"").error(function ()
			{
				setTimeout(""GetNewImage();"", "                 + (refreshTime < 0 ? 1000 : refreshTime) + @");
			});
			GetNewImage();
		}
		function PopupMessage(msg)
		{
			var pm = $(""#popupMessage"");
			if(pm.length < 1)
				$(""#camFrame"").after('<div id=""popupFrame""><div id=""popupMessage"">' + msg + '</div><center><input type=""button"" value=""Close Message"" onclick=""CloseMessage()""/></center></div>');
			else
				pm.append(msg);
		}
		function CloseMessage()
		{
			$(""#popupFrame"").remove();
		}
		function GetNewImage()
		{
			$(""#imgFrame"").attr('src', '"             + camId + "." + (refreshTime < 0 ? "m" : "") + @"jpg?patience=" + patience + "&" + httpProcessor.GetParam("imgargs") + @"&nocache=' + new Date().getTime());
		}
		function disableRefresh()
		{
			refreshDisabled = true;
			PopupMessage('This page has been open for "             + minutesLabel + @".  To save resources, the image will no longer refresh automatically.  <a href=""javascript:top.location.reload();"">Click here</a> to reload this page.');" + (refreshTime < 0 ? @"$(""#imgFrame"").attr('src', '" + camId + @".jpg?nocache=' + new Date().getTime());" : "") + @"
		}
		"         + (enableAutoResize ? "$(window).load(resize); $(window).resize(resize);" : "") + @"
		function resize(width, height)
		{
			var newHeight;
			var newWidth;
			var currentImage = document.getElementById(""imgFrame"");
			if (currentImage == null)
			{
				currentImage = document.getElementById(""vlcFrame"");
				
				var vlc = document.getElementById('vlc')
				if(vlc && !sizeOverridden)
				{
					originwidth = parseInt(vlc.video.width);
					originheight = parseInt(vlc.video.height);
					if(originwidth == 0)
						originwidth = 640;
					if(originheight == 0)
						originheight = 360;
				}
			}
			if (currentImage == null)
				return;
			if (typeof (width) == 'undefined' || typeof (height) == 'undefined')
			{
				var imgOff = FindOffsets(currentImage);
				var screenOff = GetViewportDims();
				// Calculate available dimensions
				var availableHeight = (screenOff.height - imgOff.top) - 7 - (showPTH ? 130 : 0);
				var availableWidth = (screenOff.width - imgOff.left) - 21;
				// Take into consideration the original width and height for the image
				newHeight = originheight < availableHeight ? originheight : availableHeight;
				newWidth = originwidth < availableWidth ? originwidth : availableWidth;
				// Calculate ratios
				var originRatio = originwidth / originheight;
				var newRatio = newWidth / newHeight;
				if (newRatio < originRatio)
					newHeight = newWidth / originRatio;
				else
					newWidth = newHeight * originRatio;
				currentImage.onclick = function ()
				{
					if(clickCausesResize)
						resize(originwidth, originheight);
				}
			}
			else
			{
				var newHeight = height;
				var newWidth = width;
				currentImage.onclick = function ()
				{
					if(clickCausesResize)
						resize();
				}
			}
			$(currentImage).height(newHeight);
			$(currentImage).width(newWidth);

			$(""#vlcFrame"").width(newWidth);
			$(""#vlcFrame"").height(newHeight);
			$(""#vlc"").attr('width', newWidth + 'px');
			$(""#vlc"").attr('height', newHeight + 'px');
			
			$(""#camFrame"").width(newWidth);
		}
		function GetViewportDims()
		{
			var w;
			var h;
			if (typeof (window.innerWidth) != 'undefined')
			{
				w = window.innerWidth;
				h = window.innerHeight;
			}
			else if (typeof (document.documentElement) != 'undefined' && typeof (document.documentElement.clientWidth) != 'undefined' && document.documentElement.clientWidth != 0)
			{
				w = document.documentElement.clientWidth;
				h = document.documentElement.clientHeight;
			}
			else
			{
				w = document.getElementsByTagName('body')[0].clientWidth;
				h = document.getElementsByTagName('body')[0].clientHeight;
			}
			return { width: w, height: h };
		}
		function FindOffsets(node)
		{
			var oLeft = 0;
			var oTop = 0;
			var oWidth = node.offsetWidth;
			var oHeight = node.offsetHeight;
			if (oWidth == 0)
				oWidth += node.scrollWidth;
			oLeft = node.offsetLeft;
			oTop = node.offsetTop;
			if (oHeight == 0)
			{
				if (node.childNodes.length > 0)
				{
					oHeight += node.childNodes[0].offsetHeight;
					oTop = node.childNodes[0].offsetTop;
				}
				if (oHeight == 0)
					oHeight += node.scrollHeight;
			}
			node = node.offsetParent;
			while (node)
			{
				oLeft += node.offsetLeft;
				oTop += node.offsetTop;
				node = node.offsetParent;
			}
			return { left: oLeft, top: oTop, width: oWidth, height: oHeight };
		}
	</script>
	<style type=""text/css"">
		.CamImg
		{
			width: "             + width + @"px;
			height: "             + height + @"px;
		}
		#vlcFrame
		{
			width: "             + width + @"px;
			height: "             + height + @"px;
		}
		body
		{
			margin: 3px;
		}
		#camFrame
		{
			background-color: #666666;
			border: 1px Solid Black;
			border-radius: 5px;
			padding: 3px;
			width: "             + width + @"px;
		}
		#popupFrame
		{
			position: fixed;
			background-color: #BB0000;
			border: 1px Solid White;
			border-radius: 5px;
			padding: 5px;
			top: 15px;
			width: 300px;
			left: 20px;
		}
		#popupMessage
		{
			color: White;
			margin-bottom: 5px;
		}
		#popupMessage a
		{
			color: #DDDDFF;
		}
		#pthDiv, #camControls
		{
			margin-top: 3px;
			padding: 0px 3px 0px 3px;
			background-color: #AAAAAA;
		}
		#pthCell
		{
			vertical-align: top;
		}
		#pthTable td
		{
			text-align: center;
		}
		.nounderline, .nounderline a
		{
			text-decoration: none;
		}
		.flip-horizontal
		{
			-moz-transform: scaleX(-1);
			-webkit-transform: scaleX(-1);
			-o-transform: scaleX(-1);
			transform: scaleX(-1);
			-ms-filter: fliph; /*IE*/
			filter: fliph; /*IE*/
		}
		.flip-vertical
		{
			-moz-transform: scaleY(-1);
			-webkit-transform: scaleY(-1);
			-o-transform: scaleY(-1);
			transform: scaleY(-1);
			-ms-filter: flipv; /*IE*/
			filter: flipv; /*IE*/
		}
		.flip-both
		{
			-moz-transform: scale(-1,-1);
			-webkit-transform: scale(-1,-1);
			-o-transform: scale(-1,-1);
			transform: scale(-1,-1);
			-ms-filter: flipv fliph; /*IE*/
			filter: flipv fliph; /*IE*/
		}
		.arrow-up
		{
			width: 0px;
			height: 0px;
			border-bottom: 20px solid #00AA00;
			border-left: 20px solid transparent;
			border-right: 20px solid transparent;
		}
		.arrow-down
		{
			width: 0px;
			height: 0px;
			border-top: 20px solid #00AA00;
			border-left: 20px solid transparent;
			border-right: 20px solid transparent;
		}
		.arrow-left
		{
			width: 0px;
			height: 0px;
			border-bottom: 10px solid transparent;
			border-top: 10px solid transparent;
			border-right: 10px solid #00AA00;
		}
		.arrow-right
		{
			width: 0px;
			height: 0px;
			border-bottom: 10px solid transparent;
			border-left: 10px solid #00AA00;
			border-top: 10px solid transparent;
		}
	</style>
</head>
<body onload=""myOnLoad();"">
	<div id=""camFrame"">
		"         + cameraImgLink + @"
		<table style=""width: 100%"">
			<tbody>
				<tr>
					"                     + PTZ.GetHtml(camId, cam) + @"
				</tr>
			</tbody>
		</table>
	</div>
</body>
</html>");
        }
        public void handler(IWebSocketConnection socket)
        {
            socket.OnOpen = () =>
            {
                try
                {
                    Console.WriteLine("WebSocket Open!");
                    lock (allSockets)
                    {
                        allSockets[socket] = 0;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex);
                }
            };
            socket.OnClose = () =>
            {
                try
                {
                    Console.WriteLine("WebSocket Close!");
                    lock (allSockets)
                    {
                        allSockets.Remove(socket);
                        foreach (HashSet <IWebSocketConnection> socketSet in registration_cameraToSocket.Values)
                        {
                            if (socketSet != null)
                            {
                                socketSet.Remove(socket);
                            }
                        }
                        registration_socketToCamera.Remove(socket);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex);
                }
            };
            socket.OnMessage = message =>
            {
                try
                {
                    Console.WriteLine(message);

                    if (message.StartsWith("session "))
                    {
                        Session s = MJpegServer.sm.GetSession(message.Substring("session ".Length));
                        //if (s == null)
                        //    socket.Send("sessioninvalid");
                        //else
                        //{
                        socket.Send("sessionaccepted");
                        lock (allSockets)
                        {
                            allSockets[socket] = (s == null ? 0 : s.permission);
                        }
                        //}
                    }
                    else if (message.StartsWith("login "))
                    {
                        Session s = MJpegServer.sm.GetSession(null, message.Substring("login ".Length));
                        lock (allSockets)
                        {
                            allSockets[socket] = s.permission;
                        }
                    }
                    else if (message.StartsWith("loginraw "))
                    {
                        Session s = MJpegServer.sm.GetSession(null, null, message.Substring("loginraw ".Length));
                        lock (allSockets)
                        {
                            allSockets[socket] = s.permission;
                        }
                    }
                    else if (message.StartsWith("register "))
                    {
                        string cameraId;
                        if (registration_socketToCamera.TryGetValue(socket, out cameraId))
                        {
                            socket.Send("registrationfailed alreadyregistered");
                            socket.Close();
                        }
                        cameraId = message.Substring("register ".Length);
                        IPCameraBase cam = MJpegServer.cm.GetCamera(cameraId);
                        if (cam == null)
                        {
                            socket.Send("registrationfailed cameraunavailable");
                        }
                        else
                        {
                            int minPermission = cam.cameraSpec.minPermissionLevel;
                            if (minPermission == 101)
                            {
                                socket.Send("registrationfailed cameraunavailable");
                            }
                            else
                            {
                                bool permissionOkay = false;
                                lock (allSockets)
                                {
                                    int currentPermission = allSockets[socket];
                                    if (currentPermission >= minPermission)
                                    {
                                        permissionOkay = true;
                                        HashSet <IWebSocketConnection> registeredList;
                                        if (!registration_cameraToSocket.TryGetValue(cameraId, out registeredList))
                                        {
                                            registration_cameraToSocket[cameraId] = registeredList = new HashSet <IWebSocketConnection>();
                                        }
                                        registeredList.Add(socket);
                                        registration_socketToCamera[socket] = cameraId;
                                    }
                                }
                                if (permissionOkay)
                                {
                                    socket.Send("registrationaccepted");
                                    AdvPtz obj = AdvPtz.GetPtzObj(cameraId);

                                    if (obj != null)
                                    {
                                        socket.Send("sup " + cameraId + " " + obj.ptzController.GetStatusUpdate());
                                    }
                                }
                                else
                                {
                                    socket.Send("registrationfailed insufficientpermission");
                                }
                            }
                        }
                    }
                    else if (message.StartsWith("abs "))
                    {
                        double   x;
                        double   y;
                        double   z;
                        string[] parts = message.Split(' ');
                        if (parts.Length == 4 && double.TryParse(parts[1], out x) && double.TryParse(parts[2], out y) && double.TryParse(parts[3], out z))
                        {
                            string cameraId;
                            if (registration_socketToCamera.TryGetValue(socket, out cameraId))
                            {
                                IPCameraBase cam = MJpegServer.cm.GetCamera(cameraId);
                                if (cam.isRunning)
                                {
                                    AdvPtz obj = AdvPtz.GetPtzObj(cameraId);
                                    if (obj != null)
                                    {
                                        obj.ptzController.PrepareWorkerThreadIfNecessary();
                                        obj.ptzController.SetAbsolutePTZPosition(new FloatVector3(Util.Clamp((float)x, 0f, 1f), Util.Clamp((float)y, 0f, 1f), Util.Clamp((float)z, 0f, 1f)));
                                    }
                                    else
                                    {
                                        socket.Send("error Camera is not correct type.");
                                    }
                                }
                                else
                                {
                                    socket.Send("error Camera is not running. Refresh page.");
                                }
                            }
                            else
                            {
                                socket.Send("error This WebSocket connection does not have a camera registered.");
                            }
                        }
                    }
                    else if (message.StartsWith("3dpos "))
                    {
                        double   x;
                        double   y;
                        double   w;
                        double   h;
                        int      zoom;
                        string[] parts = message.Split(' ');
                        if (parts.Length == 6 && double.TryParse(parts[1], out x) && double.TryParse(parts[2], out y) && double.TryParse(parts[3], out w) && double.TryParse(parts[4], out h) && int.TryParse(parts[5], out zoom))
                        {
                            string cameraId;
                            if (registration_socketToCamera.TryGetValue(socket, out cameraId))
                            {
                                IPCameraBase cam = MJpegServer.cm.GetCamera(cameraId);
                                if (cam.isRunning)
                                {
                                    AdvPtz obj = AdvPtz.GetPtzObj(cameraId);
                                    if (obj != null)
                                    {
                                        obj.ptzController.PrepareWorkerThreadIfNecessary();
                                        obj.ptzController.Set3DPTZPosition(new Pos3d(Util.Clamp((float)x, 0, 1), Util.Clamp((float)y, 0, 1), Util.Clamp((float)w, 0, 1), Util.Clamp((float)h, 0, 1), zoom == 1 ? true : false));
                                    }
                                    else
                                    {
                                        socket.Send("error Camera is not correct type.");
                                    }
                                }
                                else
                                {
                                    socket.Send("error Camera is not running. Refresh page.");
                                }
                            }
                            else
                            {
                                socket.Send("error This WebSocket connection does not have a camera registered.");
                            }
                        }
                    }
                    else if (message.StartsWith("zoom "))
                    {
                        double   z;
                        string[] parts = message.Split(' ');
                        if (parts.Length == 2 && double.TryParse(parts[1], out z))
                        {
                            string cameraId;
                            if (registration_socketToCamera.TryGetValue(socket, out cameraId))
                            {
                                IPCameraBase cam = MJpegServer.cm.GetCamera(cameraId);
                                if (cam.isRunning)
                                {
                                    AdvPtz obj = AdvPtz.GetPtzObj(cameraId);
                                    if (obj != null)
                                    {
                                        obj.ptzController.PrepareWorkerThreadIfNecessary();
                                        obj.ptzController.SetZoomPosition(z);
                                    }
                                    else
                                    {
                                        socket.Send("error Camera is not correct type.");
                                    }
                                }
                                else
                                {
                                    socket.Send("error Camera is not running. Refresh page.");
                                }
                            }
                            else
                            {
                                socket.Send("error This WebSocket connection does not have a camera registered.");
                            }
                        }
                    }
                    else if (message.StartsWith("genpano "))
                    {
                        bool permissionOkay = false;
                        lock (allSockets)
                        {
                            if (allSockets[socket] >= 100)
                            {
                                permissionOkay = true;
                            }
                        }
                        if (permissionOkay)
                        {
                            string cameraId;
                            if (registration_socketToCamera.TryGetValue(socket, out cameraId))
                            {
                                IPCameraBase cam = MJpegServer.cm.GetCamera(cameraId);
                                if (cam.isRunning)
                                {
                                    AdvPtz obj = AdvPtz.GetPtzObj(cameraId);
                                    if (obj != null)
                                    {
                                        if (message.EndsWith(" full"))
                                        {
                                            obj.ptzController.PrepareWorkerThreadIfNecessary();
                                            obj.ptzController.GeneratePanorama(true);
                                        }
                                        else if (message.EndsWith(" pseudo"))
                                        {
                                            obj.ptzController.PrepareWorkerThreadIfNecessary();
                                            obj.ptzController.GeneratePanorama(false);
                                        }
                                    }
                                    else
                                    {
                                        socket.Send("error Camera is not correct type.");
                                    }
                                }
                                else
                                {
                                    socket.Send("error Camera is not running. Refresh page.");
                                }
                            }
                            else
                            {
                                socket.Send("error This WebSocket connection does not have a camera registered.");
                            }
                        }
                        else
                        {
                            socket.Send("error Insufficient Permission");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex);
                }
            };
        }
Пример #13
0
        public static void RunCommand(string cameraId, string cmd)
        {
            IPCameraBase cam = MJpegServer.cm.GetCamera(cameraId);

            if (cam == null)
            {
                return;
            }

            if (cam.cameraSpec.ptz_proxy)
            {
                string auth = (!string.IsNullOrEmpty(cam.cameraSpec.ptz_username) && !string.IsNullOrEmpty(cam.cameraSpec.ptz_password)) ? "rawauth=" + HttpUtility.UrlEncode(cam.cameraSpec.ptz_username) + ":" + HttpUtility.UrlEncode(cam.cameraSpec.ptz_password) + "&" : "";
                SimpleProxy.GetData("http://" + cam.cameraSpec.ptz_hostName + "/control/PTZ?" + auth + "id=" + HttpUtility.UrlEncode(cam.cameraSpec.ptz_proxy_cameraId) + "&cmd=" + HttpUtility.UrlEncode(cmd));
            }
            else if (cam.cameraSpec.ptzType == PtzType.LoftekCheap)
            {
                LoftekCheapPTZ.RunCommand(cam, cameraId, cmd);
            }
            //else if (cam.cameraSpec.ptzType == PtzType.Dahua)
            //    DahuaPTZ.RunCommand(cam, cmd);
            else if (cam.cameraSpec.ptzType == PtzType.WanscamCheap)
            {
                WanscamCheapPTZ.RunCommand(cam, cameraId, cmd);
            }
            //else if (cam.cameraSpec.ptzType == PtzType.TrendnetIP672)
            //	IP672SeriesPTZ.RunCommand(cam, cameraId, cmd);
            else if (cam.cameraSpec.ptzType == PtzType.IPS_EYE01)
            {
                PanTiltZoom.PTZDirection dir = PanTiltZoom.PTZDirection.Up;
                if (cmd.StartsWith("d"))
                {
                    dir = PanTiltZoom.PTZDirection.Down;
                }
                else if (cmd.StartsWith("l"))
                {
                    dir = PanTiltZoom.PTZDirection.Left;
                }
                else if (cmd.StartsWith("r"))
                {
                    dir = PanTiltZoom.PTZDirection.Right;
                }
                new PanTiltZoom.IPS_EYE01.IPS_EYE01_PTZ(cam.cameraSpec).MoveSimple(dir);
            }
            else if (cam.cameraSpec.ptzType == PtzType.TrendnetTVIP400)
            {
                PanTiltZoom.PTZDirection dir = PanTiltZoom.PTZDirection.Up;
                if (cmd.StartsWith("d"))
                {
                    dir = PanTiltZoom.PTZDirection.Down;
                }
                else if (cmd.StartsWith("l"))
                {
                    dir = PanTiltZoom.PTZDirection.Left;
                }
                else if (cmd.StartsWith("r"))
                {
                    dir = PanTiltZoom.PTZDirection.Right;
                }
                new PanTiltZoom.TrendNet.TV_IP400(cam.cameraSpec).MoveSimple(dir);
            }
            else if (cam.cameraSpec.ptzType == PtzType.CustomPTZProfile || cam.cameraSpec.ptzType == PtzType.Huisun)
            {
                object ptzProfile = null;
                if (cam.cameraSpec.ptzType == PtzType.CustomPTZProfile)
                {
                    ptzProfile = new PanTiltZoom.Custom.CustomPTZProfile(cam.cameraSpec, cam);
                }
                else if (cam.cameraSpec.ptzType == PtzType.Huisun)
                {
                    ptzProfile = new PanTiltZoom.HuisunBullet(cam.cameraSpec, cam);
                }

                int presetNum;
                if (cmd == "u")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.Up);
                }
                else if (cmd == "d")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.Down);
                }
                else if (cmd == "l")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.Left);
                }
                else if (cmd == "r")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.Right);
                }
                else if (cmd == "ul")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.UpLeft);
                }
                else if (cmd == "ur")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.UpRight);
                }
                else if (cmd == "dl")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.DownLeft);
                }
                else if (cmd == "dr")
                {
                    ((IPTZSimple)ptzProfile).MoveSimple(PanTiltZoom.PTZDirection.DownRight);
                }
                else if (cmd == "i3")
                {
                    ((IPTZSimple)ptzProfile).Zoom(PanTiltZoom.ZoomDirection.In, PanTiltZoom.ZoomAmount.Long);
                }
                else if (cmd == "o3")
                {
                    ((IPTZSimple)ptzProfile).Zoom(PanTiltZoom.ZoomDirection.Out, PanTiltZoom.ZoomAmount.Long);
                }
                else if (cmd == "i2")
                {
                    ((IPTZSimple)ptzProfile).Zoom(PanTiltZoom.ZoomDirection.In, PanTiltZoom.ZoomAmount.Medium);
                }
                else if (cmd == "o2")
                {
                    ((IPTZSimple)ptzProfile).Zoom(PanTiltZoom.ZoomDirection.Out, PanTiltZoom.ZoomAmount.Medium);
                }
                else if (cmd == "i1")
                {
                    ((IPTZSimple)ptzProfile).Zoom(PanTiltZoom.ZoomDirection.In, PanTiltZoom.ZoomAmount.Short);
                }
                else if (cmd == "o1")
                {
                    ((IPTZSimple)ptzProfile).Zoom(PanTiltZoom.ZoomDirection.Out, PanTiltZoom.ZoomAmount.Short);
                }
                else if (cmd.Length == 3 && cmd.StartsWith("pl") && int.TryParse(cmd.Substring(2), out presetNum))
                {
                    ((IPTZPresets)ptzProfile).LoadPreset(presetNum);
                }
                else if (cmd.Length == 3 && cmd.StartsWith("ps") && int.TryParse(cmd.Substring(2), out presetNum))
                {
                    ((IPTZPresets)ptzProfile).SavePreset(presetNum);
                }
            }
        }