IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Arduino Discussion :

Serveur NTP et IOT


Sujet :

Arduino

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éprouvé
    Inscrit en
    Juillet 2004
    Messages
    954
    Détails du profil
    Informations forums :
    Inscription : Juillet 2004
    Messages : 954
    Par défaut Serveur NTP et IOT
    Bonjour à tous,

    en complément avec mon précédent post, je souhaitais pouvoir faire un server NTP et ensuite distribuer l'heure et la date à l'ensemble des objets connectés en local
    j'ai donc fait ce petit croquis sans prétention qui me donne l'heure et la date du jour mais je ne saisis pas bien comment faire pour interroger ce serveur à distance et utiliser ses données

    je dispose pour ce serveur :
    N° IP
    N° Port

    comment faire ensuite, j'avais l'idée par exemple de faire une horloge pour enfant à partir d'une matrice 16x16
    mais je ne vois comment y parvenir pour traiter le paquet ?

    merci par avance pour vos idées ...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
     
    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include <WiFiUdp.h>
    #include <Wire.h>
    #include <FS.h> // FOR SPIFFS
    #include <ctype.h> // for isNumber check
    #include "Time.h"
    #include "TimeLib.h"
    #include "SSD1306.h"
     
     
    const char ssid[] = "xxxxxxx";  //  le SSID (nom) de votre réseau
    const char pass[] = "xxxxxx";       // votre mot de passe réseau
    const String fName = "props.txt"; // fichier de propriétés
     
    float UTCoffset = 0;
    unsigned long lastMillis = 0;
    unsigned long currentMillis = 0;
    unsigned long secsSince1900 = 0;
    bool daylightSavings = false;
    bool hourTime = false;
    //int interval = 30000; //
    int interval = 900*1000;
    String timeStr = "";
    String webMessage = "";
    String dateStr = "";
     
    unsigned int localPort = 2390;      // port local pour l'écoute des paquets UDP
     
    /* Ne pas câbler l'adresse IP ou nous n'obtiendrons pas les avantages du pool.
        Rechercher l'adresse IP pour le nom d'hôte à la place */
    //IPAddress timeServer(129, 6, 15, 28) ; // serveur NTP time.nist.gov
    IPAddress timeServerIP; // time.nist.gov NTP server address
    const char* ntpServerName = "time.nist.gov";
     
    const int NTP_PACKET_SIZE = 48; // L'horodatage NTP se trouve dans les 48 premiers octets du message.
     
    byte packetBuffer[ NTP_PACKET_SIZE]; //tampon pour contenir les paquets entrants et sortants
     
    // Une instance UDP pour nous permettre d'envoyer et de recevoir des paquets via UDP
    WiFiUDP udp;
     
    // Initialiser l'écran OLED à l'aide de la bibliothèque Wire
    // l'adresse I2C "0x3c" a été déterminée en utilisant le sketch I2C_Scanner.ino
    SSD1306  display(0x3c, D3, D5);
     
    ESP8266WebServer server(80);
     
     
    ///////////////////////////////////////////////////////////////////////////
    // Time functions
    ////////////////////////////////////////////////////////////////////////////
     
    // envoie une requête NTP au serveur de temps à l'adresse donnée
    //unsigned long sendNTPpacket(IPAddress& address)
    void sendNTPpacket(IPAddress& address)
    {
      Serial.println("sending NTP packet...");
      // mettre tous les octets de la mémoire tampon à 0
      memset(packetBuffer, 0, NTP_PACKET_SIZE);
      // Initialiser les valeurs nécessaires à la formation de la requête NTP
      // (voir l'URL ci-dessus pour plus de détails sur les paquets)
      packetBuffer[0] = 0b11100011;   // LI, version, mode
      packetBuffer[1] = 0;     // Strate, ou type d'horloge
      packetBuffer[2] = 6;     // Intervalle d'interrogation
      packetBuffer[3] = 0xEC;  // Précision de l'horloge du pair
      // 8 octets de zéro pour le délai racine et la dispersion racine
      packetBuffer[12]  = 49;
      packetBuffer[13]  = 0x4E;
      packetBuffer[14]  = 49;
      packetBuffer[15]  = 52;
     
      // tous les champs NTP ont reçu des valeurs, maintenant
      // vous pouvez envoyer un paquet demandant un horodatage :
      udp.beginPacket(address, 123); //NTP requests are to port 123
      udp.write(packetBuffer, NTP_PACKET_SIZE);
      udp.endPacket();
    }
     
    /////////////////////////////////////////////////////////////////////////////////////
     
     
    void setDateTime()
    {
     
      unsigned long epoch;
     
      Serial.print(".....Updating Time.....");
     
      display.clear();
      display.drawString(0, 0,  timeStr);
      display.drawString(0, 19, dateStr);
      display.drawString(0, 40, "--- MAJ ---");
      display.display();
     
      lastMillis = currentMillis;
     
      //get a random server from the pool
      WiFi.hostByName(ntpServerName, timeServerIP);
     
      sendNTPpacket(timeServerIP); // envoie un paquet NTP à un serveur de temps
      // attend de voir si une réponse est disponible
      delay(1000);
     
      int cb = udp.parsePacket();
      if (!cb) {
        Serial.println("pas encore de paquet");
      }
      else {
        Serial.print("paquet reçu, longueur=");
        Serial.println(cb);
        // Nous avons reçu un paquet, lisons les données qu'il contient
        udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
     
        //l'horodatage commence à l'octet 40 du paquet reçu et est de quatre octets,
        // ou deux mots. Commençons par extraire les deux mots :
     
        unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
        unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
        // combine les quatre octets (deux mots) en un entier long
        // il s'agit du temps NTP (secondes depuis le 1er janvier 1900) :
        secsSince1900 = highWord << 16 | lowWord;
     
      }
      //Serial.print("secsSince1900 : ") ;
      //Serial.println(secsSince1900) ;
      const unsigned long seventyYears = 2208988800UL;
      // soustraire soixante-dix ans :
      epoch = secsSince1900 - seventyYears;
     
      epoch = epoch + (int)(UTCoffset * 3600);
      if (daylightSavings)
      {
        epoch = epoch + 3600;
      }
     
      setTime(epoch);
     
    }
     
    /////////////////////////////////////////
    //        HTML functions
    ////////////////////////////////////////
     
    String getDropDown()
    {
      String webString = "";
      webString += "<select name=\"timezone\">\n";
      webString += "   <option value=\"1\" ";
      if (UTCoffset == -12)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -12:00) Eniwetok, Kwajalein</option>\n";
     
      webString += "   <option value=\"-11\" ";
      if (UTCoffset == -11)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -11:00) Midway Island, Samoa</option>\n";
     
      webString += "   <option value=\"-10\" ";
      if (UTCoffset == -10)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -10:00) Hawaii</option>\n";
     
      webString += "   <option value=\"-9\" ";
      if (UTCoffset == -9)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -9:00) Alaska</option>\n";
     
      webString += "   <option value=\"-8\" ";
      if (UTCoffset == -8)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -8:00) Pacific Time (US &amp; Canada)</option>\n";
     
      webString += "   <option value=\"-7\" ";
      if (UTCoffset == -7)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -7:00) Mountain Time (US &amp; Canada)</option>\n";
     
      webString += "   <option value=\"-6\" ";
      if (UTCoffset == -6)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -6:00) Central Time (US &amp; Canada), Mexico City</option>\n";
     
      webString += "   <option value=\"-5\" ";
      if (UTCoffset == -5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -5:00) Eastern Time (US &amp; Canada), Bogota, Lima</option>\n";
     
      webString += "   <option value=\"-4.5\" ";
      if (UTCoffset == -4.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -4:30) Caracas</option>\n";
     
      webString += "   <option value=\"-4\" ";
      if (UTCoffset == -4)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -4:00) Atlantic Time (Canada), La Paz, Santiago</option>\n";
     
      webString += "   <option value=\"-3.5\" ";
      if (UTCoffset == -3.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -3:30) Newfoundland</option>\n";
     
      webString += "   <option value=\"-3\" ";
      if (UTCoffset == -3)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -3:00) Brazil, Buenos Aires, Georgetown</option>\n";
     
      webString += "   <option value=\"-2\" ";
      if (UTCoffset == -2)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -2:00) Mid-Atlantic</option>\n";
     
      webString += "   <option value=\"-1\" ";
      if (UTCoffset == -1)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT -1:00 hour) Azores, Cape Verde Islands</option>\n";
     
      webString += "   <option value=\"0\" ";
      if (UTCoffset == 0)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT) Western Europe Time, London, Lisbon, Casablanca, Greenwich</option>\n";
     
      webString += "   <option value=\"1\" ";
      if (UTCoffset == 1)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +1:00 hour) Brussels, Copenhagen, Madrid, Paris</option>\n";
     
      webString += "   <option value=\"2\" ";
      if (UTCoffset == 2)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +2:00) Kaliningrad, South Africa, Cairo</option>\n";
     
      webString += "   <option value=\"3\" ";
      if (UTCoffset == 3)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg</option>\n";
     
      webString += "   <option value=\"3.5\" ";
      if (UTCoffset == 3.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +3:30) Tehran</option>\n";
     
      webString += "   <option value=\"4\" ";
      if (UTCoffset == 4)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +4:00) Abu Dhabi, Muscat, Yerevan, Baku, Tbilisi</option>\n";
     
      webString += "   <option value=\"4.5\" ";
      if (UTCoffset == 4.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +4:30) Kabul</option>\n";
     
      webString += "   <option value=\"5\" ";
      if (UTCoffset == 5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent</option>\n";
     
      webString += "   <option value=\"5.5\" ";
      if (UTCoffset == 5.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +5:30) Mumbai, Kolkata, Chennai, New Delhi</option>\n";
     
      webString += "   <option value=\"5.75\" ";
      if (UTCoffset == 5.75)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +5:45) Kathmandu</option>\n";
     
      webString += "   <option value=\"6\" ";
      if (UTCoffset == 6)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +6:00) Almaty, Dhaka, Colombo</option>\n";
     
      webString += "   <option value=\"6.5\" ";
      if (UTCoffset == 6.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +6:30) Yangon, Cocos Islands</option>\n";
     
      webString += "   <option value=\"7\" ";
      if (UTCoffset == 7)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +7:00) Bangkok, Hanoi, Jakarta</option>\n";
     
      webString += "   <option value=\"8\" ";
      if (UTCoffset == 8)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +8:00) Beijing, Perth, Singapore, Hong Kong</option>\n";
     
      webString += "   <option value=\"9\" ";
      if (UTCoffset == 9)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk</option>\n";
     
      webString += "   <option value=\"9.5\" ";
      if (UTCoffset == 9.5)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +9:30) Adelaide, Darwin</option>\n";
     
      webString += "   <option value=\"10\" ";
      if (UTCoffset == 10)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +10:00) Eastern Australia, Guam, Vladivostok</option>\n";
     
      webString += "   <option value=\"11\" ";
      if (UTCoffset == 11)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +11:00) Magadan, Solomon Islands, New Caledonia</option>\n";
     
      webString += "   <option value=\"12\" ";
      if (UTCoffset == 12)
        webString += " selected=\"seleted\" ";
      webString += ">(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka</option>\n";
      webString += "  </select>\n";
     
      return webString;
    }
     
    ////////////////////////////////////////////////////////////////////
     
    String getAJAXcode()
    {
     
      String webStr = "";
      webStr += "<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> \n";
      webStr += "<script>\n";
     
      webStr += " function loadTime() { \n";
      webStr += " $(\"#timeDiv\").load(\"http://" + WiFi.localIP().toString() + "/time\"); \n";
      webStr += "} \n\n";
     
      webStr += " setInterval(loadTime, 1000); \n"; // toutes les x milli secondes
      webStr += " loadTime(); \n";// on load
     
      webStr += " </script> \n";
      return webStr;
    }
     
    ///////////////////////////////////////////////////////////////////////////////////////
     
    String setHTML()
    {
      String webString = "<html><head>\n";
      //  webString += "<meta http-equiv=\"refresh\" content=\"30;url=http://" + WiFi.localIP().toString() + "\N"> \N" ;
      webString += getAJAXcode();
      webString += "</head><body>\n";
      webString += "<form action=\"http://" + WiFi.localIP().toString() + "/submit\" method=\"POST\">";
      webString += "<h1>ESP8266-12E OLED Clock IoT </h1>\n";
      webString += "<div style=\"color:red\">" + webMessage + "</div>\n";
     
      webString += "<div id=\"timeDiv\" style=\"color:blue; font-size:24px; font-family:'Comic Sans MS'\">" + dateStr + " &nbsp; &nbsp; &nbsp; " + timeStr + "</div>\n";
     
      webString += "<br><br>" + getDropDown();
     
      webString += "<br><table style=\"width:400px;\"><tr>";
      webString += "<td style=\"text-align:right\">";
      webString += "<div>Time Server Update Interval: </div>\n";
      webString += "<div>Daylight Savings: </div>\n";
      webString += "<div>24 hour: </div>\n";
      webString += "</td>";
      webString += "<td>";
      webString += " <input type='text' value='" + String(interval / 1000) + "' name='interval' maxlength='10' size='4'> (secs)<br>\n";
     
      if (daylightSavings)
        webString += " <input type='checkbox' checked name='daySave' value='" +  String(daylightSavings) + "'/>";
      else
        webString += " <input type='checkbox' name='daySave' value='" +  String(daylightSavings) + "'  />";
     
     
      if (hourTime)
        webString += "<br><input type='checkbox' checked name='24hour' value='" +  String(hourTime) + "'/>";
      else
        webString += "<br><input type='checkbox' name='24hour' value='" +  String(hourTime) + "'  />";
     
      webString += " <input type='submit' value='Submit' >\n";
     
      webString += "</td></tr></table>\n";
     
      webString += "<div><a href=\"/\">Refresh</a></div> \n";
      webString += "</form></body></html>\n";
      return webString;
    }
     
     
    /////////////////////////////////////////////////////////////
    //   File functions
    /////////////////////////////////////////////////////////////
     
    void updateProperties()
    {
      File f = SPIFFS.open(fName, "w");
      if (!f) {
     
        Serial.println("Echec de l'ouverture d'un fichier pour les proprietes");
      }
      else
      {
        Serial.println("====== Updating to properties file =========");
        display.clear();
        display.drawString(0, 0, " MAJ");
        display.drawString(0, 19, "propriétés");
        display.drawString(0, 40, "des dossiers...");
        display.display();
     
        f.print(UTCoffset); f.print( ","); f.print(daylightSavings);
        f.print("~"); f.print(interval);
        f.print(":"); f.println(hourTime);
     
        Serial.println("MAJ du fichier des propriétés");
     
        f.close();
      }
    }
     
    /////////////////////////////////////////
     
    void initPropFile()
    {
     
      SPIFFS.begin();
      delay(10);
      /////////////////////////////////////////////////////////
      // SPIFFS.format() ; // décommenter pour effacer complètement les données
      // return;
      ///////////////////////////////////////////////////////////
      File f = SPIFFS.open(fName, "r");
     
      if (!f) {
     
        Serial.println("Veuillez attendre 30 secondes pour que SPIFFS soit formaté.");
     
        display.clear();
        display.drawString(0, 0,  "Formatage...");
        display.drawString(0, 19, "Veuillez patienter 30");
        display.drawString(0, 40, "secondes.");
        display.display();
     
        SPIFFS.format();
     
        Serial.println("Formatage Spiffs");
     
        updateProperties();
     
      }
      else
      {
        Serial.println("Le fichier de propriétés existe. Lecture.");
     
        while (f.available()) {
     
          //Lisons ligne par ligne le fichier
          String str = f.readStringUntil('\n');
     
          String offsetStr = str.substring(0, str.indexOf(",")  );
          String dSavStr = str.substring(str.indexOf(",") + 1, str.indexOf("~") );
          String intervalStr = str.substring(str.indexOf("~") + 1, str.indexOf(":") );
          String hourStr = str.substring(str.indexOf(":") + 1 );
     
          UTCoffset = offsetStr.toFloat();
          daylightSavings = dSavStr.toInt();
          interval = intervalStr.toInt();
          hourTime = hourStr.toInt();
     
        }
     
        f.close();
      }
     
    }
     
    //////////////////////////////////////////////////////////
    // utilisé pour vérifier les erreurs de saisie dans la zone de texte
    /////////////////////////////////////////////////////////
     
    boolean isValidNumber(String str) {
      for (byte i = 0; i < str.length(); i++)
      {
        if (isDigit(str.charAt(i))) return true;
      }
      return false;
    }
     
    //////////////////////////////////////////////////////////////////////////////////////
    /// les gestionnaires de clientèle
    //////////////////////////////////////////////////////////////////////////////////////
     
    void handle_submit() {
     
      webMessage = "";
      daylightSavings = false;
      hourTime = false;
     
      if (server.args() > 0 ) {
        for ( uint8_t i = 0; i < server.args(); i++ ) {
     
          // peut être utile pour déterminer les valeurs d'un formulaire.
          //  webMessage += "<br>Server arg " + server.arg(i);
          //  webMessage += "<br>Server argName " + server.argName(i);
     
          if (server.argName(i) == "daySave") {
            // checkbox is checked
            daylightSavings = true;
          }
     
          if (server.argName(i) == "24hour") {
            // checkbox is checked
            hourTime = true;
          }
     
          if (server.argName(i) == "interval") {
     
            if (isValidNumber(server.arg(i)) ) // vérification des erreurs pour s'assurer que nous avons un numéro
            {
              interval = server.arg(i).toInt() * 1000;
            }
            else
            {
              webMessage = "L'intervalle doit être un nombre valide";
            }
     
          }
     
          if (server.argName(i) == "fuseau horaire") {
     
            UTCoffset = server.arg(i).toFloat();
          }
     
        }
      }
     
      if (webMessage == "")
      {
        updateProperties();
        webMessage = "Mise à jour des paramètres";
      }
     
      setDateTime();
     
      String webString = setHTML();
      server.send(200, "text/html", webString);            // envoyer vers le navigateur d'une personne lorsque cela lui est demandé
     
    }
     
     
    //////////////////////////////////////////////////////////////////////////////////////
     
    void handle_time() // cette fonction gère l'appel AJAX
    {
      server.send(200, "text/html", dateStr + " &nbsp; &nbsp; &nbsp; " + timeStr);
    }
     
    ////////////////////////////////////////////////////////////////////////////////////////
     
    void handle_root() {
     
      webMessage = "";
      String webString = setHTML();
      server.send(200, "text/html", webString);            // envoyer vers le navigateur d'une personne lorsque cela lui est demandé
     
    }
     
     
    ////////////////////////////////////////////////////////////////////////////////////////
     
    void setup() {
     
      Serial.begin(115200);
      Serial.println("Démarrage...");
     
      display.init();
     
      display.flipScreenVertically();
      display.setFont(ArialMT_Plain_16);
      display.setTextAlignment(TEXT_ALIGN_LEFT);
     
     
      // Nous commençons par nous connecter à un réseau WiFi
      Serial.print("Se connecter à ");
      Serial.println(ssid);
      WiFi.begin(ssid, pass);
     
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
     
      // créer et/ou lire un fichier de propriétés
      initPropFile();
     
      Serial.println("WiFi connecte");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
     
      Serial.println("Démarrage de l'UDP");
      udp.begin(localPort);
      Serial.print("Local port: ");
      Serial.println(udp.localPort());
     
      server.on("/", handle_root);
     
      server.on("/submit", handle_submit);
     
      server.on("/time", handle_time); // Utilisé pour les appels AJAX
     
      server.begin();
     
      delay(100);
     
      setDateTime();
     
      if (secsSince1900 == 0) // réessayer, le serveur NTP n'a peut-être pas répondu à temps
        setDateTime();
     
    }
     
     
    //////////////////////////////////////////////////
     
    void loop() {
     
      currentMillis = millis();
     
      String AmPm = "";
     
      // Combien de temps s'est écoulé, en tenant compte de la reconduction par soustraction !
      if ((unsigned long)(currentMillis - lastMillis) >= interval )
      {
        setDateTime();
      }
     
      // configurer l'heure et la dateChaîne de caractères
     
      int thour = hour();
     
      if (!hourTime) // s'il ne s'agit pas d'un horaire de 24 heures
      {
        AmPm = "AM";
        if (thour > 12)
        {
          thour = thour - 12;
          AmPm = "PM";
        }
        else
        {
          AmPm = "AM";
          if (thour == 12)
            AmPm = "PM";
        }
        if (thour == 0)
          thour = 12;
      }
      timeStr = thour;
     
      Serial.print("L'heure est ");
      Serial.print(hour());
      Serial.print(':');
      timeStr += ":";
     
      if ( minute() < 10 ) {
        // Dans les 10 premières minutes de chaque heure, nous voudrons un "0" initial
        Serial.print('0');
        timeStr += "0";
      }
     
      Serial.print(minute());
     
      timeStr += minute();
      Serial.print(':');
      timeStr += ":";
     
      if ( second() < 10 ) {
        // Dans les 10 premières secondes de chaque minute, nous voudrons un "0" initial
        Serial.print('0');
        timeStr += "0";
      }
     
      Serial.println(second());
     
      timeStr += second();
      timeStr += " " + AmPm;
     
      dateStr = day();
      dateStr += ".";
      dateStr += month();
      dateStr += "." ;
      dateStr += year();
     
      Serial.println(dateStr);
     
      display.clear();
      display.drawString(0, 0,  timeStr);
      display.drawString(0, 19, dateStr);
      display.drawString(0, 40, WiFi.localIP().toString());
      display.display();
     
      server.handleClient();
     
      delay(1000); // délai d'une seconde avant la mise à jour de l'écran OLED
     
     
    }

  2. #2
    Responsable Arduino et Systèmes Embarqués


    Avatar de f-leb
    Homme Profil pro
    Enseignant
    Inscrit en
    Janvier 2009
    Messages
    13 194
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Janvier 2009
    Messages : 13 194
    Billets dans le blog
    47
    Par défaut
    Salut,

    Citation Envoyé par cobra38 Voir le message
    en complément avec mon précédent post, je souhaitais pouvoir faire un server NTP et ensuite distribuer l'heure et la date à l'ensemble des objets connectés en local
    Je n'ai pas lu tout ton code (+700 lignes quand même...) mais je lis que tu as déjà configuré un serveur Web (port 80) sur ton serveur NTP.

    Le plus simple est d'ajouter une route /ntp qui renverrait la date/heure au format texte ou JSON.

    Les autres clients devront faire une requête http GET /ntp à l'url http://ip_serveur/time pour recevoir la date/heure. Localement, avec millis(), tu continues à faire tourner l'heure. Il faudra réinterroger le serveur de temps en temps pour se resynchroniser.

  3. #3
    Membre éprouvé
    Inscrit en
    Juillet 2004
    Messages
    954
    Détails du profil
    Informations forums :
    Inscription : Juillet 2004
    Messages : 954
    Par défaut
    Salut f-leb

    j'ai essayé çà avec la fonction configTime()


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    #include <ESP8266WiFi.h>
    #include <time.h>
     
    const char ssid[] = "xxxxx";  //  le SSID (nom) de votre réseau
    const char pass[] = "xxxxxx";       // votre mot de passe réseau
     
    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
     
      // Configuration de l'heure via NTP
      configTime(0, 0, "192.168.1.128"); // fuseaux horaires à 0 = UTC
     
      struct tm timeinfo;
      if (!getLocalTime(&timeinfo)) {
        Serial.println("Erreur de récupération du temps");
        return;
      }
     
      Serial.println(&timeinfo, "Temps actuel : %H:%M:%S %d-%m-%Y");  /// <<=== 
    }
     
    void loop() {
      delay(10000);
    }
    mais il me jette avec çà :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
       26 |   Serial.println(&timeinfo, "Temps actuel : %H:%M:%S %d-%m-%Y");
          |                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          |                             |
          |                             const char*
    EDIT : je viens de comprendre que çà ne marche pas avec ESP8266 avec un ESP32 je n'ai plus l'erreur mais je n'arrive pas à me connecter

  4. #4
    Responsable Arduino et Systèmes Embarqués


    Avatar de f-leb
    Homme Profil pro
    Enseignant
    Inscrit en
    Janvier 2009
    Messages
    13 194
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Janvier 2009
    Messages : 13 194
    Billets dans le blog
    47
    Par défaut
    On doit pouvoir formater avec strftime :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    char timebuffer[50];
     
    size_t x = strftime(timebuffer, sizeof(timebuffer), "Temps actuel : %H:%M:%S %d-%m-%Y", &timeinfo);
     
    if (x > 0) {
      Serial.println(timebuffer);
    } else {
      Serial.println("Erreur formatage !");
    }
    mais je ne sais pas si ça fonctionnera sur esp8266...

  5. #5
    Membre éprouvé
    Inscrit en
    Juillet 2004
    Messages
    954
    Détails du profil
    Informations forums :
    Inscription : Juillet 2004
    Messages : 954
    Par défaut
    Bonjour ,

    j'ai du changer , je suis passé sous un ESP32 que j'avais dans un tiroir
    si le problème << const char* >> semble résolu par contre je n'arrive pas à me connecter au Server NTP
    avec le croquis suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    #include <WiFi.h>
    #include <time.h>
     
    const char* ssid = "xxxxxx";
    const char* password = "xxxxxx";
     
    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
     
      // Configuration de l'heure via NTP
      configTime(0, 0, "192.168.1.128"); // fuseaux horaires à 0 = UTC
     
      struct tm timeinfo;
      if (!getLocalTime(&timeinfo)) {
        Serial.println("Erreur de récupération du temps");
        return;
      }
     
      Serial.println(&timeinfo, "Temps actuel : %H:%M:%S %d-%m-%Y");
    }
     
    void loop() {
      delay(10000);
    }
    Si vous avez une idée , je suis preneur

    merci bien
    pascal

  6. #6
    Responsable Arduino et Systèmes Embarqués


    Avatar de f-leb
    Homme Profil pro
    Enseignant
    Inscrit en
    Janvier 2009
    Messages
    13 194
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Enseignant

    Informations forums :
    Inscription : Janvier 2009
    Messages : 13 194
    Billets dans le blog
    47
    Par défaut
    [QUOTE]
    Citation Envoyé par cobra38 Voir le message
    par contre je n'arrive pas à me connecter au Server NTP avec le croquis suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
      // Configuration de l'heure via NTP
      configTime(0, 0, "192.168.1.128"); // fuseaux horaires à 0 = UTC
    192.168.1.128 est l'adresse IP de l'autre esp32, c'est ça ? Sauf que ton autre esp32 n'est pas un serveur NTP, mais un client qui va chercher l'heure en NTP sur Internet. Tu pourrais aussi le configurer en vrai serveur NTP (avec le port udp, le protocole ntp, etc.), mais comme tu l'as déjà configuré en serveur Web sur le port 80, le plus simple est de créer une nouvelle route /ntp :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    server.on("/ntp", handle_ntp);
    ...
     
    void handle_ntp() {
     {
        // ...
        // récupération de l'heure en NTP dans une chaîne de caractères timestring
        // ...
        server.send(200, "text/plain", timestring); // en text, ou en json, à voir...
     }
    Et tu te connectes en HTTP sur les clients (bibliothèque HTTPClient) pour faire des requêtes GET http://192.168.1.128/ntp.

+ Répondre à la discussion
Cette discussion est résolue.

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo