Ejemplo n.º 1
0
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int datain;

            datain = serialPort1.ReadByte();
            //可用swtich case语句替换
            if (datain == 0xff)//预约的洗衣机门未关
            {
                ThreadHelperClass.AddText(this, textSysInfo, "\r\n洗衣机未关门!!关门后自动继续...");
            }
            else if (datain == 0xf9)//预约的洗衣机门已关
            {
                ThreadHelperClass.AddText(this, textSysInfo, "\r\n洗衣机已关门,开始洗衣!");
            }
            else if (datain == 0xfe)//预约的洗衣机开始洗衣
            {
                ThreadHelperClass.SetText(this, labelWashState, "占用");
                ThreadHelperClass.AddText(this, textSysInfo, "\r\n洗衣开始!");
                //ifZaiXiYuyue = true;
            }
            else if (datain == 0xfd)//预约的洗衣机结束洗衣
            {
                ThreadHelperClass.SetText(this, labelWashState, "空闲");
                ThreadHelperClass.AddText(this, textSysInfo, "\r\n洗衣结束!");
            }
            else if (datain == 0xfa)//预约取消
            {
                ThreadHelperClass.SetText(this, labelWashState, "空闲");
                ThreadHelperClass.AddText(this, textSysInfo, "\r\n预约已取消!");

                ZaiXiEndTime = DateTime.Now.Subtract(ts1m); //如果预约取消,将zaiXiEndTime置为当前时间以前的一个时刻  ???
            }
            else if (datain == 0xfc)                        //非预约的洗衣机正在洗衣
            {
                ThreadHelperClass.SetText(this, labelWashState, "占用");
                //ifZaiXiYuyue = false;
            }
            else if (datain == 0xfb)//非预约的洗衣机没有洗衣
            {
                ThreadHelperClass.SetText(this, labelWashState, "空闲");
            }

            else if (datain < _128[0])
            {
                if (ConvertIntToByteArray(datain, ref temp))
                {
                    washdatain[0] = temp[0]; //下位机发来洗衣时长
                }
                //ThreadHelperClass.AddText(this, textSysInfo, washdatain[0].ToString());
            }
            else if (datain > _128[0] && datain < 256)
            {
                if (ConvertIntToByteArray(datain, ref temp))
                {
                    washdatain[1] = (byte)(temp[0] - _128[0]); //下位机发来脱水时长,按下位机的代码,只可能在洗衣机空闲时发来!
                                                               //下位机在预约等待 或 洗衣状态 都不能按键
                    isStartOk();                               //可以调用吗???
                }
            }
        }
Ejemplo n.º 2
0
        private void BtnAutoTune_Click(object sender, EventArgs e)
        {
            if (serialMessages == null)
            {
                return;
            }

            btnAutoTune.Enabled    = false;
            numMaxAngleError.Value = 0;

            pidAutotuneClass.Clear();

            serialMessages.MessageReceived += SerialMessages_MessageReceived1;

            var period  = numericUpDownStepInterval.Value;
            var starter = new ThreadStart(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    SoftMove(2048, i % 2);
                    Thread.Sleep((int)period);
                }
                serialMessages.MessageReceived -= SerialMessages_MessageReceived1;
                ThreadHelperClass.SetEnable(this, btnAutoTune, true);
                ThreadHelperClass.SetNumericUpDownValue(this, numMaxAngleError, (decimal)pidAutotuneClass.GetMaxAngleError);
                ThreadHelperClass.SetNumericUpDownValue(this, numAvgAngleError, (decimal)pidAutotuneClass.GetAvgAngleError);
            });

            var pidAutotuneThread = new Thread(starter)
            {
                IsBackground = true
            };

            pidAutotuneThread.Start();
        }
