Browse Source

图片上传

WIN-GH9CEESPLTB\Administrator 6 days ago
parent
commit
7eee10aeac

+ 2 - 0
MainForm/ClassFile/ProjectClass/GlobalContext.cs

@@ -143,6 +143,7 @@ namespace MainForm
         public static bool MESIsConnect;  // MES是否正常连接
         public static string UpFileUrl;  // 文档库地址
         public static string UpFilePath;  // 本地文件路径
+        public static bool IsSendUpFile;    // 启用上传文件
 
         // IOT - MQTT
         public static bool IsUseIot;  // 是否 启用IOT
@@ -383,6 +384,7 @@ namespace MainForm
                 IsSendWorkingData = bool.Parse(IniFile.INIGetStringValue(FilePath, "MES", "IsSendWorkingData", ConstIsSend));
                 IsSendAlarmData = bool.Parse(IniFile.INIGetStringValue(FilePath, "MES", "IsSendAlarmData", ConstIsSend));
                 IsUseMESRoute = bool.Parse(IniFile.INIGetStringValue(FilePath, "MES", "IsUseMESRoute", ConstIsSend));
+                IsSendUpFile = bool.Parse(IniFile.INIGetStringValue(FilePath, "MES", "IsSendUpFile", ConstIsSend));
 
                 // MQTT
                 IsUseIot = bool.Parse(IniFile.INIGetStringValue(FilePath, "MES", "IsUseIot", "false"));

+ 173 - 0
MainForm/ClassFile/XiaomiAPI_MES/XiaomiMESHttp_UpLoadFile.cs

@@ -0,0 +1,173 @@
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Policy;
+using System.Text;
+using static MainForm.ClassFile.XiaomiAPI.XiaomiMqttClient_Extend;
+using static MainForm.ClassFile.XiaomiAPI_MES.XiaomiMESHttp_StationInbound;
+
+namespace MainForm.ClassFile.XiaomiAPI_MES
+{
+    /// <summary>
+    /// 小米MES - 进站接⼝
+    /// 接口地址:
+    /// 接口方法:UnitConfirmDataSetIn
+    /// </summary>
+    public class XiaomiMESHttp_UpLoadFile : XiaomiMESHttp_X5
+    {
+        #region 变量
+        /// <summary>
+        /// 接口地址
+        /// </summary>
+        protected new static string UpFileUrl { set; get; } = GlobalContext.UpFileUrl;
+
+        /// <summary>
+        /// 接口方法
+        /// </summary>
+        protected new static string Method { set; get; } = "UploadMqtt";
+        #endregion 变量
+
+        /// <summary>
+        /// 小米上传文档
+        /// </summary>
+        /// <param name="requestBody"></param>
+        /// <returns></returns>
+        public static XmMES_UpFile_Response UpFilePost(XmMES_UpFile_Request_Body body)
+        {
+            XmMES_UpFile_Response stationInResponse = new XmMES_UpFile_Response();
+
+            string bodyJson = JsonConvert.SerializeObject(body);
+            XiaomiMES_X5RequestHeader header = new XiaomiMES_X5RequestHeader();
+            header.appid = Appid;                               // 系统分配的应⽤ID
+            header.method = Method;                             // API接⼝名称
+            header.sign = GetSign_Up(Appid, bodyJson, Appkey);  // md5签名
+            header.url = UpFileUrl;                                // 接⼝地址
+
+            //XmMES_StationInRequest request = new XmMES_StationInRequest();
+            //request.header = header;
+            //request.body = body;
+            //string data = JsonConvert.SerializeObject(request);
+
+            //转base64
+            dynamic requestData = new { header = header, body = bodyJson };
+            var serializedBody = JsonConvert.SerializeObject(requestData);
+            var base64EncodedBody = Convert.ToBase64String(Encoding.UTF8.GetBytes(serializedBody));
+            XiaomiMES_X5Response response = Post(UpFileUrl, base64EncodedBody);
+            // ZS保存日志
+
+
+            stationInResponse.header = response.header;
+            string responseBody = response.body;
+            stationInResponse.body = JsonConvert.DeserializeObject<XmMES_UpFile_Response_Body>(responseBody);
+            return stationInResponse;
+        }
+
+        #region 入参
+        /// <summary>
+        /// 上传图片 - 入参
+        /// </summary>
+        public class XmMES_UpFile_Request
+        {
+            /// <summary>
+            /// 进站接⼝ - 入参 - header
+            /// </summary>
+            public XiaomiMES_X5RequestHeader header { get; set; } = new XiaomiMES_X5RequestHeader();
+
+            /// <summary>
+            /// 进站接⼝ - 入参 - body
+            /// </summary>
+            public XmMES_UpFile_Request_Body body { get; set; } = new XmMES_UpFile_Request_Body();
+        }
+
+        /// <summary>
+        /// 进站接⼝ - 入参 - Body 实体
+        /// </summary>
+        public class XmMES_UpFile_Request_Body
+        {
+            /// <summary>
+            /// ⽂件所属包  格式为:/A/B,如/home/work/app
+            /// </summary>
+            public string bucket { get; set; } = string.Empty;
+            /// <summary>
+            /// ⽂件名
+            /// </summary>
+            public string name { get; set; } = string.Empty;
+            /// <summary>
+            /// ⽂件内容
+            /// </summary>
+            public string file { get; set; } = string.Empty;
+            /// <summary>
+            /// ⽂件唯⼀标识  可选项,⽤于⾃⾏⽣成⽂件标识符,⽂件服务后台会进⾏判重
+            /// </summary>
+            public string uuid { get; set; } = string.Empty;
+            /// <summary>
+            /// 可选项,⽤于校验⽂件上传是否正确
+            /// </summary>
+            public string md5 { get; set; } = string.Empty;
+            /// <summary>
+            /// 是否上云
+            /// </summary>
+            public bool uploadCloud { get; set; } = false;
+            /// <summary>
+            /// 是否通知mqtt
+            /// </summary>
+            public bool informMqtt { get; set; } = false;
+            /// <summary>
+            /// 发送通知时的负载
+            /// </summary>
+            public string mqttPayload { get; set; } = string.Empty;
+        }
+        #endregion
+
+
+        #region 出参
+        /// <summary>
+        /// 上传图片 - 出参
+        /// </summary>
+        public class XmMES_UpFile_Response
+        {
+            /// <summary>
+            /// header字段描述
+            /// </summary>
+            public XiaomiMES_X5ResponseHeader header { get; set; } = new XiaomiMES_X5ResponseHeader();
+
+            /// <summary>
+            /// body字段描述
+            /// </summary>
+            public XmMES_UpFile_Response_Body body { get; set; } = new XmMES_UpFile_Response_Body();
+        }
+
+        /// <summary>
+        /// 出参
+        /// </summary>
+        public class XmMES_UpFile_Response_Body
+        {
+            /// <summary>
+            /// 关键参数代码
+            /// 200:成功
+            /// 400:参数错误
+            /// 500:服务器内部错误
+            /// </summary>
+            public string code { get; set; } = string.Empty;
+            /// <summary>
+            /// 关键参数msg
+            /// </summary>
+            public string msg { get; set; } = string.Empty;
+            /// <summary>
+            /// 关键参数值,如果是⽂件,这⾥是下载⽂件的url
+            /// </summary>
+            public UploadResult data { get; set; } = new UploadResult();
+
+        }
+
+        public class UploadResult
+        {
+            public string uuid { get; set; } = string.Empty;
+
+        }
+        #endregion 出参
+    }
+
+
+}

