串列埠通訊系列六-串列埠與上位機通訊呼叫Flash及Flash視訊切換(非互動)

YF_IOT發表於2018-02-27
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SerialFlash
{
    public partial class Form1 : Form
    {
        public Form1() {
            InitializeComponent();
        }

        private SerialPort ComDevice;

        string path = Application.StartupPath + "\\" + "系統檔案" + ".txt";

        string path1 = System.Windows.Forms.Application.StartupPath + "\\Flash\\" + "1" + ".swf";
        string path2 = System.Windows.Forms.Application.StartupPath + "\\Flash\\" + "2" + ".swf";
        string path3 = System.Windows.Forms.Application.StartupPath + "\\Flash\\" + "3" + ".swf";
        string path4 = System.Windows.Forms.Application.StartupPath + "\\Flash\\" + "4" + ".swf";
        string path5 = System.Windows.Forms.Application.StartupPath + "\\Flash\\" + "5" + ".swf";

        //宣告
        string Mode;
        string PortName;
        string BaudRate;
        string ParityBit;
        string DataBits;
        string StopBit;

        private void Form1_Load(object sender, EventArgs e) {
            DataRead();//讀引數
            SerialPortInit();//串列埠初始化
            ComDevice.DataReceived += CD_DataReceived;//從串列埠讀資料
            ComDevice.Encoding = Encoding.GetEncoding("GB2312");//支援中文
            CheckForIllegalCrossThreadCalls = false;//獲取或設定一個值,該值指示是否捕獲對錯誤執行緒的呼叫,這些呼叫在除錯應用程式時訪問控制元件的 Handle 屬性。
            if(this.Mode == "執行") {
                axShockwaveFlash1.Movie = path1;
                axShockwaveFlash1.Play();
                //實現窗體內某控制元件的全屏顯示  
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                this.WindowState = FormWindowState.Maximized;
                Rectangle ret = Screen.GetWorkingArea(this);
                this.axShockwaveFlash1.ClientSize = new Size(ret.Width, ret.Height);
                this.axShockwaveFlash1.Dock = DockStyle.Fill;
                this.axShockwaveFlash1.BringToFront();
            }
            else {
                axShockwaveFlash1.Movie = path1;
                axShockwaveFlash1.Play();
                this.axShockwaveFlash1.Dock = DockStyle.None;
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                this.WindowState = FormWindowState.Normal;
                this.ClientSize = new Size(407, 364);
                this.axShockwaveFlash1.Location = new Point(13, 13);//初始位置  
                this.axShockwaveFlash1.ClientSize = new Size(290, 208);//即是控制元件的原始尺寸  
            }
        }

        private string nstr = "";
        private string mstr = "";
        //讀串列埠中的資料
        private void CD_DataReceived(object sender, SerialDataReceivedEventArgs e) {
            //textBox1.AppendText(ComDevice.ReadExisting());

            int len = ComDevice.BytesToRead;
            byte[] Buf = new byte[len];
            ComDevice.Read(Buf, 0, len);

            foreach(byte Member in Buf) {
                nstr += (char)Member;
                if(nstr.Contains("!")) {
                    break;
                }
            }

            textBox1.AppendText(nstr);
            
            if(mstr != nstr) {

                mstr = nstr;

                int start = nstr.IndexOf("@") + 1;
                int end = nstr.IndexOf("!");

                int middle = Convert.ToInt32(nstr.Substring(start, end - start), 16);//取到中間的值並轉換成整數 

                SetOvlShape(middle);
            }
            nstr = "";
            //MessageBox.Show( DataReceived + "");
        }

        private void SetOvlShape(int which) {
            switch(which) {
                case 0x01:
                    axShockwaveFlash1.Movie = path1;
                    axShockwaveFlash1.Play();
                    break;
                case 0x02:
                    axShockwaveFlash1.Movie = path2;
                    axShockwaveFlash1.Play();
                    break;
                case 0x03:
                    axShockwaveFlash1.Movie = path3;
                    axShockwaveFlash1.Play();
                    break;
                case 0x04:
                    axShockwaveFlash1.Movie = path4;
                    axShockwaveFlash1.Play();
                    break;
                case 0x05:
                    axShockwaveFlash1.Movie = path5;
                    axShockwaveFlash1.Play();
                    break;
                default:
                    break;
            }
        }

        //串列埠初始化
        private void SerialPortInit() {
            //例項化SerialPort物件
            ComDevice = new SerialPort();
            try {
                ComDevice.PortName = comboBox1.Text; //獲取埠號
                ComDevice.BaudRate = Convert.ToInt32(this.BaudRate, 10);//獲取波特率
                if(ParityBit == "n") {//校驗位
                    ComDevice.Parity = Parity.None;
                    //MessageBox.Show("n");
                }
                else if(ParityBit == "o") {
                    ComDevice.Parity = Parity.Odd;
                }
                else if(ParityBit == "e") {
                    ComDevice.Parity = Parity.Even;
                }
                else if(ParityBit == "m") {
                    ComDevice.Parity = Parity.Mark;
                }
                else if(ParityBit == "s") {
                    ComDevice.Parity = Parity.Space;
                }
                ComDevice.DataBits = Convert.ToInt32(this.DataBits, 10);//資料位
                if(StopBit == "1") {//停止位
                    ComDevice.StopBits = StopBits.One;
                    //MessageBox.Show("1");
                }
                else if(StopBit == "1.5") {
                    ComDevice.StopBits = StopBits.OnePointFive;
                }
                else if(StopBit == "2") {
                    ComDevice.StopBits = StopBits.Two;
                }

                ComDevice.Open();//開啟串列埠
            }
            catch {
                MessageBox.Show("埠錯誤,請檢查串列埠", "錯誤");
                ComDevice.Close();
            }
        }

        //讀取指定位置的txt檔案,判斷檔案是否存在,存在直接讀取,不存在建立後在讀取
        private void DataRead() {
            //判斷檔案是否存在,不存在建立並讀取檔案內容,顯示在控制元件中
            if(!File.Exists(path)) {
                WriteFile();
                CarryOut();
            }
            else {
                CarryOut();
            }
        }

        //寫內容到txt檔案
        private void WriteFile() {
            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            //回車換行寫入
            sw.WriteLine("模式:(除錯/執行)");
            sw.WriteLine("除錯");
            sw.WriteLine("COM埠:");
            sw.WriteLine("4");
            sw.WriteLine("屬性:");
            sw.WriteLine("9600, n, 8, 1");
            //重新整理快取
            sw.Flush();
            //關閉檔案流

            sw.Close();
            fs.Close();
        }
        //讀取txt中的內容並寫入list集合
        private List<string> ReadFile() {

            string line;

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            //例項化集合
            List<string> list = new List<string>();
            //讀取檔案所有內容,並寫入集合中
            while((line = sr.ReadLine()) != null) {
                //排除和刪除字串陣列中的空字串
                if(!string.IsNullOrEmpty(line)) {
                    list.Add(line.ToString());
                }
            }
            //關閉流檔案
            sr.Close();
            fs.Close();

            return list;
        }
        //分析從txt中讀到的內容並處理
        private void CarryOut() {

            string[] ArrayDara;
            //例項化一個list集合
            List<string> list = new List<string>();
            //將讀取到的資料新增到集合
            list = ReadFile();
            //防止誤操作
            //獲得List中元素數目:List.Count()
            if(list.Count() < 6 || list.Count > 6) {
                WriteFile();
                CarryOut();
                MessageBox.Show("檔案內容缺失,請勿新增或刪除檔案內容,以重新建立,請修改需要的內容", "誤操作提示");
            }
            else {
                // 在textBox1中顯示指定內容
                // 注意!使用 Environment.NewLine 實現換行
                textBox1.AppendText(list[1] + Environment.NewLine);
                textBox1.AppendText(list[3] + Environment.NewLine);
                textBox1.AppendText(list[5] + Environment.NewLine);

                Mode = list[1];
                PortName = list[3];

                comboBox1.Text = "COM" + PortName;

                ArrayDara = list[5].Split(',');
                //foreach(string str in ArrayDara) {
                //    textBox1.AppendText(str.ToString() + Environment.NewLine);
                //}
                textBox1.AppendText(ArrayDara[0].Trim() + Environment.NewLine);
                textBox1.AppendText(ArrayDara[1].Trim() + Environment.NewLine);
                textBox1.AppendText(ArrayDara[2].Trim() + Environment.NewLine);
                textBox1.AppendText(ArrayDara[3].Trim() + Environment.NewLine);

                BaudRate = ArrayDara[0].Trim();
                ParityBit = ArrayDara[1].Trim();
                DataBits = ArrayDara[2].Trim();
                StopBit = ArrayDara[3].Trim();
            }
        }
        
    }
}

相關文章