Initial merge-commit of the OIC code. Should successfully do discovery for single...
[platform/upstream/iotivity.git] / csdk / ocrandom / src / ocrandom.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Corporation All Rights Reserved.
4 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
5
6
7 #if defined(__ANDROID__) || defined(__linux__)
8 #include "fcntl.h"
9 #include "unistd.h"
10 #endif
11 #include "ocrandom.h"
12
13 #ifdef ARDUINO
14 #include "Arduino.h"
15
16 uint8_t GetRandomBitRaw() {
17     return analogRead((uint8_t)ANALOG_IN) & 0x1;
18 }
19
20 uint8_t GetRandomBitRaw2() {
21     int a = 0;
22     for(;;) {
23         a = GetRandomBitRaw() | (GetRandomBitRaw()<<1);
24         if (a==1){
25             return 0; // 1 to 0 transition: log a zero bit
26         }
27         if (a==2){
28             return 1;// 0 to 1 transition: log a one bit
29         }
30         // For other cases, try again.
31     }
32 }
33
34 uint8_t GetRandomBit() {
35     int a = 0;
36     for(;;) {
37         a = GetRandomBitRaw2() | (GetRandomBitRaw2()<<1);
38         if (a==1){
39             return 0; // 1 to 0 transition: log a zero bit
40         }
41         if (a==2){
42             return 1;// 0 to 1 transition: log a one bit
43         }
44         // For other cases, try again.
45     }
46 }
47 #endif
48
49 int8_t OCSeedRandom() {
50 #if defined(__ANDROID__) || defined(__linux__)
51     int32_t fd = open("/dev/urandom", O_RDONLY);
52     if (fd > 0) {
53         uint32_t randomSeed;
54         uint32_t totalRead = 0; //how many integers were read
55         int32_t currentRead = 0;
56         while (totalRead < sizeof(randomSeed)) {
57             currentRead = read(fd, (uint8_t*) &randomSeed + totalRead,
58                     sizeof(randomSeed) - totalRead);
59             if(currentRead > 0){
60                 totalRead += currentRead;
61             }
62         }
63         close(fd);
64         srand(randomSeed);
65         return 0;
66     }
67     close(fd);
68     return -1;
69 #elif defined ARDUINO
70     uint32_t result =0;
71     uint8_t i;
72     for (i=32; i--;){
73         result += result + GetRandomBit();
74     }
75     randomSeed(result);
76     return 0;
77 #endif
78
79 }
80
81 void OCFillRandomMem(uint8_t * location, uint16_t len) {
82     if(!location){
83         return;
84     }
85     for (; len--;){
86         *location++ = OCGetRandomByte();
87     }
88 }
89
90 uint32_t OCGetRandom() {
91     uint32_t result = 0;
92     OCFillRandomMem((uint8_t*) &result, 4);
93     return result;
94 }
95
96 uint8_t OCGetRandomByte(void) {
97 #if defined(__ANDROID__) || defined(__linux__)
98     return rand() & 0x00FF;
99 #elif defined ARDUINO
100     return random(256) & 0x00FF;
101 #endif
102 }