RemoteDecodeHelper.cs 5.5 KB
using CodeLibrary;
using HalconDotNet;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

public class RemoteDecodeHelper_mod
{
    static int webclienttimeout = 30 * 1000;
    static Process p = new Process();
    const string serverhost = "http://127.0.0.1:58137/";
    public static WebResultCode DecodeRequest(Bitmap bitmap, RemoteDecodeParam remoteDecodeParam)
    {
        CheckAndRunServer();
        if (bitmap == null)
            return null;
        byte[] requestdata;
        lock (bitmap)
        {
            using (MemoryStream mStream = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(mStream, bitmap);
                requestdata = mStream.ToArray();
                mStream.Close();
            }
        }
        return DecodeRequest(requestdata, remoteDecodeParam);
    }
    static WebResultCode DecodeRequest(byte[] requestdata, RemoteDecodeParam remoteDecodeParam,bool isHObject=false)
    {
        //CheckAndRunServer();
        string param;
        using (MemoryStream mStreamparam = new MemoryStream())
        {
            XmlSerializer xf = new XmlSerializer(typeof(RemoteDecodeParam));
            xf.Serialize(mStreamparam, remoteDecodeParam);
            param = base64UrlEncode(mStreamparam.ToArray());
            mStreamparam.Close();
        }
        string url = serverhost+ "NeoScan/ProcessBitmap?param=";
        if (isHObject)
            url = serverhost+ "NeoScan/Process?param=";
        byte[] resp;
        try
        {
            MyWebClient webClient = new MyWebClient(webclienttimeout);
            resp = webClient.UploadData(url + param, requestdata);
            requestdata = null;
            webClient.Dispose();
        }
        catch(WebException we)
        {
            return null;
        }
        catch
        {
            return null;
        }

        WebResultCode codeInfos = null;
        var ss = Encoding.UTF8.GetString(resp);
        try
        {

            codeInfos = JsonConvert.DeserializeObject<WebResultCode>(ss);

        }
        catch (Exception ex)
        {
            throw new Exception("数据解析出错:" + ex + "\r\n" + ss);
        }
        return codeInfos;
    }

    /// <summary>
    /// 在url中传递base64字符串需要替换加号等符号
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    static string base64UrlEncode(byte[] input)
    {
        return Convert.ToBase64String(input).Replace('+', '-').Replace('/', '_');
    }
    /// <summary>
    /// 检查并自动启动服务器
    /// </summary>
    static void CheckAndRunServer()
    {
        lock (p)
        {
            var pss = Process.GetProcessesByName("Neo Scan");
            if (pss.Length > 0)
                return;

            var f = "NeoScan\\Neo Scan.exe";
            if (!File.Exists(f))
                throw new Exception("找不到扫码服务器文件");
            p.StartInfo = new ProcessStartInfo(f);
            p.StartInfo.Arguments = "hide";
            p.Start();
            int checkcount = 5;
            while (checkcount > 0)
            {
                checkcount--;
                Thread.Sleep(500);
                MyWebClient webClient = new MyWebClient(webclienttimeout);
                var s = webClient.DownloadString(serverhost + "alive");
                if (s.Trim() == "\"1\"")
                    return;
            }
            throw new Exception("扫码服务器打开失败");
        }
    }

    [Serializable]
    public struct RemoteDecodeParam
    {
        public string[] codeTypeList;
        public int codeCount;
        public int timeout;
    }

    

    [Serializable]
    public class WebResultCode
    {
        public int ErrorCode { get; set; }
        public string Msg { get; set; }
        //public WebCodeText[] Data { get; set; }
        public List<KeyValuePair<string,string>> workCodeKeyword;
        public List<BarcodeInfo> workCodeInfo;

        public WebResultCode()
        {
            ErrorCode = 0;
            Msg = "OK";
        }
    }
    //
    // 摘要:
    //     条码信息,1DBarcode、2DBarcode
    [Serializable]
    public class BarcodeInfo
    {
        //
        // 摘要:
        //     文本
        public string Text { get; set; }
        //
        // 摘要:
        //     条码类型
        public string CodeType { get; set; }
        //
        // 摘要:
        //     中心点
        public PointF Center { get; set; }
        //
        // 摘要:
        //     角度,3点钟方向0°,逆时针为正,顺时针为负。
        public float Angle { get; set; }
        //
        // 摘要:
        //     条码尺寸大小
        //public SizeF Size { get; set; }
        //
        // 摘要:
        //     原点垂直于经过中心点的直线的距离
        public float Distance { get; set; }
    }


    public class MyWebClient : WebClient
    {
        private int _timeout;
        public MyWebClient(int timeout)
        {
            this._timeout = timeout;
        }
        protected override WebRequest GetWebRequest(Uri address)
        {
            var result = base.GetWebRequest(address);
            result.Timeout = this._timeout;
            return result;
        }
    }

}