1technophile / OpenMQTTGateway

MQTT gateway for ESP8266 or ESP32 with bidirectional 433mhz/315mhz/868mhz, Infrared communications, BLE, Bluetooth, beacons detection, mi flora, mi jia, LYWSD02, LYWSD03MMC, Mi Scale, TPMS, BBQ thermometer compatibility & LoRa.
https://docs.openmqttgateway.com
GNU General Public License v3.0
3.5k stars 775 forks source link

[FR] LYWSD02 NTP clock sync #1306

Open nonflammable opened 1 year ago

nonflammable commented 1 year ago

Feature request: LYWSD02 internal clock is not precise. After few weeks time can be shitf over minute. A good solution would be to synchronize the time with a NTP server via OMG.

1technophile commented 1 year ago

Good catch, for info Theengs Gateway does it automatically thanks to @koenvervloesem. https://github.com/theengs/gateway

But agreed, could be considered with OMG

github-actions[bot] commented 9 months ago

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] commented 8 months ago

This issue was closed because it has been inactive for 14 days since being marked as stale.

netroy commented 8 months ago

I'm able to do this using the commands/MQTTtoBT topic with a payload like this

{
  "ble_write_address":"[[LYWSD02 MAC ADDRESS]]",
  "ble_write_service":"ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6",
  "ble_write_char":"ebe0ccb7-7a0a-4b0c-8a1a-6ff2997da3a6",
  "ble_write_value":"09c93f6501",
  "value_type":"HEX",
  "immediate":true
}

I'm calculating the ble_write_value using this JS code in my browser console

(() => {
  const timeZone = 1; // CET
  const buffer = new ArrayBuffer(5);
  new DataView(buffer).setUint32(0, Math.floor(Date.now()/1000), true);
  new DataView(buffer).setUint8(4, timeZone);
  return [...new Uint8Array(buffer)]
    .map(x => x.toString(16).padStart(2, '0'))
    .join('')
})();

So, theoretically it should be possible to add this

  1. in main/ZgatewayBT.ino, as a GATT characteristic write right after reading temperature/humidity (which seems too frequent, and seems to drain the battery much quicker), or
  2. as a button using createDiscovery("button" in main/ZmqttDiscovery.ino to let users press a button to trigger the sync via mqtt, or
  3. somehow add keep track of all clocks that need syncing, and then sync them in syncNTP once every day or so.
nonflammable commented 6 months ago

bash version:

timestamp=`date +%s|xargs printf %x`
czas=$(printf %s "$timestamp" | dd conv=swab 2> /dev/null | rev)

mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{
  "ble_write_address":"AA:BB:CC:DD:EE:FF",
  "ble_write_service":"ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6",
  "ble_write_char":"ebe0ccb7-7a0a-4b0c-8a1a-6ff2997da3a6",
  "ble_write_value":"'$czas'01",
  "value_type":"HEX",
  "immediate":true
}'

be sure to change:

MQTT TOPIC: mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT

MAC: "ble_write_address":"AA:BB:CC:DD:EE:FF"

TIMEZONE: "ble_write_value":"'$czas'01" 01=CET