Browse Source

first commit

pull/2/head
Vladimir Smagin 6 months ago
commit
66f632e0d5
9 changed files with 1709 additions and 0 deletions
  1. 1
    0
      .gitignore
  2. BIN
      IMG_20190204_025627_HDR-01.jpg
  3. 354
    0
      LM1640Display.cpp
  4. 379
    0
      LM1640Display.h
  5. 394
    0
      NTPClientLib.cpp
  6. 430
    0
      NtpClientLib.h
  7. 3
    0
      readme.md
  8. 145
    0
      tm1640-ntp.ino
  9. 3
    0
      wifi.h.sample

+ 1
- 0
.gitignore View File

@@ -0,0 +1 @@
wifi.h

BIN
IMG_20190204_025627_HDR-01.jpg View File


+ 354
- 0
LM1640Display.cpp View File

@@ -0,0 +1,354 @@
// Inspired by LM1640Display, Author: avishorp@gmail.com, https://github.com/avishorp/TM1637
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

extern "C" {
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
}

#include "LM1640Display.h"
#include <Arduino.h>

#define TM1637_I2C_COMM1 0b01000000
#define TM1637_I2C_COMM2 0b11000000
#define TM1637_I2C_COMM3 0b10000000
#define S7_DP 0x0080

//
// A
// ---
// F | | B
// -G-
// E | | C
// ---
// D

const uint8_t digitToSegment[] = {
// XGFEDCBA
0b00111111, // 0
0b00000110, // 1
0b01011011, // 2
0b01001111, // 3
0b01100110, // 4
0b01101101, // 5
0b01111101, // 6
0b00000111, // 7
0b01111111, // 8
0b01101111, // 9
0b01110111, // A
0b01111100, // b
0b00111001, // C
0b01011110, // d
0b01111001, // E
0b01110001 // F
};

const uint8_t clr[] = {
// XGFEDCBA
0b00000000, // 0
0b00000000, // 1
0b00000000, // 2
0b00000000, // 3
0b00000000, // 4
0b00000000, // 5
0b00000000, // 6
0b00000000, // 7
0b00000000, // 8
0b00000000, // 9
0b00000000, // A
0b00000000, // b
0b00000000, // C
0b00000000, // d
0b00000000, // E
0b00000000 // F
};

const short FONT_7S[] = {
C7_SPC, //32 0x20, Space
C7_EXC,
C7_QTE,
C7_HSH,
C7_DLR,
C7_PCT,
C7_AMP,
C7_ACC,
C7_LBR,
C7_RBR,
C7_MLT,
C7_PLS,
C7_CMA,
C7_MIN,
C7_DPT,
C7_RS,
C7_0, //48 0x30
C7_1,
C7_2,
C7_3,
C7_4,
C7_5,
C7_6,
C7_7,
C7_8,
C7_9,
C7_COL, //58 0x3A
C7_SCL,
C7_LT,
C7_EQ,
C7_GT,
C7_QM,
C7_AT, //64 0x40
C7_A, //65 0x41, A
C7_B,
C7_C,
C7_D,
C7_E,
C7_F,
C7_G,
C7_H,
C7_I,
C7_J,
C7_K,
C7_L,
C7_M,
C7_N,
C7_O,
C7_P,
C7_Q,
C7_R,
C7_S,
C7_T,
C7_U,
C7_V,
C7_W,
C7_X,
C7_Y,
C7_Z, //90 0x5A, Z
C7_SBL, //91 0x5B
C7_LS,
C7_SBR,
C7_PWR,
C7_UDS,
C7_ACC,
C7_A, //97 0x61, A replacing a
C7_B,
C7_C,
C7_D,
C7_E,
C7_F,
C7_G,
C7_H,
C7_I,
C7_J,
C7_K,
C7_L,
C7_M,
C7_N,
C7_O,
C7_P,
C7_Q,
C7_R,
C7_S,
C7_T,
C7_U,
C7_V,
C7_W,
C7_X,
C7_Y,
C7_Z, // 122 0x7A, Z replacing z
C7_CBL, // 123 0x7B
C7_OR,
C7_CBR,
C7_TLD,
C7_DEL // 127
};


LM1640Display::LM1640Display(uint8_t pinClk, uint8_t pinDIO)
{
// Copy the pin numbers
m_pinClk = pinClk;
m_pinDIO = pinDIO;

// Set the pin direction and default value.
// Both pins are set as inputs, allowing the pull-up resistors to pull them up
pinMode(m_pinClk, INPUT);
pinMode(m_pinDIO,INPUT);
digitalWrite(m_pinClk, LOW);
digitalWrite(m_pinDIO, LOW);
}



void LM1640Display::setBrightness(uint8_t brightness, bool on)
{
m_brightness = (brightness & 0x7) | (on? 0x08 : 0x00);
}

void LM1640Display::clear(uint8_t length)
{
setSegments(clr, length, 0);
}

void LM1640Display::setSegments(const uint8_t segments[], uint8_t length, uint8_t pos)
{
// Write COMM1
start();
writeByte(TM1637_I2C_COMM1);
stop();

// Write COMM2 + first digit address
start();
writeByte(TM1637_I2C_COMM2 + (pos & 0x03));

// Write the data bytes
for (uint8_t k=0; k < length; k++)
writeByte(segments[k]);

stop();

// Write COMM3 + brightness
start();
writeByte(TM1637_I2C_COMM3 + (m_brightness & 0x0f));
stop();
}

//void LM1640Display::showNumberDec(int num, bool leading_zero, uint8_t length, uint8_t pos)


void LM1640Display::showString(char str[]){
// ensure str is 16 chars long
uint8_t digits[SIZE];
int to = strlen(str);
for(int8_t k = 0; k < to; k++) {
digits[k] = encodeChar(str[k]);
}
if (to < 16){
for(int8_t k = to; k < 16; k++) {
digits[k] = 0;
}
}
setSegments(digits, 16, 0);
}

