void MainLoop() { try { while (running) { // DELAY THE LOOP FOR 100 ms Thread.Sleep(100); if (IsBusy) { break; } IsBusy = true; Order orderDb = dbClient.GetCurrentOrder(); int orderIdDb = 0; if (orderDb != null) { orderIdDb = (int)orderDb.id; } int orderIdOPC = opcClient.GetCurrentOrderId(); if (orderIdDb != 0) { //There is an order in the database if (orderIdOPC != 0) { //OPC has been processing an order. //compare if it is the same order in queue. if (orderIdDb == orderIdOPC) { //Update status from opc to db // int orderStatusOPC = opcClient.GetCurrentOrderStatus(); List <OrderUserDTO> ordersUserDTO = opcClient.GetCurrentOrderStatuses(); dbClient.updateOrderStatus(ordersUserDTO.First().order, orderIdDb); //update status on outside API //OrderUserDTO orderUserDTO = new OrderUserDTO() //{ // order = 247, // robot = 1, // status_drink = 15, // drink = 385 // // status_drink = // // drink = // // ingredient = //}; //todo populate orderUserDTO foreach (var order in ordersUserDTO) { if (ChangeStatusDetected(order, orderDb)) { dbClient.updateDrinkStatus(order); UpdateUserAPI(order); } } } else { //this order has been completed. Update OPC with a new order opcClient.writeNewOrder(orderDb); } } else { //OPC is not processing any orders. //TODO - Update OPC with a new order opcClient.writeNewOrder(orderDb); } } else { //no orders in queue. Do nothing } IsBusy = false; //CHECK IF ALL CONDITIONS ARE OK, IF NO - GO TO TOP OF LOOP if (!checkConditions()) { continue; } // dbClient.updatePLCOutput(opcClient.CurrentPLCOutput); } } catch (Exception ex) { Console.Write(ex.Message); //throw; } }