C# si Arduino - control releu din interfata GUI

de George Sand


Adaugat in 2017-11-14 01:52:53





Arduino firmware

int ledPin = 13;
//alocarea pin-ilor digitali de pe MCU Arduino UNO pentru comanda releelor
int relayPin1 = 2;
int relayPin2 = 3;
int relayPin3 = 4;
int relayPin4 = 5;
int relayPin5 = 6;
int relayPin6 = 7;
int relayPin7 = 8;
int relayPin8 = 9;

//alocam 5 bit
// deocamdat vom folosi doar primi 3 biti restul ii las ca cine stie ce sf-uri imi mai vin prin cap sau ce-mi mai cere clientul
byte inputByte_0;
byte inputByte_1;
byte inputByte_2;
byte inputByte_3;
byte inputByte_4;
//daca avem ceva semnal
int serialData = 0;
//ma folosec de un mic watch dog sa fiu sigur ca conectare intre statia de comanda(aplicatia client) si MCU sunt up
int pingpong = 0;

//definire acum 
//implementarea o fac mai jos 
void reseteazaToateReleele();

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  digitalWrite(ledPin, HIGH);//
  delay(1000);//
  digitalWrite(ledPin, LOW);//
  delay(1000);//

  //TODO resetul la conectare si sa dau pentru acel reset un ceva specific in bitul 3 valoarea prmita va fi 99
  reseteazaToateReleele();
  //TODO ping pong bitul 4;
}

void loop() {

  //atentie ultimul digit este 10 care inseamna linie nou aka end line
  //
  //  if (Serial.available() > 0)
  //  {
  //    serialData = Serial.read();
  //
  //    if (serialData == 49) {
  //      digitalWrite(ledPin, HIGH);//
  //    }
  //
  //    if (serialData == 48) {
  //      digitalWrite(ledPin, LOW);//
  //    }
  //
  //    // Serial.println(serialData);
  //  }

  //Read Buffer
  if (Serial.available() == 5)
  {
    //Read buffer
    inputByte_0 = Serial.read();
    //  Serial.print(inputByte_0);
    delay(100);
    inputByte_1 = Serial.read();
    // Serial.print(inputByte_1);
    delay(100);
    inputByte_2 = Serial.read();
    //  Serial.print(inputByte_2);
    delay(100);
    inputByte_3 = Serial.read();
    //  Serial.print(inputByte_3);
    delay(100);
    inputByte_4 = Serial.read();
    //   Serial.print(inputByte_4);
  }

  //Check for start of Message
  //bitul 1 = 16 -> start schimb de mesaje
  //bitul 2 = 128 -> cheia care nespune da omule eu sunt arduino care-l cauti
  //bitul 3 = releu 1 [10 off | 11 on]
  //          releu 2 [20 off | 21 on]
  //          releu 3 [30 off | 31 on]
  //          releu 4 [40 off | 41 on]
  //          releu 5 [50 off | 51 on]
  //          releu 6 [60 off | 61 on]
  //          releu 7 [70 off | 71 on]
  //          releu 8 [80 off | 81 on]
  //          resetare toate relle [99 - functia reseteazaToateReleele() ]
  //bitul 4 = watchdog-ul PING/PONG ca suntem inca conectati [200]

  if (inputByte_0 == 16)
  {
    //detectam tipul de comanda
    switch (inputByte_1)
    {
      //      case 127:
      //        //Set PIN and value
      //        switch (inputByte_2)
      //        {
      //          case 4:
      //            if (inputByte_3 == 255)
      //            {
      //              digitalWrite(ledPin, HIGH);
      //              break;
      //            }
      //            else
      //            {
      //              digitalWrite(ledPin, LOW);
      //              break;
      //            }
      //            break;
      //        }
      //        break;
      // cheia minune care ne spune ca omule eu sunt arduino
      // prefer modul asta deaorece nu vreua sa aloc un HID (Hardweare ID ), deaorece sunt niste probleme de securitate in zona sistemului de operare windows 8/10 
      case 128:
        //Say hello
        Serial.print("HELLO FROM ARDUINO");
        break;
    }

    switch (inputByte_2) {
      //releu1 on/off
      case 10:
        digitalWrite(relayPin1, LOW);//
        break;
      case 11:
        digitalWrite(relayPin1, HIGH);//
        break;
      //releul 2 on/off
      case 20:
        digitalWrite(relayPin2, LOW);//
        break;
      case 21:
        digitalWrite(relayPin2, HIGH);//
        break;
      //releul 3 on/off
      case 30:
        digitalWrite(relayPin3, LOW);//
        break;
      case 31:
        digitalWrite(relayPin3, HIGH);//
        break;
      //releul 4 on/off
      case 40:
        digitalWrite(relayPin4, LOW);//
        break;
      case 41:
        digitalWrite(relayPin4, HIGH);//
        break;
      //releul 5 on/off
      case 50:
        digitalWrite(relayPin5, LOW);//
        break;
      case 51:
        digitalWrite(relayPin5, HIGH);//
        break;
      //releul 6 on/off
      case 60:
        digitalWrite(relayPin6, LOW);//
        break;
      case 61:
        digitalWrite(relayPin6, HIGH);//
        break;
      //releul 7 on/off
      case 70:
        digitalWrite(relayPin7, LOW);//
        break;
      case 71:
        digitalWrite(relayPin7, HIGH);//
        break;
      //releul 8 on/off
      case 80:
        digitalWrite(relayPin8, LOW);//
        break;
      case 81:
        digitalWrite(relayPin8, HIGH);//
        break;
      //aprindem/stingem ledul de pe portul dinamic 13
      case 49:
        digitalWrite(ledPin, HIGH);//
        break;
      case 48:
        digitalWrite(ledPin, LOW);
        break;
      case 99:
        reseteazaToateReleele();
        break;
    }

    switch (inputByte_3) {
      case 200:
        Serial.print("PONG");
        break;
    }

    //Clear Message bytes
    inputByte_0 = 0;
    inputByte_1 = 0;
    inputByte_2 = 0;
    inputByte_3 = 0;
    inputByte_4 = 0;// il tine deocamda de frumusete vedem mai incolo, din experienta iti tot vin idei pam pam
    //Let the PC know we are ready for more data
    Serial.print("-READY TO RECEIVE");
  }
}

