添加项目文件。
This commit is contained in:
@@ -0,0 +1,808 @@
|
||||
using JinYuan.DAL;
|
||||
using JinYuan.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows.Forms;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using JinYuan.Helper;
|
||||
using JinYuan.MES;
|
||||
using PLC;
|
||||
using PLC.PLCAlarm;
|
||||
using System.Xml.Linq;
|
||||
using JinYuan.MES.Models;
|
||||
using HML;
|
||||
using System.Data;
|
||||
using System.Collections.Concurrent;
|
||||
using JinYuan.VirtualDataLibrary.Utlis;
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary
|
||||
{
|
||||
public class CommonMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// 本地数据库
|
||||
/// </summary>
|
||||
public static ISugarHepler db = new SQLSugarService();
|
||||
/// <summary>
|
||||
/// C段出站数据库
|
||||
/// </summary>
|
||||
public static ISugarHepler dbC = new SQLSugarService();
|
||||
/// <summary>
|
||||
/// 远程服务段数据库
|
||||
/// </summary>
|
||||
public static ISugarHepler dbServer = new SQLSugarService();
|
||||
/// <summary>
|
||||
/// 全局的PLC链接
|
||||
/// </summary>
|
||||
public static List<PlcReadWriteBase> plcDevices;
|
||||
/// <summary>
|
||||
/// plc状态
|
||||
/// </summary>
|
||||
public static readonly Dictionary<PlcReadWriteBase, Dictionary<string, object>> plcStatuses = new Dictionary<PlcReadWriteBase, Dictionary<string, object>>();
|
||||
/// <summary>
|
||||
/// 报警
|
||||
/// </summary>
|
||||
public static AlarmManager alarmManager = new AlarmManager();
|
||||
/// <summary>
|
||||
/// MES接口
|
||||
/// </summary>
|
||||
public static IMes hbgMes = new MesDataProcess();
|
||||
/// <summary>
|
||||
/// 参数
|
||||
/// </summary>
|
||||
public static ProductModelParam parRange = new ProductModelParam();
|
||||
/// <summary>
|
||||
/// 全局钩子
|
||||
/// </summary>
|
||||
public static ScanerHook listener = new ScanerHook();
|
||||
|
||||
/// <summary>
|
||||
/// 创建个全局焊接功率队列数据存储
|
||||
/// </summary>
|
||||
public static List<Queue<double>> QWeldingPowerData = new List<Queue<double>>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建个全局入壳推力队列数据存储
|
||||
/// </summary>
|
||||
public static List<Queue<double>> QPlanenessData = new List<Queue<double>>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建全局的登录对象
|
||||
/// </summary>
|
||||
public static SysAdmin currentAdmin = null;
|
||||
/// <summary>
|
||||
/// 创建全局的登录对象
|
||||
/// </summary>
|
||||
public static List<NgCodeEntity> listNgCodeEntity = new List<NgCodeEntity>();
|
||||
/// <summary>
|
||||
/// 登录是否成功
|
||||
/// </summary>
|
||||
public static bool IsLoginOk = false;
|
||||
|
||||
//创建一个全局的配置对象
|
||||
public static SysConfig sysConfig = new SysConfig();
|
||||
|
||||
public static int InvadTime;
|
||||
|
||||
/// <summary>
|
||||
/// 智能电表
|
||||
/// </summary>
|
||||
public static List<ElectricEnergy> listElectricEnergy = new List<ElectricEnergy>();
|
||||
|
||||
/// <summary>
|
||||
/// 电能表
|
||||
/// </summary>
|
||||
public static EnergyMeterHelper energyMeter = new EnergyMeterHelper();
|
||||
|
||||
/// <summary>
|
||||
///是否开启刷新
|
||||
/// </summary>
|
||||
public static bool isRefreshTimerWeeding = false;
|
||||
|
||||
/// <summary>
|
||||
/// SQL语句
|
||||
/// </summary>
|
||||
public static DBSQL dBSQL { get; } = new DBSQL();
|
||||
|
||||
public static M_DBCtrl m_DBCtrl { get; } = new M_DBCtrl();
|
||||
|
||||
/// <summary>
|
||||
/// MES配置文件类
|
||||
/// </summary>
|
||||
public static MesConfig mesConfig = new MesConfig();
|
||||
|
||||
/// <summary>
|
||||
/// 打印模板配置文件类
|
||||
/// </summary>
|
||||
public static BTWConfig btwConfig = new BTWConfig();
|
||||
|
||||
///创建一个全局的连接状态
|
||||
public static bool connectState = false;
|
||||
|
||||
/// <summary>
|
||||
/// 滴答次数
|
||||
/// </summary>
|
||||
public static int tickCount = 0;
|
||||
/// <summary>
|
||||
/// QIEHUAN
|
||||
/// </summary>
|
||||
public static int tickHomeCount = 0;
|
||||
/// <summary>
|
||||
/// 报警信息
|
||||
/// </summary>
|
||||
public static string SlideAlarmText = "当前无报警";
|
||||
/// <summary>
|
||||
/// 退出
|
||||
/// </summary>
|
||||
public static bool IsExit = false;
|
||||
/// <summary>
|
||||
/// 是否登出账户
|
||||
/// </summary>
|
||||
public static bool LoginOut = false;
|
||||
/// <summary>
|
||||
/// 是否上传MES
|
||||
/// </summary>
|
||||
public static bool IsUpMes { get; set; }
|
||||
/// <summary>
|
||||
/// 是否运行
|
||||
/// </summary>
|
||||
public static bool IsRun { get; set; } = false;
|
||||
/// <summary>
|
||||
/// 上一次设备状态
|
||||
/// </summary>
|
||||
public static int DeviceStatus = 0;
|
||||
/// <summary>
|
||||
/// 上一次Guid
|
||||
/// </summary>
|
||||
public static string DeviceGuid = "";
|
||||
/// <summary>
|
||||
///第一次读取
|
||||
/// </summary>
|
||||
public static bool IsFirst = false;
|
||||
/// <summary>
|
||||
/// 焊接功率波形图显示条数
|
||||
/// </summary>
|
||||
public static int ChatLineCount = 3;
|
||||
/// <summary>
|
||||
/// 员工号
|
||||
/// </summary>
|
||||
public static string strWorker { get; set; }
|
||||
/// <summary>
|
||||
/// 是否开启智能电表
|
||||
/// </summary>
|
||||
public static bool IsStartZNDB { get; set; } = false;
|
||||
/// <summary>
|
||||
/// 白夜班
|
||||
/// </summary>
|
||||
public static string strClass { get; set; } = "白班";
|
||||
/// <summary>
|
||||
/// 时间变更
|
||||
/// </summary>
|
||||
public static string ChangeClassTime { get; set; } = "20:30:00";
|
||||
/// <summary>
|
||||
/// 设备状态
|
||||
/// </summary>
|
||||
public static List<bool> Statues { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 服务器链接状态
|
||||
/// </summary>
|
||||
public static bool EMCStatues { get; set; }
|
||||
|
||||
#region 小时产能
|
||||
/// <summary>
|
||||
/// 上个时间点的总数
|
||||
/// </summary>
|
||||
public static int LastTotalNum { get; set; } = 0;
|
||||
/// <summary>
|
||||
/// 上个时间点良品数
|
||||
/// </summary>
|
||||
public static int LastOkNum { get; set; } = 0;
|
||||
/// <summary>
|
||||
/// 上一次重置计数的时间
|
||||
/// </summary>
|
||||
public static string LastResetTime { get; set; }
|
||||
/// <summary>
|
||||
/// 上一次的小时
|
||||
/// </summary>
|
||||
public static int LastHour { get; set; }
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static List<Group> ListOmronGroups { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 12小时产能
|
||||
/// </summary>
|
||||
public static List<Chart12HourData> Lst_Prod12HourData = new List<Chart12HourData>();
|
||||
/// <summary>
|
||||
/// 不良选项(检测项不良)
|
||||
/// </summary>
|
||||
public static List<ChartDataType> Lst_DefectTypeQty = new List<ChartDataType>();
|
||||
|
||||
/// <summary>
|
||||
/// PLC报警前10项
|
||||
/// </summary>
|
||||
public static List<ChartDataType> Lst_AlarmTop10_Qty = new List<ChartDataType>();
|
||||
/// <summary>
|
||||
/// 参数项设置
|
||||
/// </summary>
|
||||
public static List<ParamList> paramlists { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 线程控制
|
||||
/// </summary>
|
||||
public static ManualResetEvent ResetEventRecv = new ManualResetEvent(true);
|
||||
|
||||
|
||||
#region 计数项
|
||||
/// <summary>
|
||||
/// 生产总数
|
||||
/// </summary>
|
||||
public static float TotalQty = 0;
|
||||
|
||||
public static float ProOKQty = 0;
|
||||
|
||||
public static float Ppm = 0;
|
||||
|
||||
public static double JiaDL = 0.0;
|
||||
|
||||
public static List<float> AntiDustAirSpeed = new List<float>();
|
||||
/// <summary>
|
||||
/// PLC开机/运行时间
|
||||
/// </summary>
|
||||
public static List<int> PlcOpenAndRunTime = new List<int>();
|
||||
/// <summary>
|
||||
/// PLC开机/运行时间地址
|
||||
/// </summary>
|
||||
public static List<string> PlcOpenAndRunTimeAdress = new List<string> { "D50", "D52", "D54", "D56", "D58", "D60" };
|
||||
public static int ProdGaoRFIDNgQty = 0;//高托杯 绑定卷心码
|
||||
public static int ProdDiRFIDNgQty = 0;//低托杯 绑定钢壳码
|
||||
|
||||
public static int ProdGangKeRFIDNgQty = 0;//钢壳托杯 绑定出站钢壳码
|
||||
public static int ProdJuanBarNgQty = 0;
|
||||
public static int ProdGangKeBarNgQty = 0;
|
||||
|
||||
public static int ProdRuKeTuiliNgQty = 0;
|
||||
public static int ProdCCDNgQty = 0;
|
||||
public static int ProdMesOutNGQty = 0;
|
||||
#endregion
|
||||
|
||||
#region 配置信息
|
||||
/// <summary>
|
||||
/// 错误日志路径
|
||||
/// </summary>
|
||||
public static string strErrorLogspath = "D:\\APILog\\Logs\\ErrorLogs";
|
||||
|
||||
public static string strSystemLogspath = "D:\\APILog\\Logs\\SystemLogs";
|
||||
public static string strAlarmLogspath = "D:\\APILog\\Logs\\AlarmLogs";
|
||||
|
||||
public static string strsqlLogspath = "";
|
||||
/// <summary>
|
||||
/// 删除路径
|
||||
/// </summary>
|
||||
public static string strDeletepath = "";
|
||||
/// <summary>
|
||||
/// 能耗保存路径
|
||||
/// </summary>
|
||||
public static string strWattrMeterpath = "D:\\APILog\\Logs\\智能电表数据";
|
||||
/// <summary>
|
||||
/// MES路径日志
|
||||
/// </summary>
|
||||
public static string strMesLogspath = "D:\\APILog\\Logs\\MesLogs";
|
||||
/// <summary>
|
||||
/// 设备状态信息路径
|
||||
/// </summary>
|
||||
public static string strDeviceStatusPath = System.Windows.Forms.Application.StartupPath + "\\Config\\DeviceStatus.cfg";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 主界面下列表绑定数据
|
||||
/// </summary>
|
||||
public static DropDownListPlusItemCollection DropDownItemList = new DropDownListPlusItemCollection();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// PLC读取寄存器配置文件路径
|
||||
/// </summary>
|
||||
public static string ConfigPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "ini\\PlcConfig.ini");
|
||||
/// <summary>
|
||||
/// 系统程序配置文件路径
|
||||
/// </summary>
|
||||
//public static string iniFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "ini\\Configure.ini");
|
||||
|
||||
public static string xmlFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Config\\Configure.xml");
|
||||
/// <summary>
|
||||
/// 配置文件字典
|
||||
/// </summary>
|
||||
public static Dictionary<string, Dictionary<string, string>> Configxml = new Dictionary<string, Dictionary<string, string>>();
|
||||
|
||||
|
||||
#region 读取配置文件
|
||||
|
||||
// 读取 XML 配置文件
|
||||
public static Dictionary<string, Dictionary<string, string>> ReadXmlConfig(string filePath)
|
||||
{
|
||||
var config = new Dictionary<string, Dictionary<string, string>>();
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
MessageBox.Show($"配置文件不存在:{filePath}\n请检查Config文件夹是否存在,且包含Configure.xml文件");
|
||||
return config;
|
||||
}
|
||||
|
||||
XDocument xmlDoc = XDocument.Load(filePath);
|
||||
|
||||
foreach (var sectionElement in xmlDoc.Root.Elements())
|
||||
{
|
||||
string sectionName = sectionElement.Name.LocalName;
|
||||
config[sectionName] = new Dictionary<string, string>();
|
||||
|
||||
foreach (var keyElement in sectionElement.Elements())
|
||||
{
|
||||
string key = keyElement.Name.LocalName;
|
||||
string value = keyElement.Value;
|
||||
config[sectionName][key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
// 获取配置值
|
||||
public static string GetConfigValue(Dictionary<string, Dictionary<string, string>> config, string section, string key, string defaultValue)
|
||||
{
|
||||
if (config.ContainsKey(section) && config[section].ContainsKey(key))
|
||||
{
|
||||
return config[section][key];
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
|
||||
// 写入 XML 文件
|
||||
public static void WriteXmlFile(Dictionary<string, Dictionary<string, string>> config, string filePath)
|
||||
{
|
||||
XDocument xmlDoc = new XDocument(new XElement("Configuration"));
|
||||
|
||||
foreach (var section in config)
|
||||
{
|
||||
var sectionElement = new XElement(section.Key);
|
||||
foreach (var keyValue in section.Value)
|
||||
{
|
||||
sectionElement.Add(new XElement(keyValue.Key, keyValue.Value));
|
||||
}
|
||||
xmlDoc.Root.Add(sectionElement);
|
||||
}
|
||||
xmlDoc.Save(filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单个配置数据保存
|
||||
/// </summary>
|
||||
/// <param name="INFO"></param>
|
||||
/// <param name="Type"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void UpdateConfig(string INFO, string Type, string value)
|
||||
{
|
||||
// 更新 Configxml 中的 SteelshellCount
|
||||
CommonMethods.Configxml[INFO][Type] = value;
|
||||
|
||||
// 将更新后的 Configxml 写入文件
|
||||
CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
///读取配置文件
|
||||
/// </summary>
|
||||
public static SysConfig GetSysConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
#region 系统配置文件
|
||||
return sysConfig = new SysConfig
|
||||
{
|
||||
AutoStart = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoStart", "true")),
|
||||
AutoLogin = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoLogin", "true")),
|
||||
AutoLock = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoLockScreen", "false")),
|
||||
LockPeriod = Convert.ToInt32(GetConfigValue(Configxml, "CONFIG_INFO", "LockIntervalTime", "0")),
|
||||
AutoQieHuanM = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoSwitchMonitor", "false")),
|
||||
QieHuanMPeriod = Convert.ToInt32(GetConfigValue(Configxml, "CONFIG_INFO", "SwitchMonitorInterval", "0")),
|
||||
ShowSeriesCount = Convert.ToInt32(GetConfigValue(Configxml, "CONFIG_INFO", "CurveDisplayCount", "0")),
|
||||
SwipeCardMode = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "EnableCardMode", "false")),
|
||||
MesModeSwitching = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "MESModeSwitch", "false")),
|
||||
GetMesParam = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "FetchMESParams", "false")),
|
||||
SaveThreadTime = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "SaveThreadTimeLog", "false")),
|
||||
IsDebugMode = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "IsDebugMode", "true"))
|
||||
};
|
||||
#endregion
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return sysConfig = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取MES配置文件
|
||||
/// </summary>
|
||||
public static MesConfig GetMesConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
#region MES配置文件
|
||||
return mesConfig = new MesConfig
|
||||
{
|
||||
siteCode = GetConfigValue(Configxml, "MES_CONFIG", "SiteCode", "57M"),
|
||||
lineCode = GetConfigValue(Configxml, "MES_CONFIG", "LineCode", "PW-571"),
|
||||
equipNum = GetConfigValue(Configxml, "MES_CONFIG", "EquipNum", "571VIM01"),
|
||||
CustomerPartNum = GetConfigValue(Configxml, "MES_CONFIG", "CustomerPartNum", "491VIM01"),
|
||||
containerCode = GetConfigValue(Configxml, "MES_CONFIG", "ContainerCode", "PLT43F030000001"),
|
||||
MESURLAddressIP = GetConfigValue(Configxml, "MES_CONFIG", "MESIp", "10.100.111.81"),
|
||||
MESURLAddressPort = GetConfigValue(Configxml, "MES_CONFIG", "MESPort", "80"),
|
||||
EmployeeAuthCheck = GetConfigValue(Configxml, "MES_CONFIG", "EmployeeAuthCheck", "571VIM01"),
|
||||
DeviceParamRequest = GetConfigValue(Configxml, "MES_CONFIG", "DeviceParamRequest", "571VIM01"),
|
||||
DeviceParamChange = GetConfigValue(Configxml, "MES_CONFIG", "DeviceParamChange", "491581VIM01VIM01"),
|
||||
DeviceAlarm = GetConfigValue(Configxml, "MES_CONFIG", "DeviceAlarm", "581VIM01"),
|
||||
DeviceStatus = GetConfigValue(Configxml, "MES_CONFIG", "DeviceStatus", "581VIM01"),
|
||||
EnergyConsumption = GetConfigValue(Configxml, "MES_CONFIG", "EnergyConsumption", "581VIM01"),
|
||||
Anemometer = GetConfigValue(Configxml, "MES_CONFIG", "Anemometer", "581VIM01"),
|
||||
//AppID = GetConfigValue(Configxml, "MES_CONFIG", "APPID", "491VIM01"),
|
||||
//AppKey = GetConfigValue(Configxml, "MES_CONFIG", "APPKEY", "491VIM01"),
|
||||
//GetTokenUrl = GetConfigValue(Configxml, "MES_CONFIG", "GetTokenUrl", "491VIM01"),
|
||||
queryCartonUrl = GetConfigValue(Configxml, "MES_CONFIG", "QueryCartonUrl", ""),
|
||||
queryPalletUrl = GetConfigValue(Configxml, "MES_CONFIG", "QueryPalletUrl", ""),
|
||||
bindingUrl = GetConfigValue(Configxml, "MES_CONFIG", "BindingUrl", ""),
|
||||
customerType = GetConfigValue(Configxml, "MES_CONFIG", "customerType", "O2"),
|
||||
};
|
||||
#endregion
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return mesConfig = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取BTW配置文件
|
||||
/// </summary>
|
||||
public static BTWConfig GetBtwConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
#region 打印模板路径配置文件
|
||||
return btwConfig = new BTWConfig
|
||||
{
|
||||
IsConnectPrinter = Convert.ToBoolean(GetConfigValue(Configxml, "BTW_CONFIG", "IsConnectPrinter", "false")),
|
||||
containerBTWPath = GetConfigValue(Configxml, "BTW_CONFIG", "ContainerBTWPath", ""),
|
||||
palletBTWPath = GetConfigValue(Configxml, "BTW_CONFIG", "PalletBTWPath", ""),
|
||||
printerName = GetConfigValue(Configxml, "BTW_CONFIG", "PrinterName", ""),
|
||||
};
|
||||
#endregion
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return btwConfig = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static string deviceConfigPath = Application.StartupPath + "\\Config\\Device.xlsx";
|
||||
public static string groupConfigPath = Application.StartupPath + "\\Config\\Group.xlsx";
|
||||
public static string variableConfigPath = Application.StartupPath + "\\Config\\Variable.xlsx";
|
||||
public static string FdConfigFilePath = Application.StartupPath + "\\Config\\FdConfig.xlsx";
|
||||
|
||||
|
||||
#region 保存配置文件
|
||||
/// <summary>
|
||||
/// 保存启动自动登录
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveAutoStart(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["AutoStart"] = value.ToString(); // 修改自动登录为 True
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// 保存开机自动启动
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveAutoLogin(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["AutoLogin"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存无操作自动锁屏
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveAutoLock(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["AutoLockScreen"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool SaveConnectPrinter(bool value)
|
||||
{
|
||||
Configxml["BTW_CONFIG"]["IsConnectPrinter"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存锁屏间隔时间
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveLockPeriod(int value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["LockIntervalTime"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 保存无操作自动切换监控界面
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveAutoQieHuanM(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["AutoSwitchMonitor"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 保存无操作自动切换监控界面
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveIsDebug(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["IsDebugMode"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存切换监控界面间隔时间
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveQieHuanMPeriod(int value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["SwitchMonitorInterval"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存曲线显示数量
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveShowSeriesCount(int value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["CurveDisplayCount"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开启刷卡模式
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveSwipeCardMode(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["EnableCardMode"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// MES/非MES模式
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveOpenMesModel(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["MESModeSwitch"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取MES参数
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveGetMesParam(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["FetchMESParams"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存线程耗时操作
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool SaveSaveThreadTime(bool value)
|
||||
{
|
||||
Configxml["CONFIG_INFO"]["SaveThreadTimeLog"] = value.ToString();
|
||||
WriteXmlFile(Configxml, xmlFilePath);
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region 委托信息
|
||||
//创建委托
|
||||
// 数据监视委托
|
||||
public static Action<int, string> AddDataMonitorDelegate;
|
||||
/// <summary>
|
||||
/// 系统日志
|
||||
/// </summary>
|
||||
public static Action<bool, string> AddLogDelegate;
|
||||
/// <summary>
|
||||
/// 操作日志
|
||||
/// </summary>
|
||||
public static Action<bool, string> AddOPLogDelegate;
|
||||
/// <summary>
|
||||
/// 报警日志
|
||||
/// </summary>
|
||||
public static Action<SysLog> AddAlarmDelegate;
|
||||
/// <summary>
|
||||
/// 显示报警信息
|
||||
/// </summary>
|
||||
public static Action<string> ShowAlarmDelegate;
|
||||
/// <summary>
|
||||
/// 参数更新
|
||||
/// </summary>
|
||||
public static Action ChangeParamDelegate;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static Action<bool> AddHomeDelegate;
|
||||
/// <summary>
|
||||
/// 显示进站信息
|
||||
/// </summary>
|
||||
public static Action<List<AGearEntity>> ShowFeedingDelegate;
|
||||
/// <summary>
|
||||
/// 显示出站数据
|
||||
/// </summary>
|
||||
public static Action<List<BGearEntity>> ShowBlankingDelegate;
|
||||
/// <summary>
|
||||
/// 显示箱唛打印信息
|
||||
/// </summary>
|
||||
public static Action<List<DGearEntity>> ShowPrintContainergDelegate;
|
||||
/// <summary>
|
||||
/// 显示栈板打印信息
|
||||
/// </summary>
|
||||
public static Action<List<EGearEntity>> ShowPrintPalletDelegate;
|
||||
/// <summary>
|
||||
/// 数据监视委托
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="info"></param>
|
||||
public static void AddDataMonitorLog(int type, string info)
|
||||
{
|
||||
//调用委托
|
||||
if (AddDataMonitorDelegate != null)
|
||||
{
|
||||
AddDataMonitorDelegate(type, info);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写入系统日志
|
||||
/// </summary>
|
||||
/// <param name="isError">是否为错误信息</param>
|
||||
/// <param name="info">日志信息</param>
|
||||
public static void AddLog(bool isError, string info)
|
||||
{
|
||||
//调用委托
|
||||
if (AddLogDelegate != null)
|
||||
{
|
||||
AddLogDelegate(isError, info);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 写入操作日志
|
||||
/// </summary>
|
||||
/// <param name="isError"></param>
|
||||
/// <param name="info"></param>
|
||||
public static void AddOPLog(bool isError, string info)
|
||||
{
|
||||
//调用委托
|
||||
if (AddLogDelegate != null)
|
||||
{
|
||||
AddOPLogDelegate(isError, info);
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddAlarmLog(SysLog sysLog)
|
||||
{
|
||||
//调用委托
|
||||
if (AddAlarmDelegate != null)
|
||||
{
|
||||
AddAlarmDelegate(sysLog);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示报警日志
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
public static void ShowAlarmLog(string info)
|
||||
{
|
||||
//调用委托
|
||||
if (ShowAlarmDelegate != null)
|
||||
{
|
||||
ShowAlarmDelegate(info);
|
||||
}
|
||||
}
|
||||
|
||||
public static void ChangeParamData()
|
||||
{
|
||||
//调用委托
|
||||
if (ChangeParamDelegate != null)
|
||||
{
|
||||
ChangeParamDelegate();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// TODO PLC变量集合
|
||||
/// KEY = VarAddress
|
||||
/// </summary>
|
||||
public static ConcurrentDictionary<string, PLCGroupVariable> PLCVariable = new ConcurrentDictionary<string, PLCGroupVariable>();
|
||||
|
||||
// 打印机
|
||||
/// <summary>
|
||||
/// zebra
|
||||
/// </summary>
|
||||
public static BartenderPrinter containerPrint;
|
||||
//public static string containerPrintName = "ContainerPrint";
|
||||
|
||||
/// <summary>
|
||||
/// 栈板
|
||||
/// </summary>
|
||||
public static BartenderPrinter palletPrint;
|
||||
//public static string palletPrintName = "PalletPrint";
|
||||
|
||||
/// <summary>
|
||||
/// 3S
|
||||
/// </summary>
|
||||
//public static BartenderPrinter _3SPrint;
|
||||
//public static string _3SPrintName = "3SPrint";
|
||||
|
||||
/// <summary>
|
||||
/// 6J
|
||||
/// </summary>
|
||||
//public static BartenderPrinter _6JPrint;
|
||||
//public static string _6JPrintName = "6JPrint";
|
||||
|
||||
public static PrintSocket.TCPClient tcpClient;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary
|
||||
{
|
||||
public class DBSQL
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 获取PLC换型参数绑定值
|
||||
/// </summary>
|
||||
/// <param name="modelName"></param>
|
||||
/// <returns></returns>
|
||||
public string GetPlcParamSql(string modelName)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
'{modelName}' AS `ModelName`,
|
||||
`pb`.`PLCAddress`,
|
||||
`pc`.`PLCValue`,
|
||||
`pc`.`UpdateTime`,
|
||||
`pb`.`PLCRemark`,
|
||||
`pb`.`OrderNum`
|
||||
FROM
|
||||
`Plcconfigbase` `pb`
|
||||
LEFT JOIN
|
||||
(SELECT * FROM `Plcconfig` WHERE `ModelName` = '{modelName}') `pc`
|
||||
ON
|
||||
`pb`.`PLCAddress` = `pc`.`PLCAddress`
|
||||
ORDER BY
|
||||
`pb`.`OrderNum`";
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取产品型号参数
|
||||
/// </summary>
|
||||
/// <param name="strModelType"></param>
|
||||
/// <returns></returns>
|
||||
public string GetParamSql(string strModelType)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
`pb`.`ParaName`,
|
||||
'{strModelType}' AS `ModelName`,
|
||||
`pl`.`ParaValueMin`,
|
||||
`pl`.`ParaValueMax`,
|
||||
`pl`.`Uint`,
|
||||
`pb`.`Remark`,
|
||||
`pl`.`UpdateTime`
|
||||
FROM
|
||||
`Parambase` `pb`
|
||||
LEFT JOIN
|
||||
(SELECT * FROM `ParamList` WHERE `ModelName` = '{strModelType}') `pl`
|
||||
ON
|
||||
`pb`.`ParaName` = `pl`.`ParaName`
|
||||
ORDER BY
|
||||
`pb`.`fNo` ASC";
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取产品型号列表
|
||||
/// </summary>
|
||||
/// <param name="strProdType"></param>
|
||||
/// <returns></returns>
|
||||
public string GetProdTypeSql(string strProdType = "")
|
||||
{
|
||||
string strSql = @"SELECT * FROM ProductModel ";
|
||||
if (strProdType != "")
|
||||
{
|
||||
strSql += string.Format(" where ModelName='{0}'", strProdType);
|
||||
}
|
||||
strSql += " order by ModelName";
|
||||
return strSql;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取产品型号
|
||||
/// </summary>
|
||||
/// <param name="strModelType"></param>
|
||||
/// <returns></returns>
|
||||
public string GetProductParaByProdModel(string strModelType)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
`pb`.`ParaName`,
|
||||
'{strModelType}' AS `ModelName`,
|
||||
`pl`.`ParaValueMin`,
|
||||
`pl`.`ParaValueMax`,
|
||||
`pl`.`Uint`,
|
||||
`pb`.`Remark`,
|
||||
`pl`.`UpdateTime`
|
||||
FROM
|
||||
`Parambase` `pb`
|
||||
LEFT JOIN
|
||||
(SELECT * FROM `Paramlist` WHERE `ModelName` = '{strModelType}') `pl`
|
||||
ON
|
||||
`pb`.`ParaName` = `pl`.`ParaName`
|
||||
ORDER BY
|
||||
`pb`.`fNo` ASC";
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
|
||||
public string GetPLCConfigBases()
|
||||
{
|
||||
string strSql = string.Format(@"SELECT * FROM `Plcconfigbase` ORDER BY `OrderNum`");
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
|
||||
public string GetSysAdminSql()
|
||||
{
|
||||
string strSql = string.Format(@"SELECT
|
||||
`LoginId`,
|
||||
`LoginName`,
|
||||
`LoginPwd`,
|
||||
`LoginUid`,
|
||||
`LoginLevel`,
|
||||
`SystemLog`,
|
||||
`CpkData`,
|
||||
`HistoryData`,
|
||||
`ParamSet`,
|
||||
`SystemSet`,
|
||||
`UserManage`
|
||||
FROM
|
||||
`SysAdmin`");
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询历史数据
|
||||
/// </summary>
|
||||
/// <param name="strBarCode"></param>
|
||||
/// <param name="strDate1"></param>
|
||||
/// <param name="strDate2"></param>
|
||||
/// <returns></returns>
|
||||
public string SelectHostData(int type, string strRfid, string strBarCode, string strDate1, string strDate2)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(strDate1)) strDate1 = "1970-01-01 00:00:00";
|
||||
if (string.IsNullOrWhiteSpace(strDate2)) strDate2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
string searchKey = strRfid?.Replace("'", "''") ?? "";
|
||||
//if (string.IsNullOrEmpty(safeBarCode))
|
||||
// return strSql;
|
||||
|
||||
var queryTemplate = new Dictionary<int, (string SelectSql, string TableName, string TimeField, string SearchField)>
|
||||
{
|
||||
{ 0, ("`ContainerCode`, DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `TestTime`, `PalletCode`, `Result`, `Remark`", "`AGearEntity`", "`TestTime`", "`ContainerCode`") },
|
||||
{ 1, ("`ContainerCode`, DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `TestTime`, `Result`, `Remark`", "`DGearEntity`", "`TestTime`", "`ContainerCode`") },
|
||||
//{ 6, ("`PalletCode`, DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `TestTime`, `Result`, `Remark`", "`EGearEntity`", "`TestTime`", "`PalletCode`") },
|
||||
{ 2, ("`ContainerCode`, `PalletCode`, DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `TestTime`, `Weight`,`Result`, `Remark`", "`BGearEntity`", "`TestTime`", "`ContainerCode`") },
|
||||
{ 3, ("`container_id` AS `ContainerCode`, `tag_code`, `tag_value`, DATE_FORMAT(`create_time`, '%Y-%m-%d %H:%i:%s') AS `TestTime`", "`ContainerKVDetail`", "`create_time`", "`container_id`") },
|
||||
{ 4, ("`pallet_id` AS `PalletCode`, DATE_FORMAT(`create_time`, '%Y-%m-%d %H:%i:%s') AS `TestTime`, `tag_code`, `tag_value`", "`PalletKVDetail`", "`create_time`", "`pallet_id`") },
|
||||
{ 5, ("`pallet_id` AS `PalletCode`, `container_id` AS `ContainerCode`, DATE_FORMAT(`create_time`, '%Y-%m-%d %H:%i:%s') AS `TestTime`", "`PalletEntity`", "`create_time`", "") }
|
||||
};
|
||||
|
||||
var (selectSql, tableName, timeField, searchField) = queryTemplate[type];
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
sqlBuilder.AppendFormat("SELECT {0} FROM {1} WHERE {2} >= '{3}' AND {4} <= '{5}'",
|
||||
selectSql,tableName,timeField,strDate1.Replace("'", "''"),timeField,strDate2.Replace("'", "''"));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(searchKey))
|
||||
{
|
||||
if (type == 5)
|
||||
{
|
||||
// type=5特殊处理:同时匹配PalletCode和ContainerCode
|
||||
sqlBuilder.AppendFormat(" AND (`PalletCode` LIKE '%{0}%' OR `ContainerCode` LIKE '%{0}%')", searchKey);
|
||||
}
|
||||
else if (type == 6)
|
||||
{
|
||||
// type=6特殊处理:同时匹配pallet_id和container_id
|
||||
sqlBuilder.AppendFormat(" AND (`pallet_id` LIKE '%{0}%' OR `container_id` LIKE '%{0}%')", searchKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 普通类型:匹配指定搜索字段
|
||||
sqlBuilder.AppendFormat(" AND {0} LIKE '%{1}%'", searchField, searchKey);
|
||||
}
|
||||
}
|
||||
|
||||
// 返回纯SQL字符串(无自定义参数格式)
|
||||
return sqlBuilder.ToString();
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 查询报警历史数据
|
||||
/// </summary>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="alarmType"></param>
|
||||
/// <returns></returns>
|
||||
public string SelectHostAlarmData(string start, string end, int alarmType)
|
||||
{
|
||||
string strSql = "";
|
||||
switch (alarmType)
|
||||
{
|
||||
case 1:
|
||||
strSql = @"SELECT
|
||||
DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
|
||||
`PLCAdress`,
|
||||
`AlarmContent`,
|
||||
`AlarmCount`,
|
||||
`Class`
|
||||
FROM
|
||||
`AlarmCountEntry`
|
||||
WHERE
|
||||
`AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + $"' AND `Class` = '{CommonMethods.strClass}'";
|
||||
break;
|
||||
case 2:
|
||||
strSql = @"SELECT
|
||||
DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
|
||||
`PLCAdress`,
|
||||
`AlarmContent`,
|
||||
`AlarmCount`,
|
||||
`Class`
|
||||
FROM
|
||||
`AlarmCountEntry`
|
||||
WHERE
|
||||
`AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + $"' AND `Class` = '{CommonMethods.strClass}'";
|
||||
break;
|
||||
default:
|
||||
case 0:
|
||||
strSql = @"SELECT
|
||||
DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
|
||||
`PLCAdress`,
|
||||
`AlarmContent`,
|
||||
`AlarmCount`,
|
||||
`Class`
|
||||
FROM
|
||||
`AlarmCountEntry`
|
||||
WHERE
|
||||
`AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "'";
|
||||
break;
|
||||
}
|
||||
#region 旧
|
||||
//if (alarmType == "全天")
|
||||
//{
|
||||
// strSql = @"SELECT
|
||||
// DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
|
||||
// `PLCAdress`,
|
||||
// `AlarmContent`,
|
||||
// `AlarmCount`,
|
||||
// `Class`
|
||||
// FROM
|
||||
// `AlarmCountEntry`
|
||||
// WHERE
|
||||
// `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "'";
|
||||
//}
|
||||
//else if (alarmType == "白班")
|
||||
//{
|
||||
// strSql = @"SELECT
|
||||
// DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
|
||||
// `PLCAdress`,
|
||||
// `AlarmContent`,
|
||||
// `AlarmCount`,
|
||||
// `Class`
|
||||
// FROM
|
||||
// `AlarmCountEntry`
|
||||
// WHERE
|
||||
// `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "' AND `Class` = '白班'";
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// strSql = @"SELECT
|
||||
// DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
|
||||
// `PLCAdress`,
|
||||
// `AlarmContent`,
|
||||
// `AlarmCount`,
|
||||
// `Class`
|
||||
// FROM
|
||||
// `AlarmCountEntry`
|
||||
// WHERE
|
||||
// `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "' AND `Class` = '夜班'";
|
||||
//}
|
||||
#endregion
|
||||
return strSql;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按日统计
|
||||
/// </summary>
|
||||
/// <param name="startDateTime"></param>
|
||||
/// <param name="endDateTime"></param>
|
||||
/// <returns></returns>
|
||||
public string GetStaticByDay(string startDateTime, string endDateTime)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:00:00') AS `Day`,
|
||||
`ProdIn`,
|
||||
`ProdOut`,
|
||||
`Ppm`,
|
||||
CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN `ProdIn` > 0 THEN ROUND(COALESCE(`ProdOut`, 0) / COALESCE(`ProdIn`, 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'
|
||||
GROUP BY
|
||||
`TestTime`, `ProdOut`, `ProdIn`, `Ppm`, `JiaDL`
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Total' AS `Day`,
|
||||
SUM(`ProdIn`) AS ProdIn,
|
||||
SUM(`ProdOut`) AS ProdOut,
|
||||
AVG(`Ppm`) AS Ppm,
|
||||
CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'";
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按周查询
|
||||
/// </summary>
|
||||
/// <param name="startDateTime"></param>
|
||||
/// <param name="endDateTime"></param>
|
||||
/// <returns></returns>
|
||||
public string GetStaticByWeek(string startDateTime, string endDateTime)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
DATE_FORMAT(`TestTime`, '%Y-%m') AS `Week`,
|
||||
SUM(`ProdIn`) AS ProdIn,
|
||||
SUM(`ProdOut`) AS ProdOut,
|
||||
AVG(`Ppm`) AS Ppm,
|
||||
CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'
|
||||
GROUP BY
|
||||
DATE_FORMAT(`TestTime`, '%Y-%m'), `JiaDL`
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Total' AS `Week`,
|
||||
SUM(`ProdIn`) AS ProdIn,
|
||||
SUM(`ProdOut`) AS ProdOut,
|
||||
AVG(`Ppm`) AS Ppm,
|
||||
CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'";
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 按月查询
|
||||
/// </summary>
|
||||
/// <param name="startDateTime"></param>
|
||||
/// <param name="endDateTime"></param>
|
||||
/// <returns></returns>
|
||||
public string GetStaticByMonth(string startDateTime, string endDateTime)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
DATE_FORMAT(`TestTime`, '%Y-%m') AS `Month`,
|
||||
SUM(`ProdIn`) AS ProdIn,
|
||||
SUM(`ProdOut`) AS ProdOut,
|
||||
AVG(`Ppm`) AS Ppm,
|
||||
CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'
|
||||
GROUP BY
|
||||
DATE_FORMAT(`TestTime`, '%Y-%m'), `JiaDL`
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Total' AS `Month`,
|
||||
SUM(`ProdIn`) AS ProdIn,
|
||||
SUM(`ProdOut`) AS ProdOut,
|
||||
AVG(`Ppm`) AS Ppm,
|
||||
CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'";
|
||||
|
||||
return strSql;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按班次统计
|
||||
/// </summary>
|
||||
/// <param name="dateTime"></param>
|
||||
/// <param name="shift"></param>
|
||||
/// <param name="changeShiftTime"></param>
|
||||
/// <returns></returns>
|
||||
public string GetStaticByShift(DateTime dateTime, int shift, string changeShiftTime)
|
||||
{
|
||||
string sDateTime1 = string.Empty;
|
||||
string sDateTime2 = string.Empty;
|
||||
if (shift == 0)// 白班
|
||||
{
|
||||
DateTime sTempDateTime = Convert.ToDateTime($"{dateTime.ToString("yyyy-MM-dd")} {changeShiftTime}");
|
||||
|
||||
sDateTime1 = sTempDateTime.AddHours(-12).ToString("yyyy-MM-dd HH:mm:ss");
|
||||
sDateTime2 = sTempDateTime.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
else
|
||||
{
|
||||
sDateTime1 = $"{dateTime.ToString("yyyy-MM-dd")} {changeShiftTime}";
|
||||
sDateTime2 = Convert.ToDateTime(sDateTime1).AddHours(12).ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
string strsql = $@"SELECT
|
||||
DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:00:00') AS `TestTime`,
|
||||
`ProdIn`,
|
||||
`ProdOut`,
|
||||
`Ppm`,
|
||||
CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN `ProdIn` > 0 THEN ROUND(COALESCE(`ProdOut`, 0) / COALESCE(`ProdIn`, 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{sDateTime1}' AND '{sDateTime2}'
|
||||
GROUP BY
|
||||
`TestTime`, `ProdOut`, `ProdIn`, `Ppm`, `JiaDL`
|
||||
UNION ALL
|
||||
SELECT
|
||||
'Total' AS `Time`,
|
||||
SUM(`ProdIn`) AS ProdIn,
|
||||
SUM(`ProdOut`) AS ProdOut,
|
||||
AVG(`Ppm`) AS Ppm,
|
||||
CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
|
||||
CONCAT(CAST(
|
||||
CASE
|
||||
WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
|
||||
ELSE 0
|
||||
END AS CHAR(10)), '%') AS `Prod`
|
||||
FROM
|
||||
`Hourprod`
|
||||
WHERE
|
||||
`TestTime` BETWEEN '{sDateTime1}' AND '{sDateTime2}'";
|
||||
|
||||
return strsql;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取最新的数据
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string GetStatic(string strDateTime)
|
||||
{
|
||||
|
||||
string strsql = $@" SELECT [FDate]
|
||||
,[FHour]
|
||||
,[ProdIn]
|
||||
,[ProdOut]
|
||||
,[TestTime]
|
||||
FROM [dbo].[Hourprod] where FDate='{strDateTime}' order by TestTime desc";
|
||||
return strsql;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据条码查询是否存在
|
||||
/// </summary>
|
||||
/// <param name="strProdType"></param>
|
||||
/// <returns></returns>
|
||||
public string GetBarcode(string barCode)
|
||||
{
|
||||
string strSql = $@"SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM `CGearEntity`
|
||||
WHERE BarCode = '{barCode}') AS barcode_exists";
|
||||
return strSql;
|
||||
}
|
||||
|
||||
///// <summary>
|
||||
///// 根据条码获取挡位最新的一条数据
|
||||
///// </summary>
|
||||
///// <param name="strProdType"></param>
|
||||
///// <returns></returns>
|
||||
//public string GetJetCodeTop1Sql(string barCode)
|
||||
//{
|
||||
// string strSql = $@"SELECT
|
||||
// `InsulationTestShift`
|
||||
// FROM
|
||||
// `BGearEntity`
|
||||
// WHERE `BarCode` = '{barCode}' ORDER BY `TestTime` DESC
|
||||
// LIMIT 1";
|
||||
// return strSql;
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 根据条码获取重量直径最新的一条数据
|
||||
///// </summary>
|
||||
///// <param name="barCode"></param>
|
||||
///// <returns></returns>
|
||||
//public string GetOutStationTop1Sql(string barCode)
|
||||
//{
|
||||
// string strSql = $@"SELECT
|
||||
// `BarCode`,
|
||||
// `Weight`,
|
||||
// `Diameter`
|
||||
// FROM
|
||||
// `BGearEntity`
|
||||
// WHERE `BarCode` = '{barCode}' ORDER BY `TestTime` DESC
|
||||
// LIMIT 1";
|
||||
// return strSql;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 获取表头注释
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string GetSqlFields(string tableName)
|
||||
{
|
||||
string strSql = $@"SELECT
|
||||
COLUMN_NAME,
|
||||
DATA_TYPE,
|
||||
COLUMN_COMMENT
|
||||
FROM
|
||||
INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE
|
||||
TABLE_SCHEMA = 'largesquareone' AND TABLE_NAME = '{tableName}'
|
||||
ORDER BY
|
||||
ORDINAL_POSITION;";
|
||||
return strSql;
|
||||
}
|
||||
}
|
||||
|
||||
public class M_DBCtrl
|
||||
{
|
||||
/// <summary>--本机数据库表名
|
||||
///
|
||||
/// </summary>
|
||||
//public string machineInSQLTable = "agearentity";
|
||||
public string machineOutSQLTable = "bgearentity";
|
||||
|
||||
private string[] headerTextOut;
|
||||
/// <summary>
|
||||
/// 出站数据库表头
|
||||
/// </summary>
|
||||
public string[] HeaderTextOut
|
||||
{
|
||||
get { return headerTextOut; }
|
||||
set { headerTextOut = value; }
|
||||
}
|
||||
|
||||
/// <summary>查询SQL数据库中的数据,并以string数组列表形式返回
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="strSql"></param>
|
||||
/// <returns>所查询到的数据,null表示不存在</returns>
|
||||
public List<string[]> SQLAllDataSearchToStrArrList(string strSql)
|
||||
{
|
||||
List<string[]> strResArrList = new List<string[]>();
|
||||
List<string> strResList = new List<string>();
|
||||
try
|
||||
{
|
||||
DataTable dt = CommonMethods.db.QueryDataTable(strSql);
|
||||
if (dt != null)
|
||||
{
|
||||
for (int i = 0; i < dt.Rows.Count; i++)
|
||||
{
|
||||
for (int j = 0; j < dt.Columns.Count; j++)
|
||||
{
|
||||
string resRow = dt.Rows[i][j].ToString();
|
||||
strResList.Add(resRow);
|
||||
}
|
||||
string[] strResArr = strResList.ToArray();
|
||||
strResList.Clear();
|
||||
strResArrList.Add(strResArr);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return strResArrList = new List<string[]>();
|
||||
}
|
||||
return strResArrList;
|
||||
}
|
||||
|
||||
/// <summary>根据下标在返回的数据库表信息 集合中获取相应数据
|
||||
/// index 0:字段 2:中文注释 1:变量类型int\char等
|
||||
/// </summary>
|
||||
/// <param name="SqlList">liststring[]类型的集合</param>
|
||||
/// <param name="index">string[] 的下标</param>
|
||||
/// <returns></returns>
|
||||
public String[] HeaderTextAssignment(List<string[]> SqlList, int index)
|
||||
{
|
||||
string[] headStringlist = new string[SqlList.Count];
|
||||
// int i = 0;
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < SqlList.Count; i++)
|
||||
{
|
||||
headStringlist[i] = SqlList[i][index];
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
return headStringlist;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
|
||||
using JinYuan.Models;
|
||||
using PLCCommunication;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary
|
||||
{
|
||||
|
||||
public delegate void dgStationFunction(JYResult<byte[]> bArrays, object plcModel);
|
||||
|
||||
/// <summary>
|
||||
/// 显示上料信息
|
||||
/// </summary>
|
||||
/// <param name="Msg"></param>
|
||||
/// <param name="state"></param>
|
||||
//public delegate void dgShowFeeding(List<AGearEntity> list);
|
||||
/// <summary>
|
||||
/// 显示下料信息
|
||||
/// </summary>
|
||||
/// <param name="Msg"></param>
|
||||
/// <param name="state"></param>
|
||||
//public delegate void dgShowBlanking(List<BlankingEntry> list);
|
||||
/// <summary>
|
||||
/// 设备综合效率
|
||||
/// </summary>
|
||||
/// <param name="battery"></param>
|
||||
public delegate void DGShow12HourData(DeviceOEE device12Hour);
|
||||
|
||||
/// <summary>
|
||||
/// 设备综合效率
|
||||
/// </summary>
|
||||
/// <param name="battery"></param>
|
||||
public delegate void DGShowAlarmData(DeviceOEE deviceAlarm);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 焊机功率
|
||||
/// </summary> Welding machine power
|
||||
/// <param name="DataList"></param>
|
||||
public delegate void DGShowWeldingPowerData(List<double> DataList);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{2AB7E380-7795-448A-933C-0F6A081B5E7E}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>JinYuan.VirtualDataLibrary</RootNamespace>
|
||||
<AssemblyName>JinYuan.VirtualDataLibrary</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<Deterministic>true</Deterministic>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="HML, Version=8.0.0.6, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libs\HML.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="PLCCommunication, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libs\PLCCommunication.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Seagull.BarTender.Print, Version=11.0.7.3146, Culture=neutral, PublicKeyToken=109ff779a1b4cbc7, processorArchitecture=AMD64">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libs\2016\Seagull.BarTender.Print.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="CommonMethods.cs" />
|
||||
<Compile Include="DBSQL.cs" />
|
||||
<Compile Include="DelegateLib.cs" />
|
||||
<Compile Include="MesConfig.cs" />
|
||||
<Compile Include="MsgshowTip.cs">
|
||||
<SubType>Form</SubType>
|
||||
</Compile>
|
||||
<Compile Include="MsgshowTip.Designer.cs">
|
||||
<DependentUpon>MsgshowTip.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Properties\Resources.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Utlis\BartenderPrinter.cs" />
|
||||
<Compile Include="Utlis\PrintDataTransfer.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\JinYuan.DAL\JinYuan.DAL.csproj">
|
||||
<Project>{114aa012-29c9-418c-a2d6-3173c5341f51}</Project>
|
||||
<Name>JinYuan.DAL</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\JinYuan.Helper\JinYuan.Helper.csproj">
|
||||
<Project>{258d0ab7-2b4f-4d8f-a3cd-7a8cb4a85360}</Project>
|
||||
<Name>JinYuan.Helper</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\JinYuan.MES\JinYuan.MES.csproj">
|
||||
<Project>{530b6426-08e7-461c-91dc-787f876620fc}</Project>
|
||||
<Name>JinYuan.MES</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\JinYuan.Models\JinYuan.Models.csproj">
|
||||
<Project>{4c0bcb84-5cd7-4846-8363-c4c10d46e391}</Project>
|
||||
<Name>JinYuan.Models</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\PLC\PLC.csproj">
|
||||
<Project>{486aecd0-c2bf-43c5-b7d7-88e565ade4b7}</Project>
|
||||
<Name>PLC</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="app.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="MsgshowTip.resx">
|
||||
<DependentUpon>MsgshowTip.cs</DependentUpon>
|
||||
</EmbeddedResource>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
<None Include="Resources\感叹号提示-块红色.png" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1,254 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary
|
||||
{
|
||||
public class MesConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// 工厂代码
|
||||
/// </summary>
|
||||
public string siteCode = "";
|
||||
/// <summary>
|
||||
/// 产线编号
|
||||
/// </summary>
|
||||
public string lineCode = "";
|
||||
/// <summary>
|
||||
/// 设备编号
|
||||
/// </summary>
|
||||
public string equipNum = "";
|
||||
/// <summary>
|
||||
/// 客户料号
|
||||
/// </summary>
|
||||
public string CustomerPartNum = "";
|
||||
|
||||
/// <summary>
|
||||
/// 容器编码
|
||||
/// </summary>
|
||||
public string containerCode = "";
|
||||
/// <summary>
|
||||
/// MES密码
|
||||
/// </summary>
|
||||
public string mesPwd = "";
|
||||
/// <summary>
|
||||
/// MES账户
|
||||
/// </summary>
|
||||
public string mesUserName = "";
|
||||
|
||||
/// <summary>
|
||||
/// 电表编号
|
||||
/// </summary>
|
||||
public List<string> electricMeterNum = new List<string>();
|
||||
|
||||
/// <summary>
|
||||
/// 风速仪个数
|
||||
/// </summary>
|
||||
public int AntiDustAirSpeedCount = 0;
|
||||
/// <summary>
|
||||
/// 风速仪编号
|
||||
/// </summary>
|
||||
public List<string> listAntiDustAirSpeedNum = new List<string>();
|
||||
|
||||
/// <summary>
|
||||
/// 权限
|
||||
/// </summary>
|
||||
public string userLevel = "";
|
||||
/// <summary>
|
||||
/// mes返回权限
|
||||
/// </summary>
|
||||
public string mesUserLevel = "";
|
||||
/// <summary>
|
||||
/// 物料编码
|
||||
/// </summary>
|
||||
public string MaterialCode = "";
|
||||
/// <summary>
|
||||
/// 生产型号
|
||||
/// </summary>
|
||||
public string ModelName = "";
|
||||
|
||||
private Dictionary<string, int> modelMapping = new Dictionary<string, int>()
|
||||
{
|
||||
{ "MB36", 1 },
|
||||
{ "MB31", 2 },
|
||||
{ "MB56", 3 }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 将电池型号转换成下发PLC的型号编号
|
||||
/// </summary>
|
||||
/// <param name="strGrade"></param>
|
||||
/// <returns></returns>
|
||||
public int GetModel(string modelName)
|
||||
{
|
||||
if (modelMapping.TryGetValue(modelName, out int result))
|
||||
{
|
||||
return result; // 键存在,返回对应值
|
||||
}
|
||||
// 键不存在,返回0
|
||||
return 0;
|
||||
}
|
||||
/// <summary>
|
||||
/// 客户类型
|
||||
/// </summary>
|
||||
public string customerType = "";
|
||||
/// <summary>
|
||||
/// 是否上传MES
|
||||
/// </summary>
|
||||
public bool isUpMes = false;
|
||||
/// <summary>
|
||||
/// MES接口URL地址中的IP地址
|
||||
/// </summary>
|
||||
public string MESURLAddressIP = "10.100.111.81";
|
||||
/// <summary>
|
||||
/// MES接口URL地址中的端口号
|
||||
/// </summary>
|
||||
public string MESURLAddressPort = "80";
|
||||
/// <summary>
|
||||
/// 是否连接MES
|
||||
/// </summary>
|
||||
public bool isConnected = false;
|
||||
/// <summary>
|
||||
/// 是否刷卡?
|
||||
/// </summary>
|
||||
public bool Isshuaka = false;
|
||||
/// <summary>
|
||||
/// 是否登录成功?
|
||||
/// </summary>
|
||||
public bool IsLoginOK = false;
|
||||
/// <summary>
|
||||
/// 是否登录MES成功?
|
||||
/// </summary>
|
||||
public bool IsLoginMesOK = false;
|
||||
/// <summary>
|
||||
/// 获取MES参数
|
||||
/// </summary>
|
||||
public bool IsMesParam = false;
|
||||
/// <summary>
|
||||
/// MES超时
|
||||
/// </summary>
|
||||
public long MesOutTime = 0;
|
||||
/// <summary>
|
||||
/// 焊接点个数
|
||||
/// </summary>
|
||||
public int weldNum = 0;
|
||||
/// <summary>
|
||||
/// 是否2个电表(此功能仅适用于908-6负极焊接两台设备共用一台敢接机只有一个电表)
|
||||
/// </summary>
|
||||
public bool IsTwoDianBiao = false;
|
||||
/// <summary>
|
||||
/// 电表编号
|
||||
/// </summary>
|
||||
public string ElectricMeterNum = "";
|
||||
/// <summary>
|
||||
/// 除尘风速
|
||||
/// </summary>
|
||||
public decimal antiDustAirSpeed = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 电机旋转速度
|
||||
/// </summary>
|
||||
public decimal dianjiXzSpeed = 0;
|
||||
/// <summary>
|
||||
/// 设备状态上传时间
|
||||
/// </summary>
|
||||
public int EquStatuasTime = 0;
|
||||
/// <summary>
|
||||
/// 获取服务器数据
|
||||
/// </summary>
|
||||
public bool IsGet_Server = true;
|
||||
/// <summary>
|
||||
/// 生成假数据
|
||||
/// </summary>
|
||||
public bool IsDebug = true;
|
||||
/// <summary>
|
||||
/// 卡板托盘计数
|
||||
/// </summary>
|
||||
public int CoreCount = 0;
|
||||
/// <summary>
|
||||
/// 卡板托盘生成时间
|
||||
/// </summary>
|
||||
public string CardTime = "";
|
||||
/// <summary>
|
||||
/// 卡板码是否发送成功
|
||||
/// </summary>
|
||||
public bool CardSuccess = false;
|
||||
|
||||
/// <summary>
|
||||
/// 原材料上料位置
|
||||
/// </summary>
|
||||
public string materialLotCodeLocator = "";
|
||||
|
||||
/// <summary>
|
||||
/// 存储服务器IP地址
|
||||
/// </summary>
|
||||
public string RotueServerIP = "192.168.2.108";
|
||||
/// <summary>
|
||||
/// 员工权限校验
|
||||
/// </summary>
|
||||
public string EmployeeAuthCheck = "http://10.100.111.81/core/api/public/equipment/base/user/permission/verify";
|
||||
///// <summary>
|
||||
///// 原材料投入信息
|
||||
///// </summary>
|
||||
//public string MaterialInputInfo = "http://10.100.111.81/core/api/public/raw/material/input/un/first/process";
|
||||
/// <summary>
|
||||
/// 设备参数设定值请求
|
||||
/// </summary>
|
||||
public string DeviceParamRequest = "http://10.100.111.81/core/api/public/param/setting/request";
|
||||
/// <summary>
|
||||
/// 设备参数设定值变更
|
||||
/// </summary>
|
||||
public string DeviceParamChange = "http://10.100.111.81/core/api/public/param/setting/change";
|
||||
|
||||
/// <summary>
|
||||
/// 箱唛信息获取
|
||||
/// </summary>
|
||||
public string queryCartonUrl = "http://10.100.111.81/core/api/public/equip/auto/cartonquery";
|
||||
|
||||
/// <summary>
|
||||
/// 栈板信息获取
|
||||
/// </summary>
|
||||
public string queryPalletUrl = "http://10.100.111.81/core/api/public/equip/auto/palletquery";
|
||||
|
||||
/// <summary>
|
||||
/// 客户标签与系统标签绑定
|
||||
/// </summary>
|
||||
public string bindingUrl = "http://10.100.111.81/core/api/public/equip/auto/customer/bind";
|
||||
/// <summary>
|
||||
/// 设备报警信息
|
||||
/// </summary>
|
||||
public string DeviceAlarm = "http://10.100.111.81/core/api/public/equipment/alarm/currency";
|
||||
/// <summary>
|
||||
/// 设备运行状态
|
||||
/// </summary>
|
||||
public string DeviceStatus = "http://10.100.111.81/core/api/public/eve/pm/eqm/run/status/operation";
|
||||
/// <summary>
|
||||
/// 能耗数据
|
||||
/// </summary>
|
||||
public string EnergyConsumption = "http://10.100.111.81/core/api/public/eve/pm/energy/consumption/collection/submit";
|
||||
/// <summary>
|
||||
/// 设备风速接口
|
||||
/// </summary>
|
||||
public string Anemometer = "https://iot.eveportal.com:9470/eve_api/ems/iot/upload_device_collect_data";
|
||||
|
||||
///// <summary>
|
||||
///// 进出站一体模式×
|
||||
///// </summary>
|
||||
//public string InAndOutStationMesUrl = "http://10.17.96.73/core/api/public/14j/out/station/process/turn-in-out";
|
||||
|
||||
/// <summary>
|
||||
/// appId
|
||||
/// </summary>
|
||||
public string AppID = "e36ef900320d442f850913e2ebc1d7a1";
|
||||
/// <summary>
|
||||
/// AppKey
|
||||
/// </summary>
|
||||
public string AppKey = "8279ce76217245f48c0cc495c09124a3";
|
||||
/// <summary>
|
||||
/// 获取TOKEN
|
||||
/// </summary>
|
||||
public string GetTokenUrl = "https://esb.evebattery.com:13502/gateway/ewms-eu/openapi/oauth/token";
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
namespace JinYuan.VirtualDataLibrary
|
||||
{
|
||||
partial class MsgshowTip
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Windows Form Designer generated code
|
||||
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this.components = new System.ComponentModel.Container();
|
||||
this.pictureBox1 = new System.Windows.Forms.PictureBox();
|
||||
this.label1 = new System.Windows.Forms.Label();
|
||||
this.timer1 = new System.Windows.Forms.Timer(this.components);
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// pictureBox1
|
||||
//
|
||||
this.pictureBox1.Image = global::JinYuan.VirtualDataLibrary.Properties.Resources.感叹号提示_块红色;
|
||||
this.pictureBox1.Location = new System.Drawing.Point(6, 3);
|
||||
this.pictureBox1.Name = "pictureBox1";
|
||||
this.pictureBox1.Size = new System.Drawing.Size(87, 80);
|
||||
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
|
||||
this.pictureBox1.TabIndex = 0;
|
||||
this.pictureBox1.TabStop = false;
|
||||
//
|
||||
// label1
|
||||
//
|
||||
this.label1.AutoSize = true;
|
||||
this.label1.Font = new System.Drawing.Font("微软雅黑", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
|
||||
this.label1.ForeColor = System.Drawing.Color.Red;
|
||||
this.label1.Location = new System.Drawing.Point(95, 29);
|
||||
this.label1.Name = "label1";
|
||||
this.label1.Size = new System.Drawing.Size(345, 28);
|
||||
this.label1.TabIndex = 1;
|
||||
this.label1.Text = "与PLC链接断开,请检查通讯线路!";
|
||||
//
|
||||
// timer1
|
||||
//
|
||||
this.timer1.Interval = 500;
|
||||
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
|
||||
//
|
||||
// MsgshowTip
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.BackColor = System.Drawing.Color.Yellow;
|
||||
this.ClientSize = new System.Drawing.Size(434, 84);
|
||||
this.Controls.Add(this.pictureBox1);
|
||||
this.Controls.Add(this.label1);
|
||||
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
|
||||
this.Name = "MsgshowTip";
|
||||
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
|
||||
this.Text = "MsgshowTip";
|
||||
this.Load += new System.EventHandler(this.MsgshowTip_Load);
|
||||
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
|
||||
this.ResumeLayout(false);
|
||||
this.PerformLayout();
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private System.Windows.Forms.PictureBox pictureBox1;
|
||||
private System.Windows.Forms.Label label1;
|
||||
private System.Windows.Forms.Timer timer1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary
|
||||
{
|
||||
public partial class MsgshowTip : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// 图标和文本之间的间距(像素)
|
||||
/// </summary>
|
||||
const int IconTextSpacing = 3;
|
||||
/// <summary>
|
||||
/// 显示文字
|
||||
/// </summary>
|
||||
string _tipText;
|
||||
/// <summary>
|
||||
/// 提示图标
|
||||
/// </summary>
|
||||
public Image TipIcon { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 提示文本
|
||||
/// </summary>
|
||||
public string TipText
|
||||
{
|
||||
get { return _tipText ?? string.Empty; }
|
||||
set { _tipText = value; }
|
||||
}
|
||||
|
||||
public MsgshowTip(string Msg)
|
||||
{
|
||||
//双缓冲。有必要
|
||||
SetStyle(ControlStyles.UserPaint, true);
|
||||
DoubleBuffered = true;
|
||||
InitializeComponent();
|
||||
this._tipText = Msg;
|
||||
}
|
||||
|
||||
private void MsgshowTip_Load(object sender, EventArgs e)
|
||||
{
|
||||
//ProcessClientSize();
|
||||
ProcessLocation();
|
||||
label1.Text = _tipText;
|
||||
timer1.Enabled = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据图标和文字处理窗体尺寸
|
||||
/// </summary>
|
||||
private void ProcessClientSize()
|
||||
{
|
||||
Size size = Size.Empty;
|
||||
if (TipIcon != null)
|
||||
{
|
||||
size += TipIcon.Size;
|
||||
}
|
||||
if (TipText.Length != 0)
|
||||
{
|
||||
if (TipIcon != null)
|
||||
{
|
||||
size.Width += IconTextSpacing;//图标与文字的间距
|
||||
}
|
||||
var textSize = TextRenderer.MeasureText(TipText, this.Font);
|
||||
size.Width += textSize.Width;
|
||||
if (size.Height < textSize.Height) { size.Height = textSize.Height; }
|
||||
}
|
||||
this.ClientSize = size + Padding.Size;
|
||||
}
|
||||
private int x, y; //显示的坐标变量
|
||||
|
||||
private void timer1_Tick(object sender, EventArgs e)
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
|
||||
private void ProcessLocation()
|
||||
{
|
||||
|
||||
#region 弹窗显示在屏幕中间
|
||||
this.y = (Screen.PrimaryScreen.Bounds.Height - 30 - this.Height) / 2;
|
||||
this.x = (Screen.PrimaryScreen.Bounds.Width - 10 - this.Width) / 2;
|
||||
this.Location = new Point(this.x, this.y);
|
||||
#endregion
|
||||
|
||||
#region 弹窗显示在屏幕右下角
|
||||
//this.x = Screen.PrimaryScreen.WorkingArea.Width - this.Width + 15;
|
||||
//this.y = Screen.PrimaryScreen.WorkingArea.Height - this.Height * i - 5 * i;
|
||||
//this.Location = new Point(this.x, this.y);
|
||||
#endregion
|
||||
|
||||
#region 弹窗跟随鼠标位置
|
||||
//var p = BasePoint;
|
||||
//p.X -= Screen.PrimaryScreen.WorkingArea.Width - this.Width - 1000;//Screen.PrimaryScreen.WorkingArea.Width-this.Width / 2;
|
||||
|
||||
////横向处理。距离屏幕左右两边太近时的处理
|
||||
//int screenWidth;
|
||||
//if (p.X < 10)
|
||||
//{
|
||||
// p.X = 10;
|
||||
//}
|
||||
//else if (p.X + this.Width > (screenWidth = Screen.PrimaryScreen.Bounds.Width) - 10)
|
||||
//{
|
||||
// p.X = screenWidth - 10 - this.Width;
|
||||
//}
|
||||
|
||||
////纵向处理。在鼠标上方显示
|
||||
//p.Y -= this.Height + 20;
|
||||
|
||||
//this.Location = p;
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// 有关程序集的一般信息由以下
|
||||
// 控制。更改这些特性值可修改
|
||||
// 与程序集关联的信息。
|
||||
[assembly: AssemblyTitle("JinYuan.VirtualDataLibrary")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("JinYuan.VirtualDataLibrary")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2023")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// 将 ComVisible 设置为 false 会使此程序集中的类型
|
||||
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
|
||||
//请将此类型的 ComVisible 特性设置为 true。
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
|
||||
[assembly: Guid("2ab7e380-7795-448a-933c-0f6a081b5e7e")]
|
||||
|
||||
// 程序集的版本信息由下列四个值组成:
|
||||
//
|
||||
// 主版本
|
||||
// 次版本
|
||||
// 生成号
|
||||
// 修订号
|
||||
//
|
||||
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
|
||||
//通过使用 "*",如下所示:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
@@ -0,0 +1,73 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// 此代码由工具生成。
|
||||
// 运行时版本:4.0.30319.42000
|
||||
//
|
||||
// 对此文件的更改可能会导致不正确的行为,并且如果
|
||||
// 重新生成代码,这些更改将会丢失。
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary.Properties {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 一个强类型的资源类,用于查找本地化的字符串等。
|
||||
/// </summary>
|
||||
// 此类是由 StronglyTypedResourceBuilder
|
||||
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
|
||||
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
|
||||
// (以 /str 作为命令选项),或重新生成 VS 项目。
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回此类使用的缓存的 ResourceManager 实例。
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JinYuan.VirtualDataLibrary.Properties.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重写当前线程的 CurrentUICulture 属性,对
|
||||
/// 使用此强类型资源类的所有资源查找执行重写。
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap 感叹号提示_块红色 {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("感叹号提示-块红色", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
|
||||
<data name="感叹号提示-块红色" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\感叹号提示-块红色.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
</root>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.9 KiB |
@@ -0,0 +1,271 @@
|
||||
using JinYuan.Helper;
|
||||
using Seagull.BarTender.Print;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
|
||||
namespace JinYuan.VirtualDataLibrary.Utlis
|
||||
{
|
||||
public class BartenderPrinter
|
||||
{
|
||||
LabelFormatDocument print;
|
||||
Engine engine;
|
||||
string PrinterName;
|
||||
string PrintLabelType;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化打印机
|
||||
/// </summary>
|
||||
/// <param name="PrinterName">打印机名称通过该名称指定打印机</param>
|
||||
/// <param name="PrintLabelType">打印机类型</param>
|
||||
public BartenderPrinter(string PrinterName, string PrintLabelType)
|
||||
{
|
||||
this.PrinterName = PrinterName;
|
||||
this.PrintLabelType = PrintLabelType;
|
||||
engine = new Engine(true);
|
||||
}
|
||||
|
||||
public BartenderPrinter(string PrinterName)
|
||||
{
|
||||
this.PrinterName = PrinterName;
|
||||
engine = new Engine(true);
|
||||
}
|
||||
|
||||
|
||||
public string[] read(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
LabelFormatDocument print;
|
||||
|
||||
|
||||
//System.Diagnostics.Process.Start("ExpLore", path);
|
||||
|
||||
|
||||
print = engine.Documents.Open(path);
|
||||
//print.PrintSetup.PrinterName = "Microsoft Print to PDF";
|
||||
//print.PrintSetup.PrinterName = "TSC MX340F";
|
||||
XmlDocument xml = new XmlDocument();
|
||||
xml.LoadXml(print.SubStrings.XML);
|
||||
//string s = print.SubStrings.XML;
|
||||
//获取XML中SubStrings/SubString
|
||||
XmlNodeList nodeList = xml.SelectNodes("SubStrings/SubString");
|
||||
string[] printColumns = new string[print.SubStrings.Count];
|
||||
int count = 0;
|
||||
foreach (XmlNode node in nodeList)
|
||||
{
|
||||
printColumns[count] = node.Attributes["Name"].Value;
|
||||
count++;
|
||||
}
|
||||
//获取栏位
|
||||
return printColumns;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行打印
|
||||
/// </summary>
|
||||
/// <param name="path">文件地址</param>
|
||||
/// <param name="printValue">字段栏位映射,key BTname ,value BTValue</param>
|
||||
/// <returns></returns>
|
||||
public bool write(string path, string jobName, Dictionary<string, string> printValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
print = engine.Documents.Open(path);
|
||||
//print.PrintSetup.PrinterName = "Microsoft Print to PDF";
|
||||
//print.PrintSetup.PrinterName = "TSC MX340";
|
||||
//print.PrintSetup.PrinterName = "TSC TTP-346MU";
|
||||
print.PrintSetup.PrinterName = this.PrinterName;
|
||||
foreach (var oneItem in printValue)
|
||||
{
|
||||
print.SubStrings.SetSubString(oneItem.Key, oneItem.Value);
|
||||
//log.Debug("[" + oneItem.Key + "]=" + oneItem.Value);
|
||||
}
|
||||
//Thread.Sleep(100);
|
||||
|
||||
Result result = print.Print(jobName); //print.Print("Label Print");
|
||||
|
||||
return result == Result.Success ? true : false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Instance.WriteEX(ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取btw檔 并确认各栏位是否能对应的到
|
||||
/// </summary>
|
||||
/// <param name="FileId"></param>
|
||||
/// <param name="Path"></param>
|
||||
/// <param name="SourceDataTable"></param>
|
||||
/// <param name="DtPrintColumn"></param>
|
||||
/// <returns></returns>
|
||||
public string LoadColumns(string FileId, string Path, DataTable SourceDataTable, DataTable DtPrintColumn)
|
||||
{
|
||||
try
|
||||
{
|
||||
string msg = "";
|
||||
|
||||
string[] btwColumns = read(Path);
|
||||
for (int i = 0; i < btwColumns.Length; i++)//版面欄位數量
|
||||
{
|
||||
bool flag = false;
|
||||
foreach (DataColumn dc in SourceDataTable.Columns)//資料庫欄位數量
|
||||
{
|
||||
if (btwColumns[i] == dc.ColumnName)
|
||||
{
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (flag == false)
|
||||
{
|
||||
if (msg == "") { msg = btwColumns[i]; }
|
||||
else { msg += "," + btwColumns[i]; }
|
||||
}
|
||||
}
|
||||
|
||||
if (msg == "")
|
||||
{
|
||||
DataTable dt = DtPrintColumn;
|
||||
string Id = FileId;
|
||||
|
||||
DataRow[] drAry = dt.Select(" Id='" + Id + "'");
|
||||
for (int j = 0; j < drAry.Length; j++)
|
||||
{
|
||||
dt.Rows.Remove(drAry[j]);
|
||||
}
|
||||
dt.AcceptChanges();
|
||||
|
||||
DataRow drNew;
|
||||
for (int j = 0; j < btwColumns.Length; j++)
|
||||
{
|
||||
drNew = dt.NewRow();
|
||||
drNew["Id"] = Id;
|
||||
drNew["Value"] = btwColumns[j];
|
||||
dt.Rows.Add(drNew);
|
||||
}
|
||||
dt.AcceptChanges();
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Instance.WriteEX(ex);
|
||||
return ex.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
// 列印 Reel或Box或Carton标签
|
||||
// TODO 偵測非同步處理
|
||||
public bool PrintLabel(DataRow dr)
|
||||
{
|
||||
try
|
||||
{
|
||||
string Id = "";
|
||||
string fileIdColumnName = "";
|
||||
string filePathColumnName = "";
|
||||
if (dr == null)
|
||||
{
|
||||
LogHelper.Instance.WriteError("DataRow is NULL");
|
||||
return false;
|
||||
}
|
||||
DataTable columnDT = new DataTable();
|
||||
if (PrintLabelType == "Box")
|
||||
{
|
||||
fileIdColumnName = "FileId";
|
||||
filePathColumnName = "Path";
|
||||
|
||||
}
|
||||
else if (PrintLabelType == "Reel")
|
||||
{
|
||||
fileIdColumnName = "ReelFileId";
|
||||
filePathColumnName = "ReelFilePath";
|
||||
|
||||
}
|
||||
else if (PrintLabelType == "Carton")
|
||||
{
|
||||
fileIdColumnName = "FileId";
|
||||
filePathColumnName = "Path";
|
||||
|
||||
}
|
||||
else if (PrintLabelType == "Carton2")
|
||||
{
|
||||
fileIdColumnName = "FileId2";
|
||||
filePathColumnName = "Path2";
|
||||
}
|
||||
else
|
||||
{
|
||||
LogHelper.Instance.WriteError("PrintLabelType =" + PrintLabelType);
|
||||
return false;
|
||||
}
|
||||
|
||||
Id = dr[fileIdColumnName].ToString();
|
||||
|
||||
DataRow[] drAry = columnDT.Select("id='" + Id + "'");
|
||||
|
||||
Dictionary<string, string> printValue = new Dictionary<string, string>();
|
||||
|
||||
for (int i = 0; i < drAry.Length; i++)
|
||||
{
|
||||
string column = drAry[i][1].ToString();
|
||||
|
||||
printValue.Add(column, dr[column].ToString().TrimEnd());
|
||||
|
||||
}
|
||||
bool writeResult = write(dr[filePathColumnName].ToString(), PrintLabelType, printValue);
|
||||
return writeResult;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Instance.WriteEX(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
//列印 Interior Label 或 Outer Label
|
||||
public bool PrintSimpleLabel(string chrCkdh, string jobname, string FilePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
Dictionary<string, string> printValue = new Dictionary<string, string>();
|
||||
printValue.Add("chrCkdh", chrCkdh.TrimEnd());
|
||||
bool writeResult = write(FilePath, jobname, printValue);
|
||||
return writeResult;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Instance.WriteEX(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Close()
|
||||
{
|
||||
try
|
||||
{
|
||||
engine.Dispose();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Instance.WriteEX(ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,943 @@
|
||||
//using JinYuan.VirtualDataLibrary.Utlis;
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.IO;
|
||||
//using System.Linq;
|
||||
//using System.Text;
|
||||
using JinYuan.MES.Models;
|
||||
using Newtonsoft.Json;
|
||||
using PLCCommunication.BasicFramework;
|
||||
|
||||
//using System.Net;
|
||||
//using System.Net.Sockets;
|
||||
//using System.Threading.Tasks;
|
||||
|
||||
|
||||
//namespace JinYuan.VirtualDataLibrary.Utlis
|
||||
//{
|
||||
// public class PrintDataModel
|
||||
// {
|
||||
// public string PrintTaskId { get; set; } = Guid.NewGuid().ToString();
|
||||
// public string PrinterName { get; set; }
|
||||
// public string Code { get; set; }
|
||||
// public Dictionary<string, string> PrintFields { get; set; } = new Dictionary<string, string>();
|
||||
// public int CopyCount { get; set; } = 1;
|
||||
// public DateTime PrintTime { get; set; } = DateTime.Now;
|
||||
// }
|
||||
|
||||
// // 通信响应实体(服务端返回处理结果)
|
||||
// public class PrintResponseModel
|
||||
// {
|
||||
// public bool Success { get; set; }
|
||||
// public string Message { get; set; }
|
||||
// public string PrintTaskId { get; set; }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// Socket通信工具类(兼容所有.NET版本)
|
||||
// /// </summary>
|
||||
// public static class SocketPrintHelper
|
||||
// {
|
||||
// // JSON序列化配置(中文不转义、缩进)
|
||||
// private static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
|
||||
// {
|
||||
// Formatting = Formatting.Indented,
|
||||
// StringEscapeHandling = StringEscapeHandling.EscapeNonAscii // 中文不转义
|
||||
// };
|
||||
|
||||
// /// <summary>
|
||||
// /// 发送打印数据(客户端核心方法)
|
||||
// /// </summary>
|
||||
// public static PrintResponseModel SendPrintData(string serverIp, int serverPort, Dictionary<string, string> printData, int timeout = 5000)
|
||||
// {
|
||||
// TcpClient tcpClient = null;
|
||||
// NetworkStream stream = null;
|
||||
// try
|
||||
// {
|
||||
// tcpClient = new TcpClient
|
||||
// {
|
||||
// ReceiveTimeout = timeout,
|
||||
// SendTimeout = timeout
|
||||
// };
|
||||
// tcpClient.Connect(serverIp, serverPort);
|
||||
// stream = tcpClient.GetStream();
|
||||
// bool bconnnet = tcpClient.Connected;
|
||||
|
||||
|
||||
// // 使用Newtonsoft.Json序列化
|
||||
// string jsonData = JsonConvert.SerializeObject(printData, _jsonSettings);
|
||||
// byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);
|
||||
|
||||
// // 发送数据长度
|
||||
// byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length);
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBytes);
|
||||
// stream.Write(lengthBytes, 0, lengthBytes.Length);
|
||||
// stream.Write(jsonBytes, 0, jsonBytes.Length);
|
||||
// Console.WriteLine($"已发送打印数据(任务ID:{printData}):\n{jsonData}");
|
||||
|
||||
// // 接收响应
|
||||
// PrintResponseModel response = ReceivePrintResponse(stream, printData["container"], timeout);
|
||||
// return response;
|
||||
// }
|
||||
// catch (SocketException ex)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"连接服务端失败:{ex.Message}(IP:{serverIp}:{serverPort})",
|
||||
// PrintTaskId = printData["container"]
|
||||
// };
|
||||
// }
|
||||
// catch (TimeoutException)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"通信超时(超时时间:{timeout}ms)",
|
||||
// PrintTaskId = printData["container"]
|
||||
// };
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"发送打印数据失败:{ex.Message}",
|
||||
// PrintTaskId = printData["container"]
|
||||
// };
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// stream?.Close();
|
||||
// tcpClient?.Close();
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 接收服务端响应
|
||||
// /// </summary>
|
||||
// private static PrintResponseModel ReceivePrintResponse(NetworkStream stream, string printTaskId, int timeout)
|
||||
// {
|
||||
// // 读取长度
|
||||
// byte[] lengthBuffer = new byte[4];
|
||||
// int readLength = stream.Read(lengthBuffer, 0, lengthBuffer.Length);
|
||||
// if (readLength != 4)
|
||||
// throw new Exception("读取响应长度失败");
|
||||
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBuffer);
|
||||
// int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
|
||||
|
||||
// // 读取数据
|
||||
// byte[] dataBuffer = new byte[dataLength];
|
||||
// int totalRead = 0;
|
||||
// while (totalRead < dataLength)
|
||||
// {
|
||||
// int read = stream.Read(dataBuffer, totalRead, dataLength - totalRead);
|
||||
// if (read == 0)
|
||||
// throw new Exception("服务端断开连接");
|
||||
// totalRead += read;
|
||||
// }
|
||||
|
||||
// // 使用Newtonsoft.Json反序列化
|
||||
// string jsonResponse = Encoding.UTF8.GetString(dataBuffer);
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = true,
|
||||
// Message = $"发送打印数据成功",
|
||||
// PrintTaskId = printTaskId
|
||||
// };
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 服务端接收打印数据
|
||||
// /// </summary>
|
||||
// public static PrintDataModel ReceivePrintData(NetworkStream stream, int timeout)
|
||||
// {
|
||||
// // 读取长度
|
||||
// byte[] lengthBuffer = new byte[4];
|
||||
// int readLength = stream.Read(lengthBuffer, 0, lengthBuffer.Length);
|
||||
// if (readLength != 4)
|
||||
// throw new Exception("读取数据长度失败");
|
||||
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBuffer);
|
||||
// int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
|
||||
|
||||
// // 读取数据
|
||||
// byte[] dataBuffer = new byte[dataLength];
|
||||
// int totalRead = 0;
|
||||
// while (totalRead < dataLength)
|
||||
// {
|
||||
// int read = stream.Read(dataBuffer, totalRead, dataLength - totalRead);
|
||||
// if (read == 0)
|
||||
// throw new Exception("客户端断开连接");
|
||||
// totalRead += read;
|
||||
// }
|
||||
|
||||
// // 核心修改:Newtonsoft.Json反序列化
|
||||
// string jsonData = Encoding.UTF8.GetString(dataBuffer);
|
||||
// PrintDataModel printData = JsonConvert.DeserializeObject<PrintDataModel>(jsonData, _jsonSettings);
|
||||
// Console.WriteLine($"服务端接收打印数据(任务ID:{printData.PrintTaskId}):\n{jsonData}");
|
||||
// return printData;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 服务端发送响应数据
|
||||
// /// </summary>
|
||||
// public static void SendPrintResponse(NetworkStream stream, PrintResponseModel response)
|
||||
// {
|
||||
// // 核心修改:Newtonsoft.Json序列化
|
||||
// string jsonResponse = JsonConvert.SerializeObject(response, _jsonSettings);
|
||||
// byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonResponse);
|
||||
|
||||
// // 发送长度+数据(逻辑不变)
|
||||
// byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length);
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBytes);
|
||||
// stream.Write(lengthBytes, 0, lengthBytes.Length);
|
||||
// stream.Write(jsonBytes, 0, jsonBytes.Length);
|
||||
// }
|
||||
// }
|
||||
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 打印数据发送客户端
|
||||
///// </summary>
|
||||
//public class PrintDataClient
|
||||
//{
|
||||
// private readonly string _serverIp;
|
||||
// private readonly int _serverPort;
|
||||
|
||||
// public PrintDataClient(string serverIp, int serverPort)
|
||||
// {
|
||||
// _serverIp = serverIp;
|
||||
// _serverPort = serverPort;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 构建并发送打印数据
|
||||
// /// </summary>
|
||||
// public void SendPrintTask(Dictionary<string, string> printData)
|
||||
// {
|
||||
|
||||
// // 发送打印数据
|
||||
// PrintResponseModel response = SocketPrintHelper.SendPrintData(_serverIp, _serverPort, printData, 5000);
|
||||
|
||||
// // 处理响应结果
|
||||
// if (response.Success)
|
||||
// {
|
||||
// Console.WriteLine($"打印任务提交成功(任务ID:{response.PrintTaskId}):{response.Message}");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Console.WriteLine($"打印任务提交失败(任务ID:{response.PrintTaskId}):{response.Message}");
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
|
||||
///// <summary>
|
||||
///// 打印数据接收服务端(打印机终端/打印服务器侧)
|
||||
///// </summary>
|
||||
//public class PrintDataServer
|
||||
//{
|
||||
// private readonly int _port;
|
||||
// private TcpListener _listener;
|
||||
// private bool _isRunning;
|
||||
|
||||
// public PrintDataServer(int port)
|
||||
// {
|
||||
// _port = port;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 启动服务端
|
||||
// /// </summary>
|
||||
// public void Start()
|
||||
// {
|
||||
// _isRunning = true;
|
||||
// _listener = new TcpListener(IPAddress.Any, _port);
|
||||
// _listener.Start();
|
||||
// Console.WriteLine($"打印数据服务端已启动,监听端口:{_port}");
|
||||
|
||||
// // 异步接受客户端连接
|
||||
// Task.Run(async () =>
|
||||
// {
|
||||
// while (_isRunning)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// TcpClient client = await _listener.AcceptTcpClientAsync();
|
||||
// Console.WriteLine($"客户端连接:{((IPEndPoint)client.Client.RemoteEndPoint).Address}");
|
||||
// // 处理客户端请求(异步,避免阻塞)
|
||||
// HandleClientAsync(client);
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (_isRunning)
|
||||
// Console.WriteLine($"接受客户端连接失败:{ex.Message}");
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 处理客户端请求
|
||||
// /// </summary>
|
||||
// private async Task HandleClientAsync(TcpClient client)
|
||||
// {
|
||||
// using (client)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// NetworkStream stream = client.GetStream();
|
||||
// client.ReceiveTimeout = 5000;
|
||||
// client.SendTimeout = 5000;
|
||||
|
||||
// // 1. 接收打印数据
|
||||
// PrintDataModel printData = SocketPrintHelper.ReceivePrintData(stream, 5000);
|
||||
|
||||
// // 2. 处理打印任务(对接你的打印逻辑)
|
||||
// PrintResponseModel response = ProcessPrintTask(printData);
|
||||
|
||||
// // 3. 发送响应给客户端
|
||||
// SocketPrintHelper.SendPrintResponse(stream, response);
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// Console.WriteLine($"处理客户端请求失败:{ex.Message}");
|
||||
// // 发送失败响应
|
||||
// try
|
||||
// {
|
||||
// SocketPrintHelper.SendPrintResponse(client.GetStream(), new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = ex.Message,
|
||||
// PrintTaskId = ""
|
||||
// });
|
||||
// }
|
||||
// catch { }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 处理打印任务
|
||||
// /// </summary>
|
||||
// private PrintResponseModel ProcessPrintTask(PrintDataModel printData)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// // --------------------------
|
||||
// // 此处对接你的实际打印逻辑:
|
||||
// // 1. 根据PrinterName选择打印机
|
||||
// // 2. 解析PrintFields填充打印模板
|
||||
// // 3. 调用打印机SDK执行打印
|
||||
// // --------------------------
|
||||
// Console.WriteLine($"开始处理打印任务(ID:{printData.PrintTaskId}):");
|
||||
// Console.WriteLine($" 打印机:{printData.PrinterName}");
|
||||
// Console.WriteLine($" 托盘号:{printData.Code}");
|
||||
// Console.WriteLine($" 打印份数:{printData.CopyCount}");
|
||||
// Console.WriteLine($" 打印字段:");
|
||||
// foreach (var field in printData.PrintFields)
|
||||
// {
|
||||
// Console.WriteLine($" {field.Key} = {field.Value}");
|
||||
// }
|
||||
|
||||
// // 模拟打印成功(替换为你的实际打印代码)
|
||||
// // CommonMethods.PrintLabel(printData);
|
||||
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = true,
|
||||
// Message = $"打印任务已执行(份数:{printData.CopyCount})",
|
||||
// PrintTaskId = printData.PrintTaskId
|
||||
// };
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"打印任务执行失败:{ex.Message}",
|
||||
// PrintTaskId = printData.PrintTaskId
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 停止服务端
|
||||
// /// </summary>
|
||||
// public void Stop()
|
||||
// {
|
||||
// _isRunning = false;
|
||||
// _listener?.Stop();
|
||||
// Console.WriteLine("打印数据服务端已停止");
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PrintSocket
|
||||
{
|
||||
public class StateObject
|
||||
{
|
||||
public Socket workSocket = null;
|
||||
public const int BufferSize = 2000;
|
||||
public byte[] buffer = new byte[BufferSize];
|
||||
public StringBuilder sb = new StringBuilder();
|
||||
}
|
||||
|
||||
//服务端类
|
||||
public class TCPServer
|
||||
{
|
||||
//私有变量
|
||||
private SocketMessage m_SocketMsgDelegate = null;
|
||||
private Socket m_Listener = null;
|
||||
private Socket m_ServerHandler = null;
|
||||
|
||||
//公开变量
|
||||
public delegate void SocketMessage(object obj);
|
||||
public string m_strInfo = null;
|
||||
|
||||
public void InitServer(string strAddr, int nPort, SocketMessage sockMsg = null) //初始化
|
||||
{
|
||||
if (sockMsg != null)
|
||||
{
|
||||
m_SocketMsgDelegate = sockMsg;
|
||||
}
|
||||
if (m_Listener != null)
|
||||
{
|
||||
try { m_Listener.Close(); } catch { }
|
||||
m_Listener = null;
|
||||
}
|
||||
|
||||
//创建套接字
|
||||
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(strAddr), nPort);
|
||||
m_Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
try
|
||||
{
|
||||
m_Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
|
||||
m_Listener.Bind(ipe);
|
||||
m_Listener.Listen(10);
|
||||
|
||||
//开启异步监听连接
|
||||
m_Listener.BeginAccept(new AsyncCallback(AcceptCallback), m_Listener);
|
||||
m_SocketMsgDelegate?.Invoke("Server online");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e.Message);
|
||||
m_SocketMsgDelegate?.Invoke(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void AcceptCallback(IAsyncResult iar)
|
||||
{
|
||||
Socket listener = (Socket)iar.AsyncState;
|
||||
m_ServerHandler = listener.EndAccept(iar); //结束接收请求
|
||||
|
||||
//创建状态对象
|
||||
StateObject state = new StateObject();
|
||||
state.workSocket = m_ServerHandler;
|
||||
m_strInfo = m_ServerHandler.RemoteEndPoint.ToString();
|
||||
m_SocketMsgDelegate?.Invoke("Client online");
|
||||
|
||||
//开启数据回调
|
||||
m_ServerHandler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
|
||||
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
|
||||
}
|
||||
|
||||
private void ReceiveCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
StateObject state = (StateObject)ar.AsyncState;
|
||||
Socket handler = state.workSocket;
|
||||
|
||||
if (handler != null && handler.Connected)
|
||||
{
|
||||
//读取数据
|
||||
int bytesRead = handler.EndReceive(ar);
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
string content = Encoding.UTF8.GetString(state.buffer, 0, bytesRead);
|
||||
state.sb.Append(content);
|
||||
string fullContent = state.sb.ToString();
|
||||
|
||||
m_SocketMsgDelegate?.Invoke(fullContent);
|
||||
|
||||
state.sb.Clear();
|
||||
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Client offline");
|
||||
m_Listener.BeginAccept(new AsyncCallback(AcceptCallback), m_Listener);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Server offline");
|
||||
}
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
m_SocketMsgDelegate?.Invoke($"{ex.ErrorCode} {ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke("Client offline");
|
||||
m_Listener.BeginAccept(new AsyncCallback(AcceptCallback), m_Listener);
|
||||
}
|
||||
}
|
||||
|
||||
public void Send(String data)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_ServerHandler == null || !m_ServerHandler.Connected)
|
||||
{
|
||||
Console.WriteLine("服务器Socket未连接,无法发送数据");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] byteData = Encoding.UTF8.GetBytes(data);
|
||||
m_ServerHandler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), m_ServerHandler);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"服务器发送数据异常:{ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
Socket handler = (Socket)ar.AsyncState;
|
||||
int bytesSent = handler.EndSend(ar);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"服务器发送回调异常:{e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void CloseSocket()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_ServerHandler != null && m_ServerHandler.Connected)
|
||||
{
|
||||
m_ServerHandler.Shutdown(SocketShutdown.Both);
|
||||
m_ServerHandler.Close();
|
||||
}
|
||||
m_Listener?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"关闭服务器Socket异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//客户端类
|
||||
public class TCPClient
|
||||
{
|
||||
public delegate void SocketMessage(object obj);
|
||||
private SocketMessage m_SocketMsgDelegate = null;
|
||||
private Socket m_Client = null;
|
||||
private Socket m_Handler = null;
|
||||
private IPEndPoint m_ipe;
|
||||
public string m_strInfo;
|
||||
|
||||
public void InitClient(string strAddr, int nPort, SocketMessage sockMsg = null)
|
||||
{
|
||||
if (sockMsg != null)
|
||||
{
|
||||
m_SocketMsgDelegate = sockMsg;
|
||||
}
|
||||
if (m_Client != null)
|
||||
{
|
||||
try { m_Client.Close(); } catch { }
|
||||
m_Client = null;
|
||||
}
|
||||
try
|
||||
{
|
||||
//端口及IP
|
||||
m_ipe = new IPEndPoint(IPAddress.Parse(strAddr), nPort);
|
||||
//创建套接字
|
||||
m_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
|
||||
//开始连接到服务器
|
||||
m_Client.BeginConnect(m_ipe, new AsyncCallback(ConnectCallback), m_Client);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 捕获初始化异常,仅提示不抛异常
|
||||
string errorMsg = $"客户端初始化连接失败:{e.Message}";
|
||||
Console.WriteLine(errorMsg);
|
||||
m_SocketMsgDelegate?.Invoke(errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
private void ConnectCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Handler = (Socket)ar.AsyncState;
|
||||
m_Handler.EndConnect(ar);
|
||||
|
||||
m_strInfo = m_Handler.LocalEndPoint.ToString();
|
||||
m_SocketMsgDelegate?.Invoke("Connection");
|
||||
|
||||
|
||||
//创建状态对象
|
||||
StateObject state = new StateObject();
|
||||
state.workSocket = m_Handler;
|
||||
|
||||
//开启数据回调
|
||||
m_Handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"客户端连接异常:{e.Message}");
|
||||
m_SocketMsgDelegate?.Invoke($"ConnectError: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void ReceiveCallBack(IAsyncResult iar)
|
||||
{
|
||||
try
|
||||
{
|
||||
StateObject state = (StateObject)iar.AsyncState;
|
||||
Socket handler = state.workSocket;
|
||||
|
||||
if (handler != null && handler.Connected)
|
||||
{
|
||||
//读取数据
|
||||
int bytesRead = handler.EndReceive(iar);
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
string content = Encoding.UTF8.GetString(state.buffer, 0, bytesRead);
|
||||
state.sb.Append(content);
|
||||
string fullContent = state.sb.ToString();
|
||||
|
||||
m_SocketMsgDelegate?.Invoke(fullContent);
|
||||
|
||||
state.sb.Clear();
|
||||
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Server offline");
|
||||
|
||||
//关闭并且允许重复使用
|
||||
m_Client.Disconnect(true);
|
||||
//重新连接到服务器
|
||||
m_Client.BeginConnect(m_ipe, new AsyncCallback(ConnectCallback), m_Client);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Client offline");
|
||||
}
|
||||
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Console.WriteLine($"客户端接收异常:{ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke($"{ex.ErrorCode} {ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke("DISCONNECT");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Send(Dictionary<string, string> printData)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 前置校验:确保 Socket 有效且已连接
|
||||
if (m_Handler == null || !m_Handler.Connected)
|
||||
{
|
||||
Console.WriteLine("客户端Socket未连接,无法发送JSON数据");
|
||||
m_SocketMsgDelegate?.Invoke("Socket未连接,发送失败");
|
||||
|
||||
return;
|
||||
}
|
||||
// 使用Newtonsoft.Json序列化
|
||||
string jsonData = JsonConvert.SerializeObject(printData);
|
||||
byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);
|
||||
m_Handler.BeginSend(jsonBytes, 0, jsonBytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), m_Handler);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 捕获并上报所有异常
|
||||
Console.WriteLine($"客户端发送JSON数据异常:{ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return m_Handler != null && m_Handler.Connected;
|
||||
}
|
||||
|
||||
public void Send(String data)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 确保 Socket 有效
|
||||
if (m_Handler == null || !m_Handler.Connected)
|
||||
{
|
||||
Console.WriteLine("客户端Socket未连接,无法发送字符串数据");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] byteData = Encoding.UTF8.GetBytes(data);
|
||||
m_Handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), m_Handler);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"客户端发送字符串数据异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
Socket handler = (Socket)ar.AsyncState;
|
||||
int bytesSent = handler.EndSend(ar);
|
||||
Console.WriteLine($"Sent {bytesSent} bytes to server.");
|
||||
m_SocketMsgDelegate?.Invoke($"发送成功,字节数:{bytesSent}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"客户端发送回调异常:{e.Message}");
|
||||
m_SocketMsgDelegate?.Invoke($"SendCallbackError: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void CloseSocket()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_Handler != null)
|
||||
{
|
||||
if (m_Handler.Connected)
|
||||
{
|
||||
m_Handler.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
m_Handler.Close();
|
||||
}
|
||||
m_Client?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"关闭客户端Socket异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class IPInfo
|
||||
{
|
||||
public string m_strIPAddr;
|
||||
public int m_nIPPort;
|
||||
public string m_strIPAddr3D;
|
||||
public int m_nIPPort3D;
|
||||
public IPInfo()
|
||||
{
|
||||
m_strIPAddr = "127.0.0.1";
|
||||
m_nIPPort = 8000;
|
||||
m_strIPAddr3D = "127.0.0.1";
|
||||
m_nIPPort3D = 8000;
|
||||
}
|
||||
}
|
||||
|
||||
public class SocketEx
|
||||
{
|
||||
//网口Socket服务
|
||||
public delegate void SocketStringMessage(string str);
|
||||
public delegate void SocketDictMessage(Dictionary<string, string> dict);
|
||||
|
||||
// 两个委托实例,分别处理字符串和字典
|
||||
public SocketStringMessage m_SockStrMsg = null;
|
||||
public SocketDictMessage m_SockDictMsg = null;
|
||||
|
||||
//定义服务器变量
|
||||
public TCPServer m_TcpServer = null; // new TCPServer();
|
||||
//定义客户端变量
|
||||
public TCPClient m_TcpClient = new TCPClient();
|
||||
//服务器或者客户端标志位:true为服务器,false微客户端
|
||||
public bool m_bTcpServer = false;
|
||||
|
||||
//ip地址和端口
|
||||
public IPInfo m_IPInfo = new IPInfo();
|
||||
|
||||
//网口接收消息委托
|
||||
public delegate void SocketMessage(string str);
|
||||
public SocketMessage m_SockMsg = null;
|
||||
|
||||
//析构函数
|
||||
~SocketEx()
|
||||
{
|
||||
CloseSocket(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 网口初始化
|
||||
/// </summary>
|
||||
/// <param name="sockMsg"></param>
|
||||
/// <param name="bTcpServer">bTCPServer: true为服务器;false为客户端</param>
|
||||
/// <returns></returns>
|
||||
public bool InitSocket(SocketStringMessage strMsg, SocketDictMessage dictMsg, bool bTcpServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_SockStrMsg = strMsg;
|
||||
m_SockDictMsg = dictMsg;
|
||||
m_bTcpServer = bTcpServer;
|
||||
if (m_bTcpServer)
|
||||
{
|
||||
TCPServer.SocketMessage msg = new TCPServer.SocketMessage(RecvSockMsg);
|
||||
m_TcpServer.InitServer(m_IPInfo.m_strIPAddr, m_IPInfo.m_nIPPort, msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
TCPClient.SocketMessage msg = new TCPClient.SocketMessage(RecvSockMsg);
|
||||
m_TcpClient.InitClient(m_IPInfo.m_strIPAddr, m_IPInfo.m_nIPPort, msg);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string str = ex.ToString();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool InitSocket(SocketMessage sockMsg, bool bTcpServer)
|
||||
{
|
||||
m_SockMsg = sockMsg;
|
||||
return InitSocket(null, null, bTcpServer);
|
||||
}
|
||||
|
||||
//关闭网口
|
||||
public void CloseSocket(bool bTcpServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (bTcpServer)
|
||||
m_TcpServer.CloseSocket();
|
||||
else
|
||||
m_TcpClient.CloseSocket();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SocketEx关闭异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
//接收网口信息
|
||||
private void RecvSockMsg(object obj)
|
||||
{
|
||||
if (obj == null) return;
|
||||
|
||||
string rawData = obj.ToString().Trim();
|
||||
try
|
||||
{
|
||||
// 第一步:判断是否为JSON字典(以{开头、以}结尾)
|
||||
if (rawData.StartsWith("{") && rawData.EndsWith("}"))
|
||||
{
|
||||
// 尝试反序列化为Dictionary<string, string>
|
||||
Dictionary<string, string> dictData = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawData);
|
||||
|
||||
// 优先调用字典回调
|
||||
m_SockDictMsg?.Invoke(dictData);
|
||||
Console.WriteLine($"SocketEx 解析出JSON字典:{string.Join("; ", dictData.Select(kv => $"{kv.Key}={kv.Value}"))}");
|
||||
|
||||
// 兼容旧版字符串回调(将字典转为可读字符串)
|
||||
m_SockMsg?.Invoke($"JSON字典:{JsonConvert.SerializeObject(dictData, Formatting.None)}");
|
||||
m_SockStrMsg?.Invoke($"JSON字典:{JsonConvert.SerializeObject(dictData, Formatting.None)}");
|
||||
}
|
||||
else
|
||||
{
|
||||
// 普通字符串,直接传递
|
||||
m_SockStrMsg?.Invoke(rawData);
|
||||
m_SockMsg?.Invoke(rawData);
|
||||
Console.WriteLine($"SocketEx 接收普通字符串:{rawData}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 反序列化失败(不是标准JSON字典),按普通字符串处理
|
||||
string errorMsg = $"数据解析失败:{ex.Message} | 原始数据:{rawData}";
|
||||
m_SockStrMsg?.Invoke(errorMsg);
|
||||
m_SockMsg?.Invoke(errorMsg);
|
||||
Console.WriteLine(errorMsg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void Send(Dictionary<string, string> dict)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!m_bTcpServer)
|
||||
{
|
||||
m_TcpClient.Send(dict);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("服务器模式下不支持发送JSON字典,请切换为客户端模式");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SocketEx发送JSON字典异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
//发送数据
|
||||
public void Send(string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_bTcpServer)
|
||||
{
|
||||
m_TcpServer.Send(str + "\r\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
m_TcpClient.Send(str + "\r\n");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SocketEx发送异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
//获取网口信息
|
||||
public string GetTCPInfo()
|
||||
{
|
||||
return m_bTcpServer ? m_TcpServer.m_strInfo : m_TcpClient.m_strInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Text.Encoding.CodePages" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Security.Cryptography.Xml" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-6.0.0.1" newVersion="6.0.0.1" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.1.0.0" newVersion="9.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.IO.Pipelines" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Google.Protobuf" publicKeyToken="a7d26565bac4d604" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.23.4.0" newVersion="3.23.4.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="ZstdSharp" publicKeyToken="8d151af33a4ad5cf" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-0.7.2.0" newVersion="0.7.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Configuration.ConfigurationManager" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /></startup></configuration>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Newtonsoft.Json" version="13.0.4" targetFramework="net48" />
|
||||
</packages>
|
||||
Reference in New Issue
Block a user