Example #1
0
        /// <summary>
        /// Write Wlist to PLC
        /// </summary>
        /// <param name="Wlist">Wlist to write</param>
        /// <returns>Completed</returns>
        public async Task <bool> WriteDataToPlcAsync(Dictionary <string, string> Wlist, IProgress <PlcProgressReportModel> progress)
        {
            List <PlcWordModel>    WrtWordList = new List <PlcWordModel>();
            List <PlcBitModel>     WrtBitList  = new List <PlcBitModel>();
            PlcProgressReportModel report      = new PlcProgressReportModel();

            await Task.Run(() =>
            {
                if (PlcDataMapper.DataNameValue_Wlist.Count > 0)
                {
                    lock (PlcDataMapper._WlistLock)
                    {
                        WrtWordList = PlcDataMapper.WListGenerateWordList(WrtWordList);
                        WrtBitList  = PlcDataMapper.WListGenerateBitList(WrtBitList);
                        foreach (var item in PlcDataMapper.DataNameValue_Wlist)
                        {
                            report.Wlist.Add(item.Key, item.Value);
                        }
                        //PlcDataMapper.WListToData();
                        PlcDataMapper.DataNameValue_Wlist.Clear();
                    }

                    //new 5. write the data individually to PLC then raise complete event
                    bool BitsWrtSuccessed  = OmronFINsProcessor.WriteBits(mainPort, WrtBitList, out string expMsgBit);
                    bool WordsWrtSuccessed = OmronFINsProcessor.WriteWords(mainPort, WrtWordList, out string expMsgWord);
                    report.WrtCompleted    = BitsWrtSuccessed & WordsWrtSuccessed;
                }
            });

            report.PercetageComplete = 2 / 2 * 100;
            report.Msg = "Writing finished.. Begin next cycle..";

            progress.Report(report);
            return(true);
        }
Example #2
0
        public async Task <bool> GetPlcDataAsync_old(int timeout_ms,
                                                     SortedList <int, int> addrDM, SortedList <int, int> addrHR, SortedList <int, int> addrWR,
                                                     CancellationToken ct, IProgress <PlcProgressReportModel> progress)
        {
            Dictionary <string, RlistDataModel> retRlist = new Dictionary <string, RlistDataModel>();
            PlcProgressReportModel report    = new PlcProgressReportModel();
            DateTimeOffset         startTime = DateTimeOffset.Now;
            bool timedout = false;
            bool canceled = false;

            if (!mainPort.IsOpen)
            {
                mainPort.Open();
            }

            await Task.Run(() =>
            {
                report.ReadCompleted = OmronFINsProcessor.ReadAllPlcWords(mainPort, addrDM, addrHR, addrWR,
                                                                          out SortedList <int, string> DMstr, out SortedList <int, string> HRstr, out SortedList <int, string> WRstr);
                lock (PlcDataMapper._WordsListLock)
                {
                    OmronFINsProcessor.UpdateStringToWords(PlcMemArea.WR_bit, WRstr);
                    OmronFINsProcessor.UpdateStringToWords(PlcMemArea.HR_bit, HRstr);
                    OmronFINsProcessor.UpdateStringToWords(PlcMemArea.DM, DMstr);
                }

                PlcDataMapper.DMWordsToData(); //4ms
                PlcDataMapper.BitsToData();    //14ms

                lock (PlcDataMapper._RWlistLock)
                {
                    PlcDataMapper.DataToRList();
                }
            });

            report.PercetageComplete = 1 / 2 * 100;
            report.Msg = "Reading finished.. Begining to write..";
            progress.Report(report);
            return(true);
        }
Example #3
0
        public static int testWorkerThread()
        {
            int startingNumber            = 1;
            int result                    = startingNumber;
            int totalNumer                = 100;
            PlcProgressReportModel report = new PlcProgressReportModel();


            for (int i = 0; i < totalNumer; i++)
            {
                result = ModifyResult(result);
                //ctsToken.ThrowIfCancellationRequested();

                report.CountedNumber     = result;
                report.PercetageComplete = result * 100 / totalNumer;
                //progress.Report(report);

                Thread.Sleep(500);
            }

            return(result);
        }
Example #4
0
 private void ReportProgress(object sender, PlcProgressReportModel e)
 {
     rtbOutput.Text            += e.Msg + Environment.NewLine;
     progressBarDashboard.Value = e.PercetageComplete;
     wireupLists(e.ReadCompleted, e.WrtCompleted, e.Wlist);
 }