void reseteazaToateReleele() {
  digitalWrite(relayPin1, LOW);//
  digitalWrite(relayPin2, LOW);//
  digitalWrite(relayPin3, LOW);//
  digitalWrite(relayPin4, LOW);//
  digitalWrite(relayPin5, LOW);//
  digitalWrite(relayPin6, LOW);//
  digitalWrite(relayPin7, LOW);//
  digitalWrite(relayPin8, LOW);//
}


C#
Form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
 
        string v_username;
        int v_idusername;
 
        public Form1()
        {
            InitializeComponent();
            
            ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
            manager.setForm1(this);
            manager.makeConnectionWithAtduinoUSB();
            manager.startTimerPingPong();
 
            OracleManager oracleMan = OracleManager.Instance;
            oracleMan.setForm1(this);
            oracleMan.doConnect();
 
            label26.Text = oracleMan.checkConnection();
 
            //   List listTestOracle = oracleMan.oracleCmd("select * from system.tabla_users");
 
            //  ListBox1.Items.Add(listTestOracle.Count);
 
            // foreach (string s in listTestOracle)
            //  {
            //     ListBox1.Items.Add(s);
            // }
 
 
            panel2.Visible = false;
            // panel2.Hide();
        }
 
        private void button5_Click(object sender, EventArgs e)
        {
 
        }
 
        Boolean active2 = false;
        private void button2_Click(object sender, EventArgs e)
        {
 
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(2);
 
            if (active2)
            {
                table.stopTimer(this);
                active2 = false;
                label18.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(20);
            }
            else
            {
                int ora = int.Parse(textBox4.Text);
                int minut = int.Parse(textBox3.Text);
                string message = String.Format("TABLA 2 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
 
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active2 = true;
                label18.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(21);
            }
 
        }
 
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
 
        }
        Boolean active = false;
        private void button1_Click(object sender, EventArgs e)
        {
 
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(1);
 
            if (active)
            {
                table.stopTimer(this);
                active = false;
                label17.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(10);
            }
            else
            {
                int ora = int.Parse(textBox1.Text);
                int minut = int.Parse(textBox2.Text);
                string message = String.Format("TABLA 1 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active = true;
                label17.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(11);
            }
 
        }
 
        public void setActive1(Boolean value)
        {
            active = value;
        }
 
        public void setActive2(Boolean value)
        {
            active2 = value;
        }
 
 
        public System.Windows.Forms.Label Label17
        {
            get
            {
                //logic here 
                return label17;
            }
            set
            {
                //logic here
                label17 = value;
            }
        }
 
 
        public System.Windows.Forms.Label Label18
        {
            get
            {
                //logic here 
                return label18;
            }
            set
            {
                //logic here
                label18 = value;
            }
        }
 
        public System.Windows.Forms.Label Label25
        {
            get
            {
                //logic here 
                return label25;
            }
            set
            {
                //logic here
                label25 = value;
            }
        }
 
 
 
        public System.Windows.Forms.Label Label19
        {
            get
            {
                //logic here 
                return label19;
            }
            set
            {
                //logic here
                label19 = value;
            }
        }
 
        public System.Windows.Forms.Label Label20
        {
            get
            {
                //logic here 
                return label20;
            }
            set
            {
                //logic here
                label20 = value;
            }
        }
 
        public System.Windows.Forms.Label Label21
        {
            get
            {
                //logic here 
                return label21;
            }
            set
            {
                //logic here
                label21 = value;
            }
        }
 
        public System.Windows.Forms.Label Label22
        {
            get
            {
                //logic here 
                return label22;
            }
            set
            {
                //logic here
                label22 = value;
            }
        }
 
        public System.Windows.Forms.Label Label23
        {
            get
            {
                //logic here 
                return label23;
            }
            set
            {
                //logic here
                label23 = value;
            }
        }
 
        public System.Windows.Forms.Label Label24
        {
            get
            {
                //logic here 
                return label24;
            }
            set
            {
                //logic here
                label24 = value;
            }
        }
 
        public System.Windows.Forms.Label Label26
        {
            get
            {
                //logic here 
                return label26;
            }
            set
            {
                //logic here
                label26 = value;
            }
        }
 
 
 
        public System.Windows.Forms.ListBox ListBox
        {
            get
            {
                //logic here 
                return listBox1;
            }
            set
            {
                //logic here
                listBox1 = value;
            }
        }
 
        private void button9_Click(object sender, EventArgs e)
        {
            ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
            arduinoManager.sendCMD(99);
            arduinoManager.stopTimerPingPong();
            arduinoManager.stopConnectionWithArduinoUSB();
 
            OracleManager oracleMan = OracleManager.Instance;
            oracleMan.doDisconnect();
 
            this.Close();
 
        }
        Boolean active3 = false;
        private void button3_Click(object sender, EventArgs e)
        {
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(3);
 
            if (active3)
            {
                table.stopTimer(this);
                active3 = false;
                label19.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(30);
            }
            else
            {
                int ora = int.Parse(textBox6.Text);
                int minut = int.Parse(textBox5.Text);
                string message = String.Format("TABLA 3 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active3 = true;
                label19.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(31);
            }
        }
 
 
        public void setActive3(Boolean value)
        {
            active3 = value;
        }
 
        Boolean active4 = false;
 
        public void setActive4(Boolean value)
        {
            active4 = value;
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(4);
 
            if (active4)
            {
                table.stopTimer(this);
                active4 = false;
                label20.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(40);
            }
            else
            {
                int ora = int.Parse(textBox8.Text);
                int minut = int.Parse(textBox7.Text);
                string message = String.Format("TABLA 4 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active4 = true;
                label20.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(41);
            }
        }
 
 
        Boolean active5 = false;
 
        public void setActive5(Boolean value)
        {
            active5 = value;
        }
 
        private void button5_Click_1(object sender, EventArgs e)
        {
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(5);
 
            if (active5)
            {
                table.stopTimer(this);
                active5 = false;
                label21.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(50);
            }
            else
            {
                int ora = int.Parse(textBox10.Text);
                int minut = int.Parse(textBox9.Text);
                string message = String.Format("TABLA 5 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active5 = true;
                label21.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(51);
            }
        }
 
        Boolean active6 = false;
 
        public void setActive6(Boolean value)
        {
            active6 = value;
        }
 
        private void button6_Click(object sender, EventArgs e)
        {
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(6);
 
            if (active6)
            {
                table.stopTimer(this);
                active6 = false;
                label22.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(60);
            }
            else
            {
                int ora = int.Parse(textBox12.Text);
                int minut = int.Parse(textBox11.Text);
                string message = String.Format("TABLA 6 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active6 = true;
                label22.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(61);
            }
        }
 
        Boolean active7 = false;
 
        public void setActive7(Boolean value)
        {
            active7 = value;
        }
 
        private void button7_Click(object sender, EventArgs e)
        {
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(7);
 
            if (active7)
            {
                table.stopTimer(this);
                active7 = false;
                label23.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(70);
            }
            else
            {
                int ora = int.Parse(textBox14.Text);
                int minut = int.Parse(textBox13.Text);
                string message = String.Format("TABLA 7 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active7 = true;
                label23.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(71);
            }
        }
 
        Boolean active8 = false;
 
        public void setActive8(Boolean value)
        {
            active8 = value;
        }
 
        private void button8_Click(object sender, EventArgs e)
        {
            TableManager tm = TableManager.Instance;
            Table table = tm.findTableByKey(8);
 
            if (active8)
            {
                table.stopTimer(this);
                active8 = false;
                label24.Text = "OPRIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(80);
            }
            else
            {
                int ora = int.Parse(textBox16.Text);
                int minut = int.Parse(textBox15.Text);
                string message = String.Format("TABLA 8 a fost activat pentru o durate de {0} ore si {1} minute", ora, minut);
                listBox1.Items.Add(message);
                table.hour = ora;
                table.minute = minut;
                table.startTimer(this);
                active8 = true;
                label24.Text = "PORNIT";
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(81);
            }
        }
 
        public System.Windows.Forms.ListBox ListBox1
        {
            get
            {
                //logic here 
                return listBox1;
            }
            set
            {
                //logic here
                listBox1 = value;
            }
        }
 
        bool testVal = false;
 
        private void button10_Click(object sender, EventArgs e)
        {
            if (!testVal)
            {
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(49);
                testVal = true;
            }
            else
            {
                ArduinoComunicatorManager arduinoManager = ArduinoComunicatorManager.Instance;
                arduinoManager.sendCMD(48);
                testVal = false;
            }
 
        }
 
        public void setIdUsername(int p_idusername)
        {
            v_idusername = p_idusername;
        }
 
        public int getIdUsername()
        {
            return v_idusername;
        }
 
        private void button11_Click(object sender, EventArgs e)
        {
            // panel1
            string username = textBox17.Text;
            string password = textBox18.Text;
 
            OracleManager oracleMan = OracleManager.Instance;
            bool isLogged = oracleMan.checkLogin(username, password);
 
            if (isLogged)
            {
                panel1.Visible = false;
 
                v_username = username;
            }
            else
            {
                string mesaj = String.Format("Utilizator si / sau Parola au fost introduse gresit.Te rog sa reincerci !");
                label29.Text = mesaj;
            }
 
        }
 
        private void button13_Click(object sender, EventArgs e)
        {
            panel2.Visible = true;
            panel2.Show();
            listBox1.Items.Add("AFISARE RAPORTARE");
 
        }
 
        private void button14_Click(object sender, EventArgs e)
        {
            panel2.Visible = false;
            panel2.Hide();
        }
 
        private void button12_Click(object sender, EventArgs e)
        {
            //TODO BUTON RAPORT preia data start si data stop si fa o logica pama 
            // cu listBox2
            //startdate =  dateTimePicker1
            //stopdate = dateTimePicker2
            listBox2.Items.Clear();
            DateTime startDate = dateTimePicker1.Value.Date;
            DateTime stopDate = dateTimePicker2.Value.Date;
            //  listBox2.Items.Add(startDate);
            //  listBox2.Items.Add(stopDate);
            OracleManager oracleMan = OracleManager.Instance;
            List listReportInfo = oracleMan.getRaportValue(startDate, stopDate);
            foreach (string str in listReportInfo)
            {
                listBox2.Items.Add(str);
            }
 
        }
    }
}

Table.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
 
 
 
namespace WindowsFormsApplication5
{
 
    class Table
    {
        //pentru aceste variabile primesc 
        public int table;
        public int hour;
        public int minute;
        //variabilele sunt initializate standard
        public int seconds = 60;
        public int miliseconds = 1000;
        public int calculateInterval;
        Form1 tmpForm;
 
        public DateTime startDate;
        public DateTime stopDate;
 
 
        //TODO 
        // de facut un obiect de tip oracle manager la care sa trimitem insformati despre obiectul table
 
        //punem in timer care va face ceva cand va fi atins sau interupt
        System.Timers.Timer timer;
 
        public Table(int pTable)
        {
            table = pTable;
            timer = new System.Timers.Timer();
        }
 
        //pornim timerul 
        public void startTimer(Form1 frmMain)
        {
            
            if (timer == null)
            {
                timer = new System.Timers.Timer();
            }
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            calculateInterval = seconds * miliseconds;
            if (minute > 0)
            {
                calculateInterval *= minute;
            }
 
            if (hour > 0)
            {
                calculateInterval *= hour;
            }
 
            tmpForm = frmMain;
            timer.Interval = calculateInterval;
            timer.Enabled = true;
            DateTime date = DateTime.Now;
            string message = String.Format("TABLA {2} -- TIMER PORNIT {0} la intervalul {1} - {3} ", timer.Enabled, timer.Interval, table, date.ToString("yyyy-MM-dd HH:mm:ss"));
            tmpForm.ListBox.Items.Add(message);
            startDate = date;
 
        }
 
        //oprim fortat timer-ul
        public void stopTimer(Form1 frmMain)
        {
            timer.Enabled = false;
            DateTime date = DateTime.Now;
            string message = String.Format("TABLA {0} -- TIMER A FOST OPRIT - {1}", table, date.ToString("yyyy-MM-dd HH:mm:ss"));
            timer = null;
            stopDate = date;
 
            if (table == 1)
            {
 
                tmpForm.Label17.Text = "OPRIT";
                tmpForm.setActive1(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                //  manager.sendCMD(48);              
                manager.sendCMD(10);
            }
 
            if (table == 2)
            {
                tmpForm.Label18.Text = "OPRIT";
                tmpForm.setActive2(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(20);
            }
 
            if (table == 3)
            {
                tmpForm.Label19.Text = "OPRIT";
                tmpForm.setActive3(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(30);
            }
 
            if (table == 4)
            {
                tmpForm.Label20.Text = "OPRIT";
                tmpForm.setActive4(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(40);
            }
 
            if (table == 5)
            {
                tmpForm.Label21.Text = "OPRIT";
                tmpForm.setActive5(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(50);
            }
 
            if (table == 6)
            {
                tmpForm.Label22.Text = "OPRIT";
                tmpForm.setActive6(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(60);
            }
 
            if (table == 7)
            {
                tmpForm.Label23.Text = "OPRIT";
                tmpForm.setActive7(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(70);
            }
 
            if (table == 8)
            {
                tmpForm.Label24.Text = "OPRIT";
                tmpForm.setActive8(false);
                ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                manager.sendCMD(80);
            }
 
            tmpForm.ListBox.Items.Add(message);
            //todo foramtul datei
            saveInfoToDatabase("insert into tabla_log (codlog,coduser,numar_tabla,data_start,data_stop,pret_total) " +
               "values (seq_tabla_log.nextval," + tmpForm.getIdUsername() + "," 
               + table + ",TO_DATE('" + startDate.ToString("yyyy-MM-dd HH:mm:ss") + "','YYYY-MM-DD hh24:mi:ss'),TO_DATE('" 
               + stopDate.ToString("yyyy-MM-dd HH:mm:ss") + "','YYYY-MM-DD hh24:mi:ss'),0)");
 
        }
 
        //functia la care am atins limita calculata
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
 
 
            //TODO dam comanda de off catre mcu arduino, stingem LED-ul si face si ceva pe ecran pam pam
            MethodInvoker inv = delegate
            {
                // this.lblCounter.Text = this.index.ToString();
                DateTime date = DateTime.Now;
                string message = String.Format("TABLA {0} -- INCHIS - {1}", table, date.ToString("yyyy-MM-dd HH:mm:ss"));
                tmpForm.ListBox.Items.Add(message);
                stopDate = date;
 
                if (table == 1)
                {
                    tmpForm.Label17.Text = "OPRIT";
                    tmpForm.setActive1(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(10);
                    //  manager.sendCMD(48);
                }
 
                if (table == 2)
                {
                    tmpForm.Label18.Text = "OPRIT";
                    tmpForm.setActive2(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(20);
                }
 
                if (table == 3)
                {
                    tmpForm.Label19.Text = "OPRIT";
                    tmpForm.setActive3(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(30);
                }
 
                if (table == 4)
                {
                    tmpForm.Label20.Text = "OPRIT";
                    tmpForm.setActive4(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(40);
                }
 
                if (table == 5)
                {
                    tmpForm.Label21.Text = "OPRIT";
                    tmpForm.setActive5(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(50);
                }
 
                if (table == 6)
                {
                    tmpForm.Label22.Text = "OPRIT";
                    tmpForm.setActive6(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(60);
                }
 
                if (table == 7)
                {
                    tmpForm.Label23.Text = "OPRIT";
                    tmpForm.setActive7(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(70);
                }
 
                if (table == 8)
                {
                    tmpForm.Label24.Text = "OPRIT";
                    tmpForm.setActive8(false);
                    ArduinoComunicatorManager manager = ArduinoComunicatorManager.Instance;
                    manager.sendCMD(80);
                }
 
            };
            tmpForm.Invoke(inv);
 
            timer.Enabled = false;
            timer = null;
            //TODO formatil datei
            saveInfoToDatabase("insert into tabla_log (codlog,coduser,numar_tabla,data_start,data_stop,pret_total) " +
              "values (seq_tabla_log.nextval,"+tmpForm.getIdUsername()+"," 
              + table + ",TO_DATE('" 
              + startDate.ToString("yyyy-MM-dd HH:mm:ss") + "','YYYY-MM-DD hh24:mi:ss'),TO_DATE('"
               + stopDate.ToString("yyyy-MM-dd HH:mm:ss") + "','YYYY-MM-DD hh24:mi:ss'),0)");
 
        }
 
        private void saveInfoToDatabase(string sql)
        {
            OracleManager oracleMan = OracleManager.Instance;
            oracleMan.insertInTablaLog(sql);
        }
 
    }

}

TableManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace WindowsFormsApplication5
{
    class TableManager
    {
        private static TableManager instance;
 
        //facem un echivalent de map din java dupa key si valoare sa ne ajute la gasirea mai repde la obiectul de care avem nevoie sa-l updatam 
        //pam pam pam
        Dictionary listaDeTable = new Dictionary();
 
        private TableManager()
        {
            //TODO vedem ce instantiem
 
            populateListDeTable();
 
        }
 
        private void populateListDeTable()
        {
            for (int x = 1; x <= 8; x++)
            {
                Table table = new Table(x);
                listaDeTable.Add(x, table);
            }
        }
 
        public static TableManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new TableManager();
                }
                return instance;
            }
        }
 
        //de aici tragem obiectul table de care avem nevoie dupa key
        public Table findTableByKey(int key)
        {
            return listaDeTable[key];
        }
 
    }
}

ArduinoComunicatorManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Threading;
using System.IO.Ports;
using System.IO;
using System.Timers;
 
//bitul 1 = 16 -> start schimb de mesaje
//bitul 2 = 128 -> cheia care nespune da omule eu sunt arduino care-l cauti
//bitul 3 = releu 1 [10 off | 11 on]
//          releu 2 [20 off | 21 on]
//          releu 3 [30 off | 31 on]
//          releu 4 [40 off | 41 on]
//          releu 5 [50 off | 51 on]
//          releu 6 [60 off | 61 on]
//          releu 7 [70 off | 71 on]
//          releu 8 [80 off | 81 on]
//          resetare toate relle [99 - functia reseteazaToateReleele() ]
//bitul 4 = watchdog-ul PING/PONG ca suntem inca conectati [200]
 
namespace WindowsFormsApplication5
{
    class ArduinoComunicatorManager
    {
        private static ArduinoComunicatorManager instance;
        string COM = null;
        int speedSerial = 9600;
        SerialPort currentPort;
        bool portFound;
        System.Timers.Timer timer;
        SerialPort port = null;
        Form1 form;
        int waitTimerPingPong = 3500;
 
        private ArduinoComunicatorManager()
        {
            //makeConnectionWithAtduinoUSB();
            timer = new System.Timers.Timer();
 
        }
 
        public void startTimerPingPong()
        {
           
            if (timer == null)
            {
                timer = new System.Timers.Timer();
            }
 
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            timer.Interval = waitTimerPingPong;
            timer.Enabled = true;
 
        }
 
        //deocamda nu vreau sa-l opresc eu 
        public void stopTimerPingPong()
        {
            timer.Enabled = false;
            timer = null;
        }
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            PingPong();
            startTimerPingPong();
        }
 
        public void sendCMD(int cmd)
        {
            //TODO de aici trimitem comenzii
 
            if (currentPort == null)
            {
                return;
            }
 
            if (!currentPort.IsOpen)
            {
                return;
            }
 
            byte[] buffer = new byte[5];
            buffer[0] = Convert.ToByte(16);
            buffer[1] = Convert.ToByte(128);
            buffer[2] = Convert.ToByte(cmd);
            buffer[3] = Convert.ToByte(0);
            buffer[4] = Convert.ToByte(0);
 
            currentPort.Write(buffer, 0, 5);
            Thread.Sleep(1000);
 
        }
 
        private void PingPong()
        {
 
            if (currentPort == null)
            {
                return;
            }
 
            if (!currentPort.IsOpen)
            {
                return;
            }
 
            byte[] buffer = new byte[5];
            buffer[0] = Convert.ToByte(16);
            buffer[1] = Convert.ToByte(128);
            buffer[2] = Convert.ToByte(0);
            buffer[3] = Convert.ToByte(200);
            buffer[4] = Convert.ToByte(0);
            currentPort.Write(buffer, 0, 5);
            Thread.Sleep(1000);
 
            int count = currentPort.BytesToRead;
            int intReturnASCII = 0;
            string returnMessage = "";
            while (count > 0)
            {
                intReturnASCII = currentPort.ReadByte();
                returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                count--;
            }
 
            // ComPort.name = returnMessage;
            //ATENTIE LA CLOSE
            //    currentPort.Close();
            if (returnMessage.Contains("PONG"))
            {
                //TODO catam lalalalala in the morning lalalaal
            }
            else
            {
                //daca nu fortam conectarea
                bool redetec = false;
                while (!redetec)
                {
                    redetec = DetectArduino();
                }
            }
        }
 
        public void setForm1(Form1 pForm)
        {
            form = pForm;
        }
 
        public void makeConnectionWithAtduinoUSB()
        {
           // COM sa ma conectez
            //string[] ports = SerialPort.GetPortNames();
            //TODO de continuat
            //port = new SerialPort(COM, speedSerial); 
 
            try
            {
                string[] ports = SerialPort.GetPortNames();
                foreach (string port in ports)
                {
                    currentPort = new SerialPort(port, 9600);
                    if (DetectArduino())
                    {
                        portFound = true;
                        form.Label25.Text = "CONNECTED TO ARDUINO";
                        break;
                    }
                    else
                    {
                        //  string mess = String.Format("CANNOT GET CONNECTED to ARDUINO DEVICE");
                        //  form.ListBox1.Items.Add(mess);
                        form.Label25.Text = "NOT CONNECTED TO ARDUINO";
                        portFound = false;
                    }
                }
 
            }
            catch (Exception e)
            {
                string mess = String.Format("CANNOT GET CONNECTED to ARDUINO DEVICE because {0}", e);
                form.ListBox1.Items.Add(mess);
            }
        }
 
        private bool DetectArduino()
        {
            try
            {
                //The below setting are for the Hello handshake
                byte[] buffer = new byte[5];
                buffer[0] = Convert.ToByte(16);
                buffer[1] = Convert.ToByte(128);
                buffer[2] = Convert.ToByte(0);
                buffer[3] = Convert.ToByte(0);
                buffer[4] = Convert.ToByte(4);
                int intReturnASCII = 0;
                char charReturnValue = (Char)intReturnASCII;
                currentPort.Open();
 
                currentPort.Write(buffer, 0, 5);
                Thread.Sleep(1000);
                int count = currentPort.BytesToRead;
                string returnMessage = "";
                while (count > 0)
                {
                    intReturnASCII = currentPort.ReadByte();
                    returnMessage = returnMessage + Convert.ToChar(intReturnASCII);
                    count--;
 
                }
 
                // ComPort.name = returnMessage;
                //ATENTIE LA CLOSE
                //    currentPort.Close();
                if (returnMessage.Contains("HELLO FROM ARDUINO"))
                {
                    string mess = String.Format("CONNECTED to ARDUINO DEVICE on port {0} | {1}", currentPort.PortName, returnMessage);
                    form.ListBox1.Items.Add(mess);
                    sendCMD(99);//ne asiguram ca toate releele sunt resetate (adica off)
                    return true;
                }
                else
                {
                    //  form.Label25.Text = "NOT CONNECTED TO ARDUINO";
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
 
        }
 
        public void stopConnectionWithArduinoUSB()
        {
            if (currentPort != null)
                currentPort.Close();
        }
 
        public static ArduinoComunicatorManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ArduinoComunicatorManager();
                }
                return instance;
            }
        }
 
 
 
    }
}

OracleManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.Data;
 
namespace WindowsFormsApplication5
{
    class OracleManager
    {
        private static OracleManager instance;
        private string host;
        private string username;
        private string password;
        private int pot;
        private string oracledb;
        private OracleConnection conn;
        private Form1 form;
        private OracleManager()
        {
 
            oracledb = "Data Source=(DESCRIPTION ="
                + "(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))"
                + "(CONNECT_DATA ="
                + "(SERVER = DEDICATED)"
                + "(SERVICE_NAME = XE)));"
                + "User Id=system;Password=student;";
        }
 
        public void setForm1(Form1 pForm)
        {
            form = pForm;
        }
 
        public bool checkLogin(string username, string password)
        {
            bool value = false;
 
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
 
            string sql = "select coduser from system.tabla_users where username = '" + username + "' and password = '" + password + "'";
            OracleCommand command = conn.CreateCommand();
            command.Connection = conn;
            command.CommandText = sql;
            command.CommandType = CommandType.Text;
            OracleDataReader reader = command.ExecuteReader();
            // bool test = reader.Read();
            /*   value = reader.HasRows;
               if (!value)
               {
                   value = reader.Read();
               }
               if (!value)
               {
                  value = reader.NextResult();
               }*/
            if (reader.HasRows)
                value = true;
 
             while (reader.Read())
            {
                form.setIdUsername(Convert.ToUInt16(reader["CODUSER"]));
                break;
            }
 
            reader.Close();
            reader.Dispose();
            //command.Close();
            command.Dispose();
 
            return value;
        }
 
        public List getRaportValue(DateTime pStartDate, DateTime pStopDate)
        {
            List tmpList = new List();
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
            string sql = "select tabla_log.numar_tabla, tabla_log.data_start, tabla_log.data_stop,tabla_users.username from tabla_log inner join "+
                    " tabla_users on tabla_users.coduser = tabla_log.coduser where "+
                    " tabla_log.data_start > TO_DATE('"+ pStartDate.ToString("yyyy-MM-dd") + "','YYYY-MM-DD') and tabla_log.data_start < TO_DATE('" + pStopDate.ToString("yyyy-MM-dd") + "','YYYY-MM-DD')";
 
            OracleCommand command = conn.CreateCommand();
            command.CommandText = sql;
            command.Connection = conn;
            command.CommandType = System.Data.CommandType.Text;
            OracleDataReader reader = command.ExecuteReader();
            //resultString.Add(sql);
            //bool val = reader.HasRows; 
            // resultString.Add(Convert.ToString(val));
            // val = reader.Read();
            // resultString.Add(Convert.ToString(val));
            while (reader.Read())
            {
                int tablaNr = reader.GetInt16(0);
                DateTime datastart = reader.GetDateTime(1);
                DateTime datastop = reader.GetDateTime(2);
                string utilizator = reader.GetString(3);
                tmpList.Add(tablaNr + "|" + datastart + "|" + datastop + "|" + utilizator);
            }
 
            reader.Close();
            reader.Dispose();
            //   command.Close();
            command.Dispose();
 
 
            return tmpList;
        }
 
 
        public void doConnect()
        {
            conn = new OracleConnection(oracledb);
            conn.Open();
        }
        public string checkConnection()
        {
            return "- DB ORACLE VERSION " + conn.ServerVersion + ": " + conn.State;
        }
 
        public void insertInTablaLog(string sql)
        {
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
 
            OracleCommand command = conn.CreateCommand();
            command.CommandText = sql;
            command.Connection = conn;
            command.CommandType = System.Data.CommandType.Text;
            command.ExecuteNonQuery();
 
 
 
            //   command.Close();
            command.Dispose();
        }
 
        public List oracleCmd(string sql)
        {
            List resultString = new List();
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
 
            OracleCommand command = conn.CreateCommand();
            command.CommandText = sql;
            command.Connection = conn;
            command.CommandType = System.Data.CommandType.Text;
            OracleDataReader reader = command.ExecuteReader();
            //resultString.Add(sql);
            //bool val = reader.HasRows; 
            // resultString.Add(Convert.ToString(val));
            // val = reader.Read();
            // resultString.Add(Convert.ToString(val));
            while (reader.Read())
            {
                string coduse = (string)reader["CODUSER"].ToString();
                string username = (string)reader["USERNAME"].ToString();
                string password = (string)reader["PASSWORD"].ToString();
                string role = (string)reader["ROLE"].ToString();
                resultString.Add(coduse + "|" + username + "|" + password + "|" + role);
            }
 
            reader.Close();
            reader.Dispose();
            //   command.Close();
            command.Dispose();
 
            return resultString;
 
        }
 
        public void doDisconnect()
        {
            conn.Close();
            conn.Dispose();
        }
        public static OracleManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new OracleManager();
                }
                return instance;
            }
        }
 
    }
}


Tag-uri cautare Releu Relee CSharp C# si Arduino - control rele din interfata GUI C# Arduino 5V Relay
Trimite unui prieten aceasta postare
sau distribuie postarea la tine pe perete
Inapoi

Lasa un comentariu