1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
/*
Copyright (c) 2016 CurlyMo <curlymoo1@gmail.com>
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "wiringx.h"
void drop_privileges();
int main() {
if(wiringXSetup("raspberrypi3", NULL) == -1) {
wiringXGC();
return -1;
}
pinMode(9, PINMODE_OUTPUT);
digitalWrite(9, HIGH);
pinMode(9, PINMODE_INPUT);
pinMode(8, PINMODE_OUTPUT);
drop_privileges();
// start bit
digitalWrite(8, HIGH);
usleep(18000);
digitalWrite(8, LOW);
int bit = -3;
char data[5];
memset(&data[0], 0, 5);
while ((bit != 40) || ((data[0]+data[1]+data[2]+data[3]-data[4]) % 255 != 0)) {
sleep(2);
if (bit > -3)
fprintf(stderr, ".");
// start bit
digitalWrite(8, HIGH);
usleep(18000);
digitalWrite(8, LOW);
long int cycles = 0;
int last_state = digitalRead(9);
// ignore 2 bits: reaction on command + "official" start bit
bit = -2;
memset(&data[0], 0, 5);
while (cycles < 100000) {
cycles++;
if (last_state == digitalRead(9))
continue;
if (last_state == 1) {
if ((bit >= 0) && (cycles>400))
data[bit / 8] |= 1 << 7 - (bit % 8);
bit++;
}
cycles = 0;
last_state = 1-last_state;
}
}
printf("RH: %f %%\nT: %f °C\n", data[0] + data[1]/256., data[2] + data[3]/256.);
} // main
//
// Drop (root) privileges
//
void drop_privileges() {
/* Drop superuser privileges in correct order */
int is_already_unprivileged = 0;
if (setgid(65534) == -1) { // nobody
perror("can't drop group privileges");
if (! (is_already_unprivileged = (errno == 1)))
exit(-1);
}
if (setuid(65534) == -1) { // nobody
perror("can't drop user privileges");
if (is_already_unprivileged != (errno == 1))
exit(-1);
}
} // drop_privileges
|