Контроллер микроклимата и полива

fedoroff_alexander
Offline
Зарегистрирован: 12.04.2015

 

Контроль микроклимата жилья, полива земли, обустройства теплиц, инкубаторов, помещений для домашних животных, бассейнов, аквариумов, высокогорных террариумов. Все что требует автоматического поддержания температуры, влажности, освещения и давления. Автоматическое управление 12 внешними устройствами Используется микроконтроллер Wemos D1 mini, ESP8266.

Можно без ограничений и условий скачать двоичные файлы программы и WEB сервера для самостоятельной прошивки с использованием IDE Arduino. Дополнительно можно скачать открытый полный исходный код WEB сервера. Полная документация со схемами и описанием подключения и настроек.

К сожалению нет возможности движка форума закачивать архивные файлы поэтому дам ссылку по запросу.

Выдержка из документации: " НАЗНАЧЕНИЕ Устройство серии Интернет вещей (IoT) управляющее включением выключением 12 единиц внешнего оборудования в автоматическом режиме. Для управления настройками параметров температуры, влажности, давления, освещения и контроля внешнего оборудования имеется возможность подключения к облачным программным сервисам и управлением через мобильные устройства. Встроенный асинхронный WEB сервер так же, одновременно позволяет управлять и контролировать параметры из WEB браузера пользователя. Существует возможность подключить одну внешнюю IP видеокамеру указав строку подключения в оконном интерфейсе. Открытый и документированный программный интерфейс (API) позволяет подключать собственное внешнее программное обеспечение. Из него также возможно управлять включением внешнего оборудования или контролировать параметры. Интересующийся пользователь способен самостоятельно подключить голосовое управление с мобильного устройства. Например, голосовой сервис Яндекса Алиса и домовёнок Кузя. Открытый WEB интерфейс позволяет задействовать и другие Интернет сервисы такие как Telegram, Google, Facebook"

fedoroff_alexander
Offline
Зарегистрирован: 12.04.2015

fedoroff_alexander пишет:

 

Контроль микроклимата жилья, полива земли, обустройства теплиц, инкубаторов, помещений для домашних животных, бассейнов, аквариумов, высокогорных террариумов. Все что требует автоматического поддержания температуры, влажности, освещения и давления. Автоматическое управление 12 внешними устройствами Используется микроконтроллер Wemos D1 mini, ESP8266.

Можно без ограничений и условий скачать двоичные файлы программы и WEB сервера для самостоятельной прошивки с использованием IDE Arduino. Дополнительно можно скачать открытый полный исходный код WEB сервера. Полная документация со схемами и описанием подключения и настроек.

К сожалению нет возможности движка форума закачивать архивные файлы поэтому дам ссылку по запросу.

Выдержка из документации: " НАЗНАЧЕНИЕ Устройство серии Интернет вещей (IoT) управляющее включением выключением 12 единиц внешнего оборудования в автоматическом режиме. Для управления настройками параметров температуры, влажности, давления, освещения и контроля внешнего оборудования имеется возможность подключения к облачным программным сервисам и управлением через мобильные устройства. Встроенный асинхронный WEB сервер так же, одновременно позволяет управлять и контролировать параметры из WEB браузера пользователя. Существует возможность подключить одну внешнюю IP видеокамеру указав строку подключения в оконном интерфейсе. Открытый и документированный программный интерфейс (API) позволяет подключать собственное внешнее программное обеспечение. Из него также возможно управлять включением внешнего оборудования или контролировать параметры. Интересующийся пользователь способен самостоятельно подключить голосовое управление с мобильного устройства. Например, голосовой сервис Яндекса Алиса и домовёнок Кузя. Открытый WEB интерфейс позволяет задействовать и другие Интернет сервисы такие как Telegram, Google, Facebook"

Исходный код IP Web видеокамеры для проекта Climatic Post

