//***********************************************************************/
//*                                                                     */
//*     IF-60 API Sample Program                                        */
//*                                                      2014/9/2       */
//*     Copyright(c) 2012  TEXIO TECHNOLOGY CORPORATION                 */
//***********************************************************************/

#pragma once

#include "IF60_Api_m.h"

namespace PSF_Access {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace System::IO::Ports;

	/// <summary>
	/// PSF_Access の概要
	///
	/// 警告: このクラスの名前を変更する場合、このクラスが依存するすべての .resx ファイルに関連付けられた
	///          マネージ リソース コンパイラ ツールに対して 'Resource File Name' プロパティを
	///          変更する必要があります。この変更を行わないと、
	///          デザイナと、このフォームに関連付けられたローカライズ済みリソースとが、
	///          正しく相互に利用できなくなります。
	/// </summary>
	public ref class PSF_Access : public System::Windows::Forms::Form
	{
	public:
		PSF_Access(void)
		{
			InitializeComponent();
			//
			//TODO: ここにコンストラクタ コードを追加します
			//
		}

	protected:
		/// <summary>
		/// 使用中のリソースをすべてクリーンアップします。
		/// </summary>
		~PSF_Access()
		{
			if (components)
			{
				delete components;
			}
		}
	private: System::Windows::Forms::GroupBox^  groupBox1;
	protected: 
	private: System::Windows::Forms::Label^  label2;
	private: System::Windows::Forms::Label^  label1;
	private: System::Windows::Forms::ComboBox^  comboBox3;
	private: System::Windows::Forms::ComboBox^  comboBox2;
	private: System::Windows::Forms::ComboBox^  comboBox1;
	private: System::Windows::Forms::Button^  button1;
	private: System::Windows::Forms::Label^  label3;
	private: System::Windows::Forms::GroupBox^  groupBox2;
	private: System::Windows::Forms::Button^  button2;
	private: System::Windows::Forms::GroupBox^  groupBox3;
	private: System::Windows::Forms::Button^  button6;
	private: System::Windows::Forms::Button^  button5;
	private: System::Windows::Forms::Button^  button4;
	private: System::Windows::Forms::Button^  button3;
	private: System::Windows::Forms::Button^  button7;
	private: System::Windows::Forms::TextBox^  textBox1;






	private:
		/// <summary>
		/// 必要なデザイナ変数です。
		/// </summary>
		System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
		/// <summary>
		/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディタで変更しないでください。
		/// </summary>
		void InitializeComponent(void)
		{
			System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(PSF_Access::typeid));
			this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
			this->label3 = (gcnew System::Windows::Forms::Label());
			this->label2 = (gcnew System::Windows::Forms::Label());
			this->label1 = (gcnew System::Windows::Forms::Label());
			this->comboBox3 = (gcnew System::Windows::Forms::ComboBox());
			this->comboBox2 = (gcnew System::Windows::Forms::ComboBox());
			this->comboBox1 = (gcnew System::Windows::Forms::ComboBox());
			this->button1 = (gcnew System::Windows::Forms::Button());
			this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());
			this->button2 = (gcnew System::Windows::Forms::Button());
			this->groupBox3 = (gcnew System::Windows::Forms::GroupBox());
			this->button6 = (gcnew System::Windows::Forms::Button());
			this->button5 = (gcnew System::Windows::Forms::Button());
			this->button4 = (gcnew System::Windows::Forms::Button());
			this->button3 = (gcnew System::Windows::Forms::Button());
			this->button7 = (gcnew System::Windows::Forms::Button());
			this->textBox1 = (gcnew System::Windows::Forms::TextBox());
			this->groupBox1->SuspendLayout();
			this->groupBox2->SuspendLayout();
			this->groupBox3->SuspendLayout();
			this->SuspendLayout();
			// 
			// groupBox1
			// 
			this->groupBox1->Controls->Add(this->label3);
			this->groupBox1->Controls->Add(this->label2);
			this->groupBox1->Controls->Add(this->label1);
			this->groupBox1->Controls->Add(this->comboBox3);
			this->groupBox1->Controls->Add(this->comboBox2);
			this->groupBox1->Controls->Add(this->comboBox1);
			this->groupBox1->Controls->Add(this->button1);
			this->groupBox1->Location = System::Drawing::Point(12, 12);
			this->groupBox1->Name = L"groupBox1";
			this->groupBox1->Size = System::Drawing::Size(349, 64);
			this->groupBox1->TabIndex = 0;
			this->groupBox1->TabStop = false;
			this->groupBox1->Text = L"Device";
			// 
			// label3
			// 
			this->label3->AutoSize = true;
			this->label3->Location = System::Drawing::Point(271, 19);
			this->label3->Name = L"label3";
			this->label3->Size = System::Drawing::Size(62, 12);
			this->label3->TabIndex = 6;
			this->label3->Text = L"SYS_ADDR";
			// 
			// label2
			// 
			this->label2->AutoSize = true;
			this->label2->Location = System::Drawing::Point(186, 19);
			this->label2->Name = L"label2";
			this->label2->Size = System::Drawing::Size(56, 12);
			this->label2->TabIndex = 5;
			this->label2->Text = L"PC_ADDR";
			// 
			// label1
			// 
			this->label1->AutoSize = true;
			this->label1->Location = System::Drawing::Point(105, 19);
			this->label1->Name = L"label1";
			this->label1->Size = System::Drawing::Size(50, 12);
			this->label1->TabIndex = 4;
			this->label1->Text = L"Interface";
			// 
			// comboBox3
			// 
			this->comboBox3->FormattingEnabled = true;
			this->comboBox3->Location = System::Drawing::Point(273, 34);
			this->comboBox3->Name = L"comboBox3";
			this->comboBox3->Size = System::Drawing::Size(60, 20);
			this->comboBox3->TabIndex = 3;
			// 
			// comboBox2
			// 
			this->comboBox2->FormattingEnabled = true;
			this->comboBox2->Location = System::Drawing::Point(188, 34);
			this->comboBox2->Name = L"comboBox2";
			this->comboBox2->Size = System::Drawing::Size(66, 20);
			this->comboBox2->TabIndex = 2;
			// 
			// comboBox1
			// 
			this->comboBox1->FormattingEnabled = true;
			this->comboBox1->Location = System::Drawing::Point(107, 34);
			this->comboBox1->Name = L"comboBox1";
			this->comboBox1->Size = System::Drawing::Size(63, 20);
			this->comboBox1->TabIndex = 1;
			this->comboBox1->Text = L"USB";
			// 
			// button1
			// 
			this->button1->Location = System::Drawing::Point(18, 32);
			this->button1->Name = L"button1";
			this->button1->Size = System::Drawing::Size(71, 23);
			this->button1->TabIndex = 0;
			this->button1->Text = L"OPEN";
			this->button1->UseVisualStyleBackColor = true;
			this->button1->Click += gcnew System::EventHandler(this, &PSF_Access::button1_Click);
			// 
			// groupBox2
			// 
			this->groupBox2->Controls->Add(this->button2);
			this->groupBox2->Location = System::Drawing::Point(14, 82);
			this->groupBox2->Name = L"groupBox2";
			this->groupBox2->Size = System::Drawing::Size(103, 52);
			this->groupBox2->TabIndex = 1;
			this->groupBox2->TabStop = false;
			this->groupBox2->Text = L"Output";
			// 
			// button2
			// 
			this->button2->Enabled = false;
			this->button2->Location = System::Drawing::Point(17, 18);
			this->button2->Name = L"button2";
			this->button2->Size = System::Drawing::Size(70, 25);
			this->button2->TabIndex = 0;
			this->button2->Text = L"ON";
			this->button2->UseVisualStyleBackColor = true;
			this->button2->Click += gcnew System::EventHandler(this, &PSF_Access::button2_Click);
			// 
			// groupBox3
			// 
			this->groupBox3->Controls->Add(this->button6);
			this->groupBox3->Controls->Add(this->button5);
			this->groupBox3->Controls->Add(this->button4);
			this->groupBox3->Controls->Add(this->button3);
			this->groupBox3->Location = System::Drawing::Point(132, 85);
			this->groupBox3->Name = L"groupBox3";
			this->groupBox3->Size = System::Drawing::Size(229, 49);
			this->groupBox3->TabIndex = 2;
			this->groupBox3->TabStop = false;
			this->groupBox3->Text = L"Preset";
			// 
			// button6
			// 
			this->button6->Enabled = false;
			this->button6->Location = System::Drawing::Point(174, 18);
			this->button6->Name = L"button6";
			this->button6->Size = System::Drawing::Size(39, 21);
			this->button6->TabIndex = 3;
			this->button6->Text = L"OFF";
			this->button6->UseVisualStyleBackColor = true;
			this->button6->Click += gcnew System::EventHandler(this, &PSF_Access::button6_Click);
			// 
			// button5
			// 
			this->button5->Enabled = false;
			this->button5->Location = System::Drawing::Point(123, 18);
			this->button5->Name = L"button5";
			this->button5->Size = System::Drawing::Size(39, 21);
			this->button5->TabIndex = 2;
			this->button5->Text = L"3";
			this->button5->UseVisualStyleBackColor = true;
			this->button5->Click += gcnew System::EventHandler(this, &PSF_Access::button5_Click);
			// 
			// button4
			// 
			this->button4->Enabled = false;
			this->button4->Location = System::Drawing::Point(68, 18);
			this->button4->Name = L"button4";
			this->button4->Size = System::Drawing::Size(39, 21);
			this->button4->TabIndex = 1;
			this->button4->Text = L"2";
			this->button4->UseVisualStyleBackColor = true;
			this->button4->Click += gcnew System::EventHandler(this, &PSF_Access::button4_Click);
			// 
			// button3
			// 
			this->button3->Enabled = false;
			this->button3->Location = System::Drawing::Point(14, 18);
			this->button3->Name = L"button3";
			this->button3->Size = System::Drawing::Size(39, 21);
			this->button3->TabIndex = 0;
			this->button3->Text = L"1";
			this->button3->UseVisualStyleBackColor = true;
			this->button3->Click += gcnew System::EventHandler(this, &PSF_Access::button3_Click);
			// 
			// button7
			// 
			this->button7->Enabled = false;
			this->button7->Location = System::Drawing::Point(31, 148);
			this->button7->Name = L"button7";
			this->button7->Size = System::Drawing::Size(70, 27);
			this->button7->TabIndex = 3;
			this->button7->Text = L"READ";
			this->button7->UseVisualStyleBackColor = true;
			this->button7->Click += gcnew System::EventHandler(this, &PSF_Access::button7_Click);
			// 
			// textBox1
			// 
			this->textBox1->Location = System::Drawing::Point(132, 152);
			this->textBox1->Multiline = true;
			this->textBox1->Name = L"textBox1";
			this->textBox1->Size = System::Drawing::Size(229, 85);
			this->textBox1->TabIndex = 4;
			// 
			// PSF_Access
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(377, 251);
			this->Controls->Add(this->textBox1);
			this->Controls->Add(this->button7);
			this->Controls->Add(this->groupBox3);
			this->Controls->Add(this->groupBox2);
			this->Controls->Add(this->groupBox1);
			this->Icon = (cli::safe_cast<System::Drawing::Icon^  >(resources->GetObject(L"$this.Icon")));
			this->Name = L"PSF_Access";
			this->Text = L"PSF_Access";
			this->Load += gcnew System::EventHandler(this, &PSF_Access::PSF_Access_Load);
			this->FormClosing += gcnew System::Windows::Forms::FormClosingEventHandler(this, &PSF_Access::PSF_Access_FormClosing);
			this->groupBox1->ResumeLayout(false);
			this->groupBox1->PerformLayout();
			this->groupBox2->ResumeLayout(false);
			this->groupBox3->ResumeLayout(false);
			this->ResumeLayout(false);
			this->PerformLayout();

		}
