HVideoManager.cs 8.5 KB
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using TSA_V.Common;

namespace TSA_V.DeviceLibrary
{
    public  class HVideoManager
    {

        //private static  int ServerPort = 8765;
        //public   static string LastMsg = ""; 
        public static HandInfo lastInfo = new HandInfo();
        private  static HttpListener listener = null;
        private  static bool mStart = false;
        public static bool StartRun()
        {
            try
            {
                HandRecordManager.Reset();
                if (Setting_NInit.Hand_ServerPort > 0)
                {
                    listener = new HttpListener();
                    listener.Prefixes.Add($"http://localhost:{Setting_NInit.Hand_ServerPort}/"); // 监听的URL地址
                    listener.Start();
                    LogUtil.info($"HTTP服务已启动,正在监听{Setting_NInit.Hand_ServerPort}端口...");
                    Task.Factory.StartNew(() =>
                    {
                           Run();
                    });
                }
                return true;

            }
            catch (Exception ex)
            {
                LogUtil.error("hVideoManager StartRun 出错:" + ex.ToString());
                return false;
            }
        }
        private static void Run() {
            mStart = true;
            while (mStart)
            {
                try
                {
                    // 等待请求连接
                    HttpListenerContext context = listener.GetContext();

                    // 获取请求对象和响应对象
                    HttpListenerRequest request = context.Request;
                    HttpListenerResponse response = context.Response;
                    try
                    {
                        // 处理指定路径和POST请求
                        if (request.HttpMethod == "POST" && request.Url.AbsolutePath == "/rest/api/v1/imgUpload")
                        {
                            // 读取POST数据
                            string postData;
                            using (StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
                            {
                                postData = reader.ReadToEnd();
                                //Console.WriteLine("收到POST请求数据:" + postData);
                            }
                            ServerOnReceived(request.Url.AbsolutePath, postData);
                            //// 将POST数据转换为字典
                            //NameValueCollection formData = ParseFormData(postData);

                            //// 获取inputText的值并保存
                            //string inputText = formData["inputText"];
                            //Console.WriteLine("获取到的inputText的值为:" + inputText);
                            //// 在这里进行保存操作
                            //// ...

                            // 返回响应
                            string responseString = "OK";
                            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                            response.ContentLength64 = buffer.Length;
                            response.OutputStream.Write(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            // 不支持其他请求方法或路径
                            response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                        }

                    }
                    catch (Exception e)
                    {
                        LogUtil.error("出错:" + e.ToString());
                    }
                    finally
                    {
                        // 关闭响应流
                        response.Close();
                    } 
                }
                catch (Exception ex)
                {
                    LogUtil.error("出错:" + ex.ToString());
                }

            }
        }


        public static void StopRun()
        {
            try
            {
                mStart = false;
                Thread.Sleep(100);
                listener.Stop();
            }
            catch (Exception ex)
            {
                LogUtil.error("出错:" + ex.ToString());
            }
        }

        private  static string ImgUpload = "/rest/api/v1/imgUpload";
        private static string ServerOnReceived(string reqPath, string paramStr)
        {
            if (paramStr == "" || reqPath=="")
            {
                return "";
            }
            //LogUtil.info("ServerOnReceived [" + reqPath + "] [" + paramStr + "] ");
            //paramStr = paramStr.Replace("%23", "#");
            try
            {
                Dictionary<string, object> paramMap = JsonHelper.DeserializeJsonToObject< Dictionary<string, object>>(paramStr);
                if (reqPath.Equals(ImgUpload))
                {
                    HandInfo obj = new HandInfo();
                    bool result = paramMap.TryGetValue("input", out object imgStr);
                    if (result)
                    {
                        obj.ImgStr = imgStr.ToString();
                    }
                    int length = 0;
                    result = paramMap.TryGetValue("pointLen", out object lenObj);
                    if (result)
                    {
                        length = Convert.ToInt32(lenObj);
                        obj.pointCount = length;
                    }

                    result = paramMap.TryGetValue("points", out object pArray);
                    if (result && length > 0)
                    {
                        List<List<int>> list = JsonHelper.DeserializeJsonToList<List<int>>(pArray.ToString());
                        obj.points = list;
                        //LogUtil.info(pArray.ToString()+"\r\n"+JsonHelper.SerializeObject(pArray));

                        //  foreach (List<int> o in list)
                        //  { 
                        //      if (o.Count == 3)
                        //      {
                        //          LogUtil.info($"{o[0]},{o[1]},{o[2]}");
                        //      }
                        //  }

                    }
                    lastInfo = obj;
                    HandRecordManager.ProcessPoint(lastInfo.pointCount, lastInfo.points);

                    //if (Setting_NInit.Hand_SaveImg)
                    //{
                    //    Bitmap bitmap = Base64StringToImage(obj.ImgStr);
                    //    string fileName = new DateTime().ToString("yyyyMMddHHmmss") + ".jpg";
                    //    bitmap.Save(@"D:\image\" + fileName);
                    //    bitmap.Dispose();
                    //}
                }

                else
                {
                    //LogUtil.info("[" + reqPath + "]没有相关处理");
                    return "[" + reqPath + "]没有相关处理";
                }
                return "OK";
            }
            catch (Exception ex)
            {
                LogUtil.info("[" + reqPath + "][" + paramStr + "]处理错误:" + ex.ToString());
                return "Error";
            }
        } 


        private static Bitmap Base64StringToImage(string inputStr)
        {
            try
            {
                if (inputStr == "")
                {
                    return null ;
                }
                byte[] arr = Convert.FromBase64String(inputStr);
                using (MemoryStream ms = new MemoryStream(arr))
                {
                    Bitmap bmp = new Bitmap(ms);
                    ms.Close();
                    return bmp;
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("Base64StringToImage 转换失败/nException:" +ex.ToString());
                return null;
            }
        }

        public static Bitmap GetLastImg( )
        {
            string inputStr = lastInfo!=null?lastInfo.ImgStr:""; 
            if (inputStr != "")
            {
                return Base64StringToImage(inputStr);
            }
            return null;
        }

    }

    public class HandInfo  {

        public string ImgStr { get; set; } = "";

        public int pointCount { get; set; } = 0;


        public List<List<int>> points { get; set; } = new List<List<int>>();
    }
}