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
//! The functions for dealing with time and timestamps were taken from
//! experiments from my own project from the past - `esp-clock-nostd`
//! (available on: https://github.com/playfulFence/esp-clock-nostd/tree/main)
//!
//! General knowledge about Wi-Fi was obtained from the `esp-wifi`
//! project available on https://github.com/esp-rs/esp-wifi/tree/main

use embedded_svc::io::{Read, Write};
use esp_println::println;
use esp_wifi::{
    current_millis,
    wifi::WifiDeviceMode,
    wifi_interface::{Socket, WifiStack},
};
use smoltcp::wire::Ipv4Address;

/// Represents the IP address for the WorldTime API server.
pub const WORLDTIMEAPI_IP: &str = "213.188.196.246";

/// Converts a string IP address into a 4-byte array.
///
/// # Arguments
/// * `ip` - A string slice representing the IP address.
///
/// # Returns
/// A result containing the IP address as a `[u8; 4]` array or an error message
/// if the conversion fails.
pub fn ip_string_to_parts(ip: &str) -> Result<[u8; 4], &'static str> {
    let mut parts = [0u8; 4];
    let mut current_part = 0;
    let mut value: u16 = 0; // Use u16 to check for values larger than 255

    for c in ip.trim_end_matches('.').chars() {
        match c {
            '.' => {
                if current_part == 4 {
                    return Err("Too many parts");
                }
                if value > 255 {
                    return Err("Each part must be between 0 and 255");
                }
                parts[current_part] = value as u8;
                current_part += 1;
                value = 0;
            }
            '0'..='9' => {
                value = value * 10 + c.to_digit(10).unwrap() as u16;
                if value > 255 {
                    return Err("Each part must be between 0 and 255");
                }
            }
            _ => return Err("Invalid character in IP address"),
        }
    }

    // Check if last part is valid and assign it
    if current_part != 3 || value > 255 {
        return Err("Invalid IP address format");
    }

    parts[3] = value as u8;

    Ok(parts)
}

/// Extracts a UNIX timestamp from a server response.
///
/// # Arguments
/// * `response` - A byte slice containing the server's response.
///
/// # Returns
/// An option containing the UNIX timestamp if found and successfully parsed, or
/// `None` otherwise.
pub fn find_unixtime(response: &[u8]) -> Option<u64> {
    // Convert the response to a string slice
    let response_str = core::str::from_utf8(response).ok()?;

    // Look for the "unixtime" key in the response
    let unixtime_key = b"\"unixtime\":";
    if let Some(start) = response_str.find(core::str::from_utf8(unixtime_key).ok()?) {
        // Find the start of the number (skipping the key and any potential spaces)
        let number_start = start + unixtime_key.len();
        let number_end = response_str[number_start..]
            .find(|c: char| !c.is_digit(10) && c != ' ')
            .map_or(response_str.len(), |end| number_start + end);

        // Parse the number
        response_str[number_start..number_end].parse().ok()
    } else {
        None
    }
}

/// Converts a UNIX timestamp into hours, minutes, and seconds.
///
/// # Arguments
/// * `timestamp` - The UNIX timestamp to convert.
///
/// # Returns
/// A tuple containing the hours, minutes, and seconds.
pub fn timestamp_to_hms(timestamp: u64) -> (u8, u8, u8) {
    let seconds_per_minute = 60;
    let minutes_per_hour = 60;
    let hours_per_day = 24;
    let seconds_per_hour = seconds_per_minute * minutes_per_hour;
    let seconds_per_day = seconds_per_hour * hours_per_day;

    let hours = (timestamp % seconds_per_day) / seconds_per_hour;
    let minutes = (timestamp % seconds_per_hour) / seconds_per_minute;
    let seconds = timestamp % seconds_per_minute;

    (hours as u8, minutes as u8, seconds as u8)
}

/// Gets a weekday from a UNIX timestamp
///
/// # Arguments
/// * `timestamp` - The UNIX timestamp to convert.
///
/// # Returns
/// String with the name of the day
pub fn weekday_from_timestamp(timestamp: &u64) -> &'static str {
    let days_since_1970 = timestamp / 86400; // seconds in a day
    let day_of_week = (days_since_1970 + 4) % 7; // Adjusting the offset since 1-1-1970 was a Thursday
    match day_of_week {
        0 => "Sunday",
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 => "Saturday",
        _ => "Error",
    }
}

/// Creates a new socket for communication over WiFi.
///
/// # Arguments
/// * `wifi_stack` - Reference to the `WifiStack` to use for creating the
///   socket.
/// * `ip_string` - The IP address as a string to which the socket should
///   connect.
/// * `port` - The port number for the connection.
/// * `rx_buffer` - A mutable reference to the buffer used for receiving data.
/// * `tx_buffer` - A mutable reference to the buffer used for transmitting
///   data.
///
/// # Returns
/// Returns a `Socket` instance ready for communication.
pub fn create_socket<'a, 's, MODE>(
    wifi_stack: &'s WifiStack<'a, MODE>,
    ip_string: &str,
    port: u16,
    rx_buffer: &'a mut [u8],
    tx_buffer: &'a mut [u8],
) -> Socket<'s, 'a, MODE>
where
    MODE: WifiDeviceMode,
{
    let mut socket = wifi_stack.get_socket(rx_buffer, tx_buffer);
    socket.work();

    let ip_parts = ip_string_to_parts(ip_string).unwrap();

    match socket.open(
        smoltcp::wire::IpAddress::Ipv4(Ipv4Address::new(
            ip_parts[0],
            ip_parts[1],
            ip_parts[2],
            ip_parts[3],
        )),
        port,
    ) {
        Ok(_) => println!("Socket opened..."),
        Err(e) => panic!("Error opening socket: {:?}", e),
    }

    socket
}

/// Sends a request over the specified socket.
///
/// # Arguments
/// * `socket` - A mutable reference to the `Socket` over which to send the
///   request.
/// * `request` - The request string to send.
pub fn send_request<'a, 's, MODE>(socket: &mut Socket<'s, 'a, MODE>, request: &'a [u8])
where
    MODE: WifiDeviceMode,
{
    socket.write(request).unwrap();
    socket.flush().unwrap();
}

/// Retrieves the current time from the WorldTimeAPI.
///
/// # Arguments
/// * `socket` - The `Socket` to use for making the request to the WorldTimeAPI.
///
/// # Returns
/// Returns a tuple `(u8, u8, u8)` representing the hours, minutes, and
/// seconds if successful. Returns an error otherwise.
pub fn get_time<'a, 's, MODE>(mut socket: Socket<'s, 'a, MODE>) -> Result<(u8, u8, u8), ()>
where
    MODE: WifiDeviceMode,
{
    let request = "GET /api/timezone/Europe/Prague HTTP/1.1\r\nHost: worldtimeapi.org\r\n\r\n".as_bytes();

    // Using classic "worldtime.api" to get time
    send_request(&mut socket, request);

    let (response, total_size) = get_response(socket).unwrap();

    if let Some(timestamp) = find_unixtime(&response[..total_size]) {
        let mut timestamp = timestamp;
        timestamp += 120 * 60 + 10; // align with CEST and compensate socket delay
        return Ok(timestamp_to_hms(timestamp));
    } else {
        println!("Failed to find or parse the 'unixtime' field.");
        return Err(());
    }
}

/// Retrieves the current time as a UNIX timestamp from the WorldTimeAPI.
///
/// # Arguments
/// * `socket` - The `Socket` to use for making the request to the WorldTimeAPI.
///
/// # Returns
/// Returns a timestamp representing time if successful. Returns an error
/// otherwise.
pub fn get_timestamp<'a, 's, MODE>(mut socket: Socket<'s, 'a, MODE>) -> Result<u64, ()>
where
    MODE: WifiDeviceMode,
{
    let request = "GET /api/timezone/Europe/Prague HTTP/1.1\r\nHost: worldtimeapi.org\r\n\r\n".as_bytes();

    // Using classic "worldtime.api" to get time
    send_request(&mut socket, request);

    let (response, total_size) = get_response(socket).unwrap();

    if let Some(timestamp) = find_unixtime(&response[..total_size]) {
        let mut timestamp = timestamp;
        timestamp += 120 * 60 + 10; // align with CEST and compensate socket delay
        return Ok(timestamp);
    } else {
        println!("Failed to find or parse the 'unixtime' field.");
        return Err(());
    }
}

/// Receives a message over the specified socket.
///
/// # Arguments
/// * `socket` - The `Socket` from which to read the message.
///
/// # Returns
/// Returns a tuple containing the message as a byte array and the size of the
/// message if successful. Returns an error otherwise.
pub fn get_response<'a, 's, MODE>(
    mut socket: Socket<'s, 'a, MODE>,
) -> Result<([u8; 4096], usize), ()>
where
    MODE: WifiDeviceMode,
{
    let mut buffer = [0u8; 4096];
    let mut total_size = 0usize;

    loop {
        if total_size >= buffer.len() {
            // Buffer is full
            println!("Buffer is full, processed {} bytes", total_size);
            // Here you might want to process the buffer and then clear it
            total_size = 0; 
            break;
        }

        let buffer_slice = &mut buffer[total_size..]; // Slice the buffer from the current total_size to the end
        match socket.read(buffer_slice) {
            Ok(0) => {
                // The connection has been closed by the peer
                println!("Connection closed, total read size: {}", total_size);
                break;
            }
            Ok(len) => {
                println!("Read {} bytes", len);
                total_size += len;
                // buffer[..total_size] now contains the data read in this
                // iteration
            }
            Err(e) => {
                println!("Failed to read from socket: {:?}", e);
                break;
            }
        }
    }

    socket.disconnect();
    println!("Socket disconnected, waiting...");
    let wait_end = current_millis() + 5 * 1000;
    while current_millis() < wait_end {
        socket.work();
    }
    println!("Waiting finished");

    Ok((buffer, total_size))
}