void LM1640Display::showNumberDec(int num, bool leading_zero, uint8_t length, uint8_t pos)
{
uint8_t digits[length];
const static int divisors[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000};
bool leading = true;

for(int8_t k = 0; k < length; k++) {
if (leading_zero){
digits[k] = encodeDigit(0);
}
else{
digits[k] = 0;
}
}

for(int8_t k = 5; k < 16; k++) {
int divisor = divisors[16 - k - 1];
int d = num / divisor;
uint8_t digit = 0;

if (d == 0) {
if (leading_zero || !leading)
digit = encodeDigit(d);
else
digit = 0;
}
else {
digit = encodeDigit(d);
num -= d * divisor;
leading = false;
}
digits[k] = digit;
}
setSegments(digits, length, pos);
}


void LM1640Display::bitDelay()
{
delayMicroseconds(100);
}

void LM1640Display::start()
{
pinMode(m_pinDIO, OUTPUT);
bitDelay();
}

void LM1640Display::stop()
{
pinMode(m_pinDIO, OUTPUT); //LOW
bitDelay();
pinMode(m_pinClk, INPUT); // HIGH
bitDelay();
pinMode(m_pinDIO, INPUT); // HIGH
bitDelay();
}

bool LM1640Display::writeByte(uint8_t b)
{
uint8_t data = b;

//Serial.print("DATA: ");
//Serial.println(data);

// 8 Data Bits
for(uint8_t i = 0; i < 8; i++) {
// CLK low
pinMode(m_pinClk, OUTPUT);
bitDelay();

uint8_t heisan = data & 0x01;
// Set data bit
if (heisan) // HIGH
pinMode(m_pinDIO, INPUT);
else //LOW
pinMode(m_pinDIO, OUTPUT);

bitDelay();

// CLK high
pinMode(m_pinClk, INPUT);
bitDelay();
data = data >> 1;
}

// CLK to zero
pinMode(m_pinClk, OUTPUT); // LOW
bitDelay();
return true;
}

uint8_t LM1640Display::encodeDigit(uint8_t digit)
{
return digitToSegment[digit];
}

uint8_t LM1640Display::encodeChar(char ch)
{
return FONT_7S[ch-32];
}





+ 379
- 0
LM1640Display.h View File

@@ -0,0 +1,379 @@
// lib for JY-LM1640 - inspired by: https://github.com/avishorp/TM1637
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

#ifndef __LM1640DISPLAY__
#define __LM1640DISPLAY__

#include <inttypes.h>

// A
// -----
// | |
// F | | B
// | G |
// -----
// | |
// E | | C
// | |
// ----- * DP
// D
//
#define S7_A 0x0001
#define S7_B 0x0002
#define S7_C 0x0004
#define S7_D 0x0008
#define S7_E 0x0010
#define S7_F 0x0020
#define S7_G 0x0040
#define S7_DP 0x0080




