Skip to content

Commit

Permalink
mimxrt: Refactor the reading of the machine id.
Browse files Browse the repository at this point in the history
The ID is read in a single function and used for:
- machine.unique_id()
- Ethernet MAC addresses.
- ...

That facilitates use of other MCU using a different access method for
the ID (e.g. i.MX RT1176).
  • Loading branch information
robert-hh committed Dec 14, 2021
1 parent 1e9eaa7 commit 74e8db0
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
5 changes: 1 addition & 4 deletions ports/mimxrt/modmachine.c
Expand Up @@ -37,7 +37,6 @@
#include "pin.h"
#include "modmachine.h"
#include "fsl_clock.h"
#include "fsl_ocotp.h"
#include "fsl_wdog.h"

#include CPU_HEADER_H
Expand All @@ -52,9 +51,7 @@ typedef enum {

STATIC mp_obj_t machine_unique_id(void) {
unsigned char id[8];
OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk));
*(uint32_t *)&id[0] = OCOTP->CFG0;
*(uint32_t *)&id[4] = OCOTP->CFG1;
mp_hal_get_unique_id(id);
return mp_obj_new_bytes(id, sizeof(id));
}
MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id);
Expand Down
18 changes: 15 additions & 3 deletions ports/mimxrt/mphalport.c
Expand Up @@ -123,13 +123,25 @@ uint64_t mp_hal_time_ns(void) {
/*******************************************************************************/
// MAC address

void mp_hal_get_unique_id(uint8_t id[]) {
OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk));
*(uint32_t *)&id[0] = OCOTP->CFG0;
*(uint32_t *)&id[4] = OCOTP->CFG1;
}

// Generate a random locally administered MAC address (LAA)
void mp_hal_generate_laa_mac(int idx, uint8_t buf[6]) {
// Take the MAC addr from the OTP's Configuration and Manufacturing Info
OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk));
unsigned char id[8];
mp_hal_get_unique_id(id);

uint32_t pt1 = *(uint32_t *)&id[0];
uint32_t pt2 = *(uint32_t *)&id[4];

buf[0] = 0x02; // Locally Administered MAC
*(uint32_t *)&buf[1] = OCOTP->CFG0 ^ (OCOTP->CFG0 >> 8);
*(uint16_t *)&buf[4] = (uint16_t)(OCOTP->CFG1 ^ (OCOTP->CFG1 >> 16));
*(uint32_t *)&buf[1] = pt1 ^ (pt1 >> 8);
*(uint16_t *)&buf[4] = (uint16_t)(pt2 ^ pt2 >> 16);
buf[5] ^= (uint8_t)idx;
}

// A board can override this if needed
Expand Down
1 change: 1 addition & 0 deletions ports/mimxrt/mphalport.h
Expand Up @@ -103,5 +103,6 @@ enum {
void mp_hal_generate_laa_mac(int idx, uint8_t buf[6]);
void mp_hal_get_mac(int idx, uint8_t buf[6]);
void mp_hal_get_mac_ascii(int idx, size_t chr_off, size_t chr_len, char *dest);
void mp_hal_get_unique_id(uint8_t id[]);

#endif // MICROPY_INCLUDED_MIMXRT_MPHALPORT_H

0 comments on commit 74e8db0

Please sign in to comment.