FrmOperation_test
Anonymous
plain_text
02/24/2026 3:38 AM
28.5 KB
8
Indexable
#define TESTING
using AioiSystems.Lightstep;
using Azure;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using UISystem_1202.Utils;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
namespace UISystem_1202.Forms
{
public partial class FrmOperation : Form
{
const int MAX_PICK = 3;
const int BLUE = 1;
const int YELLOW = 2;
const int RED = 3;
private readonly EthernetController ethernetController = new EthernetController();
private readonly string ControllerIP = ConfigurationManager.AppSettings["ControllerIP"];
private DataTable _Blue = new DataTable();
private DataTable _Yellow = new DataTable();
private DataTable _Red = new DataTable();
private DataTable _orderList = new DataTable();
private DataTable _orderStatus = new DataTable();
private readonly BindingSource SourceBlue = new BindingSource();
private readonly BindingSource SourceYellow = new BindingSource();
private readonly BindingSource SourceRed = new BindingSource();
private readonly BindingSource SourceStatus = new BindingSource();
private readonly BindingSource SourceOrderList = new BindingSource();
private OrderPicking orderPicking = new OrderPicking();
private readonly ConcurrentDictionary<string, List<Orders>> AllPickingItems = new ConcurrentDictionary<string, List<Orders>>();
private ConcurrentQueue<Tuple<int, string, List<Orders>>> AllQueues = new ConcurrentQueue<Tuple<int, string, List<Orders>>>();
private ConcurrentBag<Tuple<string, string, List<Orders>>> AllErrors = new ConcurrentBag<Tuple<string, string, List<Orders>>>();
private List<OrderDetails> _orderDetails;
private List<OrderComplete> _orderCompletes;
private readonly Dictionary<int, Queue<string>> ZoneQueues = new Dictionary<int, Queue<string>>
{
{BLUE, new Queue<string>() },
{YELLOW, new Queue<string>() },
{RED, new Queue<string>() },
};
public FrmOperation()
{
InitializeComponent();
ethernetController.SetLicense("9070-00C7-1618-17A2-1E74");
ethernetController.CommandReceived += EthernetController_CommandReceived;
ethernetController.EndConnect += EthernetController_EndConnect;
}
private async void FrmOperation_Load(object sender, EventArgs e)
{
MaximumSize = MinimumSize = Size;
SetDoubleBuffered(dgvOrderList);
SetDoubleBuffered(dgvOrderStatus);
SetDoubleBuffered(dgvZone1);
SetDoubleBuffered(dgvZone2);
SetDoubleBuffered(dgvZone3);
SetDoubleBuffered(txtSearchOrder);
SetDoubleBuffered(btnCallApi);
SetDoubleBuffered(btnPrioritize);
SetDoubleBuffered(btnDelete);
SetDoubleBuffered(rtbStatus);
await dgvPickOrders();
_Blue = await Functions.SoDetailInitialize();
_Yellow = await Functions.SoDetailInitialize();
_Red = await Functions.SoDetailInitialize();
_orderStatus = await Functions.SoDetailInitialize();
SourceBlue.DataSource = _Blue;
SourceYellow.DataSource = _Yellow;
SourceRed.DataSource = _Red;
SourceStatus.DataSource = _orderStatus;
dgvZone1.DataSource = SourceBlue;
dgvZone2.DataSource = SourceYellow;
dgvZone3.DataSource = SourceRed;
dgvOrderStatus.DataSource = _orderStatus;
#if TESTING
txtTest.Visible = true;
btnTest.Visible = true;
#endif
}
#region Dgv UI
private async Task dgvPickOrders()
{
try
{
dgvZone1.DefaultCellStyle.BackColor = Color.Blue;
dgvZone1.DefaultCellStyle.ForeColor = Color.White;
dgvZone1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
dgvZone1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
dgvZone1.EnableHeadersVisualStyles = false;
dgvZone2.DefaultCellStyle.BackColor = Color.Yellow;
dgvZone2.DefaultCellStyle.ForeColor = Color.Black;
dgvZone2.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow;
dgvZone2.ColumnHeadersDefaultCellStyle.ForeColor= Color.Black;
dgvZone2.EnableHeadersVisualStyles = false;
dgvZone3.DefaultCellStyle.BackColor = Color.Red;
dgvZone3.DefaultCellStyle.ForeColor = Color.White;
dgvZone3.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;
dgvZone3.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
dgvZone3.EnableHeadersVisualStyles = false;
}
catch (Exception ex)
{
WriteText(ex.ToString(), Color.Red);
}
}
#endregion
#region controller
private async Task ConnectionController()
{
try
{
#if !TESTING
ethernetController.Connect(ControllerIP, 5003);
WriteText("Controller connect successfully", Color.Green);
Logging.LogInfo("Controller connect successfully", "Operation - Connection", 1);
await SendToController("Z");
#endif
}
catch(Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - Connection", 2);
MessageBox.Show($"{ex.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async Task SendToController(string v)
{
try
{
#if !TESTING
ethernetController.SendCommand(v);
#endif
}
catch (Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - Send command", 2);
MessageBox.Show($"{ex.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void EthernetController_EndConnect(object sender, EndConnectEventArgs e)
{
if (e.Error != null)
{
Logging.LogInfo($"{e.Error.Message}", "Operation - End connect", 2);
return;
}
}
private async void EthernetController_CommandReceived(object sender, EventArgs e)
{
try
{
CommandInfo cmd = ethernetController.GetCommand();
if (cmd == null)
return;
AddressInfo[] lists = AddressInfo.SplitCommand(cmd.GetCommandBytes());
foreach(AddressInfo address in lists)
{
await ConfirmLightModule(address);
}
}
catch(Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - Get command",2);
}
}
#endregion
private async void btnCallApi_Click(object sender, EventArgs e)
{
try
{
Logging.LogInfo("Enter orderID search", "Operation - Search order", 1);
string OrderID = txtSearchOrder.Text.Trim();
if (string.IsNullOrEmpty(OrderID))
{
WriteText("Empty orderID not allowed");
MessageBox.Show("Empty orderID not allowed", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (IsOrderInPicking(OrderID))
{
WriteText("Order already pick");
ResetTextBox(false);
return;
}
else
{
Logging.LogInfo($"{OrderID}", "Operation - search order", 1);
var result = await APIHander.GetOrdersByID(OrderID);
var orders = result.Item2;
if (orders != null && orders.Count > 0)
{
var newData = await Functions.ConvertOrderListToDataTable(orders);
if (newData.Rows.Count == 0 || newData.Columns.Count == 0)
{
Logging.LogInfo("Data order not found", "Operation - Load data order", 2);
ResetTextBox(false);
WriteText("Data order not found", Color.Red);
}
else
{
_orderList.Merge(newData);
WriteText("Load data order successfully", Color.Green);
ResetTextBox(false);
await DgvShowData();
}
ZoneQueues[BLUE].Enqueue(OrderID);
if (string.IsNullOrEmpty(orderPicking[BLUE].OrderID))
{
await StartNextOrderInZone(BLUE);
}
}
else
{
Logging.LogInfo("Data order not found", "Operation - Load data order", 2);
ResetTextBox(false);
WriteText("Data order not found", Color.Red);
}
}
txtSearchOrder.Focus();
}
catch (Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - Search Order", 2);
WriteText($"{ex.Message}", Color.Red);
}
}
private async Task StartNextOrderInZone(int zone)
{
if (ZoneQueues[zone].Count == 0)
return;
string nextOrder = ZoneQueues[zone].Dequeue();
orderPicking[zone].OrderID = nextOrder;
string startAddress = GetStartAddressByZone(zone);
string cmd = CommandMgr.CommandBuilder(
CommandMgr.GetModeCommand(zone),
startAddress,
nextOrder);
await SendToController(cmd);
}
private async Task CommandLightModuleStart(List<Orders> data, int colorFlag)
{
try
{
var LightMode = CommandMgr.GetModeCommand(colorFlag);
string Address = GetStartAddressByZone(colorFlag);
string OrderID = data.First().OrderID;
string ModuleCmd = CommandMgr.CommandBuilder(LightMode, Address, OrderID);
var AllreadyOn = AllPickingItems.ContainsKey(Address);
if (AllreadyOn)
{
var queueList = AllQueues.ToList();
var queues_exists = queueList.FindLastIndex(o => o.Item1 == colorFlag);
var newQueueItem = Tuple.Create(colorFlag, Address, data);
if (queues_exists >= 0)
{
queueList.Insert(queues_exists + 1, newQueueItem);
AllQueues = new ConcurrentQueue<Tuple<int, string, List<Orders>>>(queueList);
}
else
{
AllQueues.Enqueue(newQueueItem);
}
}
else
{
AllPickingItems.AddOrUpdate(Address, data, (key, oldValue) => data);
await SendToController(ModuleCmd);
}
}
catch (Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - Command light module",2);
}
}
private async Task ConfirmLightModule(AddressInfo Address)
{
try
{
string adr = Address.Address;
if(adr == "1000")
{
await HanderStartZone(BLUE);
}
else if(adr == "1010")
{
await HanderStartZone(YELLOW);
}
else if(adr == "1020")
{
await HanderStartZone(RED);
}
else
{
await HandlePickConfirm(Address);
}
}
catch (Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - operation confirm light module", 2);
}
}
private async Task HandlePickConfirm(AddressInfo address)
{
int zone = GetZoneByAddress(address.Address);
if (zone == 0)
return;
DataTable dt = GetTableByZone(zone);
var row = dt.AsEnumerable().FirstOrDefault(o => o.Field<string>("Address") == address.Address);
if (row != null)
dt.Rows.Remove(row);
await DgvOrderDetailList();
if (dt.Rows.Count == 0)
await ZoneCompleted(zone);
}
private async Task ZoneCompleted(int zone)
{
throw new NotImplementedException();
}
private DataTable GetTableByZone(int zone)
{
return zone switch
{
BLUE => _Blue,
YELLOW => _Yellow,
RED => _Red,
_ => null
};
}
private int GetZoneByAddress(string address)
{
throw new NotImplementedException();
}
private async Task HanderStartZone(int zone)
{
try
{
WriteText($"Confirm light start", Color.Orange);
string orderID = orderPicking[zone].OrderID;
if (string.IsNullOrEmpty(orderID))
{
WriteText("OrderID does not exist");
}
var result = await APIHander.GetOrderDetails(orderID);
var details = result.Item2;
if(details == null || details.Count == 0)
{
WriteText("Not found data order detail", Color.Red);
return;
}
var zoneDetails = details.Where(o => o.Zone == zone.ToString()).ToList();
if(zoneDetails.Count == 0)
{
return;
}
var dt = await Functions.ConvertListOrderDetailToDataTable(zoneDetails);
switch (zone)
{
case BLUE:
_Blue.Merge(dt);
break;
case YELLOW:
_Yellow.Merge(dt);
break;
case RED:
_Red.Merge(dt);
break;
}
await DgvOrderDetailList();
foreach(var item in zoneDetails)
{
string cmd = CommandMgr.CommandBuilder(CommandMgr.GetModeCommand(zone), item.Address, item.OrderID);
await SendToController(cmd);
}
WriteText($"Load zone and turn on light", Color.Green);
}
catch(Exception ex)
{
WriteText($"{ex.Message}", Color.Red);
Logging.LogInfo($"{ex.Message}", "Operation - Hand zone", 2);
}
}
private async Task DgvShowData()
{
try
{
if (_orderList.Rows.Count !=0)
{
var filterOrderList = _orderList.AsEnumerable()
.GroupBy(r => r["OrderID"].ToString())
.Select(g => g.First());
DataTable data = filterOrderList.CopyToDataTable();
dgvOrderList.DataSource = data;
dgvOrderList.Refresh();
dgvOrderList.FirstDisplayedScrollingColumnIndex = 0;
dgvOrderList.Columns[1].Visible = false;
dgvOrderList.Columns[2].Visible = false;
}
}
catch(Exception ex)
{
Logging.LogInfo($"{ex.Message}", "Operation - OrderList", 2);
WriteText($"{ex.Message}", Color.Red);
}
}
private Task DgvOrderDetailList()
{
if(_Blue.Columns.Count > 0)
{
SourceBlue.DataSource = _Blue;
}
if (_Yellow.Columns.Count > 0)
{
SourceYellow.DataSource = _Yellow;
}
if(_Red.Columns.Count > 0)
{
SourceRed.DataSource = _Red;
}
return Task.CompletedTask;
}
private Task<DataTable> GetInformationByZone(DataTable data, int flag)
{
if (data == null || data.Rows.Count == 0)
{
return Task.FromResult(new DataTable());
}
if (!data.Columns.Contains("zone"))
throw new Exception("Column 'zone' not found in DataTable");
var zoneRows = data.AsEnumerable()
.Where(o => o.Field<string>("zone") == flag.ToString())
.ToList();
if (!zoneRows.Any())
{
return Task.FromResult(data.Clone());
}
return Task.FromResult(zoneRows.CopyToDataTable());
}
private async Task DgvListRemoveRow(string orderID)
{
try
{
var rowToRemove = _orderList.AsEnumerable()
.Where(o => o.Field<string>("OrderID") == orderID).ToList();
foreach (var row in rowToRemove)
{
_orderList.Rows.Remove(row);
}
}
catch(Exception ex)
{
Logging.LogInfo(ex.Message, "Operation - Remove order list", 2);
WriteText($"{ex.Message}", Color.Red);
}
}
private void ResetTextBox(bool v)
{
if (txtSearchOrder.InvokeRequired)
{
txtSearchOrder.Clear();
}
else
{
txtSearchOrder.Clear();
}
}
private bool IsOrderInPicking(string orderID)
{
if (string.IsNullOrEmpty(orderID))
{
return false;
}
return IsOrderInZone(_Blue, orderID)
|| IsOrderInZone(_Yellow, orderID)
|| IsOrderInZone(_Red, orderID);
}
private bool IsOrderInZone(DataTable table, string orderID)
{
if(table == null || string.IsNullOrEmpty(orderID))
{
return false;
}
return table.AsEnumerable().Any(r => r.Field<string>("OrderID") == orderID);
}
public void WriteText(string message, Color? color = null)
{
if (rtbStatus.InvokeRequired)
{
rtbStatus.BeginInvoke(new Action(() =>
WriteText(message, color)
));
return;
}
rtbStatus.SelectionStart = rtbStatus.TextLength;
rtbStatus.SelectionLength = 0;
rtbStatus.SelectionColor = color ?? Color.Black;
rtbStatus.AppendText($"[{DateTime.Now:HH:mm:ss}]{message}{Environment.NewLine}");
rtbStatus.ScrollToCaret();
}
public static void SetDoubleBuffered(Control c)
{
if (SystemInformation.TerminalServerSession)
return;
System.Reflection.PropertyInfo aProp = typeof(Control).GetProperty("DoubleBuffered",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
aProp.SetValue(c, true, null);
}
private string GetStartAddressByZone(int zone)
{
switch (zone)
{
case BLUE: return "1000";
case YELLOW: return "1010";
case RED: return "1020";
default: return "";
}
}
#if TESTING
private async void btnTest_Click(object sender, EventArgs e)
{
if (txtTest.TextLength > 0)
{
AddressInfo address = new AddressInfo
{
Address = txtTest.Text,
Status = "00"
};
await ConfirmLightModule(address);
}
txtTest.Focus();
}
#endif
}
}
Editor is loading...
Leave a Comment