// Segment bit positions for 7 Segment display using the CATALEX and ROBOTDYN mapping for TM1637
// Modify this table for different 'bit-to-segment' mappings. The ASCII character defines and the FONT_7S const table below
// will be adapted automatically according to the bit-to-segment mapping. Obviously this will only work when the segment
// mapping is identical for every digit position. This will be the case unless the hardware designer really hates software developers.
//
// A
// -----
// | |
// F | | B
// | G |
// -----
// | |
// E | | C
// | |
// ----- * DP
// D
//
#define S7_A 0x0001
#define S7_B 0x0002
#define S7_C 0x0004
#define S7_D 0x0008
#define S7_E 0x0010
#define S7_F 0x0020
#define S7_G 0x0040
#define S7_DP 0x0080
#define SIZE 16
//Mask for blending out and setting 7 segments digits
#define MASK_7S_ALL = (S7_A | S7_B | S7_C | S7_D | S7_E | S7_F | S7_G}
//The CATALAX mapping between Digit positions or Columns (Left to Right) and Grids (ie memory address) are:
//The column numbers are:
// 0 1 2 3
//The Grids are:
// GR1 GR2 GR3 GR4
//The memory addresses are:
// 0 1 2 3
//The ROBOTDYN mapping between Digit positions or columns (Left to Right) and Grids (ie memory address) are:
//The column numbers are:
// 0 1 2 3 4 5
//The Grids are:
// GR3 GR2 GR1 GR6 GR5 GR4
//The memory addresses are:
// 2 1 0 5 4 3
//The EYEWINK mapping between Digit positions or columns (Left to Right) and Grids (ie memory address) are:
//The column numbers are:
// 0 1 2 3 4 5
//The Grids are:
// GR1 GR2 GR3 GR4 GR5 GR6
//The memory addresses are:
// 0 1 2 3 4 5
//Icons Grid 1
#define S7_DP1 0x0080
#define S7_ICON_GR1 (0x0000)
//#define S7_ICON_GR1 (S7_DP1)
//Icons Grid 2
#define S7_DP2 0x0080
#define S7_COL2 0x0080
#define S7_ICON_GR2 (0x0000)
//#define S7_ICON_GR2 (S7_DP2)
//Icons Grid 3
#define S7_DP3 0x0080
#define S7_ICON_GR3 (0x0000)
//#define S7_ICON_GR3 (S7_DP3)
//Icons Grid 4
#define S7_DP4 0x0080
#define S7_ICON_GR4 (0x0000)
//#define S7_ICON_GR4 (S7_DP4)
//Icons Grid 5
#define S7_DP5 0x0080
#define S7_ICON_GR5 (0x0000)
//#define S7_ICON_GR5 (S7_DP5)
//Icons Grid 6
#define S7_DP6 0x0080
#define S7_ICON_GR6 (0x0000)
//#define S7_ICON_GR6 (S7_DP6)
//Mask for blending out and restoring Icons
extern const char MASK_ICON_GRID[];
// ASCII Font definitions for segments in each character
//
//32 0x20 Symbols
#define C7_SPC (0x0000)
#define C7_EXC (S7_B | S7_C) //!
#define C7_QTE (S7_B | S7_F) //"
#define C7_HSH (S7_C | S7_D | S7_E | S7_G) //#
#define C7_DLR (S7_A | S7_C | S7_D | S7_F | S7_G) //$
#define C7_PCT (S7_C | S7_F) //%
#define C7_AMP (S7_A | S7_C | S7_D | S7_E | S7_F | S7_G) //&
#define C7_ACC (S7_B) //'
#define C7_LBR (S7_A | S7_D | S7_E | S7_F) //(
#define C7_RBR (S7_A | S7_B | S7_C | S7_D) //)
#define C7_MLT (S7_B | S7_C | S7_E | S7_F | S7_G) //*
#define C7_PLS (S7_B | S7_C | S7_G) //+
#define C7_CMA (S7_DP)
#define C7_MIN (S7_G)
#define C7_DPT (S7_DP)
#define C7_RS (S7_B | S7_E | S7_G) // /
//48 0x30 Digits
#define C7_0 (S7_A | S7_B | S7_C | S7_D | S7_E | S7_F)
#define C7_1 (S7_B | S7_C)
#define C7_2 (S7_A | S7_B | S7_D | S7_E | S7_G)
#define C7_3 (S7_A | S7_B | S7_C | S7_D | S7_G)
#define C7_4 (S7_B | S7_C | S7_F | S7_G)
#define C7_5 (S7_A | S7_C | S7_D | S7_F | S7_G)
#define C7_6 (S7_A | S7_C | S7_D | S7_E | S7_F | S7_G)
#define C7_7 (S7_A | S7_B | S7_C)
#define C7_8 (S7_A | S7_B | S7_C | S7_D | S7_E | S7_F | S7_G)
#define C7_9 (S7_A | S7_B | S7_C | S7_D | S7_F | S7_G)
//58 0x3A
#define C7_COL (S7_D | S7_G) // :
#define C7_SCL (S7_D | S7_G) // ;
#define C7_LT (S7_D | S7_E | S7_G) // <
#define C7_EQ (S7_D | S7_G) // =
#define C7_GT (S7_C | S7_D | S7_G) // >
#define C7_QM (S7_A | S7_B | S7_E | S7_G) // ?
#define C7_AT (S7_A | S7_B | S7_C | S7_D | S7_E | S7_G) // @
//65 0x41 Upper case alphabet
#define C7_A (S7_A | S7_B | S7_C | S7_E | S7_F | S7_G )
#define C7_B (S7_C | S7_D | S7_E | S7_F | S7_G)
#define C7_C (S7_A | S7_D | S7_E | S7_F)
#define C7_D (S7_B | S7_C | S7_D | S7_E | S7_G)
#define C7_E (S7_A | S7_D | S7_E | S7_F | S7_G)
#define C7_F (S7_A | S7_E | S7_F | S7_G)
#define C7_G (S7_A | S7_C | S7_D | S7_E | S7_F)
#define C7_H (S7_B | S7_C | S7_E | S7_F | S7_G)
#define C7_I (S7_B | S7_C)
#define C7_J (S7_B | S7_C | S7_D | S7_E)
#define C7_K (S7_B | S7_C | S7_E | S7_F | S7_G)
#define C7_L (S7_D | S7_E | S7_F)
#define C7_M (S7_A | S7_C | S7_E)
#define C7_N (S7_A | S7_B | S7_C | S7_E | S7_F)
#define C7_O (S7_A | S7_B | S7_C | S7_D | S7_E | S7_F)
#define C7_P (S7_A | S7_B | S7_E | S7_F | S7_G)
#define C7_Q (S7_A | S7_B | S7_C | S7_F | S7_G)
#define C7_R (S7_E | S7_G )
#define C7_S (S7_A | S7_C | S7_D | S7_F | S7_G)
#define C7_T (S7_D | S7_E | S7_F | S7_G)
#define C7_U (S7_B | S7_C | S7_D | S7_E | S7_F)
#define C7_V (S7_B | S7_C | S7_D | S7_E | S7_F)
#define C7_W (S7_B | S7_D | S7_F)
#define C7_X (S7_B | S7_C | S7_E | S7_F | S7_G)
#define C7_Y (S7_B | S7_C | S7_D | S7_F | S7_G)
#define C7_Z (S7_A | S7_B | S7_D | S7_E | S7_G)
//91 0x5B
#define C7_SBL (S7_A | S7_D | S7_E | S7_F) // [
#define C7_LS (S7_C | S7_F | S7_G) // left slash
#define C7_SBR (S7_A | S7_B | S7_C | S7_D) // ]
#define C7_PWR (S7_A | S7_B | S7_F) // ^
#define C7_UDS (S7_D) // _
#define C7_DSH (S7_F) // `
//97 0x61 Lower case alphabet
#define C7_a C7_A
#define C7_b C7_B
#define C7_c C7_C
#define C7_d C7_D
#define C7_e C7_E
#define C7_f C7_H
#define C7_g C7_G
#define C7_h C7_H
#define C7_i C7_I
#define C7_j C7_J
#define C7_k C7_K
#define C7_l C7_L
#define C7_m C7_M
//#define C7_n C7_N
#define C7_n (S7_C | S7_E | S7_G)
//#define C7_o C7_O
#define C7_o (S7_C | S7_D | S7_E | S7_G)
#define C7_p C7_P
#define C7_q C7_Q
//#define C7_r C7_R
#define C7_r (S7_E | S7_G)
#define C7_s C7_S
#define C7_t C7_T
#define C7_u C7_U
#define C7_v C7_V
#define C7_w C7_W
#define C7_x C7_X
#define C7_y C7_Y
#define C7_z C7_Z
//123 0x7B
#define C7_CBL (S7_A | S7_D | S7_E | S7_F) // {
#define C7_OR (S7_B | S7_C) // |
#define C7_CBR (S7_A | S7_B | S7_C | S7_D) // }
#define C7_TLD (S7_B | S7_E | S7_G ) // ~
#define C7_DEL (0x0000)
//User Defined Characters (some examples)
#define C7_DGR (S7_A | S7_B | S7_F | S7_G) //Degrees
// Font data selection for transmission to TM1637 memory
#define LO(x) ( x & 0xFF)
#define HI(x) ((x >> 8) & 0xFF)
// ASCII Font definition table
//
#define FONT_7S_START 0x20
#define FONT_7S_END 0x7F
//#define FONT_7S_NR_CHARS (FONT_7S_END - FONT_7S_START + 1)




