Skip to content

Commit 92bf392

Browse files
committed
Adapt read function
Signed-off-by: cybnon <stefan.weber93@googlemail.com>
1 parent 0f8b451 commit 92bf392

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

src/atecc608_handler.cpp

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -255,39 +255,55 @@ int atecc_handler_write_data(int slot, uint8_t* data, size_t data_len) {
255255
* \return ATCA_SUCCESS on success, otherwise an error code.
256256
*/
257257
int atecc_handler_read_data(int slot, uint8_t* data, size_t data_len) {
258-
if (!data || data_len == 0) {
258+
if (!data || data_len == 0 || data_len % 4 != 0) {
259259
return ATCA_BAD_PARAM;
260260
}
261261

262-
ATCA_STATUS status = atcab_wakeup();
262+
size_t slot_size;
263+
ATCA_STATUS status = atcab_get_zone_size(ATCA_ZONE_DATA, slot, &slot_size);
264+
if (status != ATCA_SUCCESS) {
265+
return status;
266+
}
267+
268+
if (data_len > slot_size) {
269+
return ATCA_BAD_PARAM; // Data length exceeds slot size
270+
}
271+
272+
status = atcab_wakeup();
263273
if (status != ATCA_SUCCESS) {
264274
return status;
265275
}
266276

267-
// Calculate the number of blocks and any remaining bytes
268277
size_t num_blocks = data_len / 32;
269278
size_t remaining_bytes = data_len % 32;
279+
size_t bytes_read = 0;
270280

271-
// Read full blocks
281+
// Read full 32-byte blocks
272282
for (size_t i = 0; i < num_blocks; i++) {
273-
status = atcab_read_zone(ATCA_ZONE_DATA, slot, i, 0, &data[i * 32], 32);
283+
status = atcab_read_zone(ATCA_ZONE_DATA, slot, i, 0, &data[bytes_read], 32);
274284
if (status != ATCA_SUCCESS) {
275285
return status;
276286
}
287+
bytes_read += 32;
277288
}
278289

279-
// Read remaining bytes if any
280-
if (remaining_bytes > 0) {
281-
status = atcab_read_zone(ATCA_ZONE_DATA, slot, num_blocks, 0, &data[num_blocks * 32], remaining_bytes);
290+
// Read remaining 4-byte words
291+
size_t num_words = remaining_bytes / 4;
292+
for (size_t w = 0; w < num_words; w++) {
293+
size_t block = num_blocks;
294+
size_t offset = w;
295+
status = atcab_read_zone(ATCA_ZONE_DATA, slot, block, offset, &data[bytes_read], 4);
282296
if (status != ATCA_SUCCESS) {
283297
return status;
284298
}
299+
bytes_read += 4;
285300
}
286301

287302
return ATCA_SUCCESS;
288303
}
289304

290305

306+
291307
/** \brief Initialize atecc object and bus
292308
* \param[in] slot slot number of key to be written
293309
* \param[in] pub_key public key will be written here

0 commit comments

Comments
 (0)