You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

676 lines
27 KiB

using DyeingComputer.UserClass;
using LiveChartsCore.Geo;
10 months ago
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenTK.Graphics.ES11;
using SunlightCentralizedControlManagement_SCCM_.Properties;
using SunlightCentralizedControlManagement_SCCM_.UserClass;
using SunlightCentralizedControlManagement_SCCM_.WindowsView;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Threading;
10 months ago
using System.Xml.Linq;
using TouchSocket.Core;
using TouchSocket.Sockets;
10 months ago
using static MaterialDesignThemes.Wpf.Theme;
using static SunlightCentralizedControlManagement_SCCM_.UserClass.SqliteHelper;
using static System.Net.WebRequestMethods;
namespace SunlightCentralizedControlManagement_SCCM_.ViewModel
{
/// <summary>
/// 变量传递至ui
/// </summary>
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
if (propertyName != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
public class MainWindowViewModel : ViewModelBase
{
//调用配置文件
private static UserClass.IniFile.IniFiles Configini = new UserClass.IniFile.IniFiles(Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory) + "SCCM.ini");
public static string SQLIP; //读配置文件
public static string SQLNAME;
public static string SQMOD;
public static string SQLUSER;
public static string SQLPASWORD;
public static string SN_ID;
public static string SN_KEY;
public static bool DyelotsDispenser;
public static SqlConnection conn_SC =new SqlConnection();//数据库
10 months ago
private SQLiteHelper SQLiteHelpers = null; //定义数据库
private readonly string DBAddress = Environment.CurrentDirectory + "\\DataBase\\SCCM.db"; //数据库路径
public static DataTable Machines = new DataTable(); //设备表缓存
public static DataRow MachinesROW;
public static DataTable USER_data = new DataTable();
10 months ago
public static UserControls.info[] inf = new UserControls.info[999]; //定义总览信息卡
public static int ERR_c = 0;//错误计数器
public static bool[] USER_Capacity { set; get; } = new bool[99];
10 months ago
public MainWindowViewModel()
{
try
{
SQLIP = Configini.IniReadvalue("SQL_SERVER", "SQL1"); //读配置文件
SQLNAME = Configini.IniReadvalue("SQL_SERVER", "SQL2");
SQMOD = Configini.IniReadvalue("SQL_SERVER", "SQL3");
SQLUSER = Configini.IniReadvalue("SQL_SERVER", "SQL4");
SQLPASWORD = Configini.IniReadvalue("SQL_SERVER", "SQL5");
SN_ID = Configini.IniReadvalue("SN", "SN2");
SN_KEY = Configini.IniReadvalue("SN", "SN1");
DyelotsDispenser = Convert.ToBoolean(Configini.IniReadvalue("SYS", "DyelotsDispenser"));
}
catch (Exception ex) { LogGing.ERRDATA(ex); }
10 months ago
SQLiteHelpers = new SQLiteHelper(DBAddress); //数据库连接路径
SQLiteHelpers.Open(); //打开数据库
Machines = SQLiteHelpers.ExecuteDataSet("select * from Machines Order by id", null).Tables[0]; //读取表写入缓存
USER_data = SQLiteHelpers.ExecuteDataSet("select * from USER order by Name desc", null).Tables[0];
10 months ago
SQLiteHelpers.Close();
MachinesROW = Machines.NewRow();
USERCapacity(App.USER_Purview);//App.USER_Purview);
10 months ago
CountDown();
TcpClientNEW();
SQL_LINK();
}
public static void USERCapacity(string user) //权限
{
if (user != "ENGINEER")
{
string USER_Cap = USER_data.Select("Name='" + user + "'").First().Field<string>("Capacity").ToString();
for (int i = 0; i < USER_Cap.Length; i++)
{
if (USER_Cap.Substring(i, 1) == "1")
{
USER_Capacity[i] = true;
}
else
{
USER_Capacity[i] = false;
}
}
}
else
{
for (int i = 0; i < 99; i++)
{
USER_Capacity[i] = true;
}
}
}
public static async void SQL_LINK()//连接dbc数据库
{
if (conn_SC.State == ConnectionState.Open) conn_SC.Close();
try
{
if (SQMOD == "Windows Authentication") //连接数据库测试
{
conn_SC = new SqlConnection("server=" + SQLIP + ";database=" + SQLNAME + ";Trusted_Connection=SSPI");
}
else
{
conn_SC = new SqlConnection("server=" + SQLIP + ";database=" + SQLNAME + ";User ID=" + SQLUSER + ";Password=" + SQLPASWORD);
}
await conn_SC.OpenAsync(); //连接数据库
//conn_SC.Close();
}
catch (Exception ex)
{
LogGing.LogGingDATA("[Database='" + ex + "']=SQLSERVER");
ERR_c++;
}
}
public void CountDown()
{
DispatcherTimer timer1s = new DispatcherTimer//初始化循环,每1秒调用一次Tick
{
Interval = TimeSpan.FromSeconds(1)//秒
};
timer1s.Tick += Tick_Event_1S;
timer1s.Start();
DispatcherTimer dis50ms = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(10) //毫秒
};
dis50ms.Tick += new EventHandler(DisTimer_50MS);//每一秒执行的方法
dis50ms.Start();//计时开始
}//时间周期初始化
void DisTimer_50MS(object sender, EventArgs e)//Tick_Event周期执行事件50MS
{
if (stringQueue.Count > 0) //信息发送队列
{
QueueString t = stringQueue.Dequeue();
MachiensTcpClient[t.ID].SendAsync(t.DAT);
}
}
void Tick_Event_1S(object sender, EventArgs e)//Tick_Event周期执行事件1S
{
DATA_view();
//下传工单信息
SQLiteHelper WorkOrderSQL = new SQLiteHelper(DBAddress); //数据库连接路径
WorkOrderSQL.Open(); //打开数据库
DataTable WorkOrderstepdata = WorkOrderSQL.ExecuteDataSet("select * from WorkOrder where State='111'", null).Tables[0]; //读取表写入缓存
for (int k = 0; k < WorkOrderstepdata.Rows.Count; k++)
{
string WorkOrderdata_m = WorkOrderstepdata.Select()[k].Field<object>("Machines").ToString();
DataTable dataTable = WorkOrderSQL.ExecuteDataSet("select * from WorkorderSteps where WorkOrder='" +
WorkOrderstepdata.Select()[k].Field<object>("WorkOrder").ToString() + "'", null).Tables[0];
int index = Convert.ToInt16(Selet_Machines(Machines, "ID", "Name='" + WorkOrderdata_m + "'").ToString());
stringQueue.Enqueue(new QueueString
{
ID = index,
DAT = "SC811" + Selet_Machines(Machines, "SYSKEY", "ID='" + index + "'") + dataTable.ToJsonString()
});
WorkOrderSQL.Update("WorkOrder", new Dictionary<string, object> { { "State", 112 } },
"WorkOrder ='" + WorkOrderstepdata.Select()[k].Field<object>("WorkOrder").ToString() + "'", null);
}
//下传工单总览
10 months ago
DataTable WorkOrderdata = WorkOrderSQL.ExecuteDataSet("select * from WorkOrder where State='100'", null).Tables[0]; //读取表写入缓存
for (int k = 0; k < WorkOrderdata.Rows.Count; k++)
10 months ago
{
string WorkOrderdata_m = WorkOrderdata.Select()[k].Field<object>("Machines").ToString();
string State = Selet_Machines(Machines, "State", "Name='" + WorkOrderdata_m + "'").ToString();
10 months ago
if ((State == "101") || (State == "201") || (State == "202") || (State == "309"))
{
DataTable dataTable = WorkOrderdata.Clone();
// WorkOrderdata.Columns.Remove("Machines");
10 months ago
DataRow dt_temp = WorkOrderdata.Select()[k];
dt_temp.BeginEdit();
dt_temp["State"] = "101";
dt_temp.EndEdit();
dataTable.Rows.Add(dt_temp.ItemArray);
int index = Convert.ToInt16(Selet_Machines(Machines, "ID", "Name='" + WorkOrderdata_m + "'").ToString());
10 months ago
stringQueue.Enqueue(new QueueString
{
ID = index,
DAT = "SC810" + Selet_Machines(Machines, "SYSKEY", "ID='" + index + "'") + DataTableToDictionary(dataTable).ToJsonString()
10 months ago
});
WorkOrderSQL.Update("WorkOrder", new Dictionary<string, object> { { "State", 110 } },
10 months ago
"WorkOrder ='" + WorkOrderdata.Select()[k].Field<object>("WorkOrder").ToString() + "'", null);
}
}
WorkOrderSQL.Close();
//系统时间
Sys_Time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
//更新机台状态与发送指令
for (int i = 0; i < Machinesdata_Count; i++)
{
if (Selet_Machines(Machines, "State", "ID='" + i + "'").ToString() == "802")
{
stringQueue.Enqueue(new QueueString
{
ID = i,
DAT = "SC830" + Selet_Machines(Machines, "SYSKEY", "ID='" + i + "'").ToString()
});//信息插入队列
Updata_Machines(Machines, "State", "ID='" + i + "'", "101");
}
}
for (int i = 0; i < Machinesdata_Count; i++)
{
string mac_s = Selet_Machines(Machines, "State", "ID='" + i + "'").ToString();
if ((mac_s == "101") || (mac_s == "201") || (mac_s == "202") || (mac_s == "309"))//获取信息
{
stringQueue.Enqueue(new QueueString
{
ID = i,
DAT = "SC830" + Selet_Machines(Machines, "SYSKEY", "ID='" + i + "'").ToString()
});//信息插入队列
}
}
if (Time5 > 5)
{
Tick_Event_5S();
Time5 = 0;
}
else { Time5++; }
if (Time60 > 60)
{
Tick_Event_60S();
Time60= 0;
}
else { Time60++; }
}
int Time5=0,Time60;
void Tick_Event_5S()//Tick_Event周期执行事件5S
{
for (int i = 0; i < Machinesdata_Count; i++)
{
if (Selet_Machines(Machines, "State", "ID='" + i + "'").ToString() == "801")
{
stringQueue.Enqueue(new QueueString
{
ID = i,
DAT = "SC800:SCCM[" + MachiensTcpClient[i].IP + ";" + MachiensTcpClient[i].Port + "]"
});//信息插入队列
}
10 months ago
}//发送800指令
}
void Tick_Event_60S()
{
for (int i = 0; i < Machinesdata_Count; i++)
{
if (Selet_Machines(Machines, "State", "ID='" + i + "'").ToString() == "800")
{
MachiensTcpClient[i] = new TcpClient();
DataRow dt = machinesdata[i];
_ = AsyncTcpClient.TcpClient(MachiensTcpClient[i] //建立tcp连接
, Selet_Machines(Machines, "IP", "ID='" + Convert.ToInt16(dt["ID"]) + "'" ).ToString()
, Selet_Machines(Machines, "PORT", "ID='" + Convert.ToInt16(dt["ID"]) + "'").ToString());
}
10 months ago
}//重连
}
10 months ago
public static TcpClient[] MachiensTcpClient = new TcpClient[999];
public static DataRow[] machinesdata = new DataRow[999];
public int Machinesdata_Count;
public void TcpClientNEW()
{
// bool Machine_ ;
machinesdata = Machines.Select("PORT>0 AND IP<>''", "id asc");//获取连接有效的组
Machinesdata_Count = machinesdata.Count();
for (int i = 0; i < Machinesdata_Count; i++)
{
MachiensTcpClient[i] = new TcpClient();
DataRow dt = machinesdata[i];
Updata_Machines(Machines, "State", "ID='" + Convert.ToInt16(dt["ID"]) + "'", "800");
_ = AsyncTcpClient.TcpClient(MachiensTcpClient[i] //建立tcp连接
, Selet_Machines(Machines, "IP", "ID='" + Convert.ToInt16(dt["ID"]) + "'").ToString()
, Selet_Machines(Machines, "PORT", "ID='" + Convert.ToInt16(dt["ID"]) + "'").ToString());
}
}
public static string SYS_WorkNumder; //工单号
public static int SYS_AT1; //附缸1-3
public static int SYS_AT2;
public static int SYS_AT3;
public string sys_Time; //显示系统时间
public string Sys_Time //通知UI控件参数改变
{
get { return sys_Time; }
set { sys_Time = value; OnPropertyChanged("Sys_Time"); }
}
public static string MachineLOG;
public string sys_machine; //显示log
public string Sys_machine //通知UI控件参数改变
{
get { return sys_machine; }
set { sys_machine = value; OnPropertyChanged("Sys_machine"); }
}
public static object Selet_Machines(DataTable DB, string name, string key)//查询
{
try
{
lock (DB)
{
DataRow drEmployee = DB.Select(key).First();
object index = drEmployee.Field<object>(name);
return index;
}
}
catch (Exception ex)
{
LogGing.LogGingDATA("SDTD:" + ex.ToString());
return "ERR";
}
}
public static void Updata_Machines(DataTable DB, string name, string key, string Value)//更新数据
{
try
{
lock (DB)
{
DataRow drEmployee = DB.Select(key).First();
drEmployee.BeginEdit();
drEmployee[name] = Value;
drEmployee.EndEdit();
drEmployee.AcceptChanges();
// drEmployee.ClearErrors();
}
}
catch (Exception ex)
{
LogGing.LogGingDATA("SDTD:" + ex.ToString());
}
}
public static DataTable dt_d = new DataTable("DIO");
public static DataTable dt_a = new DataTable("AIO");
public static DataTable dt_m = new DataTable("M");
public static DataTable dt_TM = new DataTable();
public static DataTable dt_TP = new DataTable();
public static DataTable dt_ParameterSet = new DataTable();
public static DataTable dt_SysSet = new DataTable();
public static bool TechnologicalProcess_bool =true;
public static bool A_view =true;
public static bool D_view =true;
public static bool IO_view;
public static bool ParameterSet_view=true;
public static bool SysSet_view=true;
private async void DATA_view()//IO显示
{
await Task.Run(() =>
{
try
{
if (dt_m.Rows.Count >= 0)
{
SYSData_M = ToObservableCollection<DATA_M>(dt_m);
}
}
catch (Exception ) { }
try
{
if (dt_a.Rows.Count >= 0)
{
if ((bool)A_view) SYSData_A = ToObservableCollection<DATA_A>(dt_a);
}
}
catch (Exception ) { }
try
{
if (dt_d.Rows.Count >= 0)
{
if ((bool)D_view) SYSData_D = ToObservableCollection<DATA_D>(dt_d);
}
}
catch (Exception) { }
try
{
TechnologicalMachine_View = ToObservableCollection<TechnologicalM>(Machines);
}
catch (Exception) { }
try
{
if (dt_ParameterSet.Rows.Count >= 0)
{
if(ParameterSet_view) Paramete_Set = ToObservableCollection<ParameterSet>(dt_ParameterSet);
}
}
catch (Exception) { }
try
{
if (dt_SysSet.Rows.Count >= 0)
{
if (SysSet_view) Sys_Set = ToObservableCollection<SysSet>(dt_SysSet);
}
}
catch (Exception) { }
try
{
if (dt_TP.Rows.Count >= 0)
{
if(TechnologicalProcess_bool) TechnologicalProcess_View = ToObservableCollection<TechnologicalP>(dt_TP);
Sys_machine = MachineLOG;
}
}
catch (Exception) { }
});
}
ObservableCollection<DATA_A> sysData_A = new ObservableCollection<DATA_A>();
ObservableCollection<DATA_D> sysData_D = new ObservableCollection<DATA_D>();
ObservableCollection<DATA_M> sysData_M = new ObservableCollection<DATA_M>();
ObservableCollection<ParameterSet> paramete_Set = new ObservableCollection<ParameterSet>();
ObservableCollection<SysSet> sys_Set = new ObservableCollection<SysSet>();
ObservableCollection<TechnologicalP> technologicalProcess_View = new ObservableCollection<TechnologicalP>();
ObservableCollection<TechnologicalM> technologicalMachine_View = new ObservableCollection<TechnologicalM>();
public ObservableCollection<DATA_A> SYSData_A
{
get { return sysData_A; }
set
{
sysData_A = value;
RaisePropertyChanged("SYSData_A");
}
}
public ObservableCollection<DATA_D> SYSData_D
{
get { return sysData_D; }
set
{
sysData_D = value;
RaisePropertyChanged("SYSData_D");
}
}
public ObservableCollection<DATA_M> SYSData_M
{
get { return sysData_M; }
set
{
sysData_M = value;
RaisePropertyChanged("SYSData_M");
}
}
public ObservableCollection<TechnologicalP> TechnologicalProcess_View
{
get { return technologicalProcess_View; }
set
{
technologicalProcess_View = value;
RaisePropertyChanged("TechnologicalProcess_View");
}
}
public ObservableCollection<TechnologicalM> TechnologicalMachine_View
{
get { return technologicalMachine_View; }
set
{
technologicalMachine_View = value;
RaisePropertyChanged("TechnologicalMachine_View");
}
}
public ObservableCollection<ParameterSet> Paramete_Set
{
get { return paramete_Set; }
set
{
paramete_Set = value;
RaisePropertyChanged("Paramete_Set");
}
}
public ObservableCollection<SysSet> Sys_Set
{
get { return sys_Set; }
set
{
sys_Set = value;
RaisePropertyChanged("Sys_Set");
}
}
public class DATA_A
{
public string IOName { get; set; }
public int AIO { get; set; }
public string ID { get; set; }
public string PLC { get; set; }
public string type { get; set; }
}
public class DATA_D
{
public string IOName { get; set; }
public bool DIO { get; set; }
public string ID { get; set; }
public string PLC { get; set; }
public string type { get; set; }
}
public class DATA_M
{
public string IOName { get; set; }
public double Value { get; set; }
public string ID { get; set; }
public string PLC { get; set; }
public string type { get; set; }
}
public class TechnologicalM
{
public string Name { get; set; }
public string WorkOrder { get; set; }
public string Dyelot { get; set; }
public string Temperature { get; set; }
public string WaterLevel { get; set; }
public string Process { get; set; }
public string Step { get; set; }
public string Message { get; set; }
public string State { get; set; }
}
public class TechnologicalP
{
public string ProgramID { get; set; }
public string Program { get; set; }
public double Step { get; set; }
public string StepID { get; set; }
public string StepName { get; set; }
public string ParameterName { get; set; }
public string Parameter1 { get; set; }
public string Parameter2 { get; set; }
public string Parameter3 { get; set; }
public string Parameter4 { get; set; }
public string Parameter5 { get; set; }
public string DYELOT { get; set; }
}
public class ParameterSet
{ public string Category { get; set; }
public string ParameterID { get; set; }
public string ParameterName { get; set; }
public string Value { get; set; }
}
public class SysSet
{
public string Category { get; set; }
public string ParameterID { get; set; }
public string ParameterName { get; set; }
public string Value { get; set; }
}
public ObservableCollection<T> ToObservableCollection<T>(DataTable dt) where T : class, new()
{
Type t = typeof(T);
PropertyInfo[] propertys = t.GetProperties();
ObservableCollection<T> lst = new ObservableCollection<T>();
string typeName = string.Empty;
foreach (DataRow dr in dt.Rows)
{
T entity = new T();
foreach (PropertyInfo pi in propertys)
{
typeName = pi.Name;
if (dt.Columns.Contains(typeName))
{
if (!pi.CanWrite) continue;
object value = dr[typeName];
if (value == DBNull.Value) continue;
if (pi.PropertyType == typeof(string))
{
pi.SetValue(entity, value.ToString(), null);
}
else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
{
pi.SetValue(entity, int.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
{
pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(float))
{
pi.SetValue(entity, float.Parse(value.ToString()), null);
}
else if (pi.PropertyType == typeof(double))
{
pi.SetValue(entity, double.Parse(value.ToString()), null);
}
else
{
pi.SetValue(entity, value, null);
}
}
}
lst.Add(entity);
}
return lst;
}
//通讯队列
public static UInt32 RX=0;
public static UInt32 TX=0;
public class QueueString
{
public int ID { get; set; }
public string DAT { get; set; }
}
public static class Queue
{
public static int ID { get; set; }
public static string DAT { get; set; }
}
// 创建一个字符串类型的队列
public static Queue<QueueString> stringQueue = new Queue<QueueString>();
10 months ago
/// <summary>
/// 将 DataTable 转换为 Dictionary 类型数据
/// </summary>
public Dictionary<string, object> DataTableToDictionary(DataTable dataTable)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (dataTable != null)
{
foreach (DataRow dataRow in dataTable.Rows)
{
foreach (DataColumn dataColumn in dataTable.Columns)
{
result.Add(dataColumn.ColumnName, dataRow[dataColumn].ToString());
//result = Console.WriteLine(dataRow[dataColumn].ToString());
//result.Add(dataColumn.ColumnName, dataRow[dataColumn].ToString())(new RepeatDictionaryComparer());
}
}
}
else
{
result = null;
}
return result;
}
}
}