#pragma endregion

		private: int DeviceId;				// オープンしたデバイスのID。
		private: int if_sel;
		private: static const int IF_USB = 1;
		private: static const int IF_GPIB0 = 2;
		private: static const int IF_COM1 = 3;

		private: SerialPort^ serialPort1;	// COM1 Object

		private: String^ SYSAddr;			// local Addr Name
		private: int PcAddr;				// PC Addr

		private: bool DeviceOpen;
		private: bool DeviceOn;

    // フォームロード
	private: System::Void PSF_Access_Load(System::Object^  sender, System::EventArgs^  e)
	{
		//System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(PSF_Access::typeid));
		//this->Icon = (System::Drawing::Icon^) resources->GetObject("PSF_Acces.ico");

        // 使用するインターフェースを選択できるようにする。
        comboBox1->Items->Add("USB");
        comboBox1->Items->Add("COM");
        comboBox1->SelectedIndex = 0;

        // PCアドレス
        for (int address = 1; address < 30; address++)
        {
            comboBox2->Items->Add(address.ToString());
        }
        comboBox2->SelectedIndex = 0;

        // システムアドレス
        for (int address = 1; address < 30; address++)
        {
            comboBox3->Items->Add(address.ToString());
        }
        comboBox3->SelectedIndex = 0;

        serialPort1 = gcnew SerialPort();
	}

    // フォームクローズ
	private: System::Void PSF_Access_FormClosing(System::Object^  sender, System::Windows::Forms::FormClosingEventArgs^  e)
	{
        if(if_sel != 0)
        {
            // OUTPUT OFF
            PSF_Send(PcAddr, ":outp 0");

            // ローカル状態
            PSF_Send(PcAddr, ":Remote0");

            // アドレス設定　マスタ
            PSF_Send(PcAddr, ":ADDR1");
            PSF_Send(PcAddr, ":Remote0");

            // クローズ
            PSF_DeviceClose(PcAddr);
        }
	}

	// Device Open
	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
	{
        // Device Open
        if (button1->Text == "OPEN")
        {
            // 使用するインターフェースを選択
            if(comboBox1->Text == "USB")
            {
                if_sel = IF_USB;
            }
            else if (comboBox1->Text == "COM")
            {
                if_sel = IF_COM1;
            }

            // パーソナルコンピュータアドレス
			PcAddr = Int32::Parse(comboBox2->Text);

            // システムアドレス
            SYSAddr = ":ADDR " + comboBox3->Text;

            // オープン
            DeviceId = PSF_DeviceOpen(PcAddr);

            if(DeviceId > 0)
            {
                // アドレス設定
                PSF_Send(PcAddr, SYSAddr);

                // OUTPUT OFF
                PSF_Send(PcAddr, ":OUTP 0");

                // 表示切り替え CHA-電圧-電流
                PSF_Send(PcAddr, ":Conf:disp1");

                // 画面表示
                button1->Text = "CLOSE";
                button2->Enabled = true;
                button2->Text = "ON";
                button3->Enabled = true;
                button4->Enabled = true;
                button5->Enabled = true;
                button6->Enabled = true;
                button7->Enabled = true;
                textBox1->Text = "";

				// デバイス情報格納
				DeviceOpen  = true;
            }
            else
            {
                // エラーを表示
                textBox1->Text = " Device Open ERR";
            }
        }
        // Device Close
        else
        {
			// OUTPUT OFF
			PSF_Send(PcAddr, ":outp 0");
			// ローカル状態
			PSF_Send(PcAddr, ":Remote0");
			// アドレス設定 マスタ
			PSF_Send(PcAddr, ":ADDR1");
			// ローカル設定
            PSF_Send(PcAddr, ":Remote0");
			// クローズ
			PSF_DeviceClose(PcAddr);

            // 画面表示
            button1->Text = "OPEN";
            button2->Text = "ON";
			button2->BackColor = System::Drawing::SystemColors::Control;
            button2->Enabled = false;
            button3->Enabled = false;
            button4->Enabled = false;
            button5->Enabled = false;
            button6->Enabled = false;
            button7->Enabled = false;
            textBox1->Text = "";
            if_sel = 0;

			// デバイスクローズ情報セット
			DeviceOpen  = false;
			DeviceOn = false;
		}
	}
    // Output On/Off
	private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)
	{
        if (button2->Text == "ON")
        {
            // OutputをONに設定
			if (button2->Enabled == true)
			{
				PSF_Send(PcAddr, ":outp1");

				// デバイスOutput情報セット
				DeviceOn = true;
			}

            // 表示の更新
            button2->Text = "OFF";
			button2->BackColor = System::Drawing::Color::Red;
        }
        else
        {
            // OutputをOFFに設定
			if (button2->Enabled == true)
			{
				PSF_Send(PcAddr, ":outp0");
				// デバイスOutput情報セット
				DeviceOn = false;
			}

            // 表示の更新
            button2->Text = "ON";
			button2->BackColor = System::Drawing::SystemColors::Control;
        }
	}

    // Preset 1
	private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e)
	{
		// Preset 1を選択
		PSF_Send(PcAddr, ":pres:call 1");
	}

    // Preset 2
	private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e)
	{
		// Preset 2を選択
		PSF_Send(PcAddr, ":pres:call 2");
	}

    // Preset 3
	private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e)
	{
		// Preset 3を選択
		PSF_Send(PcAddr, ":pres:call 3");
	}

    // Preset 0
	private: System::Void button6_Click(System::Object^  sender, System::EventArgs^  e)
	{
		// Preset 0を選択
		PSF_Send(PcAddr, ":pres:call 0");
	}

    // Read
	private: System::Void button7_Click(System::Object^  sender, System::EventArgs^  e)
	{
		String^ bbuf = "";
		array<String^>^ meas_value;

		// モニタ要求
		PSF_Send(PcAddr, ":meas?");

		// 応答待ち
		Threading::Thread::Sleep(200);

		// モニタ値受信
		PSF_Recive(PcAddr, 64, bbuf);

		// モニタ値はカンマ区切りで電圧、電流、電力、ステータス
		meas_value = bbuf->Split(',');
		if(meas_value->Length > 3)
		{
			StringBuilder^ sb = gcnew StringBuilder();
			sb->Append(meas_value[0]);
			sb->AppendLine("V");
			sb->Append(meas_value[1]);
			sb->AppendLine("A");
			sb->Append(meas_value[2]);
			sb->AppendLine("W");
			sb->Append(meas_value[3]);
			sb->Append("  0:CV/1:CC/2:CP");
			textBox1->Text = sb->ToString();
		}
	 }
    //***********************************************************************/
    //*     IF-60　Interface Select                                         */
    //***********************************************************************/

    // オープン
	private: int PSF_DeviceOpen(int addr)
    {
        int ret = -1;

		try
		{
			switch (if_sel)
			{
				case IF_USB:
					ret = USB488_DeviceOpen(addr);
					break;

				case IF_COM1:
                    serialPort1->PortName = "COM" + addr.ToString();
                    serialPort1->BaudRate = 57600;
                    serialPort1->DataBits = 8;
					serialPort1->Parity = System::IO::Ports::Parity::None;
					serialPort1->StopBits = System::IO::Ports::StopBits::One;
					serialPort1->Handshake = System::IO::Ports::Handshake::RequestToSend;
                    serialPort1->RtsEnable = true;
                    serialPort1->ReadTimeout = 3000;
                    serialPort1->WriteTimeout = 500;
                    serialPort1->Open();
                    serialPort1->DiscardInBuffer();
                    ret = 1;
					break;
			}
        }
        catch(Exception^ caught)
        {
			MessageBox::Show(caught->Message, "Open Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
            ret = -1;
		}

        return ret;
    }

    // クローズ
	private: int PSF_DeviceClose(int addr)
    {
        int ret = -1;
        switch (if_sel)
        {
            case IF_USB:
				ret = USB488_DeviceClose(addr);
                break;

            case IF_COM1:
                serialPort1->Close();
                ret = 0;
                break;
        }

        return ret;
    }

    // リモート
	private: int PSF_SetRemote(int addr, int rMode)
    {
        int ret = -1;
        switch (if_sel)
        {
            case IF_USB:
                ret = USB488_SetRemote(addr, rMode);
                break;

            case IF_COM1:
                ret = 0;
                break;
        }
        return ret;
    }

    // コマンド送信
	private: int PSF_Send(int addr, String^ strBuf)
    {
        int ret = -1;

		try
		{
			switch (if_sel)
			{
				case IF_USB:
					ret = USB488_Send(addr, strBuf);
					break;

				case IF_COM1:
					serialPort1->WriteLine(strBuf);
					ret = strBuf->Length;
					break;
			}
        }
        catch(Exception^ caught)
        {
			MessageBox::Show(caught->Message, "Send Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
            ret = -1;
		}
        return ret;
    }

    // 応答受信
	private: int PSF_Recive(int addr, int Count, String^% strBuf)
    {
        int ret = -1;
        StringBuilder^ sb = gcnew StringBuilder(Count + 1);

		try
		{
			switch (if_sel)
			{
				case IF_USB:
					ret = USB488_Receive(addr, Count, sb);
					if (ret > 0)
					{
						strBuf = sb->ToString();
					}
					else
					{
						strBuf = "";
					}
					break;

				case IF_COM1:
					strBuf = serialPort1->ReadLine();
					ret = strBuf->Length;
					break;
			}
        }
        catch(Exception^ caught)
        {
			MessageBox::Show(caught->Message, "Read Error", MessageBoxButtons::OK, MessageBoxIcon::Error);
            strBuf = "";
            ret = -1;
		}

        return ret;
    }
};
}