003//C:\Users\alex\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.6\libraries\HTTPUpdateServer\examples\WebUpdater
004//описание RTSP протокола и сервера <a href="https://www.medialan.de/usecase0001.html" title="https://www.medialan.de/usecase0001.html" rel="nofollow">https://www.medialan.de/usecase0001.html</a>
005/****************************************************************************************************************************************************
006 *  TITLE: HOW TO BUILD A $9 RSTP VIDEO STREAMER: Using The ESP-32 CAM Board || Arduino IDE - DIY #14
007 *  DESCRIPTION: This sketch creates a video streamer than uses RTSP. You can configure it to either connect to an existing WiFi network or to create
008 *  a new access point that you can connect to, in order to stream the video feed.
009 *
010 *  By Frenoy Osburn
011 *  YouTube Video: <a href="https://youtu.be/1xZ-0UGiUsY" title="https://youtu.be/1xZ-0UGiUsY" rel="nofollow">https://youtu.be/1xZ-0UGiUsY</a>
013 ****************************************************************************************************************************************************/
014 
015  /********************************************************************************************************************
016 *  AI_THINKER
017 *  Board Settings:
018 *  Board: "ESP32 Wrover Module"
019 *  Upload Speed: "921600"
020 *  Flash Frequency: "80MHz"
021 *  Flash Mode: "QIO"
022 *  Partition Scheme: "Hue APP (3MB No OTA/1MB SPIFFS)"
023 *  Core Debug Level: "None"
024 *  COM Port: Depends *On Your System*
025 *********************************************************************************************************************/
026 
027#include "src/OV2640.h"
028#include <WiFi.h>
029#include <WebServer.h>
030#include <WiFiClient.h>
031#include "src/SimStreamer.h"
032#include "src/OV2640Streamer.h"
033#include "src/CRtspSession.h"
034#include <WiFiManager.h>         //<a href="https://github.com/tzapu/WiFiManager" rel="nofollow">https://github.com/tzapu/WiFiManager</a>
035#include <HTTPUpdateServer.h>
036//#define ENABLE_OLED //if want use oled ,turn on thi macro
037#define ENABLE_WEBSERVER
038#define ENABLE_RTSPSERVER
039 
040#ifdef ENABLE_OLED
041#include "SSD1306.h"
042#define OLED_ADDRESS 0x3c
043#define I2C_SDA 14
044#define I2C_SCL 13
045SSD1306Wire display(OLED_ADDRESS, I2C_SDA, I2C_SCL, GEOMETRY_128_32);
046bool hasDisplay; // we probe for the device at runtime
047#endif
048 
049// Select camera model
050//#define CAMERA_MODEL_WROVER_KIT
051//#define CAMERA_MODEL_ESP_EYE
052//#define CAMERA_MODEL_M5STACK_PSRAM
053//#define CAMERA_MODEL_M5STACK_WIDE
054#define CAMERA_MODEL_AI_THINKER
055 
056#include "camera_pins.h"
057 
058OV2640 cam;
059 
060#ifdef ENABLE_WEBSERVER
061WebServer server(81);
062HTTPUpdateServer httpUpdater;
063#endif
064 
065#ifdef ENABLE_RTSPSERVER
066WiFiServer rtspServer(8554);
067#endif
068 
069#ifdef ENABLE_WEBSERVER
070void handle_jpg_stream(void)
071{
072    WiFiClient client = server.client();
073    String response = "HTTP/1.1 200 OK\r\n";
074    response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
075    server.sendContent(response);
076 
077    while (1)
078    {
079        cam.run();
080        if (!client.connected())
081            break;
082        response = "--frame\r\n";
083        response += "Content-Type: image/jpeg\r\n\r\n";
084        server.sendContent(response);
085   
086        client.write((char *)cam.getfb(), cam.getSize());
087        server.sendContent("\r\n");
088        if (!client.connected())
089            break;
090        if(digitalRead(12) == HIGH)
091          digitalWrite(4, HIGH);
092        else
093          digitalWrite(4, LOW);
094    }
095}
096 
097void handle_jpg(void)
098{
099    WiFiClient client = server.client();
100 
101    cam.run();
102    if (!client.connected())
103    {
104        return;
105    }
106    String response = "HTTP/1.1 200 OK\r\n";
107    response += "Content-disposition: inline; filename=capture.jpg\r\n";
108    response += "Content-type: image/jpeg\r\n\r\n";
109    server.sendContent(response);
110    client.write((char *)cam.getfb(), cam.getSize());
111}
112 
113void handleNotFound()
114{
115    String message = "Server is running!\n\n";
116    message += "URI: ";
117    message += server.uri();
118    message += "\nMethod: ";
119    message += (server.method() == HTTP_GET) ? "GET" : "POST";
120    message += "\nArguments: ";
121    message += server.args();
122    message += "\n";
123    server.send(200, "text/plain", message);
124}
125#endif
126 
127void lcdMessage(String msg)
128{
129  #ifdef ENABLE_OLED
130    if(hasDisplay) {
131        display.clear();
132        display.drawString(128 / 2, 32 / 2, msg);
133        display.display();
134    }
135  #endif
136}
137 
138void setup()
139{
140  Serial.begin(115200);
141  WiFiManager wm;
142  //wm.resetSettings(); // wipe settings
143  bool res;
144  //res = wm.autoConnect(); // auto generated AP name from chipid
145  // res = wm.autoConnect("AutoConnectAP"); // anonymous ap
146  res = wm.autoConnect("CAM32","12345678"); // password protected ap
147  if(!res) {
148        Serial.println("Failed to connect");
149        // ESP.restart();
150  }
151  else {
152        //if you get here you have connected to the WiFi   
153        Serial.println("connected...yeey :)");
154  }
155  #ifdef ENABLE_OLED
156    hasDisplay = display.init();
157    if(hasDisplay) {
158        display.flipScreenVertically();
159        display.setFont(ArialMT_Plain_16);
160        display.setTextAlignment(TEXT_ALIGN_CENTER);
161    }
162  #endif
163  //lcdMessage("booting");
164    String IpAdr += WiFi.localIP().toString();
165    Serial.print("1. <a href="" title="http://"">http://"</a>); Serial.print(IpAdr); Serial.println(":81");
166    Serial.print("2. Stream Link: rtsp://"); Serial.print(IpAdr); Serial.println(":8554/mjpeg/1");
167    Serial.println("3. Picture: <a href="http://LocalIP:81//jpg" title="http://LocalIP:81//jpg"" rel="nofollow">http://LocalIP:81//jpg"</a>);
168    Serial.printf("4. HTTPUpdateServer ready! Open <a href="/update" title="http://%s:81/update">http://%s:81/update</a> in your browser\n", IpAdr );
169    //Serial.println("4. HTTPUpdateServer ready! Open <a href="http://LocalIP:81/update" title="http://LocalIP:81/update"" rel="nofollow">http://LocalIP:81/update"</a>);
170 
171    camera_config_t config;
172    config.ledc_channel = LEDC_CHANNEL_0;
173    config.ledc_timer = LEDC_TIMER_0;
174    config.pin_d0 = Y2_GPIO_NUM;
175    config.pin_d1 = Y3_GPIO_NUM;
176    config.pin_d2 = Y4_GPIO_NUM;
177    config.pin_d3 = Y5_GPIO_NUM;
178    config.pin_d4 = Y6_GPIO_NUM;
179    config.pin_d5 = Y7_GPIO_NUM;
180    config.pin_d6 = Y8_GPIO_NUM;
181    config.pin_d7 = Y9_GPIO_NUM;
182    config.pin_xclk = XCLK_GPIO_NUM;
183    config.pin_pclk = PCLK_GPIO_NUM;
184    config.pin_vsync = VSYNC_GPIO_NUM;
185    config.pin_href = HREF_GPIO_NUM;
186    config.pin_sscb_sda = SIOD_GPIO_NUM;
187    config.pin_sscb_scl = SIOC_GPIO_NUM;
188    config.pin_pwdn = PWDN_GPIO_NUM;
189    config.pin_reset = RESET_GPIO_NUM;
190    config.xclk_freq_hz = 20000000;
191    config.pixel_format = PIXFORMAT_JPEG;
192    config.frame_size = FRAMESIZE_SVGA;
193    //config.frame_size = FRAMESIZE_VGA;
194    config.jpeg_quality = 12;
195    config.fb_count = 2;      
196   
197    #if defined(CAMERA_MODEL_ESP_EYE)
198      pinMode(13, INPUT_PULLUP);
199      pinMode(14, INPUT_PULLUP);
200    #endif
201   
202    cam.init(config);
203     
204    IPAddress ip;
205 
206    
207#ifdef ENABLE_WEBSERVER
208    server.on("/", HTTP_GET, handle_jpg_stream);
209    server.on("/jpg", HTTP_GET, handle_jpg);
210    httpUpdater.setup(&server);
211    server.onNotFound(handleNotFound);
212    server.begin();
213#endif
214 
215#ifdef ENABLE_RTSPSERVER
216    rtspServer.begin();
217#endif
218pinMode(12, INPUT); //включение светодиода
219digitalWrite(12,LOW);
220pinMode(4, OUTPUT); //светодиод flash
221digitalWrite(4,HIGH);
222delay(1000);
223digitalWrite(4, LOW);
224delay(1000);
225}
226 
227CStreamer *streamer;
228CRtspSession *session;
229WiFiClient client; // FIXME, support multiple clients
230 
231void loop()
232{
233#ifdef ENABLE_WEBSERVER
234    server.handleClient(); //для сервера Updater
235#endif
236 
237#ifdef ENABLE_RTSPSERVER
238    uint32_t msecPerFrame = 100;
239    static uint32_t lastimage = millis();
240 
241    // If we have an active client connection, just service that until gone
242    // (FIXME - support multiple simultaneous clients)
243    if(session) {
244        session->handleRequests(0); // we don't use a timeout here,
245        // instead we send only if we have new enough frames
246 
247        uint32_t now = millis();
248        if(now > lastimage + msecPerFrame || now < lastimage) { // handle clock rollover
249            session->broadcastCurrentFrame(now);
250            lastimage = now;
251 
252            // check if we are overrunning our max frame rate
253            now = millis();
254            if(now > lastimage + msecPerFrame)
255                printf("warning exceeding max frame rate of %d ms\n", now - lastimage);
256        }
257 
258        if(session->m_stopped) {
259            delete session;
260            delete streamer;
261            session = NULL;
262            streamer = NULL;
263        }
264    }
265    else {
266        client = rtspServer.accept();
267 
268        if(client) {
269            //streamer = new SimStreamer(&client, true);  // our streamer for UDP/TCP based RTP transport
270            streamer = new OV2640Streamer(&client, cam);  // our streamer for UDP/TCP based RTP transport
271 
272            session = new CRtspSession(&client, streamer); // our threads RTSP session and state
273        }
274    }
275#endif
276    if(digitalRead(12) == HIGH)
277          digitalWrite(4, HIGH);
278    else
279          digitalWrite(4, LOW);
280}