UnifiedDataHandler.cs 12.4 KB
using BLL;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OnlineStore.Common.util
{
    public static class UnifiedDataHandler
    {
        private static string server = "service/video/upload";
        private static object lockRecordPrintNg = new object();
        /// <summary>
        /// 记录当天打印和ng数量
        /// </summary>
        /// <param name="isquery">为true时,只查询不修改</param>
        /// <param name="isPrint">true增加打印数量,反之增加ng数量</param>
        /// <param name="ints">返回打印和ng数量</param>
        /// <returns></returns>
        public static int RecordPrintNg(bool isquery, bool isPrint, out string[] strarrys)
        {
            lock (lockRecordPrintNg)
            {
                strarrys = new string[2];
                try
                {
                    int cut = 0;
                    string txtpath = Path.Combine(Application.StartupPath, ConfigHelper.Config.Get("RecordPrintNg", "Config\\RecordPrintNg.txt"));
                    //0日期;1打印数量;2ng数量
                    string[] strs = { DateTime.Today.ToString("dd-MM-yyyy"), "0", "0" };
                    if (File.Exists(txtpath))
                    {
                        string json = File.ReadAllText(txtpath);

                        if (!string.IsNullOrWhiteSpace(json.Replace("\0","")))
                        {
                            string[] strings = JsonConvert.DeserializeObject<string[]>(json);

                            if (strings[0] == DateTime.Today.ToString("dd-MM-yyyy"))
                            {
                                strs[0] = strings[0];
                                strs[1] = strings[1];
                                strs[2] = strings[2];
                            }
                        }
                    }
                    if (!isquery)
                    {
                        cut = isPrint ? int.Parse(strs[1]) + 1 : int.Parse(strs[2]) + 1;
                        strs[isPrint ? 1 : 2] = cut.ToString();
                    }
                    strarrys[0] = strs[1];
                    strarrys[1] = strs[2];
                    string updatedJson = JsonConvert.SerializeObject(strs);
                    File.WriteAllText(txtpath, updatedJson);
                    return cut;
                }
                catch (Exception ex)
                {
                    LogNet.log.Error($"写入print和ng数量出错:{ex}");
                    strarrys[0] = null;
                    strarrys[1] = null;
                    return 0;
                }
            }
        }
        private static object lockRecordEmsData = new object();
        /// <summary>
        /// 写入mes通信数据
        /// </summary>
        /// <param name="isquery">是否查询数据</param>
        /// <param name="str">保存内容</param>
        /// <returns></returns>
        private static string RecordEmsData(bool isquery, string str = null)
        {
            lock (lockRecordEmsData)
            {
                try
                {
                    string strs = null;
                    string txtpath = Path.Combine(Application.StartupPath, ConfigHelper.Config.Get("RecordEmsData", "Config\\RecordEmsData.txt"));
                    if (File.Exists(txtpath))
                    {
                        strs = File.ReadAllText(txtpath);
                    }
                    if (!isquery)
                    {
                        File.WriteAllText(txtpath, str);
                        strs = str;
                    }
                    return strs;
                }
                catch (Exception ex)
                {
                    LogNet.log.Error($"写入ems通信数据出错:{ex}");
                    return null;
                }
            }
        }
        /// <summary>
        /// 向服务器请求类添加ng、打印、ems请求数据
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> PrintNgMESData()
        {
            Dictionary<string, string> valuePairs = new Dictionary<string, string>();
            try
            {
                RecordPrintNg(true, true, out string[] strarrys);
                string mesdata = RecordEmsData(true);
                valuePairs.Add("tPCount", strarrys[0]);
                valuePairs.Add("tNGCount", strarrys[1]);
                valuePairs.Add("MES", mesdata);
                return valuePairs;
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"向服务器传输ng和print,出错:{ex}");
                return valuePairs;
            }

        }

       /// <summary>
       /// 检查料串状态
       /// </summary>
       /// <param name="isright">true右侧步骤判断</param>
       /// <param name="mostop"></param>
       /// <returns></returns>
        public static string ShelfStatus(bool isright,int mostop) 
        {
            if (mostop==0)
            {
                return "IDLE";
            }
            if (isright)
            {               
                if (mostop >= 24 && mostop <= 28)//出料中
                {
                    return "EMPTY_OUT";
                }
                if (mostop >= 30 && mostop <= 35)//入料中
                {
                    return "LOADING";
                }
                if (mostop == 20 || mostop == 23)//料串已清空,等待取走料串
                {
                    return "EMPTY_OUT";
                }
                return "LOADING";//运行中-入库中
            }
            else
            {
                if (mostop>=49&&mostop<=54)//出料中
                {
                    return "FULL_OUT";
                }
                if (mostop >= 55 && mostop <= 60)//入料中
                {
                    return "UNLOADING";
                }
                if (mostop == 47 || mostop == 48)//料串已满,等待取走料串
                {
                    return "FULL_OUT";
                }
                return "UNLOADING";//运行中-出库中
            }           
        }

        private static string BitMapToBase64(Bitmap bitmap, int width, int height, int quality)
        {
            try
            {
                if (bitmap == null) return "";
                using (MemoryStream ms = new MemoryStream())
                {
                    var tarbmp = ZoomImage(bitmap, height, width, quality);
                    tarbmp.Save(ms, ImageFormat.Jpeg);
                    byte[] bytes = ms.GetBuffer();
                    string base64 = Convert.ToBase64String(bytes);
                    // tarbmp.Save($".\\test_BitMapToBase64.bmp",ImageFormat.Jpeg);
                    //File.WriteAllText("E:\\Neotel\\Codes\\DLL\\IPCamera\\WindowsFormsApp1\\bin\\Debug\\test_BitMapToBase64.txt", base64);
                    //Base64ToBitmap(base64);
                    return base64;

                }
            }
            catch (Exception e)
            {
                LogNet.log.Error("图片转base64失败原因:", e);
            }
            return "";
        }

        /// <summary>
        /// 不管多大的图片都能在指定大小picturebox控件中显示
        /// </summary>
        /// <param name="bitmap">图片</param>
        /// <param name="destHeight">picturebox控件高</param>
        /// <param name="destWidth">picturebox控件宽</param>
        /// <returns></returns>
        private static Image ZoomImage(Image bitmap, int destHeight, int destWidth, int quality = 100)
        {
            try
            {
                System.Drawing.Image sourImage = bitmap;
                int width = 0, height = 0;
                //按比例缩放             
                int sourWidth = sourImage.Width;
                int sourHeight = sourImage.Height;
                if (sourHeight > destHeight || sourWidth > destWidth)
                {
                    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                    {
                        width = destWidth;
                        height = (destWidth * sourHeight) / sourWidth;
                    }
                    else
                    {
                        height = destHeight;
                        width = (sourWidth * destHeight) / sourHeight;
                    }
                }
                else
                {
                    width = sourWidth;
                    height = sourHeight;
                }
                Bitmap destBitmap = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                //设置画布的描绘质量           
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                //g.DrawImage(sourImage, new Rectangle(0, 0, destWidth, destHeight), new Rectangle(0, 0, sourImage.Width, sourImage.Height), GraphicsUnit.Pixel);
                g.Dispose();
                //设置压缩质量       
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] qualitys = [quality];
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualitys);
                encoderParams.Param[0] = encoderParam;
                //sourImage.Dispose();
                return destBitmap;
            }
            catch (Exception ex)
            {
                LogNet.log.Error("图片压缩失败:" + ex);
                return bitmap;
            }
        }

        public static async Task PostSmfImageAsync(Bitmap bitmap, Dictionary<string,string> dic,int w=1920,int h=1080)
        {
            try
            {
                string http = BLLCommon.config.SmfServer;
                if (!http.StartsWith("http"))
                {
                    return;
                }
                if (!http.EndsWith("/"))
                    http += "/";
                string imgbase64 = BitMapToBase64(bitmap, w, h, 100);               
                string url = http + server;               
                dic.Add("img",imgbase64);
                string json = JsonConvert.SerializeObject(dic);
                await PostAsync(url, json);
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"向smf发送图片失败:{ex}");
            }          
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <param name="timeout">秒</param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        private static async Task PostAsync(string url,string json,int timeout=1,string contentType = "application/json") 
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(timeout);
                    using (HttpContent content = new StringContent(json))
                    {
                        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                        HttpResponseMessage response = await client.PostAsync(url, content);
                        if (response.IsSuccessStatusCode)
                        {
                            LogNet.log.Info("上传smf图片完成");
                        }
                        else
                        {
                            LogNet.log.Info($"上传smf图片失败,错误码:{response.StatusCode}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Info($"上传smf图片失败,原因:{ex.Message}");
            }           
        }
    }
}