class LM1640Display {

public:
//! Initialize a LM1640Display object, setting the clock and
//! data pins.
//!
//! @param pinClk - The number of the digital pin connected to the clock pin of the module
//! @param pinDIO - The number of the digital pin connected to the DIO pin of the module
LM1640Display(uint8_t pinClk, uint8_t pinDIO);

//! Sets the brightness of the display.
//!
//! The setting takes effect when a command is given to change the data being
//! displayed.
//!
//! @param brightness A number from 0 (lowes brightness) to 7 (highest brightness)
//! @param on Turn display on or off
void setBrightness(uint8_t brightness, bool on = true);

//! Display arbitrary data on the module
//!
//! This function receives raw segment values as input and displays them. The segment data
//! is given as a byte array, each byte corresponding to a single digit. Within each byte,
//! bit 0 is segment A, bit 1 is segment B etc.
//! The function may either set the entire display or any desirable part on its own. The first
//! digit is given by the @ref pos argument with 0 being the leftmost digit. The @ref length
//! argument is the number of digits to be set. Other digits are not affected.
//!
//! @param segments An array of size @ref length containing the raw segment values
//! @param length The number of digits to be modified
//! @param pos The position from which to start the modification (0 - leftmost, 3 - rightmost)
void setSegments(const uint8_t segments[], uint8_t length = 16, uint8_t pos = 0);

//! Displayes a decimal number
//!
//! Dispalyes the given argument as a decimal number
//!
//! @param num The number to be shown
//! @param leading_zero When true, leading zeros are displayed. Otherwise unnecessary digits are
//! blank
//! @param length The number of digits to set. The user must ensure that the number to be shown
//! fits to the number of digits requested (for example, if two digits are to be displayed,
//! the number must be between 0 to 99)
//! @param pos The position most significant digit (0 - leftmost, 3 - rightmost)
void showNumberDec(int num, bool leading_zero = false, uint8_t length = 16, uint8_t pos = 0);

//! Displayes a decimal number, with dot control
//!
//! Dispalyes the given argument as a decimal number. The dots between the digits (or colon)
//! can be individually controlled
//!
//! @param num The number to be shown
//! @param dots Dot/Colon enable. The argument is a bitmask, with each bit corresponding to a dot
//! between the digits (or colon mark, as implemented by each module). i.e.
//! For displays with dots between each digit:
//! * 0.000 (0b10000000)
//! * 00.00 (0b01000000)
//! * 000.0 (0b00100000)
//! * 0.0.0.0 (0b11100000)
//! For displays with just a colon:
//! * 00:00 (0b01000000)
//! For displays with dots and colons colon:
//! * 0.0:0.0 (0b11100000)
//! @param leading_zero When true, leading zeros are displayed. Otherwise unnecessary digits are
//! blank
//! @param length The number of digits to set. The user must ensure that the number to be shown
//! fits to the number of digits requested (for example, if two digits are to be displayed,
//! the number must be between 0 to 99)
//! @param pos The position least significant digit (0 - leftmost, 3 - rightmost)
void showNumberDecEx(int num, uint8_t dots = 0, bool leading_zero = false, uint8_t length = 16, uint8_t pos = 0);


void clear(uint8_t length = 16);

//! Translate a single digit into 7 segment code
//!
//! The method accepts a number between 0 - 15 and converts it to the
//! code required to display the number on a 7 segment display.
//! Numbers between 10-15 are converted to hexadecimal digits (A-F)
//!
//! @param digit A number between 0 to 15
//! @return A code representing the 7 segment image of the digit (LSB - segment A;
//! bit 6 - segment G; bit 7 - always zero)
uint8_t encodeDigit(uint8_t digit);

uint8_t encodeChar(char ch);
void showString(char str[]);
protected:
void bitDelay();

void start();

void stop();

bool writeByte(uint8_t b);

private:
uint8_t m_pinClk;
uint8_t m_pinDIO;
uint8_t m_brightness;
};

#endif // __LM1640Display__

+ 394
- 0
NTPClientLib.cpp View File

@@ -0,0 +1,394 @@
/*
Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met :

1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and / or other materials
provided with the distribution.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of German Martin
*/
//
//
//

#include "NtpClientLib.h"

#define DBG_PORT Serial

#ifdef DEBUG_NTPCLIENT
#define DEBUGLOG(...) DBG_PORT.printf(__VA_ARGS__)
#else
#define DEBUGLOG(...)
#endif


NTPClient::NTPClient () {
}

bool NTPClient::setNtpServerName (String ntpServerName) {
char * name = (char *)malloc ((ntpServerName.length () + 1) * sizeof (char));
if (!name)
return false;
ntpServerName.toCharArray (name, ntpServerName.length () + 1);
DEBUGLOG ("NTP server set to %s\n", name);
free (_ntpServerName);
_ntpServerName = name;
return true;
}

bool NTPClient::setNtpServerName (char* ntpServerName) {
char *name = ntpServerName;
if (name == NULL)
return false;
DEBUGLOG ("NTP server set to %s\n", name);
free (_ntpServerName);
_ntpServerName = name;
return true;
}

String NTPClient::getNtpServerName () {
return String (_ntpServerName);
}

char* NTPClient::getNtpServerNamePtr () {
return _ntpServerName;
}

bool NTPClient::setTimeZone (int8_t timeZone, int8_t minutes) {
if ((timeZone >= -12) && (timeZone <= 14) && (minutes >= -59) && (minutes <= 59)) {
// Temporarily set time to new time zone, before trying to synchronize
int8_t timeDiff = timeZone - _timeZone;
_timeZone = timeZone;
_minutesOffset = minutes;
setTime (now () + timeDiff * SECS_PER_HOUR + minutes * SECS_PER_MIN);
if (udp && (timeStatus () != timeNotSet)) {
setTime (getTime ());
}
DEBUGLOG ("NTP time zone set to: %d\r\n", timeZone);
return true;
}
return false;
}