+ 73 - 2
MainForm/FaForm/Form_Home.cs

@@ -37,6 +37,9 @@ using System.Web.Services.Description;
 using System.Numerics;
 using MathNet.Numerics.RootFinding;
 using System.Net.Http;
+using static MainForm.ClassFile.XiaomiAPI_MES.XiaomiMESHttp_UpLoadFile;
+using MathNet.Numerics.Statistics;
+using System.Runtime.Remoting.Contexts;
 
 /*
  * 注:本源码对外提供,所以有些地方使用中文命名方法及变量
@@ -1332,6 +1335,8 @@ namespace MainForm
             string leftPath = path + "\\Left";
             string rightPath = path + "\\Right";
             string sql = "";
+            Guid guid;
+            int result = 0;
             var formData = new MultipartFormDataContent();
 
             // 获取所有图片文件
@@ -1341,6 +1346,7 @@ namespace MainForm
             {
                 foreach (string imageFile in imageFiles_L)
                 {
+                    guid = Guid.NewGuid();
                     //formData = MultipartbyFile(imageFile);
                     sql = string.Format("INSERT INTO [dbo].[DataFiles](stationCode,stationName,CarrierBarcode,ProductBarcode,bucket,fileName,fileContext,uuid,fileUrl,status,submitTime,createTime) " +
                         "VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')"
@@ -1351,13 +1357,14 @@ namespace MainForm
                         , "/mesCommToPC/pic/left"
                         , Path.GetFileName(imageFile)
                         , ""
-                        , ""
+                        , guid.ToString()
                         , ""
                         , 0
                         , ""
                         , DateTime.Now
                         );
                     string ret = SQLHelper_New.ExecuteNonQuery(sql, null);
+                    sendPostFile(path, Path.GetFileName(imageFile), guid.ToString(), "");
                 }
                 foreach (string imageFile in imageFiles_R)
                 {
@@ -1378,13 +1385,14 @@ namespace MainForm
                         , DateTime.Now
                         );
                     string ret = SQLHelper_New.ExecuteNonQuery(sql, null);
+                    result = ret == "成功" ? 1 : 6;
                 }
             }
             catch (Exception)
             {
                 AddMessage_Station(stationName, LogType.Error, $"图片保存失败!载具码:{stPLC_MesData.BarcodeSet.strCarrierBarcode}产品码{stPLC_MesData.BarcodeSet.strProductBarcode}");
-
             }
+
         }
 
         /// <summary>
@@ -1432,6 +1440,69 @@ namespace MainForm
             }
         }
 
+        public int sendPostFile(string bucket, string filename,string guid, string context)
+        {
+            int result = 0;
+
+            XmMES_UpFile_Request_Body inRequest_Body = new XmMES_UpFile_Request_Body();
+            inRequest_Body.bucket = bucket;
+            inRequest_Body.name = filename;
+            inRequest_Body.uuid = guid;
+            inRequest_Body.file = context;     
+
+            string json_Body = JsonConvert.SerializeObject(inRequest_Body);
+            //await Task.Delay(200);
+            // 上传MES
+            if (GlobalContext.IsSendStationIn)
+            {
+                try
+                {
+                    XmMES_UpFile_Response response = new XmMES_UpFile_Response();
+                    string mesRet = string.Empty;
+                    int i = 0;
+                    while (i < 2)  // 1009会多次尝试上传
+                    {
+                        response = XiaomiMESHttp_UpLoadFile.UpFilePost(inRequest_Body);
+                        if (response != null && response.header.code == "200")
+                            break;
+                        else if (!mesRet.Contains("1009"))  // 1009是未知错误
+                            i++;
+
+                        i++;
+
+                        mesRet = $"[{response?.header?.code}]{response?.header?.desc}";
+                        // 记录失败原因
+                        OnMessage(LogType.Error, "上传出站数据到MES服务器---失败!正在重新上传!接口报错信息:" + mesRet + "参数:" + json_Body);
+                    }
+
+
+                    if (response?.header?.code == "200")
+                    {
+                        //string sql_Upd = stationIn.ToStringUpdateStatusByID(1);
+                        //string ret_Upd = SQLHelper_New.ExecuteNonQuery(sql_Upd, null);
+                        //result = ret_Upd == "成功" ? 1 : 6;
+                        //AddMessage(LogType.Info, $"【进站数据 SN {stationIn.Sn}】上传MES服务器---成功");
+                    }
+                    else
+                    {
+                        result = 5;
+                        //AddMessage(LogType.Info, $"【进站数据 SN {stationIn.Sn}】上传MES服务器---失败!接口报错信息:" + mesRet);
+                    }
+                    //string sql_response = stationIn.ToStringUpdateStationInReturn_body(JsonConvert.SerializeObject(response));
+                    //SQLHelper_New.ExecuteNonQuery(sql_response, null);
+                }
+                catch (Exception ex)
+                {
+                    result = 6;
+                    string str = ex.StackTrace;
+                    //AddMessage_Station(stationNameStr, LogType.Error, $"PLC上传进站数据MES报错!错误信息:" + ex.Message.ToString() + ";异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1));
+                }
+            }
+
+            return result;
+        }
+
+
         //private void CollectAndProcessDataLeft(string sn, string direction, string ip, string port, int connectTimeOut, int sendDataTimeOut)
         //{
         //    Stopwatch stopwatch = new Stopwatch();

+ 1 - 0
MainForm/MainForm.csproj

@@ -285,6 +285,7 @@
     <Compile Include="ClassFile\XiaomiAPI_IOT\Extend\XiaomiMqttClient_PassStationResult.cs" />
     <Compile Include="ClassFile\XiaomiAPI_IOT\XiaomiMqttLoginParam.cs" />
     <Compile Include="ClassFile\XiaomiAPI_IOT\XiaomiMqttResponse_ErrCode.cs" />
+    <Compile Include="ClassFile\XiaomiAPI_MES\XiaomiMESHttp_UpLoadFile.cs" />
     <Compile Include="ClassFile\XiaomiAPI_MES\XiaomiMESHttp_StationOutbound.cs" />
     <Compile Include="ClassFile\XiaomiAPI_MES\XiaomiMESHttp_StationInbound.cs" />
     <Compile Include="ClassFile\XiaomiAPI_MES\XiaomiMESHttp_X5.cs" />