Advertisement
Guest User

BG_RACK_v6

a guest
Nov 21st, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 25.21 KB | None | 0 0
  1. // Project:     Ethernet Controller Board
  2. // date :       15/Oct/2019
  3. // Main MCU:    Mega 2560 pro mini
  4.  
  5. /* Hardware Connected
  6.     // W5500 Module Ethernet PHY
  7.     // Eight Relay
  8.       6 light
  9.       2 Fan
  10.     // two digital input
  11.     // 4 analog input
  12.  Progrem Development
  13.   1) Rack controller firmware implement:
  14.  
  15.   Timer as real time clock for plants light system
  16.   Network Time Protocol (NTP) Client
  17.   scheduling
  18.  
  19.   1) Network Time Protocol (NTP) Client DONE
  20.   2) Timer as real time clock for plants light system scheduling. DONE but Test
  21.   3) througnt MQTT do board setting
  22.  
  23.   Date: 21/11/2019
  24.   By : Stanley Seow
  25.  
  26.   Fixed :
  27.   - mqtt incoming parse error buffers
  28.  
  29.   Added/ changes :
  30.   - Change subscribed topic to /bg/fc/racks/cmds
  31.   - Change published topic to /bg/fc/racks/status
  32.   - Change events topic to /bg/fc/events
  33.  
  34.  
  35.  
  36. */
  37. #include <ArduinoJson.h>
  38. #include <SPI.h>
  39. #include <Ethernet.h>
  40. #include <PubSubClient.h>
  41. #include <EEPROM.h>
  42. #include <avr/wdt.h>
  43. #include <EthernetUdp.h>
  44. // ---------------------------- Function prototype
  45.   char DIP_scan();
  46.   void sendEvent(String type, byte level, String status,String msg);
  47.   void publishStatus();
  48.   void SerialAvailable();
  49.   void Serial2Available();
  50.   void ethernetConn();
  51.   void sendNTPpacket(const char * address);
  52. // ---------------------------- Board Info
  53.   #define version "V6"
  54.   #define S1 "L1"
  55.   #define S2 "L2"
  56.   #define S3 "L3"
  57.   #define S4 "L4"
  58.   #define S5 "L5"
  59.   #define S6 "L6"
  60.   #define F1 "F1"
  61.   #define F2 "F2"
  62. // ---------------------------- EEPROM Address
  63.   #define EP_S1 1
  64.   #define EP_S2 2
  65.   #define EP_S3 3
  66.   #define EP_S4 4
  67.   #define EP_S5 5
  68.   #define EP_S6 6
  69.   #define EP_S7 7
  70.   #define EP_S8 8
  71.   #define EP_KeepAlive 21
  72.   #define FirstBoot 20
  73.  
  74. // ---------------------------- Rack's name
  75.   #define R0    "mixture"
  76.   #define R1    "rack01"
  77.   #define R2    "rack02"
  78.   #define R3    "rack03"
  79.   #define R4    "rack04"
  80.   #define R5    "rack05"
  81.   #define R6    "rack06"
  82.   #define R7    "rack07"
  83.   #define R8    "rack08"
  84.   #define R9    "rack09"
  85.   #define R10   "rack10"
  86.   #define R11   "rack11"
  87.   #define R12   "rack12"
  88.   #define R13   "rack13"
  89.   #define R14   "rack14"
  90.   #define R15   "rack15"
  91.   String boardName[17] = {R0,R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, R14, R15};
  92. // ---------------------------- GPIO In
  93.   #define ADC_1 A0
  94.   #define ADC_2 A1
  95.   #define ADC_3 A2
  96.   #define ADC_4 A3
  97.   #define MAG_1 2
  98.   #define MAG_2 3
  99.   #define DIP_1 9
  100.   #define DIP_2 8
  101.   #define DIP_3 7
  102.   #define DIP_4 6
  103.  
  104.   #define IN1 31
  105.   #define IN2 29
  106.   #define IN3 27
  107.   #define IN4 25
  108.   #define IN5 23
  109.   #define IN6 21
  110.   #define IN7 19
  111. // ---------------------------- GPIO Out
  112.   #define Relay_1 45
  113.   #define Relay_2 46
  114.   #define Relay_3 44
  115.   #define Relay_4 42
  116.   #define Relay_5 41
  117.   #define Relay_6 40
  118.   #define Relay_7 39
  119.   #define Relay_8 47
  120.   #define RS485_TX 16
  121.   #define RS485_RX 17
  122.   #define LED_1 4 // States
  123.   #define LED_2 5 // Ethernet
  124.  
  125.  
  126. // ---------------------------- Reconnect
  127.   unsigned char reconnectTask;
  128.   unsigned short reconnectDelay;
  129.   unsigned char reconnectRetry;
  130. // ---------------------------- Data type
  131.   union {
  132.     uint8_t Byte;
  133.     struct {
  134.       uint8_t  r1 : 1; // bit position 0
  135.       uint8_t  r2 : 1; // bit positions 1..2
  136.       uint8_t  r3 : 1; // bit positions 3..5
  137.       uint8_t  r4 : 1; // bit positions 6..7
  138.       uint8_t  r5 : 1; // bit positions 6..7
  139.       uint8_t  r6 : 1; // bit positions 6..7
  140.       uint8_t  r7 : 1; // bit positions 6..7
  141.       uint8_t  r8 : 1; // bit positions 6..7
  142.       // total # of bits just needs to add up to the uint8_t size
  143.     }bit;
  144.   } DIP_Struct;
  145.  
  146.   long prevmillis;
  147.   long oneSTask;
  148.   bool blinkLED;
  149.   // char buffer[200];
  150.   bool bootup;
  151.  
  152.   char RelayArray[] = {0, Relay_1, Relay_2 ,Relay_3 ,Relay_4 ,Relay_5 ,Relay_6 ,Relay_7 ,Relay_8};
  153.   char RelayStates[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
  154.   char DIP_Temp;
  155.  
  156.   char RelayRunNB = 1;
  157.  
  158.   unsigned long upTime_min;
  159.   unsigned char hour;
  160.   unsigned char min;
  161.   unsigned int oneMin;
  162.   unsigned char oneHour;
  163.   bool oneHourTask_start;
  164.   unsigned char keepAliveCout;
  165.  
  166.   bool masterModeU0;
  167.   bool masterModeMQTT;
  168. // ---------------------------- UDP NTP -------------------------------------------//
  169.   unsigned char Udp_Task;
  170.   unsigned long Udp_Taskdelay;
  171.   unsigned char Udp_TimeSet_hour;
  172. // ----------------------------- Ethernet -------------------------------------------//
  173.   // byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEE };
  174.   // IPAddress ip(192, 168, 0, 150);
  175.   IPAddress server(192, 168, 0, 10);
  176.   unsigned long lastTx = 0;
  177.   EthernetClient ethClient;
  178.   PubSubClient client(ethClient);
  179.   char publishData[255];
  180.   char subscribeData[64];
  181.   #define ETH_ADD_LAST_VALUE 200
  182.   // --------------------------------- UDP
  183.   unsigned int localPort = 8888;       // local port to listen for UDP packets
  184.   const char timeServer[] = "192.168.0.250"; // time.nist.gov NTP server
  185.   const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
  186.   byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
  187.   // A UDP instance to let us send and receive packets over UDP
  188.   EthernetUDP Udp;
  189.  
  190. // ============================= Callback ========================================== //
  191.   void callback(char* topic, char* payload, unsigned int length) {
  192.     // int i;
  193.  
  194.   char inBuffer[101];
  195.  
  196.   for (int i = 0; i < length; i++) {
  197.     inBuffer[i] = (char)payload[i];
  198.     inBuffer[i + 1] = '\0';   // Terminate the string
  199.   }
  200.  
  201.    
  202.     Serial.print("Message arrived [");
  203.     Serial.print(topic);
  204.     Serial.print("] ");
  205.  
  206.     Serial.println(inBuffer);
  207.    
  208.     StaticJsonBuffer<100> jsonBuffer2;
  209.     JsonObject& root = jsonBuffer2.parseObject(inBuffer);
  210.  
  211.     if (!root.success()) {
  212.       Serial.println("{\"Error\":\"parseObject_callback\"}");
  213.       Serial.println();
  214.       return;
  215.     }
  216.  
  217.     if(root.containsKey("STATUS")) {
  218.       publishStatus();
  219.     } else if(root.containsKey("test")) {
  220.       Serial.println("Got test from MQTT");
  221.     } else if(root.containsKey("keepalive") && root["keepalive"] < 0){
  222.       keepAliveCout = root["keepalive"];
  223.       EEPROM.write(EP_KeepAlive, keepAliveCout);
  224.     }
  225.     else if(root["master"] == 1){
  226.       // root.remove("master");
  227.       root.printTo(publishData);
  228.       Serial2.println(publishData);
  229.       masterModeMQTT = 1;
  230.       return;
  231.     }
  232.  
  233.     if ( root.containsKey("name") && root["name"] == boardName[DIP_Temp] ) {
  234.       Serial.println("Matching name");
  235.       Serial.println(boardName[DIP_Temp]);
  236.    
  237.         if(root.containsKey(F2) && root[F2] < 2){
  238.           if(root[F2] != RelayStates[8]){
  239.             RelayRunNB = 8;
  240.             EEPROM.write(EP_S8, root[F2]);
  241.             RelayStates[8] = root[F2];  
  242.           }
  243.         }
  244.         if(root.containsKey(F1) && root[F1] < 2){
  245.           if(root[F1] != RelayStates[7]){
  246.             RelayRunNB = 7;
  247.             EEPROM.write(EP_S7, root[F1]);
  248.             RelayStates[7] = root[F1];  
  249.           }
  250.         }
  251.         if(root.containsKey(S6) && root[S6] < 2){
  252.           if(root[S6] != RelayStates[6]){
  253.             RelayRunNB = 6;
  254.             EEPROM.write(EP_S6, root[S6]);
  255.             RelayStates[6] = root[S6];  
  256.           }
  257.         }  
  258.         if(root.containsKey(S5) && root[S5] < 2){
  259.           if(root[S5] != RelayStates[5]){
  260.             RelayRunNB = 5;
  261.             EEPROM.write(EP_S5, root[S5]);
  262.             RelayStates[5] = root[S5];  
  263.           }
  264.         }
  265.         if(root.containsKey(S4) && root[S4] < 2){
  266.           if(root[S4] != RelayStates[4]){
  267.             RelayRunNB = 4;
  268.             EEPROM.write(EP_S4, root[S4]);
  269.             RelayStates[4] = root[S4];  
  270.           }
  271.         }
  272.         if(root.containsKey(S3) && root[S3] < 2){
  273.           if(root[S3] != RelayStates[3]){
  274.             RelayRunNB = 3;
  275.             EEPROM.write(EP_S3, root[S3]);
  276.             RelayStates[3] = root[S3];  
  277.           }
  278.         }
  279.         if(root.containsKey(S2) && root[S2] < 2){
  280.           if(root[S2] != RelayStates[2]){
  281.             RelayRunNB = 2;
  282.             EEPROM.write(EP_S2, root[S2]);
  283.             RelayStates[2] = root[S2];  
  284.           }
  285.         }
  286.         if(root.containsKey(S1) && root[S1] < 2){
  287.           if(root[S1] != RelayStates[1]){
  288.             RelayRunNB = 1;
  289.             EEPROM.write(EP_S1, root[S1]);
  290.             RelayStates[1] = root[S1];  
  291.           }
  292.         }
  293.  
  294.     } // end of matching json name
  295.  
  296.     if (root["RESET"] == 1) asm volatile ("  jmp 0");
  297.     //  {
  298.     //  client.publish("/boomgrow/foodcomputer3/events","{\"ERROR\":\"CMD NO FOND\"}");
  299.     //  Serial.println("CMD NO FOND");
  300.     // }
  301.   }
  302.  
  303. // ============================= Reconnect ========================================== //
  304.   void reconnect() {
  305.     digitalWrite(LED_2, 0);
  306.     Serial.print("Attempting MQTT connection...");
  307.     char tempString[64];
  308.     boardName[DIP_Temp].toCharArray(tempString,7);
  309.     if (client.connect(tempString)) {
  310.       Serial.println("connected");
  311.       sendEvent("MQTT", 3, "MQTT=1", "connected to MQTT");
  312.       // resubscribe
  313.       sprintf(subscribeData,"/bg/fc/racks/cmds", tempString);
  314.       Serial.print("subscribe: ");
  315.       Serial.println(subscribeData);
  316.       client.subscribe(subscribeData);
  317.       digitalWrite(LED_2, 1);
  318.       reconnectTask = 0;
  319.     } else {
  320.       Serial.print("failed, rc=");
  321.       Serial.println(client.state());
  322.       reconnectTask = 1;
  323.       reconnectDelay = 1000;
  324.     }
  325.   }
  326.  
  327. // ============================= Setup ========================================== //
  328.   void setup()
  329.   {
  330.     unsigned char i;
  331.     // ---------------------------- Serial
  332.     Serial.begin(57600);
  333.     Serial2.begin(9600);
  334.     // ---------------------------- Watch dog timer
  335.       wdt_enable(WDTO_8S);
  336.     // ---------------------------- GPIO Config
  337.     pinMode(MAG_1, INPUT);
  338.     pinMode(MAG_2, INPUT);
  339.     pinMode(DIP_1, INPUT_PULLUP);
  340.     pinMode(DIP_2, INPUT_PULLUP);
  341.     pinMode(DIP_3, INPUT_PULLUP);
  342.     pinMode(DIP_4, INPUT_PULLUP);
  343.  
  344.     pinMode(IN1, INPUT_PULLUP);
  345.     pinMode(IN2, INPUT_PULLUP);
  346.     pinMode(IN3, INPUT_PULLUP);
  347.     pinMode(IN4, INPUT_PULLUP);
  348.     pinMode(IN5, INPUT_PULLUP);
  349.     pinMode(IN6, INPUT_PULLUP);
  350.     pinMode(IN7, INPUT_PULLUP);
  351.  
  352.     pinMode(ADC_1, INPUT);
  353.     pinMode(ADC_2, INPUT);
  354.     pinMode(ADC_3, INPUT);
  355.     pinMode(ADC_4, INPUT);
  356.  
  357.     pinMode(Relay_1, OUTPUT);
  358.     pinMode(Relay_2, OUTPUT);
  359.     pinMode(Relay_3, OUTPUT);
  360.     pinMode(Relay_4, OUTPUT);
  361.     pinMode(Relay_5, OUTPUT);
  362.     pinMode(Relay_6, OUTPUT);
  363.     pinMode(Relay_7, OUTPUT);
  364.     pinMode(Relay_8, OUTPUT);
  365.     pinMode(LED_1, OUTPUT);
  366.     pinMode(LED_2, OUTPUT);
  367.     // ---------------------------- Timer
  368.     //set timer1 interrupt at 1Hz
  369.     TCCR1A = 0;// set entire TCCR1A register to 0
  370.     TCCR1B = 0;// same for TCCR1B
  371.     TCNT1  = 0;//initialize counter value to 0
  372.     // set compare match register for 1hz increments
  373.     OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  374.     // turn on CTC mode
  375.     TCCR1B |= (1 << WGM12);
  376.     // Set CS12 and CS10 bits for 1024 prescaler
  377.     TCCR1B |= (1 << CS12) | (1 << CS10);  
  378.     // enable timer compare interrupt
  379.     TIMSK1 |= (1 << OCIE1A);
  380.     // ---------------------------- Ethernet Server
  381.     DIP_Temp = DIP_scan();
  382.     Ethernet.init(53); // You can use Ethernet.init(pin) to configure the CS pin
  383.     ethernetConn();
  384.     Udp.begin(localPort);
  385.     // ---------------------------- MQTT
  386.     client.setServer(server, 1883);
  387.     client.setCallback(callback);
  388.     // ---------------------------- Data
  389.     // RelayStates.Byte = 255;
  390.     if (EEPROM.read(EP_KeepAlive) == 255) EEPROM.write(EP_KeepAlive,59);
  391.     keepAliveCout = EEPROM.read(EP_KeepAlive);
  392.     if (EEPROM.read(FirstBoot) > 1)
  393.     {
  394.         EEPROM.write(FirstBoot,1);
  395.         for (i = EP_S1; i < 9; i++) EEPROM.write(i,0);
  396.         for (i = EP_S1; i < 9; i++) RelayStates[i] = 0;
  397.     }else   for (i = EP_S1; i < 9; i++) RelayStates[i] = EEPROM.read(i);
  398.     // Serial.print("FirstBoot ");
  399.     // Serial.println(EEPROM.read(FirstBoot)); // FistBoot = 255
  400.     if (!client.connected()) reconnect();  
  401.     // Udp.begin(localPort);
  402.  
  403.     sendEvent("power-up", 3, "POWERUP=1", "power up/rebooted");
  404.     reconnectRetry = 0;
  405.     upTime_min = 0;
  406.     oneMin = 0;
  407.     oneHour = 0;
  408.     oneHourTask_start = 0;
  409.  
  410.     masterModeMQTT = 0;
  411.     masterModeU0 = 0;
  412.   }
  413.   ISR(TIMER1_COMPA_vect){ //timer1 interrupt 1Hz to increament Uptime
  414.     oneMin++;
  415.     if (oneMin > 59)
  416.     {
  417.       min++;
  418.       upTime_min++;
  419.       oneHour++;
  420.       oneMin = 0;
  421.     }
  422.     if (oneHour > keepAliveCout)
  423.     {
  424.       oneHour = 0;
  425.       oneHourTask_start = 1;
  426.     }
  427.     if (min > 59){
  428.       min = 0;
  429.       hour++;
  430.       if (hour > 23)  hour = 0;
  431.     }
  432.    
  433.   }
  434. // ============================= Loop ========================================== //
  435.  
  436.   void loop()
  437.   {
  438.     long currtmillis = millis();
  439.     if (currtmillis - prevmillis > 1) {
  440.       prevmillis = currtmillis;
  441.  
  442.       // if (!client.connected()) {
  443.       switch (reconnectTask)
  444.       {
  445.         case 0:
  446.           if (!client.connected()) {
  447.             reconnect();
  448.             reconnectDelay = 2000;
  449.             reconnectRetry = 0;
  450.             reconnectTask = 1;
  451.           }
  452.           break;
  453.         case 1:
  454.           if (reconnectDelay > 0) reconnectDelay--;
  455.           else {
  456.             reconnectTask = 0;
  457.             reconnectRetry += 1;
  458.           }
  459.           if (reconnectRetry > 4) reconnectTask = 2;
  460.           break;
  461.         case 2:
  462.           // ---------------------------- MQTT
  463.           client.setServer(server, 1883);
  464.           client.setCallback(callback);
  465.           // ---------------------------- Ethernet Server
  466.           DIP_Temp = DIP_scan();
  467.           ethernetConn();
  468.           reconnectRetry = 0;
  469.           reconnectTask = 0;
  470.           break;
  471.       }
  472.       // }else reconnectTask = 0;
  473.  
  474.       ++oneSTask;
  475.       if(oneSTask > 300){
  476.         oneSTask=0;
  477.         blinkLED = !blinkLED;
  478.         digitalWrite(LED_1, blinkLED);
  479.  
  480.         digitalWrite(RelayArray[RelayRunNB], RelayStates[RelayRunNB]);
  481.         RelayRunNB++;
  482.         if(RelayRunNB > 8) RelayRunNB = 1;
  483.  
  484.         if (oneHourTask_start)
  485.         {
  486.           oneHourTask_start = 0;
  487.           sendEvent("keep-alive", 4, "KEEPALIVE=1", "keep alive every 1H");
  488.         }
  489.  
  490.         // ----------------------------------------------- NTP task
  491.         switch (Udp_Task)
  492.         {
  493.         case 0:
  494.           sendNTPpacket(timeServer); // send an NTP packet to a time server
  495.           Udp_Task++;
  496.           break;
  497.         case 1:
  498.           if (Udp.parsePacket()) {
  499.             // We've received a packet, read the data from it
  500.             Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
  501.  
  502.             // the timestamp starts at byte 40 of the received packet and is four bytes,
  503.             // or two words, long. First, extract the two words:
  504.  
  505.             unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
  506.             unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
  507.             // combine the four bytes (two words) into a long integer
  508.             // this is NTP time (seconds since Jan 1 1900):
  509.  
  510.             unsigned long secsSince1900 = highWord << 16 | lowWord;
  511.             // Serial.print("Seconds since Jan 1 1900 = ");
  512.             // Serial.println(secsSince1900);
  513.  
  514.             // // now convert NTP time into everyday time:
  515.             // Serial.print("Unix time = ");
  516.             // // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
  517.             const unsigned long seventyYears = 2208988800UL;  
  518.             // // subtract seventy years:
  519.             unsigned long epoch = secsSince1900 - seventyYears;
  520.             // // print Unix time:
  521.             // Serial.println(epoch);
  522.  
  523.  
  524.             // print the hour, minute and second:
  525.             Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
  526.             hour = (epoch  % 86400L) / 3600 + 8;
  527.             Serial.print(hour); // print the hour (86400 equals secs per day)
  528.             Serial.print(':');
  529.             if (((epoch % 3600) / 60) < 10) {
  530.               // In the first 10 minutes of each hour, we'll want a leading '0'
  531.               Serial.print('0');
  532.             }
  533.             min = (epoch  % 3600) / 60;
  534.             Serial.print(min); // print the minute (3600 equals secs per minute)
  535.             Serial.print(':');
  536.             if ((epoch % 60) < 10) {
  537.               // In the first 10 seconds of each minute, we'll want a leading '0'
  538.               Serial.print('0');
  539.             }
  540.             Serial.println(epoch % 60); // print the second
  541.             Udp_Task++;
  542.             Udp_Taskdelay = upTime_min;
  543.           }
  544.           break;
  545.         case 2:
  546.           if(hour = 11 && Udp_Taskdelay != 1){
  547.             Udp_Taskdelay = 1;
  548.             Ethernet.maintain();
  549.             Udp_Task = 0;
  550.           }
  551.           if (hour == 12)
  552.           {
  553.             // Udp_Task = 0;
  554.             Udp_Taskdelay = 0;
  555.           }
  556.          
  557.           // if (Udp_Taskdelay > 0) Udp_Taskdelay--;
  558.           // else
  559.           // {
  560.           // }
  561.           break;
  562.  
  563.         default:
  564.           break;
  565.         }
  566.  
  567.        
  568.       }
  569.      
  570.     }
  571.  
  572.     client.loop();
  573.     if (Serial.available()) {
  574.       SerialAvailable();
  575.     }
  576.     if (Serial2.available()) {
  577.       Serial2Available();
  578.     }
  579.  
  580.     wdt_reset();
  581.   }
  582. // ============================= Serial ========================================== //
  583.   void SerialAvailable(){
  584.     char Rx0[100];
  585.     StaticJsonBuffer<100> jsonBuffer;
  586.     Serial.readBytesUntil('\n', Rx0, 100);
  587.     JsonObject& root = jsonBuffer.parseObject(Rx0);
  588.    
  589.     if (!root.success()) {
  590.       Serial.println("{\"Error\":\"parseObject\"}");
  591.       Serial.println(Rx0);
  592.       return;
  593.     }
  594.     else if(root["master"] == 1){
  595.       root.printTo(publishData);
  596.       Serial2.println(publishData);
  597.       masterModeU0 = 1;
  598.     }
  599.     else if(root["test"] == 1){
  600.       Serial.println("{\"recei\":\"test = 1\"}");
  601.     }
  602.     else if(root["name"] == boardName[DIP_Temp]){
  603.       if(root.containsKey("hi")){
  604.         root["name"] = boardName[DIP_Temp];
  605.         root["hi"] = "say hi to master";
  606.  
  607.         root.printTo(publishData);
  608.         Serial.println(publishData);
  609.       }
  610.     }
  611.     if (root["RESET"] == 1) asm volatile ("  jmp 0");
  612.   }
  613. // ============================= Serial 2 ========================================== //
  614.   void Serial2Available(){
  615.     char Rx0[100];
  616.     StaticJsonBuffer<100> jsonBuffer;
  617.     Serial2.readBytesUntil('\n', Rx0, 100);
  618.     JsonObject& root = jsonBuffer.parseObject(Rx0);
  619.    
  620.     if (!root.success()) {
  621.       // Serial2.println("{\"Error\":\"parseObject\"}");
  622.       // Serial2.println(Rx0);
  623.       masterModeU0 = 0;
  624.       masterModeMQTT = 0;
  625.       return;
  626.     }
  627.    
  628.     else if (masterModeU0){
  629.       root.printTo(publishData);
  630.       Serial.println(publishData);
  631.       masterModeU0 = 0;
  632.     }
  633.     else if (masterModeMQTT){
  634.       root.printTo(publishData);
  635.       client.publish("/bg/fc/events",publishData);
  636.       masterModeMQTT = 0;
  637.     }
  638.     else if(root["test"] == 1){
  639.       Serial2.println("{\"recei\":\"test = 1\"}");
  640.     }
  641.  
  642.     else if(root["name"] == boardName[DIP_Temp]){
  643.       if(root.containsKey("hi")){
  644.         root["name"] = boardName[DIP_Temp];
  645.         root["hi"] = "say hi to master";
  646.         root.printTo(publishData);
  647.         Serial2.println(publishData);
  648.       }
  649.       if(root.containsKey(F2) && root[F2] < 2){
  650.         if(root[F2] != RelayStates[8]){
  651.           RelayRunNB = 8;
  652.           EEPROM.write(EP_S8, root[F2]);
  653.           RelayStates[8] = root[F2];  
  654.         }
  655.       }
  656.       if(root.containsKey(F1) && root[F1] < 2){
  657.         if(root[F1] != RelayStates[7]){
  658.           RelayRunNB = 7;
  659.           EEPROM.write(EP_S7, root[F1]);
  660.           RelayStates[7] = root[F1];  
  661.         }
  662.       }
  663.       if(root.containsKey(S6) && root[S6] < 2){
  664.         if(root[S6] != RelayStates[6]){
  665.           RelayRunNB = 6;
  666.           EEPROM.write(EP_S6, root[S6]);
  667.           RelayStates[6] = root[S6];  
  668.         }
  669.       }  
  670.       if(root.containsKey(S5) && root[S5] < 2){
  671.         if(root[S5] != RelayStates[5]){
  672.           RelayRunNB = 5;
  673.           EEPROM.write(EP_S5, root[S5]);
  674.           RelayStates[5] = root[S5];  
  675.         }
  676.       }
  677.       if(root.containsKey(S4) && root[S4] < 2){
  678.         if(root[S4] != RelayStates[4]){
  679.           RelayRunNB = 4;
  680.           EEPROM.write(EP_S4, root[S4]);
  681.           RelayStates[4] = root[S4];  
  682.         }
  683.       }
  684.       if(root.containsKey(S3) && root[S3] < 2){
  685.         if(root[S3] != RelayStates[3]){
  686.           RelayRunNB = 3;
  687.           EEPROM.write(EP_S3, root[S3]);
  688.           RelayStates[3] = root[S3];  
  689.         }
  690.       }
  691.       if(root.containsKey(S2) && root[S2] < 2){
  692.         if(root[S2] != RelayStates[2]){
  693.           RelayRunNB = 2;
  694.           EEPROM.write(EP_S2, root[S2]);
  695.           RelayStates[2] = root[S2];  
  696.         }
  697.       }
  698.       if(root.containsKey(S1) && root[S1] < 2){
  699.         if(root[S1] != RelayStates[1]){
  700.           RelayRunNB = 1;
  701.           EEPROM.write(EP_S1, root[S1]);
  702.           RelayStates[1] = root[S1];  
  703.         }
  704.       }
  705.       if (root["RESET"] == 1) asm volatile ("  jmp 0");
  706.     }
  707.   }
  708. // ============================= Ethernet ========================================== //
  709.   void ethernetConn(){
  710.     char i;
  711.     IPAddress ip(192, 168, 0, DIP_Temp + ETH_ADD_LAST_VALUE);
  712.     byte mac[] = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, DIP_Temp };
  713.     Ethernet.begin(mac, ip);
  714.     // if (Ethernet.begin(mac, ip) == 0) {
  715.     //  Serial.println("Failed to configure Ethernet using DHCP");
  716.     //  // Check for Ethernet hardware present
  717.     //  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
  718.     //    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
  719.     //  } else if (Ethernet.linkStatus() == LinkOFF)
  720.     //    Serial.println("Ethernet cable is not connected.");
  721.     // }else{
  722.       delay(100);
  723.       Serial.print("Ethernet IP: ");
  724.       Serial.print(ip);
  725.       Serial.print("\nMAC: ");
  726.       for(i = 0;i<6;i++){
  727.         Serial.print(mac[i]);
  728.         Serial.print(":");
  729.       }
  730.       Serial.println();
  731.     // }
  732.   }
  733. // ============================= DIP scan ========================================== //
  734.   char DIP_scan(){
  735.     DIP_Struct.bit.r1 = !digitalRead(DIP_1);
  736.     DIP_Struct.bit.r2 = !digitalRead(DIP_2);
  737.     DIP_Struct.bit.r3 = !digitalRead(DIP_3);
  738.     DIP_Struct.bit.r4 = !digitalRead(DIP_4);
  739.     return DIP_Struct.Byte;
  740.     // Serial.print("Dip: ");
  741.     // Serial.println(DIP_Struct.Byte);
  742.   }
  743. // ============================= send Even ========================================== //
  744.   void sendEvent(String type, byte level, String status,String msg)
  745.   {
  746.     // JSON declarations
  747.     StaticJsonBuffer<200> jsonBuffer;
  748.     JsonObject& root = jsonBuffer.createObject();
  749.     root["name"] = boardName[DIP_Temp];
  750.     root["events"] = 1;
  751.     root["uptime"] = upTime_min;
  752.     root["level"] = level;
  753.     root["type"] = type;
  754.     root["status"] = status;
  755.     root["msg"] = msg;
  756.  
  757.     root.printTo(publishData);
  758.     client.publish("/bg/fc/events",publishData);
  759.     Serial.println(publishData);
  760.  
  761.   }
  762.   void publishStatus(){
  763.  
  764.     StaticJsonBuffer<200> jsonBuffer;
  765.     JsonObject& root = jsonBuffer.createObject();
  766.    
  767.     root["name"] = boardName[DIP_Temp];
  768.     // root["events"] = 1;
  769.     root["version"] = version;
  770.     root["uptime"] = upTime_min;
  771.     root["hour"] = hour;
  772.     root["minute"] = min;
  773.     root["level"] = 4;
  774.     root["type"] = "status";
  775.  
  776.     root[S1] = ( RelayStates[1] ? "true":"false" ) ;
  777.     root[S2] = ( RelayStates[2] ? "true":"false" ) ;
  778.     root[S3] = ( RelayStates[3] ? "true":"false" ) ;
  779.     root[S4] = ( RelayStates[4] ? "true":"false" ) ;
  780.     root[S5] = ( RelayStates[5] ? "true":"false" ) ;
  781.     root[S6] = ( RelayStates[6] ? "true":"false" ) ;
  782.     root[F1] = ( RelayStates[7] ? "true":"false" ) ;
  783.     root[F2] = ( RelayStates[8] ? "true":"false" ) ;
  784.  
  785.     root.printTo(publishData);
  786.     client.publish("/bg/fc/racks/status",publishData);
  787.     Serial.println(publishData);
  788.   }
  789.  
  790.   // send an NTP request to the time server at the given address
  791.   void sendNTPpacket(const char * address) {
  792.     // set all bytes in the buffer to 0
  793.     memset(packetBuffer, 0, NTP_PACKET_SIZE);
  794.     // Initialize values needed to form NTP request
  795.     // (see URL above for details on the packets)
  796.     packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  797.     packetBuffer[1] = 0;     // Stratum, or type of clock
  798.     packetBuffer[2] = 6;     // Polling Interval
  799.     packetBuffer[3] = 0xEC;  // Peer Clock Precision
  800.     // 8 bytes of zero for Root Delay & Root Dispersion
  801.     packetBuffer[12]  = 49;
  802.     packetBuffer[13]  = 0x4E;
  803.     packetBuffer[14]  = 49;
  804.     packetBuffer[15]  = 52;
  805.  
  806.     // all NTP fields have been given values, now
  807.     // you can send a packet requesting a timestamp:
  808.     Udp.beginPacket(address, 123); // NTP requests are to port 123
  809.     Udp.write(packetBuffer, NTP_PACKET_SIZE);
  810.     Udp.endPacket();
  811.   }
  812.  
  813. /*
  814. {"test":1}
  815. {"master":1,"name":"rack02","hi":1}
  816.  
  817.  
  818. // {S1:0,S2:0,S3:0,S4:0,S5:0,S6:0,F1:0,F2:0}
  819. // {"S1":0,"S2":0,"S3":0,"S4":0,"S5":0,"S6":0,"S7":0,"S8":0}
  820.  
  821. {"master":1,"name":"rack06","S1":1,"S3":1}
  822.  
  823. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement