ESPHome  2024.12.2
uponor_smatrix.cpp
Go to the documentation of this file.
1 #include "uponor_smatrix.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace uponor_smatrix {
6 
7 static const char *const TAG = "uponor_smatrix";
8 
10 #ifdef USE_TIME
11  if (this->time_id_ != nullptr) {
12  this->time_id_->add_on_time_sync_callback([this] { this->send_time(); });
13  }
14 #endif
15 }
16 
18  ESP_LOGCONFIG(TAG, "Uponor Smatrix");
19  ESP_LOGCONFIG(TAG, " System address: 0x%04X", this->address_);
20 #ifdef USE_TIME
21  if (this->time_id_ != nullptr) {
22  ESP_LOGCONFIG(TAG, " Time synchronization: YES");
23  ESP_LOGCONFIG(TAG, " Time master device address: 0x%04X", this->time_device_address_);
24  }
25 #endif
26 
27  this->check_uart_settings(19200);
28 
29  if (!this->unknown_devices_.empty()) {
30  ESP_LOGCONFIG(TAG, " Detected unknown device addresses:");
31  for (auto device_address : this->unknown_devices_) {
32  ESP_LOGCONFIG(TAG, " 0x%04X", device_address);
33  }
34  }
35 }
36 
38  const uint32_t now = millis();
39 
40  // Discard stale data
41  if (!this->rx_buffer_.empty() && (now - this->last_rx_ > 50)) {
42  ESP_LOGD(TAG, "Discarding %d bytes of unparsed data", this->rx_buffer_.size());
43  this->rx_buffer_.clear();
44  }
45 
46  // Read incoming data
47  while (this->available()) {
48  // The controller polls devices every 10 seconds in some units or continuously in others with around 200 ms between
49  // devices. Remember timestamps so we can send our own packets when the bus is expected to be silent.
50  this->last_rx_ = now;
51 
52  uint8_t byte;
53  this->read_byte(&byte);
54  if (this->parse_byte_(byte)) {
55  this->rx_buffer_.clear();
56  }
57  }
58 
59  // Send packets during bus silence
60  if (this->rx_buffer_.empty() && (now - this->last_rx_ > 50) && (now - this->last_rx_ < 100) &&
61  (now - this->last_tx_ > 200)) {
62 #ifdef USE_TIME
63  // Only build time packet when bus is silent and queue is empty to make sure we can send it right away
64  if (this->send_time_requested_ && this->tx_queue_.empty() && this->do_send_time_())
65  this->send_time_requested_ = false;
66 #endif
67  // Send the next packet in the queue
68  if (!this->tx_queue_.empty()) {
69  auto packet = std::move(this->tx_queue_.front());
70  this->tx_queue_.pop();
71 
72  this->write_array(packet);
73  this->flush();
74 
75  this->last_tx_ = now;
76  }
77  }
78 }
79 
81  this->rx_buffer_.push_back(byte);
82  const uint8_t *packet = this->rx_buffer_.data();
83  size_t packet_len = this->rx_buffer_.size();
84 
85  if (packet_len < 7) {
86  // Minimum packet size is 7 bytes, wait for more
87  return false;
88  }
89 
90  uint16_t system_address = encode_uint16(packet[0], packet[1]);
91  uint16_t device_address = encode_uint16(packet[2], packet[3]);
92  uint16_t crc = encode_uint16(packet[packet_len - 1], packet[packet_len - 2]);
93 
94  uint16_t computed_crc = crc16(packet, packet_len - 2);
95  if (crc != computed_crc) {
96  // CRC did not match, more data might be coming
97  return false;
98  }
99 
100  ESP_LOGV(TAG, "Received packet: sys=%04X, dev=%04X, data=%s, crc=%04X", system_address, device_address,
101  format_hex(&packet[4], packet_len - 6).c_str(), crc);
102 
103  // Detect or check system address
104  if (this->address_ == 0) {
105  ESP_LOGI(TAG, "Using detected system address 0x%04X", system_address);
106  this->address_ = system_address;
107  } else if (this->address_ != system_address) {
108  // This should never happen except if the system address was set or detected incorrectly, so warn the user.
109  ESP_LOGW(TAG, "Received packet from unknown system address 0x%04X", system_address);
110  return true;
111  }
112 
113  // Handle packet
114  size_t data_len = (packet_len - 6) / 3;
115  if (data_len == 0) {
116  if (packet[4] == UPONOR_ID_REQUEST)
117  ESP_LOGVV(TAG, "Ignoring request packet for device 0x%04X", device_address);
118  return true;
119  }
120 
121  // Decode packet payload data for easy access
122  UponorSmatrixData data[data_len];
123  for (int i = 0; i < data_len; i++) {
124  data[i].id = packet[(i * 3) + 4];
125  data[i].value = encode_uint16(packet[(i * 3) + 5], packet[(i * 3) + 6]);
126  }
127 
128 #ifdef USE_TIME
129  // Detect device that acts as time master if not set explicitely
130  if (this->time_device_address_ == 0 && data_len >= 2) {
131  // The first thermostat paired to the controller will act as the time master. Time can only be manually adjusted at
132  // this first thermostat. To synchronize time, we need to know its address, so we search for packets coming from a
133  // thermostat sending both room temperature and time information.
134  bool found_temperature = false;
135  bool found_time = false;
136  for (int i = 0; i < data_len; i++) {
137  if (data[i].id == UPONOR_ID_ROOM_TEMP)
138  found_temperature = true;
139  if (data[i].id == UPONOR_ID_DATETIME1)
140  found_time = true;
141  if (found_temperature && found_time) {
142  ESP_LOGI(TAG, "Using detected time device address 0x%04X", device_address);
143  this->time_device_address_ = device_address;
144  break;
145  }
146  }
147  }
148 #endif
149 
150  // Forward data to device components
151  bool found = false;
152  for (auto *device : this->devices_) {
153  if (device->address_ == device_address) {
154  found = true;
155  device->on_device_data(data, data_len);
156  }
157  }
158 
159  // Log unknown device addresses
160  if (!found && !this->unknown_devices_.count(device_address)) {
161  ESP_LOGI(TAG, "Received packet for unknown device address 0x%04X ", device_address);
162  this->unknown_devices_.insert(device_address);
163  }
164 
165  // Return true to reset buffer
166  return true;
167 }
168 
169 bool UponorSmatrixComponent::send(uint16_t device_address, const UponorSmatrixData *data, size_t data_len) {
170  if (this->address_ == 0 || device_address == 0 || data == nullptr || data_len == 0)
171  return false;
172 
173  // Assemble packet for send queue. All fields are big-endian except for the little-endian checksum.
174  std::vector<uint8_t> packet;
175  packet.reserve(6 + 3 * data_len);
176 
177  packet.push_back(this->address_ >> 8);
178  packet.push_back(this->address_ >> 0);
179  packet.push_back(device_address >> 8);
180  packet.push_back(device_address >> 0);
181 
182  for (int i = 0; i < data_len; i++) {
183  packet.push_back(data[i].id);
184  packet.push_back(data[i].value >> 8);
185  packet.push_back(data[i].value >> 0);
186  }
187 
188  auto crc = crc16(packet.data(), packet.size());
189  packet.push_back(crc >> 0);
190  packet.push_back(crc >> 8);
191 
192  this->tx_queue_.push(packet);
193  return true;
194 }
195 
196 #ifdef USE_TIME
198  if (this->time_device_address_ == 0 || this->time_id_ == nullptr)
199  return false;
200 
201  ESPTime now = this->time_id_->now();
202  if (!now.is_valid())
203  return false;
204 
205  uint8_t year = now.year - 2000;
206  uint8_t month = now.month;
207  // ESPHome days are [1-7] starting with Sunday, Uponor days are [0-6] starting with Monday
208  uint8_t day_of_week = (now.day_of_week == 1) ? 6 : (now.day_of_week - 2);
209  uint8_t day_of_month = now.day_of_month;
210  uint8_t hour = now.hour;
211  uint8_t minute = now.minute;
212  uint8_t second = now.second;
213 
214  uint16_t time1 = (year & 0x7F) << 7 | (month & 0x0F) << 3 | (day_of_week & 0x07);
215  uint16_t time2 = (day_of_month & 0x1F) << 11 | (hour & 0x1F) << 6 | (minute & 0x3F);
216  uint16_t time3 = second;
217 
218  ESP_LOGI(TAG, "Sending local time: %04d-%02d-%02d %02d:%02d:%02d", now.year, now.month, now.day_of_month, now.hour,
219  now.minute, now.second);
220 
221  UponorSmatrixData data[] = {{UPONOR_ID_DATETIME1, time1}, {UPONOR_ID_DATETIME2, time2}, {UPONOR_ID_DATETIME3, time3}};
222  return this->send(this->time_device_address_, data, sizeof(data) / sizeof(data[0]));
223 }
224 #endif
225 
226 } // namespace uponor_smatrix
227 } // namespace esphome
ESPTime now()
Get the time in the currently defined timezone.
uint16_t year
Definition: date_entity.h:122
void write_array(const uint8_t *data, size_t len)
Definition: uart.h:21
std::string format_hex(const uint8_t *data, size_t length)
Format the byte array data of length len in lowercased hex.
Definition: helpers.cpp:357
A more user-friendly version of struct tm from time.h.
Definition: time.h:15
void add_on_time_sync_callback(std::function< void()> callback)
std::vector< UponorSmatrixDevice * > devices_
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition: helpers.cpp:111
uint8_t minute
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
const char *const TAG
Definition: spi.cpp:8
void check_uart_settings(uint32_t baud_rate, uint8_t stop_bits=1, UARTParityOptions parity=UART_CONFIG_PARITY_NONE, uint8_t data_bits=8)
Check that the configuration of the UART bus matches the provided values and otherwise print a warnin...
Definition: uart.cpp:13
uint8_t second
seconds after the minute [0-60]
Definition: time.h:19
bool read_byte(uint8_t *data)
Definition: uart.h:29
uint8_t hour
std::queue< std::vector< uint8_t > > tx_queue_
uint8_t second
uint8_t minute
minutes after the hour [0-59]
Definition: time.h:21
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition: helpers.h:183
bool is_valid() const
Check if this ESPTime is valid (all fields in range and year is greater than 2018) ...
Definition: time.h:59
uint8_t day_of_week
day of the week; sunday=1 [1-7]
Definition: time.h:25
uint16_t year
year
Definition: time.h:33
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
uint8_t month
month; january=1 [1-12]
Definition: time.h:31
bool send(uint16_t device_address, const UponorSmatrixData *data, size_t data_len)
uint8_t hour
hours since midnight [0-23]
Definition: time.h:23
uint8_t day_of_month
day of the month [1-31]
Definition: time.h:27
uint8_t month
Definition: date_entity.h:123