boolean sendNTPpacket (const char* address, UDP *udp) {
uint8_t ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store request message

// set all bytes in the buffer to 0
memset (ntpPacketBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
ntpPacketBuffer[1] = 0; // Stratum, or type of clock
ntpPacketBuffer[2] = 6; // Polling Interval
ntpPacketBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
ntpPacketBuffer[12] = 49;
ntpPacketBuffer[13] = 0x4E;
ntpPacketBuffer[14] = 49;
ntpPacketBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp->beginPacket (address, DEFAULT_NTP_PORT); //NTP requests are to port 123
udp->write (ntpPacketBuffer, NTP_PACKET_SIZE);
udp->endPacket ();
return true;
}

time_t NTPClient::getTime () {
//DNSClient dns;
//WiFiUDP *udpClient = new WiFiUDP(*udp);
IPAddress timeServerIP; //NTP server IP address
char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store response message


DEBUGLOG ("Starting UDP\n");
udp->begin (DEFAULT_NTP_PORT);
//DEBUGLOG ("UDP port: %d\n",udp->localPort());
while (udp->parsePacket () > 0); // discard any previously received packets
/*dns.begin(WiFi.dnsServerIP());
uint8_t dnsResult = dns.getHostByName(NTP.getNtpServerName().c_str(), timeServerIP);
DEBUGLOG(F("NTP Server hostname: "));
DEBUGLOGCR(NTP.getNtpServerName());
DEBUGLOG(F("NTP Server IP address: "));
DEBUGLOGCR(timeServerIP);
DEBUGLOG(F("Result code: "));
DEBUGLOG(dnsResult);
DEBUGLOG(" ");
DEBUGLOGCR(F("-- IP Connected. Waiting for sync"));
DEBUGLOGCR(F("-- Transmit NTP Request"));*/

//if (dnsResult == 1) { //If DNS lookup resulted ok
sendNTPpacket (getNtpServerName ().c_str (), udp);
uint32_t beginWait = millis ();
while (millis () - beginWait < NTP_TIMEOUT) {
int size = udp->parsePacket ();
if (size >= NTP_PACKET_SIZE) {
DEBUGLOG ("-- Receive NTP Response\n");
udp->read (ntpPacketBuffer, NTP_PACKET_SIZE); // read packet into the buffer
time_t timeValue = decodeNtpMessage (ntpPacketBuffer);
setSyncInterval (getLongInterval ());
if (!_firstSync) {
// if (timeStatus () == timeSet)
_firstSync = timeValue;
}
//getFirstSync (); // Set firstSync value if not set before
DEBUGLOG ("Sync frequency set low\n");
udp->stop ();
setLastNTPSync (timeValue);
DEBUGLOG ("Successful NTP sync at %s", getTimeDateString (getLastNTPSync ()).c_str ());

if (onSyncEvent)
onSyncEvent (timeSyncd);
return timeValue;
}
#ifdef ARDUINO_ARCH_ESP8266
ESP.wdtFeed ();
#endif
}
DEBUGLOG ("-- No NTP Response :-(\n");
udp->stop ();
setSyncInterval (getShortInterval ()); // Retry connection more often
if (onSyncEvent)
onSyncEvent (noResponse);
return 0; // return 0 if unable to get the time
}

int8_t NTPClient::getTimeZone () {
return _timeZone;
}

int8_t NTPClient::getTimeZoneMinutes () {
return _minutesOffset;
}

/*void NTPClient::setLastNTPSync(time_t moment) {
_lastSyncd = moment;
}*/

time_t NTPClient::s_getTime () {
return NTP.getTime ();
}

#if NETWORK_TYPE == NETWORK_W5100
bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, EthernetUDP* udp_conn) {
#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32
bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, WiFiUDP* udp_conn) {
#endif
if (!setNtpServerName (ntpServerName)) {
DEBUGLOG ("Time sync not started\r\n");
return false;
}
if (!setTimeZone (timeZone, minutes)) {
DEBUGLOG ("Time sync not started\r\n");
return false;
}
if (udp_conn)
udp = udp_conn;
else
#if NETWORK_TYPE == NETWORK_W5100
udp = new EthernetUDP ();
#else
udp = new WiFiUDP ();
#endif

//_timeZone = timeZone;
setDayLight (daylight);
_lastSyncd = 0;

if (!setInterval (DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) {
DEBUGLOG ("Time sync not started\r\n");
return false;
}
DEBUGLOG ("Time sync started\r\n");

setSyncInterval (getShortInterval ());
setSyncProvider (s_getTime);

return true;
}

bool NTPClient::stop () {
setSyncProvider (NULL);
DEBUGLOG ("Time sync disabled\n");

return true;
}

bool NTPClient::setInterval (int interval) {
if (interval >= 10) {
if (_longInterval != interval) {
_longInterval = interval;
DEBUGLOG ("Sync interval set to %d\n", interval);
if (timeStatus () == timeSet)
setSyncInterval (interval);
}
return true;
} else
return false;
}

bool NTPClient::setInterval (int shortInterval, int longInterval) {
if (shortInterval >= 10 && longInterval >= 10) {
_shortInterval = shortInterval;
_longInterval = longInterval;
if (timeStatus () != timeSet) {
setSyncInterval (shortInterval);
} else {
setSyncInterval (longInterval);
}
DEBUGLOG ("Short sync interval set to %d\n", shortInterval);
DEBUGLOG ("Long sync interval set to %d\n", longInterval);
return true;
} else
return false;
}

int NTPClient::getInterval () {
return _longInterval;
}

int NTPClient::getShortInterval () {
return _shortInterval;
}

void NTPClient::setDayLight (bool daylight) {
_daylight = daylight;
DEBUGLOG ("--Set daylight saving %s\n", daylight ? "ON" : "OFF");
setTime (getTime ());
}

bool NTPClient::getDayLight () {
return _daylight;
}

String NTPClient::getTimeStr (time_t moment) {
char timeStr[10];
sprintf (timeStr, "%02d:%02d:%02d", hour (moment), minute (moment), second (moment));

return timeStr;
}

String NTPClient::getDateStr (time_t moment) {
char dateStr[12];
sprintf (dateStr, "/ %02d-%02d", day (moment), month (moment), year (moment));

return dateStr;
}

String NTPClient::getTimeDateString (time_t moment) {
return getTimeStr (moment) + " " + getDateStr (moment);
}

time_t NTPClient::getLastNTPSync () {
return _lastSyncd;
}

void NTPClient::onNTPSyncEvent (onSyncEvent_t handler) {
onSyncEvent = handler;
}

time_t NTPClient::getUptime () {
_uptime = _uptime + (millis () - _uptime);
return _uptime / 1000;
}

String NTPClient::getUptimeString () {
uint16_t days;
uint8_t hours;
uint8_t minutes;
uint8_t seconds;

time_t uptime = getUptime ();

seconds = uptime % SECS_PER_MIN;
uptime -= seconds;
minutes = (uptime % SECS_PER_HOUR) / SECS_PER_MIN;
uptime -= minutes * SECS_PER_MIN;
hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR;
uptime -= hours * SECS_PER_HOUR;
days = uptime / SECS_PER_DAY;

char uptimeStr[20];
sprintf (uptimeStr, "%4u days %02d:%02d:%02d", days, hours, minutes, seconds);

return uptimeStr;
}

time_t NTPClient::getLastBootTime () {
if (timeStatus () == timeSet) {
return (now () - getUptime ());
}
return 0;
}

time_t NTPClient::getFirstSync () {
/*if (!_firstSync) {
if (timeStatus () == timeSet) {
_firstSync = now () - getUptime ();
}
}*/
return _firstSync;
}

bool NTPClient::summertime (int year, byte month, byte day, byte hour, byte tzHours)
// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ)
{
if ((month < 3) || (month > 10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez
if ((month > 3) && (month < 10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep
if ((month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7))) || (month == 10 && (hour + 24 * day) < (1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))))
return true;
else
return false;
}

boolean NTPClient::isSummerTimePeriod (time_t moment) {
return summertime (year (), month (), day (), hour (), getTimeZone ());
}

void NTPClient::setLastNTPSync (time_t moment) {
_lastSyncd = moment;
}

time_t NTPClient::decodeNtpMessage (char *messageBuffer) {
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)messageBuffer[40] << 24;
secsSince1900 |= (unsigned long)messageBuffer[41] << 16;
secsSince1900 |= (unsigned long)messageBuffer[42] << 8;
secsSince1900 |= (unsigned long)messageBuffer[43];

#define SEVENTY_YEARS 2208988800UL
time_t timeTemp = secsSince1900 - SEVENTY_YEARS + _timeZone * SECS_PER_HOUR + _minutesOffset * SECS_PER_MIN;

if (_daylight) {
if (summertime (year (timeTemp), month (timeTemp), day (timeTemp), hour (timeTemp), _timeZone)) {
timeTemp += SECS_PER_HOUR;
DEBUGLOG ("Summer Time\n");
} else {
DEBUGLOG ("Winter Time\n");
}
} else {
DEBUGLOG ("No daylight\n");
}
return timeTemp;
}

NTPClient NTP;

+ 430
- 0
NtpClientLib.h View File

@@ -0,0 +1,430 @@
/*
Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met :

1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and / or other materials
provided with the distribution.

THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of German Martin
*/
/*
Name: NtpClientLib
Created: 17/08/2016
Author: Germán Martín (gmag11@gmail.com)
Maintainer:Germán Martín (gmag11@gmail.com)
Editor: http://www.visualmicro.com

Library to get system sync from a NTP server
*/

#ifndef _NtpClientLib_h
#define _NtpClientLib_h

//#define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port

#ifdef ESP8266
//extern "C" {
//#include "user_interface.h"
//#include "sntp.h"
//}
#include <functional>
using namespace std;
using namespace placeholders;
#endif

#include <TimeLib.h>

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#define NETWORK_W5100 (1) // Arduino Ethernet Shield
#define NETWORK_ENC28J60 (2) // Alternate Ethernet Shield
#define NETWORK_WIFI101 (3) // WiFi Shield 101 or MKR1000
#define NETWORK_ESP8266 (100) // ESP8266 boards, not for Arduino using AT firmware
#define NETWORK_ESP32 (101) // ESP32 boards

#define DEFAULT_NTP_SERVER "pool.ntp.org" // Default international NTP server. I recommend you to select a closer server to get better accuracy
#define DEFAULT_NTP_PORT 123 // Default local udp port. Select a different one if neccesary (usually not needed)
#define NTP_TIMEOUT 1500 // Response timeout for NTP requests
#define DEFAULT_NTP_INTERVAL 1800 // Default sync interval 30 minutes
#define DEFAULT_NTP_SHORTINTERVAL 15 // Sync interval when sync has not been achieved. 15 seconds
#define DEFAULT_NTP_TIMEZONE 0 // Select your local time offset. 0 if UTC time has to be used

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message

#ifdef ARDUINO_ARCH_ESP8266
#define NETWORK_TYPE NETWORK_ESP8266
#elif defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32
#define NETWORK_TYPE NETWORK_WIFI101 // SET YOUR NETWORK INTERFACE
#elif defined ARDUINO_ARCH_AVR
#define NETWORK_TYPE NETWORK_W5100
#elif defined ARDUINO_ARCH_ESP32 || defined ESP32
#define NETWORK_TYPE NETWORK_ESP32
#endif

#if NETWORK_TYPE == NETWORK_W5100
//#include <SPI.h>
#include <EthernetUdp.h>
#include <Ethernet.h>
//#include <Dns.h>
//#include <Dhcp.h>
#elif NETWORK_TYPE == NETWORK_WIFI101
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <WiFi101.h>
#elif NETWORK_TYPE == NETWORK_ESP8266
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Udp.h>
#elif NETWORK_TYPE == NETWORK_ESP32
#include <WiFi.h>
#include <WiFiUdp.h>
#include <Udp.h>
#else
#error "Incorrect platform. Only ARDUINO and ESP8266 MCUs are valid."
#endif // NETWORK_TYPE

typedef enum {
timeSyncd, // Time successfully got from NTP server
noResponse, // No response from server
invalidAddress // Address not reachable
} NTPSyncEvent_t;

#if defined ARDUINO_ARCH_ESP8266 || defined ARDUINO_ARCH_ESP32
#include <functional>
typedef std::function<void (NTPSyncEvent_t)> onSyncEvent_t;
#else
typedef void (*onSyncEvent_t)(NTPSyncEvent_t);
#endif

class NTPClient {
public:
/**
* Construct NTP client.
*/
NTPClient ();

/**
* Starts time synchronization.
* @param[in] NTP server name as String.
* @param[in] Time offset from UTC.
* @param[in] true if this time zone has dayligth saving.
* @param[in] Minutes offset added to hourly offset (optional).
* @param[in] UDP connection instance (optional).
* @param[out] true if everything went ok.
*/
#if NETWORK_TYPE == NETWORK_W5100
bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, EthernetUDP* udp_conn = NULL);
#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32
bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, WiFiUDP* udp_conn = NULL);
#endif