Ejemplo n.º 3
0
        public void StartProcess()
        {
            try
            {
                CreatePanel();
                Process ytdl = new Process();
                processes.Add(ytdl);
                ThreadHelperClass tHelper = new ThreadHelperClass();
                threadHelper.Add(tHelper);

                id += 1;

                ytdl.StartInfo.FileName               = "C:\\xampp\\htdocs\\pyGUI\\resources\\youtube-dl.exe";
                ytdl.StartInfo.Arguments              = "-o \"C:\\xampp\\htdocs\\pyGUI\\dl\\%(title)s %(timestamp)s\" -f " + txtQuality.Text + " " + txtUrl.Text;
                ytdl.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                ytdl.StartInfo.UseShellExecute        = false;
                ytdl.StartInfo.RedirectStandardOutput = true;
                ytdl.StartInfo.CreateNoWindow         = false;
                ytdl.StartInfo.RedirectStandardOutput = true;
                ytdl.StartInfo.RedirectStandardInput  = true;
                ytdl.OutputDataReceived              += new DataReceivedEventHandler((sender, e) =>
                {
                    tHelper.SetText(this, outputLabels[id - 1], e.Data);
                });
                ytdl.Start();
                ytdl.BeginOutputReadLine();
            }
            catch
            {
                Console.WriteLine("Process error.");
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Reloading all labels with Game data statistics
 /// </summary>
 private void ReloadLabels()
 {
     ThreadHelperClass.SetText(this, label2, NumberFormatter.Double(_clickerGame.CookiesOverallyCollected));
     ThreadHelperClass.SetText(this, label4, NumberFormatter.Double(_clickerGame.CookiesOverallySpent));
     ThreadHelperClass.SetText(this, label6, _clickerGame.ClicksDone.ToString());
     ThreadHelperClass.SetText(this, label8, _clickerGame.GameStarted.ToLongDateString());
 }
Ejemplo n.º 5
0
 public void log(String message) // Log to chatbox cross thread enabled
 {
     if (Form1.count > 0)
     {
         message += "\n";
     }
     ThreadHelperClass.SetText(this, ChatBox, message);
 }
Ejemplo n.º 6
0
        private void _blockUpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var block = _httpClient.GetLastBlock();

            if (block != null)
            {
                ThreadHelperClass.SetTextBlock(this, LastVerifiedBlock, block.Hash, block.Date.ToString(), block.Miner);
            }
        }
Ejemplo n.º 7
0
 // Battery status
 public void datetime_m()
 {
     while (true)
     {
         string temp = "" + DateTime.Now;
         ThreadHelperClass.SetText(this, datetime, temp);
         Thread.Sleep(1000);
     }
 }
Ejemplo n.º 8
0
 public void OnSoftmaxFire(object soruce, cmdEventArgs e)
 {
     if (e.prediction != null)
     {
         ThreadHelperClass.SetText(this, label1, e.prediction);
     }
     else
     {
         ThreadHelperClass.SetText(this, label1, "Recognizing.......");
     }
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Reloading all labels with Game data
 /// </summary>
 private void ReloadLabels()
 {
     ThreadHelperClass.SetText(this, CookieColectedLabel, NumberFormatter.Double(_clickerGame.CookiesColected));
     ThreadHelperClass.SetText(this, CPCLabel, NumberFormatter.Double(_clickerGame.CookiesPerClick));
     ThreadHelperClass.SetText(this, CPSLabel, NumberFormatter.Double(_clickerGame.CookiesPerSecond));
     ThreadHelperClass.SetText(this, StrongClickButton, NumberFormatter.Double(_clickerGame.StrongClick.Cost));
     ThreadHelperClass.SetText(this, PointerButton, NumberFormatter.Double(_clickerGame.Pointer.Cost));
     ThreadHelperClass.SetText(this, StrongClickLevelLabel, NumberFormatter.Double(_clickerGame.StrongClick.Level));
     ThreadHelperClass.SetText(this, StrongClickCPCLabel, NumberFormatter.Double(_clickerGame.StrongClick.CpcToLabel));
     ThreadHelperClass.SetText(this, PointerLevelLabel, NumberFormatter.Double(_clickerGame.Pointer.Level));
     ThreadHelperClass.SetText(this, PointerCPSLabel, NumberFormatter.Double(_clickerGame.Pointer.CpsToLabel));
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Unlocking upgrades buttons player has enough cookies.
 /// </summary>
 /// <param name="source"></param>
 /// <param name="e"></param>
 private void ButtonsTimeEvent(object source, ElapsedEventArgs e)
 {
     if (_clickerGame.CookiesColected >= _clickerGame.StrongClick.Cost)
     {
         ThreadHelperClass.Enabled(this, StrongClickButton, true);
     }
     if (_clickerGame.CookiesColected >= _clickerGame.Pointer.Cost)
     {
         ThreadHelperClass.Enabled(this, PointerButton, true);
     }
     ReloadLabels();
 }
Ejemplo n.º 11
0
 public void OnSoftmaxFire(object soruce, cmdEventArgs e)
 {
     if (e.prediction != null)
     {
         ThreadHelperClass.SetText(this, simbolLabel, "acc= " + e.acc + "%");
         PredictionDisplay.Image =
             VisualExamples.img_dic[currentWritingSystem][Int32.Parse(e.prediction)];
     }
     else
     {
         ThreadHelperClass.SetText(this, simbolLabel, "Recognizing.......");
     }
 }
Ejemplo n.º 12
0
 private void AtualizarMensagens()
 {
     while (true)
     {
         string mensagens = "";
         foreach (var mensagem in ComunicacaoServidor.ListarMensagens())
         {
             mensagens += mensagem.usuario + ": " + mensagem.mensagem + "\n";
         }
         ThreadHelperClass.SetText(this, BoxMensagens, mensagens);
         Thread.Sleep(1000);
     }
 }
Ejemplo n.º 13
0
 private void AtualizarUsuarios()
 {
     while (true)
     {
         string textoUsuariosOnline = "";
         Thread.Sleep(100);
         foreach (var usuario in ComunicacaoServidor.ListarUsuariosOnline())
         {
             textoUsuariosOnline += usuario + "\n";
         }
         ThreadHelperClass.SetText(this, BoxUsuariosSala, textoUsuariosOnline);
         Thread.Sleep(3000);
     }
 }
Ejemplo n.º 14
0
        private CreateBlockModel Mining()
        {
            if (Block.Transactions.Count == 0)
            {
                return(null);
            }
            var transactionHash = MerkleTree <TransactionModel> .Compute(Block.Transactions.OrderBy(x => x.Id).ToList());

            var obj = new MiningBlock
            {
                Hash = transactionHash.TrimEnd('=') + Block.PreviousHash.TrimEnd('='),
                PreviousBlockHash = Block.PreviousHash.TrimEnd('='),
                Nonce             = -1,
                Miner             = User
            };
            string blockResultHash;

            using (SHA256Managed sha = new SHA256Managed())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    do
                    {
                        if (_miningTokenSource.IsCancellationRequested)
                        {
                            return(null);
                        }
                        obj.Nonce++;
                        _hashCurr   = obj.Nonce;
                        ms.Position = 0;
                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(ms, obj);

                        blockResultHash = Convert.ToBase64String(sha.ComputeHash(ms.ToArray()));
                        ThreadHelperClass.SetText(this, Output, blockResultHash);
                    }while (!blockResultHash.Substring(0, 2).All(x => x == '0'));

                    return(new CreateBlockModel
                    {
                        Date = DateTimeOffset.Now,
                        Hash = blockResultHash,
                        Miner = User,
                        Nonce = obj.Nonce,
                        PrevBlockHash = Block.PreviousHash,
                        Transactions = Block.Transactions.Select(x => x.Id).ToList()
                    });
                }
            }
        }
 private void StartScrape(FollowSpecifications fSpecs)
 {
     if (UrlIsValid())
     {
         if (FollowersFollowingValuesAreCorrect())
         {
             ThreadHelperClass.SetText(this, statusLabel, "Running...");
             var ig       = new InstaTool.MainScripts.InstagramPages.Login();
             var homepage = ig.PerformLogin(_accountInUse.EmailPhone);
             ThreadHelperClass.SetText(this, statusLabel, "Logged in...");
             var userProfile = homepage.GoToUserProfile(instagramTargetUrl.Text, true);
             ThreadHelperClass.SetText(this, statusLabel, "Started scraping...be patient");
             _scrapedUsers = userProfile.ScrapeUsersByStrategy(1, new ScrapeByNumberOfFollowers(fSpecs));
             ThreadHelperClass.SetText(this, statusLabel, "Scraping done!!");
         }
     }
 }
Ejemplo n.º 16
0
        private void chkTuningEnable_CheckedChanged(object sender, EventArgs e)
        {
            if (!sPort.IsOpen)
            {
                return;
            }

            Messages.Msg_Command cmdStreamAngle;

            if (chkTuningEnable.Checked)
            {
                cmdStreamAngle = new Messages.Msg_Command {
                    command = Messages.COMMAND_TYPES.STREAM_ANGLE, param1 = 1
                };
                ThreadHelperClass.SetEnable(this, btnAutoTune, false);

                pidAutotuneClass.Clear();

                serialMessages.MessageReceived += SerialMessages_MessageReceived1;
                timerRenderScottPlot            = new System.Threading.Timer(TimerRender, null, 5, 5);
            }
            else
            {
                cmdStreamAngle = new Messages.Msg_Command {
                    command = Messages.COMMAND_TYPES.STREAM_ANGLE, param1 = 0
                };

                serialMessages.MessageReceived -= SerialMessages_MessageReceived1;
                ThreadHelperClass.SetEnable(this, btnAutoTune, true);
                ThreadHelperClass.SetNumericUpDownValue(this, numMaxAngleError, (decimal)pidAutotuneClass.GetMaxAngleError);
                ThreadHelperClass.SetNumericUpDownValue(this, numAvgAngleError, (decimal)pidAutotuneClass.GetAvgAngleError);

                timerRenderScottPlot.Dispose();
                //timerRenderScottPlot.Change(Timeout.Infinite, Timeout.Infinite);
            }

            byte[] msgStreamAng = serialMessages.GeneratePacket(cmdStreamAngle.Serialize());

            if (sPort.IsOpen)
            {
                sPort.Write(msgStreamAng, 0, msgStreamAng.Length);
            }
        }
Ejemplo n.º 17
0
 // Battery status
 public void battery_status()
 {
     while (true)
     {
         PowerStatus p = SystemInformation.PowerStatus;
         int         a = (int)(p.BatteryLifePercent * 100);
         //MessageBox.Show("" + a);
         ThreadHelperClass.SetText(this, batter_status, "Battery Status: " + a + "%");
         Thread.Sleep(1000);
         if (global.security_fag == 1)
         {
             ThreadHelperClass.SetText(this, security, "Connected");
         }
         else
         {
             ThreadHelperClass.SetText(this, security, "Disconnected");
         }
         Thread.Sleep(1000);
     }
 }
Ejemplo n.º 18
0
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                int total   = files.Length;
                int current = 0;
                foreach (var file in files)
                {
                    // Replace string
                    string text = File.ReadAllText(file);
                    text        = Regex.Replace(text, @"<(dlc|DLC)>[\w\d\s]*<\/(dlc|DLC)>", "");
                    File.WriteAllText(file, text);

                    // Update progress bar
                    current++;
                    ThreadHelperClass.SetValue(this, progressBar, current * 100 / total);
                }
                System.Windows.Forms.MessageBox.Show($"{files.Length} files changed. You can now close the application.");
            }).Start();
        }
Ejemplo n.º 19
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            Stream stream = File.OpenRead(filePath);

            try
            {
                foreach (long offset in Researcher.FindPosition(stream, 0, offset1, blabla2))
                {
                    stream.Close();
                    BinaryWriter binaryWriter = new BinaryWriter(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite));
                    binaryWriter.Write(blabla2);
                    binaryWriter.Close();
                    ThreadHelperClass.SetText(this, richTextBox1, "Skin Sucfully Reverted!");
                    MessageBox.Show("Done!");
                }
            }
            finally
            {
            }
        }
Ejemplo n.º 20
0
        private void CrawlingElement()
        {
            string url_test = txtboxUrl.Text;

            Craw_element     = new Crawler.ElementCrawl(url_test, IsOnlyDislayed);
            btnCrawlWeb.Text = "Cancel";
            if (Craw_element.GetElements() == 1)
            {
                listElements           = Craw_element.GetListElement();
                dgvElements.DataSource = listElements;
                ThreadHelperClass.SetText(this, lbMessage, String.Format("{0} elements found. Saving into database...", listElements.Count));
                btnCrawlWeb.Enabled = false;

                try
                {
                    //InsertIntoDB(url_test);//insert into DB
                    MessageBox.Show("Retrieve and save data into database successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnGenerateTestCase.Enabled = true;
                }
                catch
                {
                    MessageBox.Show("Retrieve data successfully, but save data failed, please try again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Retrieve data failed, please try again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            btnCrawlWeb.Text    = "Crawl Data";
            btnCrawlWeb.Enabled = true;
            ThreadHelperClass.SetText(this, lbMessage, String.Format("{0} elements found.", listElements.Count));

            Crawwling++;
        }
Ejemplo n.º 21
0
 private void button2_Click(object sender, EventArgs e)
 {
     backgroundWorker2.RunWorkerAsync();
     ThreadHelperClass.SetText(this, richTextBox1, "Start Reverting...");
 }
Ejemplo n.º 22
0
        private void RunStm32Flasher(string arguments, Action <int, string> processFinished)
        {
            var errorStream = new MemoryStream();

            try
            {
                var stm32flashFile = @"stm32flash\stm32flash.exe";

                var tpStream = new ThrouputStream();

                // STM32Flash process
                var threadProcessStart = new Thread(() =>
                {
                    var exitCode = ThreadHelperClass.StartProcess(
                        stm32flashFile,
                        arguments,
#if !DEBUG
                        timeout: 10000,
#endif
                        outputTextWriter: new StreamWriter(tpStream.OutputStream),
                        errorTextWriter: new StreamWriter(errorStream)
                        ).Result;

                    // process Finished
                    _ = BeginInvoke(new Action(() =>
                    {
                        errorStream.Seek(0, SeekOrigin.Begin);
                        var errMsg = new StreamReader(errorStream).ReadToEnd();
                        processFinished(exitCode, errMsg);
                    }));
                    tpStream.Dispose();
                })
                {
                    Name = "StartProcess"
                };
                threadProcessStart.Start();

                var threadReadOutput = new Thread(() =>
                {
                    var tr = new StreamReader(tpStream.InputStream);
                    string line;
                    var processRegex = new Regex(@"(?<name>\w+\s\w+)\s(?<addr>\dx\w+)\s\((?<proc>\d+.\d+)%\)");

                    while (!tpStream.InputClosed)
                    {
                        line = tr.ReadLine();
                        if (line == null)
                        {
                            continue;
                        }

                        var mc = processRegex.Match(line);
                        if (mc.Groups.Count != 4)
                        {
                            _ = BeginInvoke(new Action <string>((s) => { rtfStm32Log.Text += $"{s}{Environment.NewLine}"; }), line);
                        }
                        else if (float.TryParse(mc.Groups["proc"].Value, out float proc))
                        {
                            _ = BeginInvoke(new Action <string, int, string>(
                                                (addr, p, l) =>
                            {
                                progressBarDownloadProgress.Value      = p;
                                progressBarDownloadProgress.CustomText = $"addr:({addr}) [{p}%]";
                                //rtfStm32Log.Text += $"{l}{Environment.NewLine}";
                            })
                                            , mc.Groups["addr"].Value, (int)proc, line);
                        }
                        else
                        {
                            _ = BeginInvoke(new Action <string>((s) => { rtfStm32Log.Text += $"{s}{Environment.NewLine}"; }), line);
                        }
                    }
                    //_ = BeginInvoke(new Action<string>((s) => { rtfStm32Log.Text += $"{s}{Environment.NewLine}"; }), "[DONE]");
                })

                {
                    Name = "ReadOutput"
                };
                threadReadOutput.Start();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, $"Fatal error");
                processFinished(-1, ex.Message);
            }
        }
Ejemplo n.º 23
0
 private void _miningTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     _miningTime = _miningTime.Add(new TimeSpan(0, 0, 1));
     ThreadHelperClass.SetText(this, TimeLabel, $"Time : {_miningTime.ToString("c")}");
 }
Ejemplo n.º 24
0
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     ThreadHelperClass.SetText(this, richTextBox1, serialPort1.ReadExisting());
 }
Ejemplo n.º 25
0
 private void _miningForm_SpeedChanged()
 {
     ThreadHelperClass.SetText(this, SpeedLabel, "Speed : " + _miningForm?.HashSpeed);
     _chartForm.AddSeries((int)_miningForm.HashSpeed);
 }