示例#1
0
        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {

                string rec_data = "Data: ";
                foreach (byte myData in args.data)
                {
                    if (myData.ToString().Length == 1)
                    {
                        rec_data += "00";
                    }

                    if (myData.ToString().Length == 2)
                    {
                        rec_data += "0";
                    }

                    rec_data += myData.ToString() + " ";
                }

                this.lb_read.Items.Insert(0, rec_data);
            }
        }
示例#2
0
 private void DataRecieved(object sender, DataRecievedEventArgs args)
 {
     if (this.OnDataRecieved != null)
     {
         this.OnDataRecieved(sender, args);
     }
 }
示例#3
0
 void OnDataReceived(object sender, DataRecievedEventArgs args)
 {
     if (DataReceived != null)
     {
         DataReceived(args.data);
     }
 }
示例#4
0
		void OnDataRecieved(object sender, DataRecievedEventArgs args)
		{
			if (IsDisposed)
				return;

			var buffer = args.data.ToList();
			if (buffer.Count < 2)
				return;
			buffer.RemoveRange(0, IsExtendedMode ? 3 : 2);
			foreach (var b in buffer)
			{
				if (LocalResult.Count > 0)
				{
					LocalResult.Add(b);
					if (b == 0x3E)
					{
						var bytes = CreateInputBytes(LocalResult);
						LocalResult = new List<byte>();

						var response = new Response
						{
							Bytes = bytes.ToList()
						};
						if (UseId)
						{
							response.Id = BytesHelper.ExtractInt(bytes.ToList(), 0);
						}
						OnResponseRecieved(response);
						OnNewResponse(response);
						return;
					}
				}
				if (b == 0x7E)
				{
					if (!IsExtendedMode)
					{
						if (buffer.IndexOf(0x7e) == 0)
							IsExtendedMode = false;
						if (buffer.IndexOf(0x7e) == 1)
							IsExtendedMode = true;
					}
					LocalResult = new List<byte> { b };
				}
				if (RequestCollection.Count() == 0)
					AutoWaitEvent.Set();
			}
		}
        private void UsbOnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            // Gets byte with the info about which buttons/pads/pedals are down
            Debug.Assert(args.data.GetLength(0) == 15, "Length detected != 15");

            HandleDPad(args.data);
            
            if (HandleButtons(args.data) == false)
            {
                if (args.data[11] != 0)
                {
                    HandleDrumPads(args.data);
                }
            }
        }
示例#6
0
 private void USB_OnDataRecieved(object sender, DataRecievedEventArgs args)
 {
     UpdateHandle(args.data);
 }
示例#7
0
        /// <summary>
        /// the below are usb event handlers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void USB_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {

        }
示例#8
0
 /// <summary>
 /// the below are usb event handlers
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void USB_OnDataRecievedEventHandler(object sender, DataRecievedEventArgs args)
 {
     this._launcher_status = args.data;
 }
示例#9
0
 private void SpecifiedDevice_DataRecieved(object sender, DataRecievedEventArgs args)
 {
     // Event weitergeben z.B. für das Hauptfenster
     if (this.ReportReceived != null)
     {
         this.ReportReceived(this, args);
     }
 }