/**
* Sets NTP server name.
* @param[in] New NTP server name.
* @param[out] True if everything went ok.
*/
bool setNtpServerName (String ntpServerName);
bool setNtpServerName (char* ntpServerName);

/**
* Sets NTP server name. DEPRECATED, only for compatibility with older versions
* @param[in] New NTP server name.
* @param[in] Server index (0-2).
* @param[out] True if everything went ok.
*/
bool setNtpServerName (String ntpServerName, int idx) {
if (idx < 0 || idx > 2)
return false;
return setNtpServerName (ntpServerName);
}

/**
* Gets NTP server name
* @param[out] NTP server name.
*/
String getNtpServerName ();
char* getNtpServerNamePtr ();

/**
* Gets NTP server name. DEPRECATED, only for compatibility with older versions
* @param[in] Server index (0-2).
* @param[out] NTP server name.
*/
String getNtpServerName (int idx) {
if (idx < 0 || idx > 2)
return "";
return getNtpServerName ();
}

/**
* Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library.
* Kept in public section to allow direct NTP request.
* @param[out] Time in UNIX time format.
*/
time_t getTime ();

/**
* Sets timezone.
* @param[in] New time offset in hours (-11 <= timeZone <= +13).
* @param[out] True if everything went ok.
*/
bool setTimeZone (int8_t timeZone, int8_t minutes = 0);

