1 | /* mbed Microcontroller Library
|
---|
2 | * Copyright (c) 2006-2017 ARM Limited
|
---|
3 | *
|
---|
4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
---|
5 | * you may not use this file except in compliance with the License.
|
---|
6 | * You may obtain a copy of the License at
|
---|
7 | *
|
---|
8 | * http://www.apache.org/licenses/LICENSE-2.0
|
---|
9 | *
|
---|
10 | * Unless required by applicable law or agreed to in writing, software
|
---|
11 | * distributed under the License is distributed on an "AS IS" BASIS,
|
---|
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
---|
13 | * See the License for the specific language governing permissions and
|
---|
14 | * limitations under the License.
|
---|
15 | */
|
---|
16 |
|
---|
17 | #if defined(DEVICE_TRNG)
|
---|
18 | #include "mbed.h"
|
---|
19 |
|
---|
20 | #define ESP32_I2C_ADDR (0x28<<1)
|
---|
21 |
|
---|
22 | void trng_init_esp32(void) {
|
---|
23 | /* P3_10(EN), P3_9(IO0) */
|
---|
24 | if (((GPIOP3 & 0x0400) == 0)
|
---|
25 | || ((GPIOPMC3 & 0x0400) != 0)
|
---|
26 | || ((GPIOPM3 & 0x0400) != 0)
|
---|
27 |
|
---|
28 | || ((GPIOP3 & 0x0200) == 0)
|
---|
29 | || ((GPIOPMC3 & 0x0200) != 0)
|
---|
30 | || ((GPIOPM3 & 0x0200) != 0)) {
|
---|
31 |
|
---|
32 | /* P3_10(EN) */
|
---|
33 | GPIOP3 &= ~0x0400; /* Outputs low level */
|
---|
34 | GPIOPMC3 &= ~0x0400; /* Port mode */
|
---|
35 | GPIOPM3 &= ~0x0400; /* Output mode */
|
---|
36 |
|
---|
37 | /* P3_9(IO0) */
|
---|
38 | GPIOP3 &= ~0x0200; /* Outputs low level */
|
---|
39 | GPIOPMC3 &= ~0x0200; /* Port mode */
|
---|
40 | GPIOPM3 &= ~0x0200; /* Output mode */
|
---|
41 |
|
---|
42 | GPIOP3 |= 0x2000; /* Outputs hi level */
|
---|
43 | wait_ms(5);
|
---|
44 | GPIOP3 |= 0x0400; /* Outputs hi level */
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | void trng_free_esp32(void) {
|
---|
49 | // do nothing
|
---|
50 | }
|
---|
51 |
|
---|
52 | int trng_get_bytes_esp32(uint8_t *output, size_t length, size_t *output_length) {
|
---|
53 | I2C mI2c(I2C_SDA, I2C_SCL);
|
---|
54 | int ret;
|
---|
55 | char send_data[1];
|
---|
56 | char recv_data[4];
|
---|
57 | size_t idx = 0;
|
---|
58 | int i;
|
---|
59 | int err_cnt = 0;
|
---|
60 |
|
---|
61 | while (idx < length) {
|
---|
62 | send_data[0] = 0;
|
---|
63 | ret = mI2c.write(ESP32_I2C_ADDR, send_data, 1);
|
---|
64 | if (ret == 0) {
|
---|
65 | mI2c.read(ESP32_I2C_ADDR, recv_data, sizeof(recv_data));
|
---|
66 | for (i = 0; (i < 4) && (idx < length); i++) {
|
---|
67 | output[idx++] = recv_data[i];
|
---|
68 | }
|
---|
69 | } else {
|
---|
70 | err_cnt++;
|
---|
71 | if (err_cnt >= 20) {
|
---|
72 | break;
|
---|
73 | }
|
---|
74 | wait_ms(100);
|
---|
75 | }
|
---|
76 | }
|
---|
77 | if (output_length != NULL) {
|
---|
78 | *output_length = idx;
|
---|
79 | }
|
---|
80 |
|
---|
81 | return (idx != 0 ? 0 : -1);
|
---|
82 | }
|
---|
83 | #endif
|
---|