Differentiate start functions rather than setting a variable
[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 esac
38 done
39 }
40
41 init_dirs() {
42 work_dir="${prefix}/${host}/${sensor}"
43 out_dir="${work_dir}/out"
44 err_file="${work_dir}/err"
45 pid_file="${work_dir}/pid"
46
47 mkdir -p "$out_dir"
48 }
49
50 streamer() {
51 sensor \
52 | while read key val
53 do
54 printf "%s\n" "$val" > "${out_dir}/${key}"
55 done
56 >> "$err_file"
57 }
58
59 poller() {
60 while :
61 do
62 streamer
63 sleep "$interval"
64 done
65 }
66
67 pid_file_create_of_parent() {
68 printf "$$\n" > "$pid_file"
69 }
70
71 pid_file_create_of_child() {
72 printf "$!\n" > "$pid_file"
73 }
74
75 pid_file_test() {
76 if test -e "$pid_file"
77 then
78 printf "Error - $sensor already running (i.e. PID file exists at $pid_file)\n" 1>&2
79 exit 1
80 fi
81 }
82
83 pid_file_remove() {
84 rm -f "$pid_file"
85 }
86
87 run_in_foreground() {
88 # TODO: Why do INT and EXIT traps only work in combination?
89 trap true INT
90 trap exit TERM
91 trap pid_file_remove EXIT
92 $1
93 }
94
95 run_in_background_2nd_fork() {
96 run_in_foreground $1 &
97 pid_file_create_of_child
98 }
99
100 run_in_background() {
101 run_in_background_2nd_fork $1 &
102 }
103
104 run() {
105 case "$run_as"
106 in 'poller' | 'streamer')
107 true
108 ;; *)
109 printf "Error - illegal value for \$run_as: $run_in\n" 1>&2
110 exit 1
111 esac
112 pid_file_test
113 case "$run_in"
114 in 'background')
115 run_in_background $1
116 ;; 'foreground')
117 pid_file_create_of_parent
118 run_in_foreground $1
119 ;; *)
120 printf "Error - illegal value for \$run_in: $run_in\n" 1>&2
121 exit 1
122 esac
123 }
124
125 # =============================================================================
126 # API
127 # -----------------------------------------------------------------------------
128 # run_as_poller
129 # run_as_streamer
130 # =============================================================================
131
132 run_as_poller() {
133 run 'poller'
134 }
135
136 run_as_streamer() {
137 run 'streamer'
138 }
139
140 set_common_options $@
141 init_dirs
This page took 0.059254 seconds and 4 git commands to generate.