Example #5
0
        private void ReportPlcProgress(object sender, PlcProgressReportModel e)
        {
            rtbOutput.Text += e.Msg + Environment.NewLine;

            if (e.PercetageComplete == 50)
            {
                //publish R list to display
                dataGridViewAll.DataSource          = null;
                dataGridViewAll.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

                dataGridViewAll.DataSource = PlcDataMapper.DataNameValue_Rlist.Select(u => new
                {
                    Name  = u.Key,
                    Value = u.Value.Value
                }).ToList();

                foreach (var cbox in this.Controls.OfType <CheckBox>())
                {
                    if (PlcDataMapper.DataNameValue_Rlist.ContainsKey(cbox.Name.Substring(3, (cbox.Name.Length - 3))))
                    {
                        if (PlcDataMapper.DataNameValue_Rlist[cbox.Name.Substring(3, (cbox.Name.Length - 3))].Value == "1")
                        {
                            cbox.BackColor = Color.Gold;
                            cbox.Enabled   = true;
                        }
                        else if (PlcDataMapper.DataNameValue_Rlist[cbox.Name.Substring(3, (cbox.Name.Length - 3))].Value == "0")
                        {
                            cbox.BackColor = Color.LightGray;
                            cbox.Enabled   = true;
                        }
                    }
                }
            }
            else if (e.PercetageComplete == 100)
            {
                //publish
                dataGridViewAllOutput.DataSource          = null;
                dataGridViewAllOutput.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

                //dataGridViewAllOutput.DataSource = PlcDataMapper.DataNameValue_Wlist.Select
                dataGridViewAllOutput.DataSource = e.Wlist.Select(u => new
                {
                    Name  = u.Key,
                    Value = u.Value
                }).ToList();

                rtbOutput.Clear();
            }
            //refresh button color if set PLC value succeeded
            foreach (var button in this.Controls.OfType <Button>())
            {
                if (PlcDataMapper.DataNameValue_Rlist.ContainsKey(button.Name.Substring(3, (button.Name.Length - 3))))
                {
                    if (PlcDataMapper.DataNameValue_Rlist[button.Name.Substring(3, (button.Name.Length - 3))].Value == "1")
                    {
                        button.BackColor = Color.Gold;
                    }
                    else if (PlcDataMapper.DataNameValue_Rlist[button.Name.Substring(3, (button.Name.Length - 3))].Value == "0")
                    {
                        button.BackColor = Color.LightGray;
                    }
                }
            }
        }
Example #6
0
        public async void RunDataExchange(int timeout, int timeDelay, CancellationToken ct, IProgress <PlcProgressReportModel> progress)
        {
            bool   canceled               = false;
            double totalSteps             = 2;
            PlcProgressReportModel report = new PlcProgressReportModel();

            //PlcProgressReportModel readResult = new PlcProgressReportModel();

            while (true)
            {
                DateTimeOffset startTime = DateTimeOffset.Now;
                report.PercetageComplete = (int)(0 / totalSteps * 100);
                report.ReadCompleted     = false;
                report.WrtCompleted      = false;
                report.Msg = "Begining to read..";
                progress.Report(report);

                if (ct.IsCancellationRequested)
                {
                    canceled = true;
                    break;
                }

                //1.Get data from PLC all areas then send to UI for updating display
                try
                {
                    //1.Get data from PLC to R list
                    bool rdFinished = await GlobalConfig.DataConnection.GetPlcDataAsync(timeout,
                                                                                        PlcDataMapper.addrIntervalDM, PlcDataMapper.addrIntervalHR, PlcDataMapper.addrIntervalWR,
                                                                                        ct, progress);

                    if (!rdFinished)
                    {
                        report.PercetageComplete = (int)(0 / totalSteps * 100);
                        report.Msg = "Reading failed.. pls retry";
                        progress.Report(report);
                        break;
                    }
                    report.PercetageComplete = (int)(1 / totalSteps * 100);
                    report.Msg = "Reading finished.. Begining to write..";
                    progress.Report(report);

                    //2.Get updated data from UI
                    //SimulateWlist();


                    var elapsedTime = DateTimeOffset.Now - startTime;
                    int timeLeft    = timeout - (int)elapsedTime.TotalMilliseconds;

                    //3.Write updated data to PLC
                    bool wrtFinished = await GlobalConfig.DataConnection.WriteDataToPlcAsync(PlcDataMapper.DataNameValue_Wlist, progress);

                    report.PercetageComplete = (int)(2 / totalSteps * 100);

                    report.Msg = "Writing finished.. Begining next cycle..";
                    progress.Report(report);

                    await Task.Delay(timeDelay);
                }
                catch (TimeoutException ex)
                {
                    break;
                }
                catch (OperationCanceledException ex)
                {
                    //report.ClrReport();
                    //report.Msg = "The operation has been canceled";
                    //progress.Report(report);
                    break;
                }
                catch (NotImplementedException ex)
                {
                    //report.ClrReport();
                    //report.Msg = ex.Message;
                    //progress.Report(report);
                    break;
                }
                catch (Exception)
                {
                    break;
                }
            }
            if (canceled)
            {
                report.Msg = "The R/W operation has canceled";
                progress.Report(report);
                //throw new OperationCanceledException();
            }

            //2.Collect UI data changed from last cycle and send to PLC for update mem
        }
