-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon.php
More file actions
111 lines (94 loc) · 2.47 KB
/
Copy pathdaemon.php
File metadata and controls
111 lines (94 loc) · 2.47 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/php
<?php
declare(ticks = 1);
// signal handler function
function sig_handler($signo) {{{
global $conn;
switch ($signo) {
case SIGKILL:
syslog(LOG_WARNING,"SIGKILL Called");
pg_close($conn);
closelog();
// handle shutdown tasks
exit;
break;
default:
// handle all other signals
}
}}}
$debug = true;
$log = '/var/log/USBSerialDaemon.log';
$filename = "/dev/tty.usbserial-A901J3MB";
$pid = pcntl_fork();
if($pid == -1){
return 1;
}
else if($pid){
exit;
}
else{
// We are the child...loop forever
fclose(STDIN); // Close all of the standard
fclose(STDOUT); // file descriptors as we
fclose(STDERR); // are running as a daemon.
// setup signal handlers
pcntl_signal(SIGKILL, "sig_handler");
openlog("myDaemon", LOG_PID|LOG_ODELAY , LOG_LOCAL3);
$fd=dio_open( $filename ,O_RDWR | O_NOCTTY | O_NDELAY);
dio_fcntl($fd,F_SETFL,0);
$result = '';
for(;;) {
$ret = dio_read($fd, 1);
if($ret == "\n") {
if($debug) syslog(LOG_DEBUG, "RX: ".$result.PHP_EOL);
$data = xml2array($result);
$data = $data['xml'];
if(array_key_exists('tmpr',$data)) {
if(!array_key_exists('h',$data)) {
$data['h'][0] = 0;
}
$conn = pg_connect("dbname=$database user=$user password=$password");
$sql = "INSERT INTO raw_data ( log_dt , tmpr , batt , node , humidty ) VALUES ( NOW() , {$data['tmpr'][0]} , {$data['v'][0]} , {$data['n'][0]} , {$data['h'][0]} );";
$result = pg_query($conn, $sql);
if (!$result) {
syslog(LOG_WARNING, "Database Error Occurred ".pg_last_error($conn));
}
}
$result = '';
}
else {
$result .= $ret;
}
}
closelog();
pg_close($conn);
}
function child_init() {{{
$fd=dio_open( $filename ,O_RDWR | O_NOCTTY | O_NDELAY);
dio_fcntl($fd,F_SETFL,0);
return $fd;
}}}
function xml2array($xml) {{{
$opened = array();
$xmlParser = xml_parser_create();
xml_parse_into_struct($xmlParser, $xml, $xmlArray);
$array = array();
for($j=0;$j<count($xmlArray);$j++){
$val = $xmlArray[$j];
switch($val["type"]){
case "open":
$opened[strtolower($val["tag"])] = $array;
unset($array);
break;
case "complete":
$array[strtolower($val["tag"])][] = $val["value"];
break;
case "close":
$opened[strtolower($val["tag"])] = $array;
$array = $opened;
break;
}
}
return $array;
}}}
?>