无代码编写自动化设备
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json;
using SQLiteHelper;//数据库sqlite助手
using System.Reflection;
using System.Windows.Forms;
using System.Threading;
namespace Test
{
public class FlowMotion
{
public int GrideIdx;//在表格内的唯一索引
public bool bActError = false;
public static bool bLogTest ;
}
public class Station : FlowMotion
{
public int Idx=-1;
public uint StaId;
public string Name;
public List<Flow> FlowList;
public bool bquit = false;
public bool bOneStep = false;
public bool bShowStepMsg = false;
public static bool bDemoRun = false;
public Station(uint staId, string name)
{
this.StaId = staId;
this.Name = name;
}
public Station()
{
}
public List<Flow> LastFlowList = new List<Flow>();
public Flow CurFlow, FirstFlow;
EmRes InitFlow()
{
if (FirstFlow == null)
{
List<uint> stepIdList = new List<uint>();
foreach (var step in FlowList)
stepIdList.Add(step.FlowId);
var firstId = stepIdList.Min();
FirstFlow = FlowList.Where(s => s.FlowId == firstId).ToList()[0];
}
CurFlow = FirstFlow;
return EmRes.Succeed;
}
public EmRes UpdateCurFlowList()
{
if (CurFlow == null) return EmRes.Error;
else
{
List<uint> stepIdList = new List<uint>();
var firstId = CurFlow.FlowId;
var otherlist = FlowList.Where(s => s.FlowId > firstId).ToList();
if (otherlist == null || otherlist.Count == 0)
{
CurFlow=null;
return EmRes.Succeed;
}
foreach (var step in otherlist)
stepIdList.Add(step.FlowId);
var objStepId = stepIdList.Min();
CurFlow = otherlist.Where(s => s.FlowId == objStepId).ToList()[0];
return EmRes.Succeed;
}
}
public EmRes RunTh()
{
EmRes res = EmRes.Succeed;
List<EmRes> ChkretList = new List<EmRes>();
if (CurFlow == null)
{
res= InitFlow();
if (res != EmRes.Succeed) return res ;
}
while (!bquit && !SysStatus.QuitFlag&& CurFlow!=null)
{
Thread.Sleep(50);
var starTime = DateTime.Now;
if (bquit || SysStatus.QuitFlag) return EmRes.Quit;
ChkretList.Clear();
var flow = CurFlow;
var RunTask = Task.Factory.StartNew(() =>
{
try
{
return flow.Func();
}
catch (Exception ee)
{
Logger.Error($"{flow.FullDesc}未知异常+{ee.ToString()}!");
return EmRes.Error;
}
}, TaskCreationOptions.LongRunning);
int i = 0;
RunTask.Wait();
var StepTime = Math.Round((DateTime.Now - starTime).TotalSeconds, 3).ToString();
var CurStepName = flow.FullDesc;
var resm = RunTask.Result;
if (resm != EmRes.Succeed && resm != EmRes.StepEnd)
{
Logger.Error(CurStepName + "-失败!");
bquit = true;
return resm;
}
if ((bOneStep || bShowStepMsg || bLogTest) && !CurStepName.Contains("等待"))
Logger.Info(CurStepName + "-用时:" + StepTime + "s");
Thread.Sleep(10);
UpdateCurFlowList();
}
if (bquit || SysStatus.QuitFlag) return EmRes.Quit;
return EmRes.Succeed;
}
public Task mtask;
public bool bRun
{
get
{
foreach (var mflow in FlowList)
{
if (mflow.RunTask != null && !mflow.RunTask.IsCompleted)
{
Thread.Sleep(100);
if (mflow.RunTask != null && !mflow.RunTask.IsCompleted)
{
return true;
}
}
}
if (mtask != null && !mtask.IsCompleted)
{
Thread.Sleep(100); if (mtask != null && !mtask.IsCompleted) return true;
}
return false;
}
}
public void Start()
{
if (SysStatus.QuitFlag || bquit)
{
Logger.Error($"{Name}系统退出状态,未初始化无法运行!");
return;
}
if (bRun)
{
Logger.Error($"{Name}严重错误有线程未退出,无法继续创建运行线程!");
bquit = true;
return;
}
Logger.Info($"创建{Name}线程!");
if (mtask != null && mtask.IsCompleted) mtask.Dispose();
mtask = Task.Factory.StartNew(() =>
{
try
{
RunTh();
}
catch (Exception ee)
{
Logger.Error($"{Name}未知异常+{ee.ToString()}!");
bquit = true;
}
finally
{
Logger.Info($"{Name}线程退出!");
}
}, TaskCreationOptions.LongRunning);
}
}
public class Flow : FlowMotion
{
public int Idx=-1;
public uint StaId;
public uint FlowId;
public string Name;
public List<Step> AllStepList;
public Station FatherStation;
public bool bShowStepMsg
{
get
{
if (bOneStep) return true;
else
if (FatherStation == null) return true;
else
return FatherStation.bShowStepMsg;
}
set
{
if (FatherStation == null) return;
else
FatherStation.bShowStepMsg = value;
}
}
public bool bquit
{
get
{
if (FatherStation == null) return true;
else
return FatherStation.bquit;
}
set
{
if (FatherStation == null) return;
else
FatherStation.bquit = value;
}
}
public bool bOneStep
{
get
{
if (FatherStation == null) return false;
else
return FatherStation.bOneStep;
}
set
{
if (FatherStation == null) return;
else
FatherStation.bOneStep = value;
}
}
public string FullDesc
{
get
{
if (FatherStation == null) return Name;
else return FatherStation.Name + "-" + Name;
}
}
//无料空跑运行,不检测传感器
public bool bDemo => Station.bDemoRun;
//逻辑测试,无任何动作
public List<Step> CurStepList=new List<Step>();
public List<Step> FirstStepList=new List<Step>();
public List<Step> LastStepList=new List<Step>();
public Task<EmRes> RunTask;
public int flowTime;
public object FlowLock;
public Flow( uint staId, uint flowId, string name)
{
this.StaId = staId;
this.FlowId = flowId;
this.Name = name;
}
public EmRes InitStep()
{
if (FirstStepList == null || FirstStepList.Count == 0)
{
List<uint> stepIdList = new List<uint>();
foreach (var step in AllStepList)
stepIdList.Add(step.StepId);
var firstId = stepIdList.Min();
FirstStepList = AllStepList.Where(s => s.StepId == firstId).ToList();
}
CurStepList = FirstStepList;
return EmRes.Succeed;
}
public EmRes UpdateCurStepList()
{
if (CurStepList == null) return EmRes.Error;
else
{
List<uint> stepIdList = new List<uint>();
var firstId = CurStepList[0].StepId;
var otherlist = AllStepList.Where(s => s.StepId > firstId).ToList();
if (otherlist == null || otherlist.Count == 0)
{
CurStepList.Clear();
return EmRes.Succeed;
}
foreach (var step in otherlist)
stepIdList.Add(step.StepId);
var objStepId = stepIdList.Min();
CurStepList = otherlist.Where(s => s.StepId == objStepId).ToList();
return EmRes.Succeed;
}
}
public EmRes Func()
{
EmRes ret = EmRes.Succeed;
DateTime timeStart = DateTime.Now;
RunTask = Task.Factory.StartNew(() =>
{
try
{
return ret = RunThtrad();
}
catch (Exception ee)
{
Logger.Error($"{Name}未知异常+{ee.ToString()}!");
return ret = EmRes.Error;
}
}, TaskCreationOptions.LongRunning);
RunTask.Wait();
var flowTime = Math.Round((DateTime.Now - timeStart).TotalSeconds, 2).ToString();
if (ret == EmRes.Succeed)
Logger.Info(FullDesc + "-流程用时:" + flowTime + "s");
return ret;
}
public EmRes RunThtrad()
{
EmRes ret = EmRes.Succeed;
List< EmRes> ChkretList = new List<EmRes>();
if (CurStepList == null|| CurStepList.Count==0)
{
ret = InitStep();
if (ret != EmRes.Succeed) return ret;
}
if (FlowLock == null) FlowLock = new object();
lock (FlowLock)
{
while (CurStepList != null&& CurStepList.Count!=0)
{
System.Threading.Thread.Sleep(10);
Application.DoEvents();
var mStepList = CurStepList;//临时记录
if (mStepList == null|| mStepList.Count==0) return ret;
if (bquit || SysStatus.QuitFlag) return EmRes.Quit;
ChkretList.Clear();
List<Task<EmRes>> taskList = new List<Task<EmRes>>();
foreach (var step in mStepList)
{
var RunTask = Task.Factory.StartNew(() =>
{
try
{
return step.StepAct();
}
catch (Exception ee)
{
Logger.Error($"{step.FullDesc}未知异常+{ee.ToString()}!");
bActError = true;
return ret = EmRes.Error;
}
}, TaskCreationOptions.LongRunning);
taskList.Add(RunTask);
}
foreach( var task in taskList)
{
task.Wait();
ChkretList.Add(task.Result);
}
foreach (var res in ChkretList)
{
if (res != EmRes.Succeed && res != EmRes.StepEnd)
{
bquit = true;
bActError = true;
return res;
}
}
if (bOneStep )
return EmRes.NextStep;
ret= UpdateCurStepList();
if (ret != EmRes.Succeed) return ret;
}
}
return EmRes.Succeed;
}
public Flow()
{
}
}
public enum StepType
{
[Description ("轴定位")]
AxisMoveTo,
[Description("打印消息")]
WriteMsg,
[Description("设置IO")]
IoSet,
[Description("下一步骤")]
NextStep,
[Description("下一流程")]
NextFlow,
[Description("下一工站")]
NextSta,
[Description("结束流程")]
StepEnd,
[Description("轴回零")]
AxisHome
}
public class Step : FlowMotion
{
public int Idx=-1;
public uint StepId;
public uint StaId;
public uint FlowId;
public string Name;
public StepType Type;
public List<string> Params;
public Flow FatherFlow;
public bool bquit
{
get
{
if (FatherFlow == null) return true;
else
return FatherFlow.bquit;
}
set
{
if (FatherFlow == null) return;
else
FatherFlow.bquit = value;
}
}
public bool bShowStepMsg
{
get
{
if (FatherFlow == null) return true;
else
return FatherFlow.bShowStepMsg;
}
set
{
if (FatherFlow == null) return;
else
FatherFlow.bShowStepMsg = value;
}
}
public Step( uint staId,uint flowId, uint stepId,string name, StepType type, List<string> mparams)
{
this.StaId = staId;
this.FlowId = flowId;
this.StepId = stepId;
this.Name = name;
this.Type = type;
this.Params = mparams;
}
public Step()
{
}
public string FullDesc
{
get
{
if (FatherFlow == null) return Name;
else return FatherFlow.FullDesc + "-" + Name;
}
}
public EmRes StepAct()
{
EmRes res = EmRes.Succeed;
DateTime timeStart = DateTime.Now;
if (Type== StepType.AxisMoveTo)
{
bool mbquit = bquit;
res= (new AxisMoveToFactory()).StepWork(ref mbquit, Params);
bquit = mbquit;
}
else
if (Type == StepType.AxisHome)
{
bool mbquit = bquit;
res = (new AxisHomeFactory()).StepWork(ref mbquit, Params);
bquit = mbquit;
}
else
if (Type== StepType.IoSet)
{
bool mbquit = bquit;
res = (new IoFactory()).StepWork(ref mbquit, Params);
bquit = mbquit;
}
var StepTime = Math.Round((DateTime.Now - timeStart).TotalSeconds, 3).ToString()+"s";
if (res== EmRes.Succeed||res== EmRes.StepEnd ||res== EmRes.Next||res== EmRes.NextStep)
Logger.Info(FullDesc + "-成功:" + "用时"+ StepTime);
else Logger.Error(FullDesc + "-失败:" + "用时" + StepTime);
return res;
}
}
public class StepFactory
{
public virtual EmRes StepWork( ref bool bquit, List<string> mparams)
{
return EmRes.Succeed;
}
}
public class AxisMoveToFactory: StepFactory
{
public override EmRes StepWork(ref bool bquit, List<string> mparams)
{
if (mparams == null || mparams.Count < 2)
return EmRes.ParamError;
string axisName = mparams[0];
double ObjPos =Convert.ToDouble( mparams[1]);
var objAxisList = MT.AxisList.Where(s => s.Description == axisName).ToList();
if(objAxisList==null|| objAxisList.Count!=1)
return EmRes.ParamError;
return objAxisList[0].MoveTo(ref bquit, ObjPos, 5000);
}
public static List<string> GetAxisNameList()
{
List<string> mlist = new List<string>();
foreach (var axis in MT.AxisList)
mlist.Add(axis.Description);
return mlist;
}
}
public class AxisHomeFactory : StepFactory
{
public override EmRes StepWork(ref bool bquit, List<string> mparams)
{
if (mparams == null || mparams.Count < 1)
return EmRes.ParamError;
string axisName = mparams[0];
var objAxisList = MT.AxisList.Where(s => s.Description == axisName).ToList();
if (objAxisList == null || objAxisList.Count != 1)
return EmRes.ParamError;
var Res= objAxisList[0].HomeWorkStart();
if (Res != EmRes.Succeed) return Res;
while(!objAxisList[0].HomeWorkIsEnd)
{
if (bquit)
{
objAxisList[0].HomeWorkStop();
return EmRes.Quit; }
Thread.Sleep(30);
}
return Res;
}
}
public class IoFactory : StepFactory
{
public virtual EmRes StepWork(ref bool bquit, List<string> mparams)
{
if (mparams == null || mparams.Count < 2)
return EmRes.ParamError;
string IoName = mparams[0].ToString();
int ObjPos = Convert.ToInt16(mparams[1]);
var objList = MT.GpioList.Where(s => s.Description == IoName).ToList();
if (objList == null || objList.Count != 1)
return EmRes.ParamError;
if (ObjPos == 0)
return objList[0].SetOff();
else
return objList[0].SetOn();
}
public static List<string> GetIoList()
{
List<string> mlist = new List<string>();
foreach (var obj in MT.GpioList)
{
if(obj.Direction== SunnyLib.Motion.Gpio.IoDirection.Out)
mlist.Add(obj.Description);
}
return mlist;
}
}
class FlowData
{
public delegate void DeleteDataUpdate();
public static DeleteDataUpdate DataUpdateEvent;
public static string GetDescription(Enum value)
{
Type enumType = value.GetType();
// 获取枚举常数名称。
string name = Enum.GetName(enumType, value);
if (name != null)
{
// 获取枚举字段。
FieldInfo fieldInfo = enumType.GetField(name);
if (fieldInfo != null)
{
// 获取描述的属性。
DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
typeof(DescriptionAttribute), false) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
public static object DbLck = new object();
private static string _FlowDataPath = "..\\syscfg\\FlowData.db";
///
/// 检查文件夹/表格是否存在,否则创建
///
/// 数据库链接
public static void ChkAndCreateTable(SQLiteConnection conn)
{
//检查文件夹
var path = Path.GetDirectoryName(conn.FileName);
if (path != null && !Directory.Exists(path))
Directory.CreateDirectory(path);
//检查表格
var cmd = new SQLiteCommand(conn)
{
CommandText = @"CREATE TABLE IF NOT EXISTS `Station`(Idx INTEGER PRIMARY KEY autoincrement,Name TEXT,StaId INTEGER)"
};
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS `Flow`(Idx INTEGER PRIMARY KEY autoincrement,Name TEXT,StaId INTEGER,FlowId INTEGER)";
cmd.ExecuteNonQuery();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS `Step`(Idx INTEGER PRIMARY KEY autoincrement,Name TEXT,StaId INTEGER,FlowId INTEGER,StepId INTEGER,Type INTEGER,ParamsOne TEXT,ParamsTwo TEXT,ParamsThree TEXT ,ParamsFore TEXT, ParamsFive TEXT)";
cmd.ExecuteNonQuery();
}
public static int CreatDataBase()
{
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
//链接
try
{
conn.Open();
if (conn.State == ConnectionState.Closed)
{
Logger.Error("链接数据出错");
return 1 ;
}
conn.Close();
return 0;
}
catch (Exception ex)
{
Logger.Error($"链接数据异常,{ex.Message}");
return 1;
}
}
}
///
/// 保存指定步骤到文件
///
/// 指定对象,静态类用typeof(类)
/// 文件路径
/// 变量重命名
/// 不为空时,只保存catalog上含此字符的参数,分系统,产品
/// 成功返回0,否则返回错误计数
public static int SaveToFile(object obj, bool bChkAlreadyHave = false)
{
if (obj == null) return -1;
var objType = obj.GetType().Name;
var errCnt = 0;
if (bChkAlreadyHave)
{
switch (objType)
{
case "Step":
var mstep = (Step)obj;
var mstepList = GetStepListFromFlow(mstep.StaId, mstep.FlowId);
var mstplist = mstepList.Where(s => s.FlowId == mstep.FlowId && s.Name == mstep.Name).ToList();
if (mstplist != null && mstplist.Count > 0)
{
Logger.Error($"当前工站已经包含相同步骤名字和序号同时重复,{mstep.Name}");
return 1;
}
break;
case "Flow":
var mflow = (Flow)obj;
var mflowList = GetFlowListFromSta(((Flow)obj).StaId);
var mlist = mflowList.Where(s => s.StaId == mflow.StaId &&( s.Name == mflow.Name|| s.FlowId == mflow.FlowId)).ToList();
if (mlist != null && mlist.Count > 0)
{
Logger.Error($"当前工站已经包含相同流程,{mflow.Name}");
return 1;
}
break;
case "Station":
var msta = (Station)obj;
var mStaList = GetAllStationList();
var mstalist = mStaList.Where(s => s.StaId == msta.StaId || s.Name == msta.Name).ToList();
if (mstalist != null && mstalist.Count > 0)
{
Logger.Error($"当前已经包含相同工站名称或id,{msta.Name}");
return 1;
}
break;
default:
return 9;//错误
}
}
bool bOk = false;
lock (DbLck)
{
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
//链接
try
{
conn.Open();
if (conn.State == ConnectionState.Closed)
{
Logger.Error("链接数据出错");
return -2;
}
}
catch (Exception ex)
{
Logger.Error($"链接数据异常,{ex.Message}");
}
//if(!File.Exists(_FlowDataPath))
//{
// conn.Close();
// conn.Open();
//}
//开始事务
var trans = conn.BeginTransaction();
//check
ChkAndCreateTable(conn);
try
{
switch (objType)
{
case "Step":
bOk= UpdateParam(conn, (Step)obj);
break;
case "Flow":
bOk= UpdateParam(conn, (Flow)obj);
break;
case "Station":
bOk= UpdateParam(conn, (Station)obj);
break;
default:
conn.Close();
return 9;//错误
}
//提交事务
trans.Commit();
}
catch (Exception ex)
{
//回滚事务
Logger.Error($"数据库回滚,{ex}");
trans.Rollback();
return 9;
}
if (bOk && DataUpdateEvent != null)
{
DataUpdateEvent();
}
}
}
return errCnt;
}
public static int DeleteFile(object obj)
{
if (obj == null) return -1;
var objType = obj.GetType().Name;
var errCnt = 0;
int res = 0;
switch (objType)
{
case "Step":
break;
case "Flow":
var steplist = GetStepListFromFlow((Flow)obj);
foreach (var step in steplist)
{
errCnt += DeleteFile(step);
}
break;
case "Station":
var mFlowlist = GetFlowListFromSta((Station)obj);
foreach (var flow in mFlowlist)
{
var msteplist = GetStepListFromFlow(flow);
foreach (var step in msteplist)
{
errCnt += DeleteFile(step);
}
errCnt += DeleteFile(flow);
}
break;
default:
return 9;//错误
}
bool bOK = false;
lock (DbLck)
{
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
//链接
try
{
conn.Open();
if (conn.State == ConnectionState.Closed)
{
Logger.Error("链接数据出错");
return -2;
}
}
catch (Exception ex)
{
Logger.Error($"链接数据异常,{ex.Message}");
}
//if(!File.Exists(_FlowDataPath))
//{
// conn.Close();
// conn.Open();
//}
//开始事务
var trans = conn.BeginTransaction();
//check
ChkAndCreateTable(conn);
try
{
switch (objType)
{
case "Step":
bOK= DeleteParams(conn, (Step)obj);
break;
case "Flow":
bOK= DeleteParams(conn, (Flow)obj);
break;
case "Station":
bOK= DeleteParams(conn, (Station)obj);
break;
default:
conn.Close();
return 9;//错误
}
//提交事务
trans.Commit();
}
catch (Exception ex)
{
//回滚事务
Logger.Error($"数据库回滚,{ex}");
trans.Rollback();
}
if (bOK && DataUpdateEvent != null)
{
DataUpdateEvent();
}
}
}
return errCnt;
}
///
/// 更新参数
///
/// SQL链接
/// 参数属性
/// 成功返回true,否则flase
private static bool UpdateParam(SQLiteConnection conn, Step step)
{
SQLiteCommand cmd;
if (step.Idx == -1)
{
cmd = new SQLiteCommand(conn)
{
CommandText = "INSERT OR REPLACE INTO `Step` ( Name, StaId, FlowId, StepId, Type, ParamsOne, ParamsTwo, ParamsThree, ParamsFore, ParamsFive) " +
"VALUES ( @Name, @StaId, @FlowId, @StepId, @Type, @ParamsOne, @ParamsTwo, @ParamsThree, @ParamsFour, @ParamsFive)"
};
}
else
cmd = new SQLiteCommand(conn)
{
CommandText = "INSERT OR REPLACE INTO `Step` (Idx, Name, StaId, FlowId, StepId, Type, ParamsOne, ParamsTwo, ParamsThree, ParamsFore, ParamsFive) " +
"VALUES (@Idx, @Name, @StaId, @FlowId, @StepId, @Type, @ParamsOne, @ParamsTwo, @ParamsThree, @ParamsFour, @ParamsFive)"
};
//插入或更新
cmd.Parameters.Clear();
if (step.Idx != -1)
cmd.Parameters.AddWithValue("@Idx", step.Idx);
cmd.Parameters.AddWithValue("@Name", step.Name);
cmd.Parameters.AddWithValue("@StaId", step.StaId);
cmd.Parameters.AddWithValue("@FlowId", step.FlowId);
cmd.Parameters.AddWithValue("@StepId", step.StepId);
cmd.Parameters.AddWithValue("@Type", step.Type);
if(step.Params.Count>0)
cmd.Parameters.AddWithValue("@ParamsOne", step.Params[0]);
if (step.Params.Count >1)
cmd.Parameters.AddWithValue("@ParamsTwo", step.Params[1]);
if (step.Params.Count > 2)
cmd.Parameters.AddWithValue("@ParamsThree", step.Params[2]);
if (step.Params.Count > 3)
cmd.Parameters.AddWithValue("@ParamsFour", step.Params[3]);
if (step.Params.Count > 4)
cmd.Parameters.AddWithValue("@ParamsFive", step.Params[4]);
//执行
if (0 == cmd.ExecuteNonQuery())
{
Logger.Error($"参数记录{cmd.CommandText.Substring(0, 6)}失败");
return false;
}
return true;
}
///
/// 更新参数
///
/// SQL链接
/// 参数属性
/// 成功返回true,否则flase
private static bool UpdateParam(SQLiteConnection conn, Flow obj)
{
SQLiteCommand cmd;
if (obj.Idx==-1)
cmd = new SQLiteCommand(conn)
{
CommandText = "INSERT OR REPLACE INTO `Flow` ( Name, StaId, FlowId) " +
"VALUES (@Name, @StaId, @FlowId)"
};
else
{
cmd = new SQLiteCommand(conn)
{
CommandText = "INSERT OR REPLACE INTO `Flow` (Idx, Name, StaId, FlowId) " +
"VALUES (@Idx,@Name, @StaId, @FlowId)"
};
}
//插入或更新
cmd.Parameters.Clear();
if (obj.Idx != -1)
cmd.Parameters.AddWithValue("@Idx", obj.Idx);
cmd.Parameters.AddWithValue("@Name", obj.Name);
cmd.Parameters.AddWithValue("@StaId", obj.StaId);
cmd.Parameters.AddWithValue("@FlowId", obj.FlowId);
//执行
if (0 == cmd.ExecuteNonQuery())
{
Logger.Error($"参数记录{cmd.CommandText}失败");
return false;
}
return true;
}
///
/// 更新参数
///
/// SQL链接
/// 参数属性
/// 成功返回true,否则flase
private static bool UpdateParam(SQLiteConnection conn, Station obj)
{
SQLiteCommand cmd;
if (obj.Idx != -1)
cmd = new SQLiteCommand(conn)
{
CommandText = "INSERT OR REPLACE INTO `Station` (Idx, Name, StaId) " +
"VALUES (@Idx, @Name, @StaId)"
};
else
cmd = new SQLiteCommand(conn)
{
CommandText = "INSERT OR REPLACE INTO `Station` ( Name, StaId) " +
"VALUES ( @Name, @StaId)"
};
//插入或更新
cmd.Parameters.Clear();
if (obj.Idx != -1)
cmd.Parameters.AddWithValue("@Idx", obj.Idx);
cmd.Parameters.AddWithValue("@Name", obj.Name);
cmd.Parameters.AddWithValue("@StaId", obj.StaId);
//执行
if (0 == cmd.ExecuteNonQuery())
{
Logger.Error($"参数记录{cmd.CommandText}失败");
return false;
}
return true;
}
private static bool DeleteParams(SQLiteConnection conn, Station obj)
{
var cmd = new SQLiteCommand(conn)
{
CommandText = $" DELETE from `Station` where Name = '{obj.Name}' ;"
};
//执行
if (0 == cmd.ExecuteNonQuery())
{
Logger.Error($"参数记录{cmd.CommandText}失败");
return false;
}
return true;
}
private static bool DeleteParams(SQLiteConnection conn, Flow obj)
{
var cmd = new SQLiteCommand(conn)
{
CommandText = $" DELETE from `Flow` where Name = '{obj.Name}'and " +
$"FlowId = {obj.FlowId} and StaId = {obj.StaId} ;"
};
//执行
if (0 == cmd.ExecuteNonQuery())
{
Logger.Error($"参数记录{cmd.CommandText}失败");
return false;
}
return true;
}
private static bool DeleteParams(SQLiteConnection conn, Step obj)
{
var cmd = new SQLiteCommand(conn)
{
CommandText = $" DELETE from `Step` where Name = '{obj.Name}'and " +
$"FlowId = {obj.FlowId} and StaId = {obj.StaId} and StepId= {obj.StepId} ;"
};
//执行
if (0 == cmd.ExecuteNonQuery())
{
Logger.Error($"参数记录{cmd.CommandText}失败");
return false;
}
return true;
}
///
/// 根据关键词提取参数表格
///
/// 关键词
/// 返回列表
public static DataTable GetStepFromFlow(Flow mflow)
{
var dtSys = new DataTable();
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
try
{
if (File.Exists(_FlowDataPath))
conn.Open();
else return null;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
if (conn.State != ConnectionState.Closed)
{
var cmd = new SQLiteCommand(conn);
var sql = new SqLiteHelper(cmd);
dtSys = sql.Select(
$@"select Idx as 序号, Name 名称,StaId 工站, FlowId 流程序号, StepId 步骤序号, Type 类型, ParamsOne 参数1,ParamsTwo 参数2, ParamsThree 参数3 ,ParamsFore 参数4
from `Step` where StaId = '{mflow.StaId}' and FlowId = '{mflow.FlowId}' order by StepId");
}
}
return dtSys;
}
public static DataTable GetStepFromFlow(uint staid,uint flowid)
{
var dtSys = new DataTable();
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
try
{
if (File.Exists(_FlowDataPath))
conn.Open();
else return null;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
if (conn.State != ConnectionState.Closed)
{
var cmd = new SQLiteCommand(conn);
var sql = new SqLiteHelper(cmd);
dtSys = sql.Select(
$@"select Idx as 序号, Name 名称,StaId 工站, FlowId 流程序号, StepId 步骤序号, Type 类型, ParamsOne 参数1,ParamsTwo 参数2, ParamsThree 参数3 ,ParamsFore 参数4
from `Step` where StaId = '{staid}' and FlowId = '{flowid}' order by StepId");
}
}
return dtSys;
}
public static DataTable GetStepFromSta(Station msta)
{
var dtSys = new DataTable();
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
try
{
if (File.Exists(_FlowDataPath))
conn.Open();
else return null;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
if (conn.State != ConnectionState.Closed)
{
var cmd = new SQLiteCommand(conn);
var sql = new SqLiteHelper(cmd);
dtSys = sql.Select(
$@"select Idx as 序号, Name 名称,StaId 工站, FlowId 流程序号, StepId 步骤序号, Type 类型, ParamsOne 参数1,ParamsTwo 参数2, ParamsThree 参数3 ,ParamsFore 参数4,ParamsFive 参数5
from `Step` where StaId = '%{msta.StaId}%'order by FlowId");
}
}
return dtSys;
}
public static DataTable GetFlowFromSta(uint mstaId)
{
var dtSys = new DataTable();
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
try
{
if (File.Exists(_FlowDataPath))
conn.Open();
else return null;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
if (conn.State != ConnectionState.Closed)
{
var cmd = new SQLiteCommand(conn);
var sql = new SqLiteHelper(cmd);
dtSys = sql.Select(
$@"select Idx as 序号, Name 名称,StaId 工站, FlowId 流程序号
from `Flow` where StaId = '{mstaId}'order by FlowId");
}
conn.Close();
}
return dtSys;
}
public static DataTable GetAllStation()
{
var dtSys = new DataTable();
using (var conn = new SQLiteConnection($@"data source={_FlowDataPath}"))
{
try
{
if (File.Exists(_FlowDataPath))
conn.Open();
else return null;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
if (conn.State != ConnectionState.Closed)
{
var cmd = new SQLiteCommand(conn);
var sql = new SqLiteHelper(cmd);
dtSys = sql.Select(
$@"select Idx as 序号, Name 名称,StaId 工站
from `Station` order by StaId");
}
}
return dtSys;
}
public static List<Station> GetAllStationList()
{
var StationList = new List<Station>();
var staTable = GetAllStation();
if (staTable == null) return null;
for(int i=0;i< staTable.Rows.Count; i++)
{
var msta = new Station();
msta.Idx =Convert.ToInt32(staTable.Rows[i]["序号"].ToString());
msta.StaId = Convert.ToUInt32 ( staTable.Rows[i]["工站"].ToString());
msta.Name = staTable.Rows[i]["名称"].ToString();
StationList.Add(msta);
}
return StationList;
}
public static List<Flow> GetFlowListFromSta(uint mstaId)
{
var ObjList = new List<Flow>();
var Table = GetFlowFromSta(mstaId);
if (Table == null) return null;
for (int i = 0; i < Table.Rows.Count; i++)
{
var obj = new Flow();
obj.Idx = Convert.ToInt32(Table.Rows[i]["序号"].ToString());
obj.StaId = Convert.ToUInt32(Table.Rows[i]["工站"].ToString());
obj.FlowId = Convert.ToUInt32(Table.Rows[i]["流程序号"].ToString());
obj.Name = Table.Rows[i]["名称"].ToString();
ObjList.Add(obj);
}
return ObjList;
}
public static List<Flow> GetFlowListFromSta(Station msta,out DataTable Table)
{
var ObjList = new List<Flow>();
Table = GetFlowFromSta(msta.StaId);
if (Table == null) return null;
for (int i = 0; i < Table.Rows.Count; i++)
{
var obj = new Flow();
obj.Idx = Convert.ToInt32(Table.Rows[i]["序号"].ToString());
obj.StaId = Convert.ToUInt32(Table.Rows[i]["工站"].ToString());
obj.FlowId = Convert.ToUInt32(Table.Rows[i]["流程序号"].ToString());
obj.Name = Table.Rows[i]["名称"].ToString();
ObjList.Add(obj);
}
msta.FlowList = ObjList;
return ObjList;
}
public static List<Flow> GetFlowListFromSta(Station msta)
{
var ObjList = new List<Flow>();
var Table = GetFlowFromSta(msta.StaId);
if (Table == null) return null;
for (int i = 0; i < Table.Rows.Count; i++)
{
var obj = new Flow();
obj.Idx = Convert.ToInt32(Table.Rows[i]["序号"].ToString());
obj.StaId = Convert.ToUInt32(Table.Rows[i]["工站"].ToString());
obj.FlowId = Convert.ToUInt32(Table.Rows[i]["流程序号"].ToString());
obj.Name = Table.Rows[i]["名称"].ToString();
obj.FatherStation = msta;
ObjList.Add(obj);
}
msta.FlowList = ObjList;
return ObjList;
}
public static List<Step> GetStepListFromFlow(Flow mflow)
{
var ObjList = new List<Step>();
var Table = GetStepFromFlow(mflow);
if (Table == null) return null;
for (int i = 0; i < Table.Rows.Count; i++)
{
var obj = new Step();
obj.Idx = Convert.ToInt32(Table.Rows[i]["序号"].ToString());
obj.StaId = Convert.ToUInt32(Table.Rows[i]["工站"].ToString());
obj.FlowId = Convert.ToUInt32(Table.Rows[i]["流程序号"].ToString());
obj.StepId = Convert.ToUInt32(Table.Rows[i]["步骤序号"].ToString());
obj.Type =(StepType) Convert.ToUInt32(Table.Rows[i]["类型"].ToString());
obj.Name = Table.Rows[i]["名称"].ToString();
List<string> mlist = new List<string>();
if(Table.Rows[i]["参数1"]!=null)
mlist.Add(Table.Rows[i]["参数1"].ToString());
if (Table.Rows[i]["参数2"] != null)
mlist.Add(Table.Rows[i]["参数2"].ToString());
if (Table.Rows[i]["参数3"] != null)
mlist.Add(Table.Rows[i]["参数3"].ToString());
if (Table.Rows[i]["参数4"] != null)
mlist.Add(Table.Rows[i]["参数4"].ToString());
obj.Params = mlist;
obj.FatherFlow = mflow;
ObjList.Add(obj);
}
mflow.AllStepList = ObjList;
return ObjList;
}
public static List<Step> GetStepListFromFlow(Flow mflow,out DataTable Table)
{
var ObjList = new List<Step>();
Table = GetStepFromFlow(mflow);
if (Table == null) return null;
for (int i = 0; i < Table.Rows.Count; i++)
{
var obj = new Step();
obj.Idx = Convert.ToInt32(Table.Rows[i]["序号"].ToString());
obj.StaId = Convert.ToUInt32(Table.Rows[i]["工站"].ToString());
obj.FlowId = Convert.ToUInt32(Table.Rows[i]["流程序号"].ToString());
obj.StepId = Convert.ToUInt32(Table.Rows[i]["步骤序号"].ToString());
obj.Name = Table.Rows[i]["名称"].ToString();
List<string> mlist = new List<string>();
if (Table.Rows[i]["参数1"] != null)
mlist.Add(Table.Rows[i]["参数1"].ToString());
if (Table.Rows[i]["参数2"] != null)
mlist.Add(Table.Rows[i]["参数2"].ToString());
if (Table.Rows[i]["参数3"] != null)
mlist.Add(Table.Rows[i]["参数3"].ToString());
if (Table.Rows[i]["参数4"] != null)
mlist.Add(Table.Rows[i]["参数4"].ToString());
obj.Params = mlist;
obj.FatherFlow = mflow;
ObjList.Add(obj);
}
mflow.AllStepList = ObjList;
return ObjList;
}
public static List<Step> GetStepListFromFlow(uint staid,uint flowid)
{
var ObjList = new List<Step>();
var Table = GetStepFromFlow(staid, flowid);
if (Table == null) return null;
for (int i = 0; i < Table.Rows.Count; i++)
{
var obj = new Step();
obj.Idx = Convert.ToInt32(Table.Rows[i]["序号"].ToString());
obj.StaId = Convert.ToUInt32(Table.Rows[i]["工站"].ToString());
obj.FlowId = Convert.ToUInt32(Table.Rows[i]["流程序号"].ToString());
obj.StepId = Convert.ToUInt32(Table.Rows[i]["步骤序号"].ToString());
obj.Name = Table.Rows[i]["名称"].ToString();
List<string> mlist = new List<string>();
if (Table.Rows[i]["参数1"] != null)
mlist.Add(Table.Rows[i]["参数1"].ToString());
if (Table.Rows[i]["参数2"] != null)
mlist.Add(Table.Rows[i]["参数2"].ToString());
if (Table.Rows[i]["参数3"] != null)
mlist.Add(Table.Rows[i]["参数3"].ToString());
if (Table.Rows[i]["参数4"] != null)
mlist.Add(Table.Rows[i]["参数4"].ToString());
obj.Params = mlist;
ObjList.Add(obj);
}
return ObjList;
}
public static EmRes ChangeStaName( Station CurStation, string Staname,out string ErrMsg)
{
ErrMsg = "";
if (CurStation == null)
{
ErrMsg="当前工站为空";
return EmRes.Error;
}
var ListStation= GetAllStationList();
var CurStalist = ListStation.Where(s => s.Name == Staname).ToList();
if (CurStalist != null && CurStalist.Count > 0)
{
ErrMsg = "工站名称有重复,请重新输入";
return EmRes.Error;
}
if (Staname == null || Staname.Length < 2 || Staname.Length > 40)
{
ErrMsg = "请输入正确的工站名称";
return EmRes.Error;
}
var tempName = CurStation.Name;
CurStation.Name = Staname;
var res = SaveToFile(CurStation);
if (res == 0) return EmRes.Succeed;
else
{
CurStation.Name = tempName;
return EmRes.Error;
}
}
public static EmRes CreatAndSaveNewSta( string Staname, out string ErrMsg)
{
ErrMsg = "";
var ListStation = GetAllStationList();
if (ListStation != null)
{
var CurStalist = ListStation.Where(s => s.Name == Staname).ToList();
if (CurStalist != null && CurStalist.Count > 0)
{
ErrMsg = "工站名称有重复,请重新输入";
return EmRes.Error;
}
}
if (Staname == null || Staname.Length < 2 || Staname.Length > 40)
{
ErrMsg = "请输入正确的工站名称";
return EmRes.Error;
}
uint staid = 0;
List<uint> stepidlist = new List<uint>();
if (ListStation != null && ListStation.Count > 0)
{
foreach (var step in ListStation)
stepidlist.Add(step.StaId);
staid = stepidlist.Max() + 1;
}
else staid = 1;
Station msta = new Station(staid, Staname);
var res = SaveToFile(msta);
if (res == 0) return EmRes.Succeed;
else return EmRes.Error;
}
public static EmRes CreatAndSaveNesFlow(string staName, string flowName, out string ErrMsg, bool bCheckAlreadyHave=true, uint flowId = uint.MaxValue)
{
ErrMsg = "";
if (staName == null || staName.Length < 2 || staName.Length > 40)
{
ErrMsg="请选择正确的工站名称";
return EmRes.Error;
}
var Stalist = GetAllStationList();
var CurStalist = Stalist.Where(s =>( s.Name == staName )).ToList();
if (CurStalist == null || CurStalist.Count==0 )
{
ErrMsg="请选择正确的工站名称";
return EmRes.Error;
}
if (flowName == null || flowName.Length < 2 || flowName.Length > 40)
{
ErrMsg="流程名称格式异常,请重新输入";
return EmRes.Error;
}
var AllFlowlist = GetFlowListFromSta(CurStalist[0]);
if (bCheckAlreadyHave)
{
var Curflowlist = AllFlowlist.Where(s => s.Name == staName || s.FlowId == flowId).ToList();
if (Curflowlist != null && Curflowlist.Count > 0)
{
ErrMsg = "当前工站已经包含该流程";
return EmRes.Error;
}
}
if (flowId == uint.MaxValue)
{
List<uint> Flowidlist = new List<uint>();
if (AllFlowlist != null && AllFlowlist.Count > 0)
{
foreach (var step in AllFlowlist)
{
Flowidlist.Add(step.FlowId);
}
flowId = Flowidlist.Max() + 1;
}
else flowId = 1;
}
Flow mflow = new Flow(CurStalist[0].StaId, flowId, flowName);
var res = SaveToFile(mflow , bCheckAlreadyHave);
if (res == 0) return EmRes.Succeed;
else return EmRes.Error;
}
public static EmRes ChangeFlowObject(Flow objFlow, out string ErrMsg)
{
ErrMsg = "";
var Stalist = GetAllStationList();
var CurStalist = Stalist.Where(s => (s.Name == objFlow.FatherStation.Name)).ToList();
if (CurStalist == null || CurStalist.Count == 0)
{
ErrMsg = "请选择正确的工站名称";
return EmRes.Error;
}
var AllFlowlist = GetFlowListFromSta(CurStalist[0]);
var Curflowlist = AllFlowlist.Where(s => s.Idx == objFlow.Idx).ToList();
if (Curflowlist == null || Curflowlist.Count == 0)
{
ErrMsg = "当前工站不包含该流程";
return EmRes.Error;
}
var res = SaveToFile(objFlow);
if (res == 0) return EmRes.Succeed;
else return EmRes.Error;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using Microsoft.VisualBasic;
namespace Test
{
public partial class GropDataGrideView : UserControl
{
public GropDataGrideView()
{
InitializeComponent();
init();
FlowData.DataUpdateEvent += new FlowData.DeleteDataUpdate(init);
}
public void init()
{
ListStation = FlowData.GetAllStationList();
}
List<Station> _ListStation;
Station CurStation;
Flow CurFlow;
Step CurStep;
public List<Station> ListStation
{
get
{
return _ListStation;
}
set
{
timer1.Enabled = false;
this.MyDge.Rows.Clear();
_ListStation = value;
CurStation=null;
CurFlow=null;
CurStep=null;
lb_Desc.Text = "请选择对象";
Addcolumn();
timer1.Enabled = true;
}
}
public void Addcolumn()
{
string mparams = "";
if (ListStation == null || ListStation.Count == 0) { return; }
foreach (var mSta in ListStation)
{
int InsertStaId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
MyDge.Rows[InsertStaId].Cells[0].Value = mSta.Name;
MyDge.Rows[InsertStaId].Cells[1].Value = mSta.StaId;
MyDge.Rows[InsertStaId].Cells[2].Value = "工站";
mSta.GrideIdx = InsertStaId;
MyDge.Rows[InsertStaId].Cells[3].Value = mSta.GrideIdx;
var flowlist = FlowData.GetFlowListFromSta(mSta);
if (flowlist == null || flowlist.Count == 0) { continue; }
foreach (var mFlow in flowlist)
{
int InsertFlowId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell());
MyDge.Rows[InsertFlowId].Cells[0].Value = mFlow.Name;
MyDge.Rows[InsertFlowId].Cells[1].Value = mFlow.FlowId;
MyDge.Rows[InsertFlowId].Cells[2].Value = "流程";
mFlow.GrideIdx = InsertFlowId;
MyDge.Rows[InsertFlowId].Cells[3].Value = mFlow.GrideIdx;
((DataGridViewGroupCell)MyDge.Rows[InsertStaId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[InsertFlowId].Cells[0]);
var StepList = FlowData.GetStepListFromFlow(mFlow);
if (StepList == null || StepList.Count == 0) { continue; }
foreach (var mStep in StepList)
{
int InsertStepId = MyDge.Rows.Add(new DataGridViewGroupCell(), new DataGridViewTextBoxCell(), new DataGridViewButtonCell(), new DataGridViewButtonCell(), new DataGridViewButtonCell());
MyDge.Rows[InsertStepId].Cells[0].Value = mStep.Name;
MyDge.Rows[InsertStepId].Cells[1].Value = mStep.StepId;
MyDge.Rows[InsertStepId].Cells[2].Value = "步骤";
mStep.GrideIdx = InsertStepId;
MyDge.Rows[InsertStepId].Cells[3].Value = mStep.GrideIdx;
MyDge.Rows[InsertStepId].Cells[4].Value =FlowData.GetDescription( mStep.Type);
mparams = "";
foreach (var str in mStep.Params)
{
mparams = mparams+ str + ";";
}
MyDge.Rows[InsertStepId].Cells[5].Value = mparams;
((DataGridViewGroupCell)MyDge.Rows[InsertFlowId].Cells[0]).AddChildCell((DataGridViewGroupCell)MyDge.Rows[InsertStepId].Cells[0]);
}
((DataGridViewGroupCell)MyDge.Rows[MyDge.Rows.Count-1].Cells[0]).Collapse();//收起节点
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (ListStation == null || ListStation.Count == 0) { return; }
foreach (var mSta in ListStation)
{
if (mSta.CurFlow != null)
{
var CurMoFlow = mSta.CurFlow;
MyDge.Rows[mSta.GrideIdx].Cells[0].Style.BackColor = CurMoFlow.bActError ? Color.Red : Color.Green;
MyDge.Rows[CurMoFlow.GrideIdx].Cells[0].Style.BackColor = CurMoFlow.bActError ? Color.Red : Color.Green;
if (CurMoFlow.CurStepList != null&& CurMoFlow.CurStepList.Count>0)
{
foreach (var CurMoStep in CurMoFlow.CurStepList)
{
MyDge.Rows[CurMoStep.GrideIdx].Cells[0].Style.BackColor = CurMoStep.bActError ? Color.Red : Color.Green;
}
}
foreach (var mflow in mSta.FlowList)
{
if (mSta.CurFlow .Name!=mflow.Name)
{
MyDge.Rows[mflow.GrideIdx].Cells[0].Style.BackColor = Color.White;
foreach (var mstep in mflow.AllStepList)
{
MyDge.Rows[mstep.GrideIdx].Cells[0].Style.BackColor = Color.White;
}
}else
{
foreach (var mstep in mflow.AllStepList)
{
if(!mflow.CurStepList.Contains(mstep))
MyDge.Rows[mstep.GrideIdx].Cells[0].Style.BackColor = Color.White;
}
}
}
}
else
{
MyDge.Rows[mSta.GrideIdx].Cells[0].Style.BackColor = Color.White;
foreach (var mflow in mSta.FlowList)
{
MyDge.Rows[mflow.GrideIdx].Cells[0].Style.BackColor = Color.White;
foreach (var mstep in mflow.AllStepList)
MyDge.Rows[mstep.GrideIdx].Cells[0].Style.BackColor = Color.White;
}
}
}
btn_StepGoto.Enabled = (CurStep != null);
btn_FlowGoto.Enabled = (CurFlow != null);
btn_NextStep.Enabled = (CurStation != null && CurStation.Name != null );
btn_NextFlow.Enabled = (CurStation != null && CurStation.Name != null );
btn_StationStart.Enabled = CurStation != null;
if (btn_NextStep.Enabled && CurStation.CurFlow != null)
{
List<Step> msteplist = new List<Step>();
foreach (var step in CurStation.CurFlow.CurStepList)
msteplist.Add(step);
string stepName = "";
if (msteplist == null|| msteplist.Count==0)
{
foreach (var step in CurStation.FirstFlow.FirstStepList)
stepName += step.FullDesc;
}
else
{
foreach( var mstep in msteplist)
stepName += mstep.FullDesc;
}
label_next.Text = "下一步骤:" + stepName;
}
else
label_next.Text = "下一步动作:无";
}
private async void btn_StepGoto_Click(object sender, EventArgs e)
{
if (CurStep == null) return;
var temp = CurStep;
var ret = SunnyLib.Sys.EmRes.Succeed;
CurStep.FatherFlow.FatherStation.CurFlow= CurStep.FatherFlow;
CurStep.FatherFlow.FatherStation.CurFlow.CurStepList.Clear();
CurStep.FatherFlow.FatherStation.CurFlow.CurStepList.Add( CurStep);
Task<SunnyLib.Sys.EmRes> task = new Task<SunnyLib.Sys.EmRes>(() =>
{
return ret = CurStep.StepAct();
});
task.Start();
await task;
if (ret != SunnyLib.Sys.EmRes.Succeed)
{
if (ret != SunnyLib.Sys.EmRes.Next)
MessageBox.Show(temp.FullDesc + "-步骤失败!");
else MessageBox.Show(temp.FullDesc + "-步骤成功!");
}
else MessageBox.Show(temp.FullDesc + "-步骤成功!");
}
private async void btn_FlowGoto_Click(object sender, EventArgs e)
{
if (CurFlow == null) return;
var temp = CurFlow;
var tempbStep = CurFlow.bOneStep;
CurFlow.bOneStep = false;
var ret = SunnyLib.Sys.EmRes.Succeed;
CurFlow.FatherStation.CurFlow= CurFlow;
Task<SunnyLib.Sys.EmRes> task = new Task<SunnyLib.Sys.EmRes>(() => { return ret = CurFlow.Func(); });
task.Start();
await task;
CurFlow.bOneStep = tempbStep;
if (ret != SunnyLib.Sys.EmRes.Succeed)
{
if (ret != SunnyLib.Sys.EmRes.NextStep)
MessageBox.Show(temp.FullDesc + "执行失败!");
else
MessageBox.Show(temp.FullDesc + "执行成功!");
}
else
MessageBox.Show(temp.FullDesc + "执行成功!");
}
private async void btn_NextStep_Click(object sender, EventArgs e)
{
if (CurStation == null ) return;
if (CurStation.CurFlow == null) return;
var CurnextStep = new List<Step>();
CurStation.bOneStep = true;
CurStation.bquit = false;
var flow = CurStation.CurFlow;
if (flow.CurStepList == null || flow.CurStepList.Count == 0)
{
flow.InitStep();
}
CurnextStep = CurnextStep.Concat(flow.CurStepList).ToList();
btn_NextStep.Enabled = false;
Task mtask = new Task(() =>
{
var ret = SunnyLib.Sys.EmRes.Succeed;
var listtask = new List<Task<SunnyLib.Sys.EmRes>>();
foreach (var nextstep in CurnextStep)
{
Task<SunnyLib.Sys.EmRes> task = new Task<SunnyLib.Sys.EmRes>(() => { return nextstep.StepAct(); });
listtask.Add(task);
task.Start();
}
int i = 0;
foreach (var tk in listtask)
{
tk.Wait();
ret = tk.Result;
if (ret != SunnyLib.Sys.EmRes.Succeed)
{
if (ret != SunnyLib.Sys.EmRes.NextStep)
{
MessageBox.Show(CurnextStep[i].FullDesc + "执行失败!");
}
else
MessageBox.Show(CurnextStep[i].FullDesc + "成功!");
}
else
MessageBox.Show(CurnextStep[i].FullDesc + "成功!");
}
});
mtask.Start();
await mtask;
btn_NextStep.Enabled = true;
}
private async void btn_Home_Click(object sender, EventArgs e)
{
//if (CurStation == null || CurStation.Desc.Contains("单元")) return;
//if (CurStation.CurMoFlow == null) return;
//var temp = CurFlow;
//CurStation.CurMoFlow.bStep = false;
//btn_NextFlow.Enabled = false;
//var ret = SunnyLib.Sys.EmRes.Succeed;
//Task task = new Task(() => { return ret = CurStation.CurMoFlow.Func(); });
//task.Start();
//await task;
//btn_NextFlow.Enabled = true;
//if (ret != SunnyLib.Sys.EmRes.Succeed)
//{
// if (ret != SunnyLib.Sys.EmRes.NextStep)
// MessageBox.Show(CurStation.CurMoFlow.FullDesc + "执行失败!");
// else
// MessageBox.Show(CurStation.CurMoFlow.FullDesc + "执行成功!");
//}
//else
// MessageBox.Show(CurStation.CurMoFlow.FullDesc + "执行成功!");
}
private void button1_Click(object sender, EventArgs e)
{
if (CurStation == null ) return;
if (DialogResult.Yes == MessageBox.Show("是否要运行工站线程注意安全?", "警告", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2))
{
CurStation.Start();
MessageBox.Show($"{CurStation.Name}开始运行");
}
}
private void btn_arr_Click(object sender, EventArgs e)
{
var controlStyle = this.tlp1.ColumnStyles[2];
if(btn_arr.Text == ">>")
{
controlStyle.Width = 1F;
btn_arr.Text = "<<";
}
else
{
controlStyle.Width = 190F;
btn_arr.Text = ">>";
}
}
private void MyDge_MouseUp(object sender, MouseEventArgs e)
{
if(MyDge.Rows.Count==0)
Menu_StaMouseRightKey.Show(MousePosition.X, MousePosition.Y);
}
private void MyDge_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= 0)
{
string Type = MyDge.Rows[e.RowIndex].Cells[2].Value. ToString();
MyDge.ClearSelection();
MyDge.Rows[e.RowIndex].Selected = true;
MyDge.CurrentCell = MyDge.Rows[e.RowIndex].Cells[e.ColumnIndex];
ContextMenuStrip CurMenu=null;
if (Type == "工站")
{
CurMenu = Menu_StaMouseRightKey;
}
else if (Type == "流程")
{
CurMenu = Menu_FlowMousrRightKey;
}
else if (Type == "步骤")
{
CurMenu = Menu_StepMousRightKey;
}
if(CurMenu!=null)
CurMenu.Show(MousePosition.X, MousePosition.Y);
}
}
}
catch (Exception)
{
MessageBox.Show("请选择内容");
}
}
private void 添加工站的子流程ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CurStation == null)
{
MessageBox.Show("当前工站为空");
return;
}
string inMsg = Input.InputBox.ShowInputBox("输入新的流程名称", string.Empty);
var flowName = inMsg.Trim();
string errMsg;
var res = FlowData.CreatAndSaveNesFlow(CurStation.Name, flowName, out errMsg);
if (res == SunnyLib.Sys.EmRes.Succeed) MessageBox.Show("成功");
else MessageBox.Show("失败--" + errMsg);
}
private void 新建工站ToolStripMenuItem_Click(object sender, EventArgs e)
{
string inMsg = Input.InputBox.ShowInputBox("输入新的工站名称", string.Empty);
var Staname = inMsg.Trim();
string errMsg;
var res = FlowData.CreatAndSaveNewSta( Staname, out errMsg);
if (res == SunnyLib.Sys.EmRes.Succeed) MessageBox.Show("成功");
else MessageBox.Show("失败--" + errMsg);
}
private void 修改工站名称ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CurStation == null)
{
MessageBox.Show("当前工站为空");
return;
}
string inMsg = Input.InputBox.ShowInputBox("输入新的工站名称", string.Empty);
var Staname = inMsg.Trim();
string errMsg;
var res = FlowData.ChangeStaName(CurStation, Staname,out errMsg);
if (res == SunnyLib.Sys.EmRes.Succeed) MessageBox.Show("成功");
else MessageBox.Show("失败--"+ errMsg);
}
private void 删除工站ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CurStation == null)
{
MessageBox.Show("当前工站为空");
return;
}
var res = FlowData.DeleteFile(CurStation);
if (res == 0) MessageBox.Show("成功");
else MessageBox.Show("失败--" );
}
private void 删除步骤ToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (CurStep == null)
{
MessageBox.Show("当前步骤为空");
return;
}
var res = FlowData.DeleteFile(CurStep);
if (res == 0) MessageBox.Show("成功");
else MessageBox.Show("失败--");
}
private void 新建流程ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CurStation == null)
{
MessageBox.Show("当前工站为空");
return;
}
string inMsg = Input.InputBox.ShowInputBox("输入新的流程名称", string.Empty);
var flowName = inMsg.Trim();
string errMsg;
var res = FlowData.CreatAndSaveNesFlow(CurStation.Name, flowName, out errMsg);
if (res == SunnyLib.Sys.EmRes.Succeed) MessageBox.Show("成功");
else MessageBox.Show("失败--" + errMsg);
}
private void 删除流程ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CurStation == null)
{
MessageBox.Show("当前工站为空");
return;
}
if(CurFlow==null)
{
MessageBox.Show("当前流程为空");
return;
}
var res = FlowData.DeleteFile(CurFlow);
if (res == 0) MessageBox.Show("成功");
else MessageBox.Show("失败--");
}
private void 修改流程ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (CurStation == null)
{
MessageBox.Show("当前工站为空");
return;
}
if (CurFlow == null)
{
MessageBox.Show("当前流程为空");
return;
}
var TempName= CurFlow.Name;
string inMsg = Input.InputBox.ShowInputBox("输入新的流程名称", string.Empty);
var flowName = inMsg.Trim();
if(flowName==null|| flowName.Length<2|| flowName.Length>40)
{
MessageBox.Show("请重新输入合适的流程名字");
return;
}
string errMsg;
CurFlow.Name = flowName;
var res = FlowData.ChangeFlowObject(CurFlow, out errMsg);
if (res == SunnyLib.Sys.EmRes.Succeed) MessageBox.Show("成功");
else
{
MessageBox.Show("失败--" + errMsg);
CurFlow.Name = TempName;
}
}
private void Menu_StepMousRightKey_Opening(object sender, CancelEventArgs e)
{
}
private void 添加子步骤ToolStripMenuItem_Click(object sender, EventArgs e)
{
FormAddFlowData FormAddStep = new FormAddFlowData();
FormAddStep.UpdateDeleteControl();
FormAddStep.cb_StalistForStep.Text = CurFlow.FatherStation.Name;
FormAddStep.cb_flowList.Text = CurFlow.Name;
FormAddStep.cb_StalistForStep.Enabled = false;
FormAddStep.cb_flowList.Enabled = false;
FormAddStep.Show();
}
private void 新建下一步ToolStripMenuItem_Click(object sender, EventArgs e)
{
FormAddFlowData FormAddStep = new FormAddFlowData();
CurFlow = CurStep.FatherFlow;
FormAddStep.UpdateDeleteControl();
FormAddStep.cb_StalistForStep.Text = CurFlow.FatherStation.Name;
FormAddStep.cb_flowList.Text = CurFlow.Name;
FormAddStep.nud_stepId.Value = (decimal)(CurStep.StepId + 1);
FormAddStep.cb_StalistForStep.Enabled = false;
FormAddStep.cb_flowList.Enabled = false;
FormAddStep.nud_stepId.Enabled = false;
FormAddStep.Show();
}
private void 新建同步骤ToolStripMenuItem_Click(object sender, EventArgs e)
{
FormAddFlowData FormAddStep = new FormAddFlowData();
CurFlow = CurStep.FatherFlow;
FormAddStep.UpdateDeleteControl();
FormAddStep.cb_StalistForStep.Text = CurFlow.FatherStation.Name;
FormAddStep.cb_flowList.Text = CurFlow.Name;
FormAddStep.nud_stepId.Value = (decimal)(CurStep.StepId);
FormAddStep.cb_StalistForStep.Enabled = false;
FormAddStep.cb_flowList.Enabled = false;
FormAddStep.nud_stepId.Enabled = false;
FormAddStep.Show();
}
private void 新建上一步骤ToolStripMenuItem_Click(object sender, EventArgs e)
{
if(CurStep.StepId<1)
{
MessageBox.Show("当前步骤id为1不能再新建上一步");
return;
}
FormAddFlowData FormAddStep = new FormAddFlowData();
CurFlow = CurStep.FatherFlow;
FormAddStep.UpdateDeleteControl();
FormAddStep.cb_StalistForStep.Text = CurFlow.FatherStation.Name;
FormAddStep.cb_flowList.Text = CurFlow.Name;
FormAddStep.nud_stepId.Value = (decimal)(CurStep.StepId-1);
FormAddStep.cb_StalistForStep.Enabled = false;
FormAddStep.cb_flowList.Enabled = false;
FormAddStep.nud_stepId.Enabled = false;
FormAddStep.Show();
}
private void 编辑步骤ToolStripMenuItem_Click(object sender, EventArgs e)
{
FormAddFlowData FormAddStep = new FormAddFlowData();
CurFlow = CurStep.FatherFlow;
FormAddStep.CurEditStepIdx = CurStep.Idx;
FormAddStep.UpdateDeleteControl();
FormAddStep.cb_StalistForStep.Text = CurFlow.FatherStation.Name;
FormAddStep.cb_flowList.Text = CurFlow.Name;
FormAddStep.nud_stepId.Value = (decimal)(CurStep.StepId);
FormAddStep.btn_addStep.Text = "修改";
FormAddStep.cb_steptype.SelectedIndex = (int)CurStep.Type;
FormAddStep.tb_stepName.Text = CurStep.Name;
FormAddStep.Show();
}
private void MyDge_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.Button == MouseButtons.Left)
{
if (e.RowIndex >= 0)
{
string Type = MyDge.Rows[e.RowIndex].Cells[2].Value.ToString();
int idex = (int)MyDge.Rows[e.RowIndex].Cells["Idx"].Value;
string MotionType = (string)MyDge.Rows[e.RowIndex].Cells["Type"].Value;
MyDge.ClearSelection();
MyDge.Rows[e.RowIndex].Selected = true;
MyDge.CurrentCell = MyDge.Rows[e.RowIndex].Cells[e.ColumnIndex];
CurStation = null;
CurFlow = null;
CurStep = null;
switch (MotionType)
{
case "工站":
foreach (var sta in ListStation)
if (sta.GrideIdx == idex)
{
CurStation = sta;
lb_Desc.Text = sta.Name;
return;
}
break;
case "流程":
foreach (var sta in ListStation)
{
foreach (var flow in sta.FlowList)
if (flow.GrideIdx == idex)
{
CurStation = sta;
CurFlow = flow;
lb_Desc.Text = flow.FullDesc;
return;
}
}
break;
case "步骤":
foreach (var sta in ListStation)
{
foreach (var flow in sta.FlowList)
{
foreach (var Step in flow.AllStepList)
if (Step.GrideIdx == idex)
{
CurStation = sta;
CurFlow = flow;
CurStep = Step;
lb_Desc.Text = Step.FullDesc;
return;
}
}
}
break;
default:
break;
}
}
}
}
catch (Exception)
{
MessageBox.Show("请选择内容");
}
}
}
}