Example #7
0
        /// <summary>
        /// Get plc data to Rlist async
        /// </summary>
        /// <param name="timeout_ms"></param>
        /// <param name="ct"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        public async Task <bool> GetPlcDataAsync(int timeout_ms,
                                                 SortedList <int, int> addrDM, SortedList <int, int> addrHR, SortedList <int, int> addrWR,
                                                 CancellationToken ct, IProgress <PlcProgressReportModel> progress)
        {
            Dictionary <string, RlistDataModel> retRlist = new Dictionary <string, RlistDataModel>();
            PlcProgressReportModel report    = new PlcProgressReportModel();
            DateTimeOffset         startTime = DateTimeOffset.Now;
            bool timedout = false;
            bool canceled = false;
            SortedList <int, string> DMstr = new SortedList <int, string>();
            SortedList <int, string> HRstr = new SortedList <int, string>();
            SortedList <int, string> WRstr = new SortedList <int, string>();

            Stopwatch stopwatch1 = new Stopwatch(); //debug watch
            Stopwatch stopwatch2 = new Stopwatch(); //debug watch
            Stopwatch stopwatch3 = new Stopwatch(); //debug watch
            Stopwatch stopwatch4 = new Stopwatch(); //debug watch
            Stopwatch stopwatch5 = new Stopwatch(); //debug watch

            if (!mainPort.IsOpen)
            {
                mainPort.Open();
            }

            //try
            //{
            await Task.Run(() =>
            {
                stopwatch1.Start();
                report.ReadCompleted = OmronFINsProcessor.ReadAllPlcWords(mainPort, addrDM, addrHR, addrWR,
                                                                          out DMstr, out HRstr, out WRstr);
                stopwatch1.Stop();
            });

            try
            {
                if (DateTimeOffset.Now.Subtract(startTime).TotalMilliseconds > timeout_ms || timedout)
                {
                    timedout = true;
                    throw new TimeoutException("reading PLC timed out..");
                }
                else if (ct.IsCancellationRequested)
                {
                    canceled = true;
                    throw new OperationCanceledException(ct);
                    //throw new Exception();
                    //ct.ThrowIfCancellationRequested();
                    //return false;
                }
            }
            catch (TimeoutException ex)
            {
                report.ClrReport();
                report.Msg = "The operation has timed out";
                progress.Report(report);
                return(false);
            }
            catch (OperationCanceledException ex)
            {
                report.ClrReport();
                report.Msg = "The operation has been canceled";
                progress.Report(report);
                return(false);
            }
            catch (Exception)
            {
                report.ClrReport();
                report.Msg = "Unkmown exception";
                progress.Report(report);
                return(false);
            }

            stopwatch2.Start();
            lock (PlcDataMapper._WordsListLock)
            {
                OmronFINsProcessor.UpdateStringToWords(PlcMemArea.WR_bit, WRstr);
                OmronFINsProcessor.UpdateStringToWords(PlcMemArea.HR_bit, HRstr);
                OmronFINsProcessor.UpdateStringToWords(PlcMemArea.DM, DMstr);
            }
            stopwatch2.Stop();

            stopwatch3.Start();
            PlcDataMapper.DMWordsToData();//4ms
            stopwatch3.Stop();

            stopwatch4.Start();
            PlcDataMapper.BitsToData();//14ms
            stopwatch4.Stop();

            stopwatch5.Start();
            lock (PlcDataMapper._RWlistLock)
            {
                PlcDataMapper.DataToRList();
            }
            stopwatch5.Stop();
            //}
            //catch (TimeoutException ex)
            //{
            //    report.ClrReport();
            //    report.Msg = "The operation has timed out";
            //    progress.Report(report);
            //    return false;
            //}
            //catch(OperationCanceledException ex)
            //{
            //    report.ClrReport();
            //    report.Msg = "The operation has been canceled";
            //    progress.Report(report);
            //    return false;
            //}
            //catch (Exception)
            //{
            //    report.ClrReport();
            //    report.Msg = "Unkmown exception";
            //    progress.Report(report);
            //    return false;
            //}

            //report.PercetageComplete = 1 / 2 * 100;
            report.Msg = "Reading finished.. Begining to write.." + "readAllWords=" + stopwatch1.ElapsedMilliseconds.ToString()
                         + "..updateStrToWords" + stopwatch2.ElapsedMilliseconds.ToString()
                         + "..DMwordsToData" + stopwatch3.ElapsedMilliseconds.ToString()
                         + "..bitsToData" + stopwatch4.ElapsedMilliseconds.ToString()
                         + "..DataToRlist" + stopwatch5.ElapsedMilliseconds.ToString();
            progress.Report(report);
            return(true);
        }