Shift X2 status from legacy to archived
[khatus.git] / x4 / bin / khatus_x4_lib_common_sensor.sh
1 #! /bin/bash
2
3 set -e
4
5 # =============================================================================
6 # Private
7 # =============================================================================
8
9 # Defaults
10 prefix='/dev/shm/khatus'
11 host="$(hostname)"
12 sensor="$(basename $0)"
13 run_in='foreground' # foreground | background
14 run_as='poller' # poller | streamer
15 interval=1 # Only relevant if run_as poller, ignored otherwise.
16
17 set_common_options() {
18 while :
19 do
20 case "$1"
21 in '')
22 break
23 ;; -d|--daemon)
24 run_in='background'
25 shift 1
26 ;; -i|--interval)
27 case "$2"
28 in '')
29 printf "Option $1 requires and argument\n" >&2
30 exit 1
31 ;; *)
32 interval="$2"
33 shift 2
34 esac
35 ;; --)
36 shift 1
37 break
38 ;; *)
39 shift 1
40 esac
41 done
42 }
43
44 init_dirs() {
45 work_dir="${prefix}/${host}/${sensor}"
46 out_dir="${work_dir}/out"
47 err_file="${work_dir}/err"
48 pid_file="${work_dir}/pid"
49
50 mkdir -p "$out_dir"
51 }
52
53 streamer() {
54 sensor \
55 | while read key val
56 do
57 printf "%s\n" "$val" > "${out_dir}/${key}"
58 done
59 >> "$err_file"
60 }
61
62 poller() {
63 while :
64 do
65 streamer
66 sleep "$interval"
67 done
68 }
69
70 pid_file_create_of_parent() {
71 printf "$$\n" > "$pid_file"
72 }
73
74 pid_file_create_of_child() {
75 printf "$!\n" > "$pid_file"
76 }
77
78 pid_file_test() {
79 if test -e "$pid_file"
80 then
81 printf "Error - $sensor already running (i.e. PID file exists at $pid_file)\n" 1>&2
82 exit 1
83 fi
84 }
85
86 pid_file_remove() {
87 rm -f "$pid_file"
88 }
89
90 run_in_foreground() {
91 # TODO: Why do INT and EXIT traps only work in combination?
92 trap true INT
93 trap exit TERM
94 trap pid_file_remove EXIT
95 $1
96 }
97
98 run_in_background_2nd_fork() {
99 run_in_foreground $1 &
100 pid_file_create_of_child
101 }
102
103 run_in_background() {
104 run_in_background_2nd_fork $1 &
105 }
106
107 run() {
108 case "$run_as"
109 in 'poller' | 'streamer')
110 true
111 ;; *)
112 printf "Error - illegal value for \$run_as: $run_in\n" 1>&2
113 exit 1
114 esac
115 pid_file_test
116 case "$run_in"
117 in 'background')
118 run_in_background $1
119 ;; 'foreground')
120 pid_file_create_of_parent
121 run_in_foreground $1
122 ;; *)
123 printf "Error - illegal value for \$run_in: $run_in\n" 1>&2
124 exit 1
125 esac
126 }
127
128 # =============================================================================
129 # API
130 # -----------------------------------------------------------------------------
131 # run_as_poller
132 # run_as_streamer
133 # =============================================================================
134
135 run_as_poller() {
136 run 'poller'
137 }
138
139 run_as_streamer() {
140 run 'streamer'
141 }
142
143 set_common_options $@
144 init_dirs
This page took 0.055651 seconds and 4 git commands to generate.