/**
* Gets timezone.
* @param[out] Time offset in hours (plus or minus).
*/
int8_t getTimeZone ();

/**
* Gets minutes fraction of timezone.
* @param[out] Minutes offset (plus or minus) added to hourly offset.
*/
int8_t getTimeZoneMinutes ();

/**
* Stops time synchronization.
* @param[out] True if everything went ok.
*/
bool stop ();

/**
* Changes sync period.
* @param[in] New interval in seconds.
* @param[out] True if everything went ok.
*/
bool setInterval (int interval);

/**
* Changes sync period in sync'd and not sync'd status.
* @param[in] New interval while time is not first adjusted yet, in seconds.
* @param[in] New interval for normal operation, in seconds.
* @param[out] True if everything went ok.
*/
bool setInterval (int shortInterval, int longInterval);

/**
* Gets sync period.
* @param[out] Interval for normal operation, in seconds.
*/
int getInterval ();

/**
* Changes sync period not sync'd status.
* @param[out] Interval while time is not first adjusted yet, in seconds.
*/
int getShortInterval ();

/**
* Gets sync period.
* @param[out] Interval for normal operation in seconds.
*/
int getLongInterval () { return getInterval (); }

/**
* Set daylight time saving option.
* @param[in] true is daylight time savings apply.
*/
void setDayLight (bool daylight);

/**
* Get daylight time saving option.
* @param[out] true is daylight time savings apply.
*/
bool getDayLight ();

/**
* Convert current time to a String.
* @param[out] String constructed from current time.
* TODO: Add internationalization support
*/
String getTimeStr () { return getTimeStr (now ()); }

/**
* Convert a time in UNIX format to a String representing time.
* @param[out] String constructed from current time.
* @param[in] time_t object to convert to extract time.
* TODO: Add internationalization support
*/
String getTimeStr (time_t moment);

/**
* Convert current date to a String.
* @param[out] String constructed from current date.
* TODO: Add internationalization support
*/
String getDateStr () { return getDateStr (now ()); }

/**
* Convert a time in UNIX format to a String representing its date.
* @param[out] String constructed from current date.
* @param[in] time_t object to convert to extract date.
* TODO: Add internationalization support
*/
String getDateStr (time_t moment);

/**
* Convert current time and date to a String.
* @param[out] String constructed from current time.
* TODO: Add internationalization support
*/
String getTimeDateString () { return getTimeDateString (now ()); }

/**
* Convert current time and date to a String.
* @param[in] time_t object to convert to String.
* @param[out] String constructed from current time.
* TODO: Add internationalization support
*/
String getTimeDateString (time_t moment);

/**
* Gets last successful sync time in UNIX format.
* @param[out] Last successful sync time. 0 equals never.
*/
time_t getLastNTPSync ();

/**
* Get uptime in human readable String format.
* @param[out] Uptime.
*/
String getUptimeString ();

/**
* Get uptime in UNIX format, time since MCU was last rebooted.
* @param[out] Uptime. 0 equals never.
*/
time_t getUptime ();

/**
* Get first boot time in UNIX format, time when MCU was last rebooted.
* @param[out] Uptime. 0 equals never.
*/
time_t getLastBootTime ();

/**
* Get first successful synchronization time after boot.
* @param[out] First sync time.
*/
time_t getFirstSync ();

/**
* Set a callback that triggers after a sync trial.
* @param[in] function with void(NTPSyncEvent_t) or std::function<void(NTPSyncEvent_t)> (only for ESP8266)
* NTPSyncEvent_t equals 0 is there is no error
*/
void onNTPSyncEvent (onSyncEvent_t handler);

/**
* True if current time is inside DST period (aka. summer time). False otherwise of if NTP object has DST
* calculation disabled
* @param[out] True = summertime enabled and time in summertime period
* False = sumertime disabled or time ouside summertime period
*/
boolean isSummerTime () {
if (_daylight)
return isSummerTimePeriod (now ());
else
return false;
}

/**
* True if given time is inside DST period (aka. summer time). False otherwise.
* @param[in] time to make the calculation with
* @param[out] True = time in summertime period
* False = time ouside summertime period
*/
boolean isSummerTimePeriod (time_t moment);