示例#10
0
文件: MainForm.cs 项目: tiemikn/ES770
        void ReceberDados(object sender, DataRecievedEventArgs e)
        {
            if(config.DeviceConnected == false) return;

            if(checkBox1.Checked) richTextBox1.Text = "";

            switch(config.ReceiveFormat)
            {
                case (int)Configs.RECEIVE_TYPES.ASCII:
                    for (int i = (int)minBufferLength.Value; i <= (int)maxBufferLength.Value; i++)
                    {
                        richTextBox1.Text += (char)e.data[i+1];
                    }
                    richTextBox1.Text += "\r";
                    break;

                case (int)Configs.RECEIVE_TYPES.DEC:
                    for (int i = (int)minBufferLength.Value; i <= (int)maxBufferLength.Value; i++)
                    {
                        richTextBox1.Text += e.data[i+1].ToString() + " ";
                    }
                    richTextBox1.Text += "\r";
                    break;

                case (int)Configs.RECEIVE_TYPES.HEX:
                    for (int i = (int)minBufferLength.Value; i <= (int)maxBufferLength.Value; i++)
                    {
                        richTextBox1.Text += e.data[i+1].ToString("X2") + " ";
                    }
                    richTextBox1.Text += "\r";
                    break;
            }

            if(checkBox2.Checked)
            {
                richTextBox1.SelectionStart = richTextBox1.Text.Length;
                richTextBox1.ScrollToCaret();
            }
        }
        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                string rec_data = String.Empty;
                for (int i = 1; i < args.data.Length; i++)
                {
                    rec_data += String.Format("{0:X2}", args.data[i]) + " ";
                }
                //foreach (byte myData in args.data)
                //{
                //    rec_data += String.Format("{0:X2}", myData) + " ";
                //} 
                //--- 若收到機器端的MAP訊號,進行awake 49h 44h
                #region MAP
                if (String.Format("{0:X2}", args.data[2], 16) == "49" && String.Format("{0:X2}", args.data[3], 16) == "44")
                {
                    lb_message.Text = "Mapping...";
                    #region awake command
                    Thread.Sleep(2000);
                    try
                    {
                        string[] arrText = { "07", "12", "16", "18", "21", "00", "00", "00" };
                        byte[] data = new byte[arrText.Length + 1];
                        data[0] = Convert.ToByte(0x00);
                        for (int i = 1; i < arrText.Length; i++)
                        {
                            if (arrText[i] != "")
                            {
                                data[i] = Convert.ToByte(arrText[i - 1], 16);
                            }
                        }

                        if (this.usb.SpecifiedDevice != null)
                        {
                            this.usb.SpecifiedDevice.SendData(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    #endregion
                }
                #endregion

                //--- 若收到Error 的 Header 1st
                #region Measure Error
                else if (String.Format("{0:X2}", args.data[2], 16) == "45"/* && String.Format("{0:X2}", args.data[3], 16) == "72"*/)
                {
                    #region decodingError
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);
                    if (dataCount > 8)
                    {
                        switch (dataAry[2])
                        {
                            case "01":
                                lb_message.Text = res_man.GetString("err1", cul);
                                break;
                            case "02":
                                lb_message.Text = res_man.GetString("err2", cul);
                                break;
                            case "03":
                                lb_message.Text = res_man.GetString("err3", cul);
                                break;
                            case "05":
                                lb_message.Text = res_man.GetString("err5", cul);
                                break;
                            case "42":
                                lb_message.Text = res_man.GetString("errB", cul);
                                break;
                        }
                        //--- Initialization
                        dataCount = 0;
                        for (int i = 0; i < dataAry.Length; i++)
                        {
                            dataAry[i] = "0";
                        }
                    }
                    #endregion
                }
                else if (dataAry[0] == "45"/* && dataAry[1] == "72"*/)
                {
                    #region decodingError 
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);

                    //--- Decoding
                    /********************************************************
                     dataAry[2] = n
                     n = 0x01: Signals is too weak
                       = 0x02: Error signal
                       = 0x03: No pressure in the cuff
                       = 0x05: Abnormal result
                       = 0x42: Low battery   
                    *********************************************************/
                    if (dataCount > 8)
                    {
                        switch (dataAry[2])
                        {
                            case "01":
                                lb_message.Text = res_man.GetString("err1", cul);
                                break;
                            case "02":
                                lb_message.Text = res_man.GetString("err2", cul);
                                break;
                            case "03":
                                lb_message.Text = res_man.GetString("err3", cul);
                                break;
                            case "05":
                                lb_message.Text = res_man.GetString("err5", cul);
                                break;
                            case "42":
                                lb_message.Text = res_man.GetString("errB", cul);
                                break;
                        }
                        //--- Initialization
                        dataCount = 0;
                        for (int i = 0; i < dataAry.Length; i++)
                        {
                            dataAry[i] = "0";
                        }
                    }

                    #endregion
                }
                #endregion

                //--- 若收到AutoSend 的 Header 1st
                #region AutoSend data
                else if (String.Format("{0:X2}", args.data[2], 16) == "4D")
                {
                    DateTimeFormatInfo fmt = new DateTimeFormatInfo();
                    if (rb_cs.Checked)
                        fmt = (new CultureInfo("cs")).DateTimeFormat;
                    else if (rb_en.Checked)
                        fmt = (new CultureInfo("en")).DateTimeFormat;
                    else if (rb_sk.Checked)
                        fmt = (new CultureInfo("sk")).DateTimeFormat;
                    #region AutoSend decoding 
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);

                    //--- 2. Confrim n = args.data[4]*256 + args.data[5], save to dataAry[n]
                    string dataSizeH = dataAry[2];
                    string dataSizeL = dataAry[3];
                    int dataSize = Convert.ToInt32(dataSizeH, 16) * 256 + Convert.ToInt32(dataSizeL, 16);

                    if (dataCount > dataSize)
                    {
                        //--- check CRC
                        if (CRC(dataAry))
                        {
                            float dataNumber = 0;
                            //--- check data number
                            if (dataSize == 27)
                                dataNumber = 1;
                            else
                                dataNumber = 3;

                            int afibCount = 0;
                            //--- pulse >200:high, <40:Low
                            bool pulseHighOrLow = false;

                            listView1.BeginUpdate();
                            for (int i = 1; i <= dataNumber; i++)
                            {
                                #region systole
                                int systole = Convert.ToInt32(dataAry[19 + (8 * (i - 1))], 16);
                                #endregion
                                #region diastole
                                int diastole = Convert.ToInt32(dataAry[20 + (8 * (i - 1))], 16);
                                #endregion
                                #region pulse
                                int pulse = Convert.ToInt32(dataAry[21 + (8 * (i - 1))], 16);
                                string pulseStr = pulse.ToString();
                                #endregion

                                string MonthStr = String.Empty;
                                string HourStr = String.Empty;
                                string DayStr = String.Empty;
                                string YearStr = String.Empty;
                                //--- Convert every data to byteString
                                string month0Day = byteTransform.To8bit(byteTransform.byteToString(dataAry[22 + 8 * (i - 1)]));
                                string month1Hour = byteTransform.To8bit(byteTransform.byteToString(dataAry[23 + 8 * (i - 1)]));
                                string AsArrYear = byteTransform.To8bit(byteTransform.byteToString(dataAry[25 + 8 * (i - 1)]));

                                #region Day
                                //--- Day b5-b0
                                for (int j = 2; j < 8; j++)
                                {
                                    DayStr += month0Day[j];
                                }
                                //--- DayStr -> bytes
                                int day = Convert.ToByte(DayStr, 2);
                                #endregion

                                #region Month
                                //--- Month 取 b7 b6
                                for (int j = 0; j < 2; j++)
                                {
                                    MonthStr += month1Hour[j];
                                }
                                for (int j = 0; j < 2; j++)
                                {
                                    MonthStr += month0Day[j];
                                }
                                int month = Convert.ToByte(MonthStr, 2);
                                #endregion

                                #region Hour
                                for (int j = 2; j < 8; j++)
                                {
                                    HourStr += month1Hour[j];
                                }
                                int hour = Convert.ToByte(HourStr, 2);
                                #endregion

                                #region Minutes
                                Int32 minutes = Convert.ToInt32(dataAry[24 + 8 * (i - 1)], 16);
                                #endregion

                                #region Arr Year
                                //--- Arr
                                string Afib = String.Empty;
                                if (AsArrYear[1] != '0')
                                {
                                    //Afib = res_man.GetString("AFIB", cul);
                                    //Afib = "\u25CF";
                                    Afib = "\u25CF";
                                    afibCount++;
                                }

                                //--- year
                                for (int j = 2; j < 8; j++)
                                {
                                    YearStr += AsArrYear[j];
                                }
                                int year = Convert.ToByte(YearStr, 2);
                                #endregion

                                //--- data sum

                                pulseSum += pulse;
                                diastoleSum += diastole;
                                systoleSum += systole;

                                #region dateFormat
                                string yearStr = "20" + year;
                                year = Convert.ToInt32(yearStr);
                                DateTime thisDate = new DateTime(year, month, day);
                                //--- 取得目前cul
                                string realDateTime = thisDate.ToString("d", fmt).Replace(" ", "") + " " + String.Format("{0:00}:{1:00}", hour, minutes);
                                #endregion

                                //--- pulse >200:high, <40:Low
                                if (pulse > 200)
                                {
                                    pulseStr = "High";
                                    pulseHighOrLow = true;
                                }
                                else if (pulse < 40)
                                {
                                    pulseStr = "Low";
                                    pulseHighOrLow = true;
                                }

                                #region listViewShowNowData
                                ListViewItem dataList = new ListViewItem("" + i);
                                dataList.SubItems.Add(realDateTime);
                                dataList.SubItems.Add("" + systole);
                                dataList.SubItems.Add("" + diastole);
                                dataList.SubItems.Add("" + pulseStr);
                                dataList.SubItems.Add("" + Afib);
                                listView1.Items.Add(dataList);
                                #endregion

                                btn_clrID.Enabled = true;
                                btn_save.Enabled = true;
                                lb_message.Text = " ";
                                //---cul can't change
                                LangCanNotChoose();
                            }
                            if (dataNumber == 3)
                            {
                                //--- Avg save to database-data Table
                                var systoleAvg = Math.Round(systoleSum / 3.0);
                                var diastoleAvg = Math.Round(diastoleSum / 3.0);
                                //--- pulse >200:high, <40:Low
                                string pulseStrAvg;
                                if (pulseHighOrLow)
                                    pulseStrAvg = "---";
                                else
                                    pulseStrAvg = Math.Round(pulseSum / 3.0).ToString();
                                //--- Afib
                                string afibSymbolAvg = String.Empty;
                                if (afibCount >= 2)
                                    afibSymbolAvg = "\u25CF";

                                #region listViewShowNowData
                                ListViewItem avg = new ListViewItem("avg");
                                avg.SubItems.Add(""+ DateTime.Now.ToString("d",fmt));
                                avg.SubItems.Add("" + systoleAvg);
                                avg.SubItems.Add("" + diastoleAvg);
                                avg.SubItems.Add("" + pulseStrAvg);
                                avg.SubItems.Add(afibSymbolAvg);
                                listView1.Items.Add(avg);
                                #endregion      
                            }
                            listView1.EndUpdate();
                            systoleSum = diastoleSum = pulseSum = 0;    //initialize

                            //--- Initialization
                            lb_message.Text = " ";
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }


                            #region Measure Finish
                            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                            DialogResult dialogResult;
                            dialogResult = MessageBox.Show(res_man.GetString("mb_finish", cul) + "\n" + res_man.GetString("mb_save", cul), "WatchBP Analyzer Office Basic", buttons, MessageBoxIcon.Question);
                            if (dialogResult == DialogResult.Yes)
                            {
                                if (string.IsNullOrWhiteSpace(tb_ID.Text))
                                {
                                    MessageBox.Show(res_man.GetString("noID", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                else if (!((new System.Text.RegularExpressions.Regex("^[A-Za-z0-9]+$")).IsMatch(tb_ID.Text)))
                                {
                                    MessageBox.Show(res_man.GetString("mb_IDinform", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                else
                                {
                                    #region listView export to CSV
                                    //declare new SaveFileDialog + set it's initial properties
                                    string path = System.AppDomain.CurrentDomain.BaseDirectory + @"WatchBP\OfficeBasic";

                                    try
                                    {
                                        // Determine whether the directory exists.
                                        if (!Directory.Exists(path))
                                        {
                                            // Try to create the directory.
                                            DirectoryInfo di = Directory.CreateDirectory(path);
                                        }
                                        string ID = tb_ID.Text.Replace(" ", "");
                                        if (!File.Exists(path + "\\" + DetermineFileName(ID) + ".csv"))
                                        {
                                            string Path = res_man.GetString("mb_path", cul) + " " + path;
                                            MessageBox.Show("ID: " + ID + "\n" + Path, "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            StreamWriter sw = new StreamWriter(new FileStream(path + "\\" + DetermineFileName(ID) + ".csv", FileMode.Create), Encoding.UTF8);

                                            string[] headers = listView1.Columns
                                                        .OfType<ColumnHeader>()
                                                        .Select(header => header.Text.Trim())
                                                        .ToArray();

                                            string[][] items = listView1.Items
                                                        .OfType<ListViewItem>()
                                                        .Select(lvi => lvi.SubItems
                                                            .OfType<ListViewItem.ListViewSubItem>()
                                                            .Select(si => si.Text).ToArray()).ToArray();

                                            string table = string.Join(",", headers) + Environment.NewLine;
                                            foreach (string[] a in items)
                                            {
                                                //a = a_loopVariable;
                                                table += string.Join(",", a) + Environment.NewLine;
                                            }
                                            table = table.TrimEnd('\r', '\n');
                                            sw.Write(table);
                                            sw.Close();

                                            #region save to database
                                            //--- save to database-data Table

                                            try
                                            {
                                                for (int columnIndex = 0; columnIndex < listView1.Items.Count; columnIndex++)
                                                {
                                                    string Query = @"INSERT OR IGNORE INTO data (primaryKey,Item,ID,DateTime,Sys,Dia,Pulse,AFIB) VALUES(null,'" + listView1.Items[columnIndex].SubItems[0].Text + "','" + ID + "','" + listView1.Items[columnIndex].SubItems[1].Text + "','" + listView1.Items[columnIndex].SubItems[2].Text + "','" + listView1.Items[columnIndex].SubItems[3].Text + "','" + listView1.Items[columnIndex].SubItems[4].Text + "','" + listView1.Items[columnIndex].SubItems[5].Text + "' )";
                                                    DataBaseOperation.ConnectToDataBase(dbConnectionString, Query, ref sqliteCon, ref sqliteCmd);
                                                    fill_comboBox();
                                                }

                                                sqliteCon.Close();
                                            }
                                            catch (Exception ex)
                                            {
                                                MessageBox.Show(ex.Message);
                                            }
                                            #endregion

                                            //--- 紀錄是否存檔過
                                            btn_save.Enabled = false;
                                            isSave = true;
                                            //currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        }
                                        //else
                                        //{
                                        //    DialogResult result;
                                        //    result = MessageBox.Show(DetermineFileName(ID) + " " + res_man.GetString("mb_fileExist", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                        //    if (result == DialogResult.Yes)
                                        //    {
                                        //        string Path = res_man.GetString("mb_path", cul) + " " + path;
                                        //        MessageBox.Show("ID: " + ID + "\n" + Path, "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        //        StreamWriter sw = new StreamWriter(new FileStream(path + "\\" + DetermineFileName(ID) + ".csv", FileMode.Create), Encoding.UTF8);

                                        //        string[] headers = listView1.Columns
                                        //                    .OfType<ColumnHeader>()
                                        //                    .Select(header => header.Text.Trim())
                                        //                    .ToArray();

                                        //        string[][] items = listView1.Items
                                        //                    .OfType<ListViewItem>()
                                        //                    .Select(lvi => lvi.SubItems
                                        //                        .OfType<ListViewItem.ListViewSubItem>()
                                        //                        .Select(si => si.Text).ToArray()).ToArray();

                                        //        string table = string.Join(",", headers) + Environment.NewLine;
                                        //        foreach (string[] a in items)
                                        //        {
                                        //            //a = a_loopVariable;
                                        //            table += string.Join(",", a) + Environment.NewLine;
                                        //        }
                                        //        table = table.TrimEnd('\r', '\n');
                                        //        sw.Write(table);
                                        //        sw.Close();
                                        //        //--- 紀錄是否存檔過 
                                        //        isSave = true;
                                        //        currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        //    }
                                        //}

                                    }
                                    catch
                                    {
                                        MessageBox.Show(res_man.GetString("mb_permission", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        string ID = tb_ID.Text.Replace(" ", "");
                                        SaveFileDialog sfd = new SaveFileDialog
                                        {
                                            Title = "Choose file to save to",
                                            FileName = DetermineFileName(ID),
                                            Filter = "CSV (*.csv)|*.csv",
                                            FilterIndex = 0,
                                            InitialDirectory = path
                                            //InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                                        };
                                        if (sfd.ShowDialog() == DialogResult.OK)
                                        {

                                            string[] headers = listView1.Columns
                                                        .OfType<ColumnHeader>()
                                                        .Select(header => header.Text.Trim())
                                                        .ToArray();

                                            string[][] items = listView1.Items
                                                        .OfType<ListViewItem>()
                                                        .Select(lvi => lvi.SubItems
                                                            .OfType<ListViewItem.ListViewSubItem>()
                                                            .Select(si => si.Text).ToArray()).ToArray();

                                            string table = string.Join(",", headers) + Environment.NewLine;
                                            foreach (string[] a in items)
                                            {
                                                //a = a_loopVariable;
                                                table += string.Join(",", a) + Environment.NewLine;
                                            }
                                            table = table.TrimEnd('\r', '\n');
                                            File.WriteAllText(sfd.FileName, table);

                                            #region save to database
                                            //--- save to database-data Table

                                            try
                                            {
                                                for (int columnIndex = 0; columnIndex < listView1.Items.Count; columnIndex++)
                                                {
                                                    string Query = @"INSERT OR IGNORE INTO data (primaryKey,Item,ID,DateTime,Sys,Dia,Pulse,AFIB) VALUES(null,'" + listView1.Items[columnIndex].SubItems[0].Text + "','" + ID + "','" + listView1.Items[columnIndex].SubItems[1].Text + "','" + listView1.Items[columnIndex].SubItems[2].Text + "','" + listView1.Items[columnIndex].SubItems[3].Text + "','" + listView1.Items[columnIndex].SubItems[4].Text + "','" + listView1.Items[columnIndex].SubItems[5].Text + "' )";
                                                    DataBaseOperation.ConnectToDataBase(dbConnectionString, Query, ref sqliteCon, ref sqliteCmd);
                                                    fill_comboBox();
                                                }

                                                sqliteCon.Close();
                                            }
                                            catch (Exception ex)
                                            {
                                                MessageBox.Show(ex.Message);
                                            }
                                            #endregion

                                            //--- 紀錄是否存檔過
                                            btn_save.Enabled = false;
                                            isSave = true;
                                            //currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        }
                                    }

                                    #endregion
                                }

                            }
                            #endregion

                        }
                        else
                        {
                            //--- Initialization
                            lb_message.Text = " ";
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }
                            MessageBox.Show(res_man.GetString("mb_data", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        } 
                    }
                    #endregion
                }
                else if (dataAry[0] == "4D")
                {
                    DateTimeFormatInfo fmt = new DateTimeFormatInfo();
                    if (rb_cs.Checked)
                        fmt = (new CultureInfo("cs")).DateTimeFormat;
                    else if (rb_en.Checked)
                        fmt = (new CultureInfo("en")).DateTimeFormat;
                    else if (rb_sk.Checked)
                        fmt = (new CultureInfo("sk")).DateTimeFormat;
                    #region AutoSend decoding 
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);
                    //--- 2. Confrim n = args.data[4]*256 + args.data[5], save to dataAry[n]
                    string dataSizeH = dataAry[2];
                    string dataSizeL = dataAry[3];
                    int dataSize = Convert.ToInt32(dataSizeH, 16) * 256 + Convert.ToInt32(dataSizeL, 16);

                    if (dataCount > dataSize)
                    {
                        //--- check CRC
                        if (CRC(dataAry))
                        {
                            float dataNumber = 0;
                            //--- check data number
                            if (dataSize == 27)
                                dataNumber = 1;
                            else
                                dataNumber = 3;

                            int afibCount = 0;
                            //--- pulse >200:high, <40:Low
                            bool pulseHighOrLow = false;

                            listView1.BeginUpdate();
                            for (int i = 1; i <= dataNumber; i++)
                            {
                                #region systole
                                int systole = Convert.ToInt32(dataAry[19 + (8 * (i - 1))], 16);
                                #endregion
                                #region diastole
                                int diastole = Convert.ToInt32(dataAry[20 + (8 * (i - 1))], 16);
                                #endregion
                                #region pulse
                                int pulse = Convert.ToInt32(dataAry[21 + (8 * (i - 1))], 16);
                                string pulseStr = pulse.ToString();
                                #endregion

                                string MonthStr = String.Empty;
                                string HourStr = String.Empty;
                                string DayStr = String.Empty;
                                string YearStr = String.Empty;
                                //--- Convert every data to byteString
                                string month0Day = byteTransform.To8bit(byteTransform.byteToString(dataAry[22 + 8 * (i - 1)]));
                                string month1Hour = byteTransform.To8bit(byteTransform.byteToString(dataAry[23 + 8 * (i - 1)]));
                                string AsArrYear = byteTransform.To8bit(byteTransform.byteToString(dataAry[25 + 8 * (i - 1)]));

                                #region Day
                                //--- Day b5-b0
                                for (int j = 2; j < 8; j++)
                                {
                                    DayStr += month0Day[j];
                                }
                                //--- DayStr -> bytes
                                int day = Convert.ToByte(DayStr, 2);
                                #endregion

                                #region Month
                                //--- Month 取 b7 b6
                                for (int j = 0; j < 2; j++)
                                {
                                    MonthStr += month1Hour[j];
                                }
                                for (int j = 0; j < 2; j++)
                                {
                                    MonthStr += month0Day[j];
                                }
                                int month = Convert.ToByte(MonthStr, 2);
                                #endregion

                                #region Hour
                                for (int j = 2; j < 8; j++)
                                {
                                    HourStr += month1Hour[j];
                                }
                                int hour = Convert.ToByte(HourStr, 2);
                                #endregion

                                #region Minutes
                                Int32 minutes = Convert.ToInt32(dataAry[24 + 8 * (i - 1)], 16);
                                #endregion

                                #region Arr Year
                                //--- Arr
                                string Afib = String.Empty;
                                if (AsArrYear[1] != '0')
                                {
                                    //Afib = res_man.GetString("AFIB", cul);
                                    //Afib = "\u25CF";
                                    Afib = "\u25CF";
                                    afibCount++;
                                }

                                //--- year
                                for (int j = 2; j < 8; j++)
                                {
                                    YearStr += AsArrYear[j];
                                }
                                int year = Convert.ToByte(YearStr, 2);
                                #endregion

                                //--- data sum

                                pulseSum += pulse;
                                diastoleSum += diastole;
                                systoleSum += systole;

                                #region dateFormat
                                string yearStr = "20" + year;
                                year = Convert.ToInt32(yearStr);
                                DateTime thisDate = new DateTime(year, month, day);
                                //--- 取得目前cul
                                string realDateTime = thisDate.ToString("d", fmt).Replace(" ", "") + " " + String.Format("{0:00}:{1:00}", hour, minutes);
                                #endregion

                                //--- pulse >200:high, <40:Low
                                if (pulse > 200)
                                {
                                    pulseStr = "High";
                                    pulseHighOrLow = true;
                                }
                                else if (pulse < 40)
                                {
                                    pulseStr = "Low";
                                    pulseHighOrLow = true;
                                }

                                #region listViewShowNowData
                                ListViewItem dataList = new ListViewItem("" + i);
                                dataList.SubItems.Add(realDateTime);
                                dataList.SubItems.Add("" + systole);
                                dataList.SubItems.Add("" + diastole);
                                dataList.SubItems.Add("" + pulseStr);
                                dataList.SubItems.Add("" + Afib);
                                listView1.Items.Add(dataList);
                                #endregion

                                btn_clrID.Enabled = true;
                                btn_save.Enabled = true;
                                lb_message.Text = " ";
                                //---cul can't change
                                LangCanNotChoose();
                            }
                            if (dataNumber == 3)
                            {
                                //--- Avg save to database-data Table
                                var systoleAvg = Math.Round(systoleSum / 3.0);
                                var diastoleAvg = Math.Round(diastoleSum / 3.0);
                                //--- pulse >200:high, <40:Low
                                string pulseStrAvg;
                                if (pulseHighOrLow)
                                    pulseStrAvg = "---";
                                else
                                    pulseStrAvg = Math.Round(pulseSum / 3.0).ToString();
                                //--- Afib
                                string afibSymbolAvg = String.Empty;
                                if (afibCount >= 2)
                                    afibSymbolAvg = "\u25CF";

                                #region listViewShowNowData
                                ListViewItem avg = new ListViewItem("avg");
                                avg.SubItems.Add("" +DateTime.Now.ToString("d",fmt)+" "+ DateTime.Now.ToString("HH:mm", fmt));
                                avg.SubItems.Add("" + systoleAvg);
                                avg.SubItems.Add("" + diastoleAvg);
                                avg.SubItems.Add("" + pulseStrAvg);
                                avg.SubItems.Add(afibSymbolAvg);
                                listView1.Items.Add(avg);
                                #endregion      
                            }
                            listView1.EndUpdate();
                            systoleSum = diastoleSum = pulseSum = 0;    //initialize

                            //--- Initialization
                            lb_message.Text = " ";
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }


                            #region Measure Finish
                            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                            DialogResult dialogResult;
                            dialogResult = MessageBox.Show(res_man.GetString("mb_finish", cul) + "\n" + res_man.GetString("mb_save", cul), "WatchBP Analyzer Office Basic", buttons, MessageBoxIcon.Question);
                            if (dialogResult == DialogResult.Yes)
                            {
                                if (string.IsNullOrWhiteSpace(tb_ID.Text))
                                {
                                    MessageBox.Show(res_man.GetString("noID", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                else if (!((new System.Text.RegularExpressions.Regex("^[A-Za-z0-9]+$")).IsMatch(tb_ID.Text)))
                                {
                                    MessageBox.Show(res_man.GetString("mb_IDinform", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                else
                                {
                                    #region listView export to CSV
                                    //declare new SaveFileDialog + set it's initial properties
                                    string path = System.AppDomain.CurrentDomain.BaseDirectory + @"WatchBP\OfficeBasic";

                                    try
                                    {
                                        // Determine whether the directory exists.
                                        if (!Directory.Exists(path))
                                        {
                                            // Try to create the directory.
                                            DirectoryInfo di = Directory.CreateDirectory(path);
                                        }
                                        string ID = tb_ID.Text.Replace(" ", "");
                                        if (!File.Exists(path + "\\" + DetermineFileName(ID) + ".csv"))
                                        {
                                            string Path = res_man.GetString("mb_path", cul) + " " + path;
                                            MessageBox.Show("ID: " + ID + "\n" + Path, "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            StreamWriter sw = new StreamWriter(new FileStream(path + "\\" + DetermineFileName(ID) + ".csv", FileMode.Create), Encoding.UTF8);

                                            string[] headers = listView1.Columns
                                                        .OfType<ColumnHeader>()
                                                        .Select(header => header.Text.Trim())
                                                        .ToArray();

                                            string[][] items = listView1.Items
                                                        .OfType<ListViewItem>()
                                                        .Select(lvi => lvi.SubItems
                                                            .OfType<ListViewItem.ListViewSubItem>()
                                                            .Select(si => si.Text).ToArray()).ToArray();

                                            string table = string.Join(",", headers) + Environment.NewLine;
                                            foreach (string[] a in items)
                                            {
                                                //a = a_loopVariable;
                                                table += string.Join(",", a) + Environment.NewLine;
                                            }
                                            table = table.TrimEnd('\r', '\n');
                                            sw.Write(table);
                                            sw.Close();

                                            #region save to database
                                            //--- save to database-data Table

                                            try
                                            {
                                                for (int columnIndex = 0; columnIndex < listView1.Items.Count; columnIndex++)
                                                {
                                                    string Query = @"INSERT OR IGNORE INTO data (primaryKey,Item,ID,DateTime,Sys,Dia,Pulse,AFIB) VALUES(null,'" + listView1.Items[columnIndex].SubItems[0].Text + "','" + ID + "','" + listView1.Items[columnIndex].SubItems[1].Text + "','" + listView1.Items[columnIndex].SubItems[2].Text + "','" + listView1.Items[columnIndex].SubItems[3].Text + "','" + listView1.Items[columnIndex].SubItems[4].Text + "','" + listView1.Items[columnIndex].SubItems[5].Text + "' )";
                                                    DataBaseOperation.ConnectToDataBase(dbConnectionString, Query, ref sqliteCon, ref sqliteCmd);
                                                    fill_comboBox();
                                                }

                                                sqliteCon.Close();
                                            }
                                            catch (Exception ex)
                                            {
                                                MessageBox.Show(ex.Message);
                                            }
                                            #endregion

                                            //--- 紀錄是否存檔過
                                            btn_save.Enabled = false;
                                            isSave = true;
                                            //currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        }
                                        //else
                                        //{
                                        //    DialogResult result;
                                        //    result = MessageBox.Show(DetermineFileName(ID) + " " + res_man.GetString("mb_fileExist", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                        //    if (result == DialogResult.Yes)
                                        //    {
                                        //        string Path = res_man.GetString("mb_path", cul) + " " + path;
                                        //        MessageBox.Show("ID: " + ID + "\n" + Path, "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        //        StreamWriter sw = new StreamWriter(new FileStream(path + "\\" + DetermineFileName(ID) + ".csv", FileMode.Create), Encoding.UTF8);

                                        //        string[] headers = listView1.Columns
                                        //                    .OfType<ColumnHeader>()
                                        //                    .Select(header => header.Text.Trim())
                                        //                    .ToArray();

                                        //        string[][] items = listView1.Items
                                        //                    .OfType<ListViewItem>()
                                        //                    .Select(lvi => lvi.SubItems
                                        //                        .OfType<ListViewItem.ListViewSubItem>()
                                        //                        .Select(si => si.Text).ToArray()).ToArray();

                                        //        string table = string.Join(",", headers) + Environment.NewLine;
                                        //        foreach (string[] a in items)
                                        //        {
                                        //            //a = a_loopVariable;
                                        //            table += string.Join(",", a) + Environment.NewLine;
                                        //        }
                                        //        table = table.TrimEnd('\r', '\n');
                                        //        sw.Write(table);
                                        //        sw.Close();
                                        //        //--- 紀錄是否存檔過 
                                        //        isSave = true;
                                        //        currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        //    }
                                        //}

                                    }
                                    catch
                                    {
                                        MessageBox.Show(res_man.GetString("mb_permission", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        string ID = tb_ID.Text.Replace(" ", "");
                                        SaveFileDialog sfd = new SaveFileDialog
                                        {
                                            Title = "Choose file to save to",
                                            FileName = DetermineFileName(ID),
                                            Filter = "CSV (*.csv)|*.csv",
                                            FilterIndex = 0,
                                            InitialDirectory = path
                                            //InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                                        };
                                        if (sfd.ShowDialog() == DialogResult.OK)
                                        {

                                            string[] headers = listView1.Columns
                                                        .OfType<ColumnHeader>()
                                                        .Select(header => header.Text.Trim())
                                                        .ToArray();

                                            string[][] items = listView1.Items
                                                        .OfType<ListViewItem>()
                                                        .Select(lvi => lvi.SubItems
                                                            .OfType<ListViewItem.ListViewSubItem>()
                                                            .Select(si => si.Text).ToArray()).ToArray();

                                            string table = string.Join(",", headers) + Environment.NewLine;
                                            foreach (string[] a in items)
                                            {
                                                //a = a_loopVariable;
                                                table += string.Join(",", a) + Environment.NewLine;
                                            }
                                            table = table.TrimEnd('\r', '\n');
                                            File.WriteAllText(sfd.FileName, table);

                                            #region save to database
                                            //--- save to database-data Table

                                            try
                                            {
                                                for (int columnIndex = 0; columnIndex < listView1.Items.Count; columnIndex++)
                                                {
                                                    string Query = @"INSERT OR IGNORE INTO data (primaryKey,Item,ID,DateTime,Sys,Dia,Pulse,AFIB) VALUES(null,'" + listView1.Items[columnIndex].SubItems[0].Text + "','" + ID + "','" + listView1.Items[columnIndex].SubItems[1].Text + "','" + listView1.Items[columnIndex].SubItems[2].Text + "','" + listView1.Items[columnIndex].SubItems[3].Text + "','" + listView1.Items[columnIndex].SubItems[4].Text + "','" + listView1.Items[columnIndex].SubItems[5].Text + "' )";
                                                    DataBaseOperation.ConnectToDataBase(dbConnectionString, Query, ref sqliteCon, ref sqliteCmd);
                                                    fill_comboBox();
                                                }

                                                sqliteCon.Close();
                                            }
                                            catch (Exception ex)
                                            {
                                                MessageBox.Show(ex.Message);
                                            }
                                            #endregion

                                            //--- 紀錄是否存檔過
                                            btn_save.Enabled = false;
                                            isSave = true;
                                            //currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        }
                                    }

                                    #endregion
                                }

                            }
                            #endregion

                        }
                        else
                        {
                            //--- Initialization
                            lb_message.Text = " ";
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }
                            MessageBox.Show(res_man.GetString("mb_data", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }

                    #endregion
                }
                #endregion


                //--- 若收到user給指令後的ACK "06"

                #region DataFromDeviceCommand
                else if (String.Format("{0:X2}", args.data[2], 16) == "06")
                {
                    lb_message.Text = " ";
                    //--- initiate
                    dataCount = 0;
                    for (int i = 0; i < dataAry.Length; i++)
                    {
                        dataAry[i] = "0";
                    }

                    //#region dataDecoding
                    //DateTimeFormatInfo fmt = new DateTimeFormatInfo();
                    //if (rb_cs.Checked)
                    //    fmt = (new CultureInfo("cs")).DateTimeFormat;
                    //else if (rb_en.Checked)
                    //    fmt = (new CultureInfo("en")).DateTimeFormat;
                    //else if (rb_sk.Checked)
                    //    fmt = (new CultureInfo("sk")).DateTimeFormat;
                    //#region dataDecoding
                    //GetByteNeedReceive(args.data);

                    ////--- 2. data receive finish (Command 22)
                    //if (dataCount == 92)
                    //{
                    //    //--- pulse >200:high, <40:Low
                    //    bool pulseHighOrLow = false;

                    //    //--- Decoding: 1. checksum
                    //    if (CheckSum(dataAry))
                    //    {
                    //        //--- decoding
                    //        listView1.BeginUpdate();
                    //        int afibCount = 0;
                    //        bool repeatData = false;

                    //        for (int i = 2; i <= 4; i++)
                    //        {
                    //            #region year Month Day Hour Minute Afib?
                    //            int year = Convert.ToInt32(dataAry[33 + (14 * (i - 1))], 16);
                    //            int month = Convert.ToInt32(dataAry[34 + (14 * (i - 1))], 16);
                    //            int day = Convert.ToInt32(dataAry[35 + (14 * (i - 1))], 16);
                    //            int hour = Convert.ToInt32(dataAry[36 + (14 * (i - 1))], 16);
                    //            int minute = Convert.ToInt32(dataAry[37 + (14 * (i - 1))], 16);
                    //            string afibSymbol = String.Empty;

                    //            if (Convert.ToInt32(dataAry[38 + (14 * (i - 1))], 16) == 49 || Convert.ToInt32(dataAry[38 + (14 * (i - 1))], 16) == 48)
                    //            { }
                    //            else
                    //            {
                    //                afibSymbol = "\u25CF";
                    //                afibCount++;
                    //            }

                    //            #endregion

                    //            #region Pulse
                    //            int pulse = Convert.ToInt32(dataAry[42 + (14 * (i - 1))], 16);
                    //            string pulseStr = pulse.ToString();
                    //            #endregion

                    //            #region Diastole
                    //            int diastole = Convert.ToInt32(dataAry[43 + (14 * (i - 1))], 16);
                    //            #endregion

                    //            #region Systole
                    //            int systole = Convert.ToInt32(dataAry[44 + (14 * (i - 1))], 16);
                    //            #endregion

                    //            //--- data sum
                    //            pulseSum += pulse;
                    //            diastoleSum += diastole;
                    //            systoleSum += systole;

                    //            #region dateFormat
                    //            string yearStr = "20" + year;
                    //            year = Convert.ToInt32(yearStr);
                    //            DateTime thisDate = new DateTime(year, month, day);
                    //            //--- 取得目前cul

                    //            string realDateTime = thisDate.ToString("d", fmt).Replace(" ", "") + " " + String.Format("{0:00}:{1:00}", hour, minute);

                    //            #endregion

                    //            //--- pulse >200:high, <40:Low
                    //            if (pulse > 200)
                    //            {
                    //                pulseStr = "High";
                    //                pulseHighOrLow = true;
                    //            }
                    //            else if (pulse < 40)
                    //            {
                    //                pulseStr = "Low";
                    //                pulseHighOrLow = true;
                    //            }
                    //            #region listViewShowNowData
                    //            ListViewItem dataList = new ListViewItem("" + (i - 1));
                    //            //ListViewItem item = listView1.FindItemWithText(realDateTime);
                    //            //if (listView1.FindItemWithText(realDateTime) == null)
                    //            //{
                    //            dataList.SubItems.Add(realDateTime);
                    //            dataList.SubItems.Add("" + systole);
                    //            dataList.SubItems.Add("" + diastole);
                    //            dataList.SubItems.Add("" + pulseStr);
                    //            dataList.SubItems.Add("" + afibSymbol);
                    //            listView1.Items.Add(dataList);
                    //            //}
                    //            //else
                    //            //    repeatData = true;

                    //            #endregion

                    //        }

                    //        //--- Avg save to database-data Table
                    //        var systoleAvg = Math.Round(systoleSum / 3.0);
                    //        var diastoleAvg = Math.Round(diastoleSum / 3.0);
                    //        //--- pulse >200:high, <40:Low
                    //        string pulseStrAvg;
                    //        if (pulseHighOrLow)
                    //            pulseStrAvg = "---";
                    //        else
                    //            pulseStrAvg = Math.Round(pulseSum / 3.0).ToString();
                    //        //--- Afib
                    //        string afibSymbolAvg = String.Empty;
                    //        if (afibCount >= 2)
                    //            afibSymbolAvg = "\u25CF";
                    //        #region listViewShowNowData
                    //        //if (repeatData)
                    //        //{ listView1.EndUpdate(); repeatData = false; }
                    //        //else
                    //        //{
                    //        ListViewItem avg = new ListViewItem("avg");

                    //        avg.SubItems.Add("" + DateTime.Now.ToString("d", fmt) + " " + DateTime.Now.ToString("HH:mm", fmt));
                    //        avg.SubItems.Add("" + systoleAvg);
                    //        avg.SubItems.Add("" + diastoleAvg);
                    //        avg.SubItems.Add("" + pulseStrAvg);
                    //        avg.SubItems.Add(afibSymbolAvg);
                    //        listView1.Items.Add(avg);
                    //        listView1.EndUpdate();
                    //        btn_save.Enabled = true;
                    //        //}

                    //        #endregion


                    //        systoleSum = diastoleSum = pulseSum = 0;    //initialize


                    //        btn_clrID.Enabled = true;
                    //        //---cul can't change
                    //        LangCanNotChoose();
                    //    }
                    //    else
                    //    {
                    //        lb_message.Text = " ";
                    //        dataCount = 0;
                    //        for (int i = 0; i < dataAry.Length; i++)
                    //        {
                    //            dataAry[i] = "0";
                    //        }
                    //        MessageBox.Show(res_man.GetString("mb_data", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //    }
                    //    //lb_message.Text = "Data error!";

                    //    //--- Initialization
                    //    lb_message.Text = " ";
                    //    dataCount = 0;
                    //    for (int i = 0; i < dataAry.Length; i++)
                    //    {
                    //        dataAry[i] = "0";
                    //    }
                    //    //dataAry[0] = "0";
                    //    //dataAry[1] = "0";
                    //}
                    //else if (dataCount > 92)
                    //{
                    //    //--- Initialization
                    //    lb_message.Text = " ";
                    //    dataCount = 0;
                    //    for (int i = 0; i < dataAry.Length; i++)
                    //    {
                    //        dataAry[i] = "0";
                    //    }
                    //}

                    //#endregion
                    //#endregion
                }
                //else if (dataAry[0] == "06")
                //{
                //    DateTimeFormatInfo fmt = new DateTimeFormatInfo();
                //    if (rb_cs.Checked)
                //        fmt = (new CultureInfo("cs")).DateTimeFormat;
                //    else if (rb_en.Checked)
                //        fmt = (new CultureInfo("en")).DateTimeFormat;
                //    else if (rb_sk.Checked)
                //        fmt = (new CultureInfo("sk")).DateTimeFormat;
                //    #region dataDecoding
                //    GetByteNeedReceive(args.data);
                //    if (dataAry[1] == "30")
                //    {
                //        //--- 2. data receive finish (Command 22)
                //        if (dataCount == 92)
                //        {
                //            //--- pulse >200:high, <40:Low
                //            bool pulseHighOrLow = false;

                //            //--- Decoding: 1. checksum
                //            if (CheckSum(dataAry))
                //            {
                //                //--- decoding
                //                listView1.BeginUpdate();
                //                int afibCount = 0;
                //                bool repeatData = false;

                //                for (int i = 2; i <= 4; i++)
                //                {
                //                    #region year Month Day Hour Minute Afib?
                //                    int year = Convert.ToInt32(dataAry[33 + (14 * (i - 1))], 16);
                //                    int month = Convert.ToInt32(dataAry[34 + (14 * (i - 1))], 16);
                //                    int day = Convert.ToInt32(dataAry[35 + (14 * (i - 1))], 16);
                //                    int hour = Convert.ToInt32(dataAry[36 + (14 * (i - 1))], 16);
                //                    int minute = Convert.ToInt32(dataAry[37 + (14 * (i - 1))], 16);
                //                    string afibSymbol = String.Empty;

                //                    if (Convert.ToInt32(dataAry[38 + (14 * (i - 1))], 16) == 49 || Convert.ToInt32(dataAry[38 + (14 * (i - 1))], 16) == 48)
                //                    { }
                //                    else
                //                    {
                //                        afibSymbol = "\u25CF";
                //                        afibCount++;
                //                    }

                //                    #endregion

                //                    #region Pulse
                //                    int pulse = Convert.ToInt32(dataAry[42 + (14 * (i - 1))], 16);
                //                    string pulseStr = pulse.ToString();
                //                    #endregion

                //                    #region Diastole
                //                    int diastole = Convert.ToInt32(dataAry[43 + (14 * (i - 1))], 16);
                //                    #endregion

                //                    #region Systole
                //                    int systole = Convert.ToInt32(dataAry[44 + (14 * (i - 1))], 16);
                //                    #endregion

                //                    //--- data sum
                //                    pulseSum += pulse;
                //                    diastoleSum += diastole;
                //                    systoleSum += systole;

                //                    #region dateFormat
                //                    string yearStr = "20" + year;
                //                    year = Convert.ToInt32(yearStr);
                //                    DateTime thisDate = new DateTime(year, month, day);
                //                    //--- 取得目前cul

                //                    string realDateTime = thisDate.ToString("d", fmt).Replace(" ", "") + " " + String.Format("{0:00}:{1:00}", hour, minute);

                //                    #endregion

                //                    //--- pulse >200:high, <40:Low
                //                    if (pulse > 200)
                //                    {
                //                        pulseStr = "High";
                //                        pulseHighOrLow = true;
                //                    }
                //                    else if (pulse < 40)
                //                    {
                //                        pulseStr = "Low";
                //                        pulseHighOrLow = true;
                //                    }
                //                    #region listViewShowNowData
                //                    ListViewItem dataList = new ListViewItem("" + (i - 1));
                //                    //ListViewItem item = listView1.FindItemWithText(realDateTime);
                //                    //if (listView1.FindItemWithText(realDateTime) == null)
                //                    //{
                //                    dataList.SubItems.Add(realDateTime);
                //                    dataList.SubItems.Add("" + systole);
                //                    dataList.SubItems.Add("" + diastole);
                //                    dataList.SubItems.Add("" + pulseStr);
                //                    dataList.SubItems.Add("" + afibSymbol);
                //                    listView1.Items.Add(dataList);
                //                    //}
                //                    //else
                //                    //    repeatData = true;

                //                    #endregion

                //                }

                //                //--- Avg save to database-data Table
                //                var systoleAvg = Math.Round(systoleSum / 3.0);
                //                var diastoleAvg = Math.Round(diastoleSum / 3.0);
                //                //--- pulse >200:high, <40:Low
                //                string pulseStrAvg;
                //                if (pulseHighOrLow)
                //                    pulseStrAvg = "---";
                //                else
                //                    pulseStrAvg = Math.Round(pulseSum / 3.0).ToString();
                //                //--- Afib
                //                string afibSymbolAvg = String.Empty;
                //                if (afibCount >= 2)
                //                    afibSymbolAvg = "\u25CF";
                //                #region listViewShowNowData
                //                //if (repeatData)
                //                //{ listView1.EndUpdate(); repeatData = false; }
                //                //else
                //                //{
                //                ListViewItem avg = new ListViewItem("avg");

                //                avg.SubItems.Add("" + DateTime.Now.ToString("d", fmt) + " " + DateTime.Now.ToString("HH:mm", fmt));
                //                avg.SubItems.Add("" + systoleAvg);
                //                avg.SubItems.Add("" + diastoleAvg);
                //                avg.SubItems.Add("" + pulseStrAvg);
                //                avg.SubItems.Add(afibSymbolAvg);
                //                listView1.Items.Add(avg);
                //                listView1.EndUpdate();
                //                btn_save.Enabled = true;
                //                //}

                //                #endregion


                //                systoleSum = diastoleSum = pulseSum = 0;    //initialize


                //                btn_clrID.Enabled = true;
                //                //---cul can't change
                //                LangCanNotChoose();
                //            }
                //            else
                //            {
                //                lb_message.Text = " ";
                //                dataCount = 0;
                //                for (int i = 0; i < dataAry.Length; i++)
                //                {
                //                    dataAry[i] = "0";
                //                }
                //                MessageBox.Show(res_man.GetString("mb_data", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //            }
                //            //lb_message.Text = "Data error!";

                //            //--- Initialization
                //            lb_message.Text = " ";
                //            dataCount = 0;
                //            for (int i = 0; i < dataAry.Length; i++)
                //            {
                //                dataAry[i] = "0";
                //            }
                //            //dataAry[0] = "0";
                //            //dataAry[1] = "0";
                //        }
                //        else if (dataCount > 92)
                //        {
                //            //--- Initialization
                //            lb_message.Text = " ";
                //            dataCount = 0;
                //            for (int i = 0; i < dataAry.Length; i++)
                //            {
                //                dataAry[i] = "0";
                //            }
                //        }
                //    }
                //    else
                //    {
                //        //initialtion
                //        lb_message.Text = " ";
                //        dataCount = 0;
                //        for (int i = 0; i < dataAry.Length; i++)
                //        {
                //            dataAry[i] = "0";
                //        }
                //    }
                    
                    
                //    #endregion
                //}
                #endregion
            }
        }
示例#12
0
文件: MainForm.cs 项目: tiemikn/ES770
        //Eventos
        public void DadosRecebidosDoPIC( object sender, DataRecievedEventArgs e )
        {
            if( e.data[1] == STX )
              		{
              			switch( e.data[CMD] )
              			{
              				case (byte)Comandos.INFO:
              					//atualiza o texto do botao desconectar
              					MainForm_Disconnect.Invoke( (MethodInvoker) delegate { MainForm_Disconnect.Text = "DESCONECTAR"; } );
              					//habilita o botao abrir
              					MainForm_Open_File.Invoke( (MethodInvoker) delegate { MainForm_Open_File.Enabled = true; } );

              					//Recupera as informações
              					bootInfo.Buffer = e.data;

              					this.MCUDevice = bootInfo.Device;
              					Flash.Size = bootInfo.FlashSize;
              					Eeprom.Size = bootInfo.EepromSize;

              					break;

              				case (byte)Comandos.WRITE:
              					//recupera o endereço de gravaçao atual
              					ulong pos = Flash.CurrentPos;

              					byte[] dados = new byte[32];

              					//Pega 32 bytes do buffer
              					for (int i = 0; i < 32; i++)
              					{
              						dados[i] = Flash.GetByte;
              					}

              					if( !StartProgramConfig && (pos < ArquivoHexadecimal.Bytes) && Send( Comandos.WRITE, (uint)pos, 0, dados ) )
              					{
              						MainForm_Progress.PerformStep();
              						this.ProgramStatus = "Gravando..." + (MainForm_Progress.Value * 100 / MainForm_Progress.Maximum).ToString() + "%";
              					}
              					else if( !StartProgramConfig )
              					{
              						if( Send( Comandos.WRITE, (bootInfo.BootStart-32), 28, StartProgramFunc ) )
              						{
              							StartProgramConfig = true;
              							MainForm_Progress.PerformStep();
              						}
              					}
              					else
              					{
              						this.ProgramStatus = "Gravação...100%";
              						Send( Comandos.REBOOT, 0, 0, null );
              					}
              					break;

              				case (byte)Comandos.ERASE:
              					this.ProgramStatus = "Memória Flash apagada";
              					Flash.CurrentPos = 0;
              					if( Send( Comandos.WRITE, 0, 0, null ) )
              					{
              						this.ProgramStatus = "Iniciando gravação...";
              						this.ProgramStatus = "Gravando...0%";
              					}
              					break;

              				case (byte)Comandos.REBOOT:
              					this.ProgramStatus = "Reset...";
              					MainForm_Progress.Value = 0;
              					this.ProgramStatus = "";
              					break;
              			}
              		}
        }
示例#13
0
文件: Sniffer.cs 项目: suan/mirlite
        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {

                string recData = "Data: ";
                bool allAreZeros = true;
                foreach (byte myData in args.data)
                {
                    if (myData != 0) allAreZeros = false;
                    var str = string.Format("{0:X} ", myData);
                    if( str.Length == 2 ) str = "0" + str;
                    recData += str;
                }
                if( !allAreZeros ) this.lb_read.Items.Insert(0, recData);
            }
        }
        protected void SpecifiedDevice_DataRecieved(object aSender, DataRecievedEventArgs aData)
        {
            //Firing
            //0 128
            //0 0
            //0 128
            //0 0
            // This occurs at fire - first one at end of prime?
            bool xTriggerLimitReachedEvent = false;

            var xData = aData.data;
            if (xData.Length != 9)
            {
                return;
            }
            if (true) DebugReceivedData(xData);

            HorizDir xHorizDir = CurrentMotion.Horizontal;
            VertDir xVertDir = CurrentMotion.Vertical;

            // Check for vertical status
            int xVertStatus = xData[1];
            if (xVertStatus == 64)
            {
                CurrentPosition.mVertical = VertPos.DownLimit;
                // Dont combine this with:
                // if (xVertStatus == 64) {
                // else when its first run and Vertical = unknown, it can allow a quick move
                if (CurrentMotion.Vertical == VertDir.Down)
                {
                    xTriggerLimitReachedEvent = true;
                    xVertDir = VertDir.None;
                }
            }
            else if (xVertStatus == 128)
            {
                CurrentPosition.mVertical = VertPos.UpLimit;
                if (CurrentMotion.Vertical == VertDir.Up)
                {
                    xTriggerLimitReachedEvent = true;
                    xVertDir = VertDir.None;
                }
            }
            else if (xVertStatus == 0)
            {
                // Don't rely on else alone - above checks also check direction, else alone will cause bug
                // Old ifs used to read:
                // } else if (xVertStatus == 128 && CurrentMotion.Vertical == VertDir.Up) {
                // But could fall through to here if starting (ie no direction) and then allow cracking of gears
                // Should not be possble now that logic has changed, however 0 is the only valid value for middle
                // and we should stick to that and not assume any value can be middle.
                CurrentPosition.mVertical = VertPos.Middle;
            }

            // Check for horiontal status
            int xHorizStatus = xData[2] & 15; // Important - Fire sets bit and can be combined (tested)
            if (xHorizStatus == 4)
            {
                CurrentPosition.mHorizontal = HorizPos.LeftLimit;
                if (CurrentMotion.Horizontal == HorizDir.Left)
                {
                    xTriggerLimitReachedEvent = true;
                    xHorizDir = HorizDir.None;
                }
            }
            else if (xHorizStatus == 8)
            {
                CurrentPosition.mHorizontal = HorizPos.RightLimit;
                if (CurrentMotion.Horizontal == HorizDir.Right)
                {
                    xTriggerLimitReachedEvent = true;
                    xHorizDir = HorizDir.None;
                }
            }
            else if (xHorizStatus == 0)
            {
                CurrentPosition.mHorizontal = HorizPos.Middle;
            }

            // Program can start up as 0 128 if shut down that way!
            // Because of this we need to check previous as well.
            if (mLastData[2] > 127 && xData[2] < 127)
            {
                OnMissileFired();
                if (mFiringAutoStop)
                {
                    StopFiring();
                }
            }

            // Take comiled directions, and if they are different than current motions, modify them
            if (xHorizDir != CurrentMotion.Horizontal || xVertDir != CurrentMotion.Vertical)
            {
                Move(xHorizDir, xVertDir, CurrentMotion.Speed);
            }

            if (xTriggerLimitReachedEvent)
            {
                OnLimitReached();
            }

            xData.CopyTo(mLastData, 0);
        }
 private void UsbOnDataRecieved(object sender, DataRecievedEventArgs args)
 {
     // Gets byte with the info about which buttons/pads/pedals are down
     if (args.data.GetLength(0) == 28)
     {
         //byte[] test = new byte[28] { 0, 0, 0, 8, 127, 127, 127, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 2, 0 };
         HandleDPad(args.data);
         HandleButtons(args.data);
         if (args.data[1] > 0)
         {
             if (args.data[2] != 0)
                 TriggerNotes(args.data[1], args.data[2], args.data[3], args.data, 12);
         }
     }
     else
     {
         Debug.Assert(false, "Length detected != 28");
     }
 }
示例#16
0
        int setTimeCount = 0; // 判斷有無設定過時間
        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                string rec_data = String.Empty;
                for (int i = 1; i < args.data.Length; i++)
                {
                    rec_data += String.Format("{0:X2}", args.data[i]) + " ";
                }
                string result;
                result = String.Format("{0:X2}", args.data[2], 16);
                //--- 若收到機器端的MAP訊號,進行awake 49h 44h
                #region MAP
                //if (String.Format("{0:X2}", args.data[2], 16) == "49" && String.Format("{0:X2}", args.data[3], 16) == "44")
                //{
                //    lb_message.Text = res_man.GetString("lb_map", cul);
                //    AllCanNotAct();
                //    #region awake command
                //    Thread.Sleep(1000);

                //    HIDWriteCommand(7, 0x12, 0x16, 0x18, 0x21, 0x00, 0x00, 0x00);
                //    Thread.Sleep(100);

                //    //--- 確認device的時間是否跟系統一樣
                //    HIDWriteCommand(4, 0x12, 0x16, 0x18, 0x26, 0x00, 0x00, 0x00);  // read the device time and date
                //    Thread.Sleep(100);
                //    #endregion
                //}
                #endregion

                //--- 若收到Error 的 Header 1st
                #region Measure Error
                if (String.Format("{0:X2}", args.data[2], 16) == "45"/* && String.Format("{0:X2}", args.data[3], 16) == "72"*/)
                {
                    #region decodingError
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);
                    if (dataCount > 8)
                    {
                        switch (dataAry[2])
                        {
                            case "01":
                                lb_message.Text = res_man.GetString("err1", cul);
                                break;
                            case "02":
                                lb_message.Text = res_man.GetString("err2", cul);
                                break;
                            case "03":
                                lb_message.Text = res_man.GetString("err3", cul);
                                break;
                            case "05":
                                lb_message.Text = res_man.GetString("err5", cul);
                                break;
                            case "42":
                                lb_message.Text = res_man.GetString("errB", cul);
                                break;
                        }
                        //--- Initialization
                        dataCount = 0;
                        for (int i = 0; i < dataAry.Length; i++)
                        {
                            dataAry[i] = "0";
                        }
                    }
                    #endregion
                }
                else if (dataAry[0] == "45"/* && dataAry[1] == "72"*/)
                {
                    #region decodingError 
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);

                    //--- Decoding
                    /********************************************************
                     dataAry[2] = n
                     n = 0x01: Signals is too weak
                       = 0x02: Error signal
                       = 0x03: No pressure in the cuff
                       = 0x05: Abnormal result
                       = 0x42: Low battery   
                    *********************************************************/
                    if (dataCount > 8)
                    {
                        switch (dataAry[2])
                        {
                            case "01":
                                lb_message.Text = res_man.GetString("err1", cul);
                                break;
                            case "02":
                                lb_message.Text = res_man.GetString("err2", cul);
                                break;
                            case "03":
                                lb_message.Text = res_man.GetString("err3", cul);
                                break;
                            case "05":
                                lb_message.Text = res_man.GetString("err5", cul);
                                break;
                            case "42":
                                lb_message.Text = res_man.GetString("errB", cul);
                                break;
                        }
                        //--- Initialization
                        dataCount = 0;
                        for (int i = 0; i < dataAry.Length; i++)
                        {
                            dataAry[i] = "0";
                        }
                    }

                    #endregion
                }
                #endregion

                //--- 若收到AutoSend 的 Header 1st
                #region AutoSend data
                else if (String.Format("{0:X2}", args.data[2], 16) == "4D")
                {
                    DateTimeFormatInfo fmt = new DateTimeFormatInfo();
                    if (rb_cs.Checked)
                        fmt = (new CultureInfo("cs")).DateTimeFormat;
                    else if (rb_en.Checked)
                        fmt = (new CultureInfo("en")).DateTimeFormat;
                    else if (rb_sk.Checked)
                        fmt = (new CultureInfo("sk")).DateTimeFormat;
                    GetByteNeedReceive(args.data);
                }
                else if (dataAry[0] == "4D")
                {
                    DateTimeFormatInfo fmt = new DateTimeFormatInfo();
                    if (rb_cs.Checked)
                        fmt = (new CultureInfo("cs")).DateTimeFormat;
                    else if (rb_en.Checked)
                        fmt = (new CultureInfo("en")).DateTimeFormat;
                    else if (rb_sk.Checked)
                        fmt = (new CultureInfo("sk")).DateTimeFormat;
                    #region AutoSend decoding 
                    //--- 1. Compare data[1] = F'N'
                    GetByteNeedReceive(args.data);
                    //--- 2. Confrim n = args.data[4]*256 + args.data[5], save to dataAry[n]
                    string dataSizeH = dataAry[2];
                    string dataSizeL = dataAry[3];
                    int dataSize = Convert.ToInt32(dataSizeH, 16) * 256 + Convert.ToInt32(dataSizeL, 16);

                    if (dataCount > dataSize)
                    {
                        //--- check CRC
                        if (CRC(dataAry))
                        {
                            float dataNumber = 0;
                            //--- check data number
                            if (dataSize == 27)
                                dataNumber = 1;
                            else
                                dataNumber = 3;

                            int afibCount = 0;
                            //--- pulse >200:high, <40:Low
                            bool pulseHighOrLow = false;

                            listView1.BeginUpdate();
                            for (int i = 1; i <= dataNumber; i++)
                            {
                                #region systole
                                int systole = Convert.ToInt32(dataAry[19 + (8 * (i - 1))], 16);
                                #endregion
                                #region diastole
                                int diastole = Convert.ToInt32(dataAry[20 + (8 * (i - 1))], 16);
                                #endregion
                                #region pulse
                                int pulse = Convert.ToInt32(dataAry[21 + (8 * (i - 1))], 16);
                                string pulseStr = pulse.ToString();
                                #endregion

                                string MonthStr = String.Empty;
                                string HourStr = String.Empty;
                                string DayStr = String.Empty;
                                string YearStr = String.Empty;
                                //--- Convert every data to byteString
                                string month0Day = byteTransform.To8bit(byteTransform.byteToString(dataAry[22 + 8 * (i - 1)]));
                                string month1Hour = byteTransform.To8bit(byteTransform.byteToString(dataAry[23 + 8 * (i - 1)]));
                                string AsArrYear = byteTransform.To8bit(byteTransform.byteToString(dataAry[25 + 8 * (i - 1)]));

                                #region Day
                                //--- Day b5-b0
                                for (int j = 2; j < 8; j++)
                                {
                                    DayStr += month0Day[j];
                                }
                                //--- DayStr -> bytes
                                int day = Convert.ToByte(DayStr, 2);
                                #endregion

                                #region Month
                                //--- Month 取 b7 b6
                                for (int j = 0; j < 2; j++)
                                {
                                    MonthStr += month1Hour[j];
                                }
                                for (int j = 0; j < 2; j++)
                                {
                                    MonthStr += month0Day[j];
                                }
                                int month = Convert.ToByte(MonthStr, 2);
                                #endregion

                                #region Hour
                                for (int j = 2; j < 8; j++)
                                {
                                    HourStr += month1Hour[j];
                                }
                                int hour = Convert.ToByte(HourStr, 2);
                                #endregion

                                #region Minutes
                                Int32 minutes = Convert.ToInt32(dataAry[24 + 8 * (i - 1)], 16);
                                #endregion

                                #region Arr Year
                                //--- Arr
                                string Afib = String.Empty;
                                if (AsArrYear[1] != '0')
                                {
                                    //Afib = res_man.GetString("AFIB", cul);
                                    //Afib = "\u25CF";
                                    Afib = "\u25CF";
                                    afibCount++;
                                }

                                //--- year
                                for (int j = 2; j < 8; j++)
                                {
                                    YearStr += AsArrYear[j];
                                }
                                int year = Convert.ToByte(YearStr, 2);
                                #endregion

                                //--- data sum

                                pulseSum += pulse;
                                diastoleSum += diastole;
                                systoleSum += systole;

                                #region dateFormat
                                string yearStr = "20" + year;
                                year = Convert.ToInt32(yearStr);
                                DateTime thisDate = new DateTime(year, month, day);
                                //--- 取得目前cul
                                string realDateTime = thisDate.ToString("d", fmt).Replace(" ", "") + " " + String.Format("{0:00}:{1:00}", hour, minutes);
                                #endregion

                                //--- pulse >200:high, <40:Low
                                if (pulse > 200)
                                {
                                    pulseStr = "High";
                                    pulseHighOrLow = true;
                                }
                                else if (pulse < 40)
                                {
                                    pulseStr = "Low";
                                    pulseHighOrLow = true;
                                }

                                #region listViewShowNowData
                                ListViewItem dataList = new ListViewItem("" + i);
                                dataList.SubItems.Add(realDateTime);
                                dataList.SubItems.Add("" + systole);
                                dataList.SubItems.Add("" + diastole);
                                dataList.SubItems.Add("" + pulseStr);
                                dataList.SubItems.Add("" + Afib);
                                listView1.Items.Add(dataList);
                                #endregion

                                btn_clrID.Enabled = true;
                                btn_save.Enabled = true;
                                lb_message.Text = " ";
                                //---cul can't change
                                LangCanNotChoose();
                            }
                            if (dataNumber == 3)
                            {
                                //--- Avg save to database-data Table
                                var systoleAvg = Math.Round(systoleSum / 3.0);
                                var diastoleAvg = Math.Round(diastoleSum / 3.0);
                                //--- pulse >200:high, <40:Low
                                string pulseStrAvg;
                                if (pulseHighOrLow)
                                    pulseStrAvg = "---";
                                else
                                    pulseStrAvg = Math.Round(pulseSum / 3.0).ToString();
                                //--- Afib
                                string afibSymbolAvg = String.Empty;
                                if (afibCount >= 2)
                                    afibSymbolAvg = "\u25CF";

                                #region listViewShowNowData
                                ListViewItem avg = new ListViewItem("avg");
                                avg.SubItems.Add("");
                                //avg.SubItems.Add("" + DateTime.Now.ToString("d", fmt) + " " + DateTime.Now.ToString("HH:mm", fmt));
                                avg.SubItems.Add("" + systoleAvg);
                                avg.SubItems.Add("" + diastoleAvg);
                                avg.SubItems.Add("" + pulseStrAvg);
                                avg.SubItems.Add(afibSymbolAvg);
                                listView1.Items.Add(avg);
                                #endregion      
                            }
                            listView1.EndUpdate();
                            systoleSum = diastoleSum = pulseSum = 0;    //initialize

                            //--- Initialization
                            lb_message.Text = " ";
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }


                            #region Measure Finish
                            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                            DialogResult dialogResult;
                            dialogResult = MessageBox.Show(res_man.GetString("mb_finish", cul) + "\n" + res_man.GetString("mb_save", cul), "WatchBP Analyzer Office Basic", buttons, MessageBoxIcon.Question);
                            if (dialogResult == DialogResult.Yes)
                            {
                                if (string.IsNullOrWhiteSpace(tb_ID.Text))
                                {
                                    MessageBox.Show(res_man.GetString("noID", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                else if (!((new System.Text.RegularExpressions.Regex("^[A-Za-z0-9]+$")).IsMatch(tb_ID.Text)))
                                {
                                    MessageBox.Show(res_man.GetString("mb_IDinform", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                else
                                {
                                    #region listView export to CSV
                                    //declare new SaveFileDialog + set it's initial properties
                                    string path = System.AppDomain.CurrentDomain.BaseDirectory + @"WatchBP\OfficeBasic";

                                    try
                                    {
                                        // Determine whether the directory exists.
                                        if (!Directory.Exists(path))
                                        {
                                            // Try to create the directory.
                                            DirectoryInfo di = Directory.CreateDirectory(path);
                                        }
                                        string ID = tb_ID.Text.Replace(" ", "");
                                        if (!File.Exists(path + "\\" + DetermineFileName(ID) + ".csv"))
                                        {
                                            string Path = res_man.GetString("mb_path", cul) + " " + path;
                                            MessageBox.Show("ID: " + ID + "\n" + Path, "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            StreamWriter sw = new StreamWriter(new FileStream(path + "\\" + DetermineFileName(ID) + ".csv", FileMode.Create), Encoding.UTF8);

                                            string[] headers = listView1.Columns
                                                        .OfType<ColumnHeader>()
                                                        .Select(header => header.Text.Trim())
                                                        .ToArray();

                                            string[][] items = listView1.Items
                                                        .OfType<ListViewItem>()
                                                        .Select(lvi => lvi.SubItems
                                                            .OfType<ListViewItem.ListViewSubItem>()
                                                            .Select(si => si.Text).ToArray()).ToArray();

                                            string table = string.Join(",", headers) + Environment.NewLine;
                                            foreach (string[] a in items)
                                            {
                                                //a = a_loopVariable;
                                                table += string.Join(",", a) + Environment.NewLine;
                                            }
                                            table = table.TrimEnd('\r', '\n');
                                            sw.Write(table);
                                            sw.Close();

                                            //--- 紀錄是否存檔過
                                            btn_save.Enabled = false;
                                            isSave = true;
                                            //currentFileName = path + "\\" + DetermineFileName(ID) + ".csv";
                                        }
                                    }
                                    catch
                                    {
                                        MessageBox.Show(res_man.GetString("mb_permission", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        string ID = tb_ID.Text.Replace(" ", "");
                                        SaveFileDialog sfd = new SaveFileDialog
                                        {
                                            Title = "Choose file to save to",
                                            FileName = DetermineFileName(ID),
                                            Filter = "CSV (*.csv)|*.csv",
                                            FilterIndex = 0,
                                            InitialDirectory = path
                                            //InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                                        };
                                        if (sfd.ShowDialog() == DialogResult.OK)
                                        {

                                            string[] headers = listView1.Columns
                                                        .OfType<ColumnHeader>()
                                                        .Select(header => header.Text.Trim())
                                                        .ToArray();

                                            string[][] items = listView1.Items
                                                        .OfType<ListViewItem>()
                                                        .Select(lvi => lvi.SubItems
                                                            .OfType<ListViewItem.ListViewSubItem>()
                                                            .Select(si => si.Text).ToArray()).ToArray();

                                            string table = string.Join(",", headers) + Environment.NewLine;
                                            foreach (string[] a in items)
                                            {
                                                //a = a_loopVariable;
                                                table += string.Join(",", a) + Environment.NewLine;
                                            }
                                            table = table.TrimEnd('\r', '\n');
                                            File.WriteAllText(sfd.FileName, table);

                                            //--- 紀錄是否存檔過
                                            btn_save.Enabled = false;
                                            isSave = true;
                                        }
                                    }

                                    #endregion
                                }

                            }
                            #endregion

                        }
                        else
                        {
                            //--- Initialization
                            lb_message.Text = " ";
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }
                            MessageBox.Show(res_man.GetString("mb_data", cul), "WatchBP Analyzer Office Basic", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }

                    #endregion
                }
                #endregion


                //--- 若收到user給指令後的ACK "06"
                /*****************************************************************
                    1. 使用者按完MAP後傳connection指令,device會回傳ACK
                ******************************************************************/
                #region DataReceive
                else if (result == "06")
                {
                    GetByteNeedReceive(args.data);
                }   
                else if (dataAry[0] == "06")
                {
                    DateTime nowTime = DateTime.Now;

                    GetByteNeedReceive(args.data);

                    #region read the device time and date
                    if (dataCount>86)
                    {
                        //--- checksum
                        if (CheckSum(dataAry))
                        {
                            setTimeCount++;
                            int i = 1;
                            string month0 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[i], 16));
                            string month1 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16)); 
                            string day0 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string day1 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string year0 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string year1 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            i = i + 2;
                            string hour0 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string hour1 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string min0 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string min1 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string sec0 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));
                            string sec1 = Char.ConvertFromUtf32(Convert.ToInt32(dataAry[++i], 16));

                            string month = month0 + month1;
                            string day = day0 + day1;
                            string year = "20"+year0 + year1;
                            string hour = hour0 + hour1;
                            string min = min0 + min1;
                            string sec = sec0 + sec1;

                            DateTime thisDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day), Convert.ToInt32(hour), Convert.ToInt32(min), Convert.ToInt32(sec));

                            //--- Initialization
                            dataCount = 0;
                            for (int j = 0; j < dataAry.Length; j++)
                            {
                                dataAry[j] = "0";
                            }

                            //--- 若device時間與PC不同強制同步
                            if (nowTime.ToShortDateString() != thisDate.ToShortDateString())
                            {
                                setTime = true;
                                HIDWriteCommand(4, 0x12, 0x16, 0x18, 0x27, 0x00, 0x00, 0x00);
                                Thread.Sleep(100);
                            }
                            else
                            {
                                if (nowTime.ToShortTimeString() != thisDate.ToShortTimeString())
                                {
                                    setTime = true;
                                    HIDWriteCommand(4, 0x12, 0x16, 0x18, 0x27, 0x00, 0x00, 0x00);
                                    Thread.Sleep(100);
                                }
                                else
                                {                                 
                                    lb_message.Text = "";
                                    AllCanAct();
                                }
                                    

                            }
                        }
                        else
                        {
                            //--- Initialization
                            dataCount = 0;
                            for (int i = 0; i < dataAry.Length; i++)
                            {
                                dataAry[i] = "0";
                            }
                            //MessageBox.Show(res_man.GetString("mb_data",cul));
                        }
                    }
                    
                    #endregion
                    
                    //#region DataFromDeviceCommand
                    //else if (String.Format("{0:X2}", args.data[2], 16) == "06")
                    //{
                    //    lb_message.Text = " ";
                    //    //--- initiate
                    //    dataCount = 0;
                    //    for (int i = 0; i < dataAry.Length; i++)
                    //    {
                    //        dataAry[i] = "0";
                    //    }

                    //}
                    //#endregion
                }
                #endregion

                #region time setting
                if (setTime)
                {
                    if (dataAry[0] == "06")
                    {
                        //if (setTimeCount>1)
                        //{
                        //    setTimeCount = 0;
                        //    AllCanAct();
                        //    lb_message.Text = "";

                        //    return;
                        //}
                        //else
                        //{
                            byte[] timeSettingBuf = new byte[14];
                            //--- fixed string
                            timeSettingBuf[6] = 0x32;
                            timeSettingBuf[7] = 0x30;
                            //---

                            #region 得到系統時間並轉成byte[]
                            string yearTemp = DateTime.Now.Year.ToString();     // ex.2016
                            char[] yearChar = yearTemp.ToCharArray();
                            byte year0 = Convert.ToByte(yearChar[2]);           // 0x31
                            byte year1 = Convert.ToByte(yearChar[3]);           // 0x36
                            timeSettingBuf[4] = year0;
                            timeSettingBuf[5] = year1;

                            string monthTemp = String.Format("{0:00}", DateTime.Now.Month);
                            char[] monthChar = monthTemp.ToCharArray();
                            byte month0 = Convert.ToByte(monthChar[0]);
                            byte month1 = Convert.ToByte(monthChar[1]);
                            timeSettingBuf[0] = month0;
                            timeSettingBuf[1] = month1;

                            string dayTemp = String.Format("{0:00}", DateTime.Now.Day);
                            char[] dayChar = dayTemp.ToCharArray();
                            byte day0 = Convert.ToByte(dayChar[0]);
                            byte day1 = Convert.ToByte(dayChar[1]);
                            timeSettingBuf[2] = day0;
                            timeSettingBuf[3] = day1;

                            string hourTemp = String.Format("{0:00}", DateTime.Now.Hour);
                            char[] hourChar = hourTemp.ToCharArray();
                            byte hour0 = Convert.ToByte(hourChar[0]);
                            byte hour1 = Convert.ToByte(hourChar[1]);
                            timeSettingBuf[8] = hour0;
                            timeSettingBuf[9] = hour1;

                            string minTemp = String.Format("{0:00}", DateTime.Now.Minute);
                            char[] minChar = minTemp.ToCharArray();
                            byte min0 = Convert.ToByte(minChar[0]);
                            byte min1 = Convert.ToByte(minChar[1]);
                            timeSettingBuf[10] = min0;
                            timeSettingBuf[11] = min1;

                            string secTemp = String.Format("{0:00}", DateTime.Now.Second);
                            char[] secChar = secTemp.ToCharArray();
                            byte sec0 = Convert.ToByte(secChar[0]);
                            byte sec1 = Convert.ToByte(secChar[1]);
                            timeSettingBuf[12] = sec0;
                            timeSettingBuf[13] = sec1;
                            #endregion

                            for (int k = 0; k < 2; k++)
                            {
                                HIDWriteCommand(7, timeSettingBuf[k * 7 + 0], timeSettingBuf[k * 7 + 1], timeSettingBuf[k * 7 + 2], timeSettingBuf[k * 7 + 3],
                                        timeSettingBuf[k * 7 + 4], timeSettingBuf[k * 7 + 5], timeSettingBuf[k * 7 + 6]);
                            }

                        setTime = false;
                        //--- Initialization
                        dataCount = 0;
                        for (int i = 0; i < dataAry.Length; i++)
                        {
                            dataAry[i] = "0";
                        }

                        AllCanAct();
                        lb_message.Text = "";
                        //}
                        
                    }
                    else
                    {
                        //--- Initialization
                        dataCount = 0;
                        for (int i = 0; i < dataAry.Length; i++)
                        {
                            dataAry[i] = "0";
                        }
                    }
                }
                #endregion
            }
        }
 private void DataRecieved(object sender, DataRecievedEventArgs args)
 {
     if(this.OnDataRecieved != null){
         this.OnDataRecieved(sender, args);
     }
 }
示例#18
0
        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
                if(!paused){

                    int captureval1 = (int)((args.data[1] + args.data[2] * 256) * 0.92f);
                    int captureval2 = (int)((args.data[3] + args.data[4] * 256) * 0.92f);
                    smplcnt++;

                    if (checkBox2.Checked)
                    // filtrage moyenne mobile
                    {
                        valbuf1[bufptr] = captureval1;
                        valbuf2[bufptr] = captureval2;
                        bufptr++; if (bufptr > maxbuf) bufptr = 0;

                        float filtered1 = 0f;
                        float filtered2 = 0f;
                        for (int i = 0; i < maxbuf; i++) { filtered1 += valbuf1[i]; filtered2 += valbuf2[i]; }
                        captureval1 = (int)(filtered1 / maxbuf);
                        captureval2 = (int)(filtered2 / maxbuf);
                    }

                    display(captureval1, captureval2);
            }
        }