mimxrt: Refactor the reading of the machine id.

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).
This commit is contained in:
robert-hh 2021-11-30 20:23:03 +01:00
parent 1e9eaa7af5
commit 74e8db0ed1
3 changed files with 17 additions and 7 deletions

View File

@ -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
@ -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);

View File

@ -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

View File

@ -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