protected:

#if NETWORK_TYPE == NETWORK_W5100
EthernetUDP *udp;
#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32
WiFiUDP *udp;
#endif
bool _daylight; ///< Does this time zone have daylight saving?
int8_t _timeZone = 0; ///< Keep track of set time zone offset
int8_t _minutesOffset = 0; ///< Minutes offset for time zones with decimal numbers
char* _ntpServerName; ///< Name of NTP server on Internet or LAN
int _shortInterval; ///< Interval to set periodic time sync until first synchronization.
int _longInterval; ///< Interval to set periodic time sync
time_t _lastSyncd = 0; ///< Stored time of last successful sync
time_t _firstSync = 0; ///< Stored time of first successful sync after boot
unsigned long _uptime = 0; ///< Time since boot
onSyncEvent_t onSyncEvent; ///< Event handler callback

/**
* Function that gets time from NTP server and convert it to Unix time format
* @param[out] Time form NTP in Unix Time Format.
*/
static time_t s_getTime ();

/**
* Calculates the daylight saving for a given date.
* @param[in] Year.
* @param[in] Month.
* @param[in] Day.
* @param[in] Hour.
* @param[in] Time zone offset.
* @param[out] true if date and time are inside summertime period.
*/
bool summertime (int year, byte month, byte day, byte hour, byte tzHours);

/**
* Helper function to add leading 0 to hour, minutes or seconds if < 10.
* @param[in] Digit to evaluate the need of leading 0.
* @param[out] Result digit with leading 0 if needed.
*/
//String printDigits(int digits);


public:
/**
* Decode NTP response contained in buffer.
* @param[in] Pointer to message buffer.
* @param[out] Decoded time from message, 0 if error ocurred.
*/
time_t decodeNtpMessage (char *messageBuffer);

/**
* Set last successful synchronization time.
* @param[out] Last sync time.
*/
void setLastNTPSync (time_t moment);

private:
/**
* Sends NTP request packet to given IP address.
* @param[in] NTP server's IP address.
* @param[out] True if everything went ok.
*/
//bool sendNTPpacket(IPAddress &address);
//#endif
};

extern NTPClient NTP;

#endif // _NtpClientLib_h

+ 3
- 0
readme.md View File

@@ -0,0 +1,3 @@
# ESP8266 NTP driven clock on TM1640

Rename `wifi.h.sample` to `wifi.h`, change NTP server to nearest to you, set timezone shift.

+ 145
- 0
tm1640-ntp.ino View File

@@ -0,0 +1,145 @@
#include <Wire.h>
#include "LM1640Display.h"

#include <TimeLib.h>
#include "NtpClientLib.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#include "wifi.h"

#define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07

#define CLK D2
#define DIO D3

LM1640Display display(CLK, DIO);

//set timezone
static const int8_t timeZone = 7;
bool wifiFirstConnected = false;
bool ntp_online = false;

void onSTAConnected (WiFiEventStationModeConnected ipInfo) {
Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str ());
}

// Start NTP only after IP network is connected
void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) {
Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str());
wifiFirstConnected = true;
//digitalWrite(ONBOARDLED, LOW); // Turn on LED
}

// Manage network disconnection
void onSTADisconnected(WiFiEventStationModeDisconnected event_info) {
Serial.printf("Disconnected from SSID: %s\n", event_info.ssid.c_str());
Serial.printf("Reason: %d\n", event_info.reason);
digitalWrite(ONBOARDLED, HIGH); // Turn off LED
//NTP.stop(); // NTP sync can be disabled to avoid sync errors
ntp_online = false;
}

void processSyncEvent(NTPSyncEvent_t ntpEvent) {
if (ntpEvent) {
Serial.print("Time Sync error: ");
if (ntpEvent == noResponse) {
Serial.println("NTP server not reachable");
ntp_online = false;
}
else if (ntpEvent == invalidAddress) {
Serial.println("Invalid NTP server address");
ntp_online = false;
}
}
else {
Serial.print("Got NTP time: ");
ntp_online = true;
Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync()));
}
}

boolean syncEventTriggered = false;
NTPSyncEvent_t ntpEvent;

void setup() {
static WiFiEventHandler e1, e2, e3;
Wire.begin();

//Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.hostname("clock16");
WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASSWD);

pinMode(ONBOARDLED, OUTPUT); // Onboard LED
digitalWrite(ONBOARDLED, HIGH); // Switch off LED

NTP.onNTPSyncEvent([](NTPSyncEvent_t event) {
ntpEvent = event;
syncEventTriggered = true;
});

e1 = WiFi.onStationModeGotIP(onSTAGotIP);// As soon WiFi is connected, start NTP Client
e2 = WiFi.onStationModeDisconnected(onSTADisconnected);
e3 = WiFi.onStationModeConnected (onSTAConnected);
digitalWrite(ONBOARDLED, HIGH); // Switch off LED
}

void starting() {

NTP.begin("ntp.tomtel.ru", timeZone, true);
NTP.setInterval(10, 600);

display.clear();
//Serial.println("Starting NTP client");
while (ntp_online == false) {
if (syncEventTriggered) {
processSyncEvent (ntpEvent);
syncEventTriggered = true;
}
display.setBrightness(7);
display.showString("connecting...");
//Serial.println("Connecting");
delay(1000);
}

display.clear();

for (uint8_t l = 0; l <= 7; l++) {
display.setBrightness(l); //set the diplay to maximum brightness
display.showString("hello int 21h");
delay(200);
}

display.clear();
}

char timebuff[17];

void loop() {
if (ntp_online == true) {
if (syncEventTriggered) {
processSyncEvent (ntpEvent);
syncEventTriggered = false;
}

String timestamp = NTP.getTimeDateString();

//Serial.print(timestamp + "\n");

timestamp.toCharArray(timebuff, 17);
display.showString( timebuff );

delay(1000);
} else {
starting();
}
}






+ 3
- 0
wifi.h.sample View File

@@ -0,0 +1,3 @@
#define YOUR_WIFI_SSID "supapupamegawifi"
#define YOUR_WIFI_PASSWD "sexdrugsrickroll"


Loading…
Cancel
Save