| 1 | #!/bin/bash |
| 2 | # Simple sleep monitor (Harvie 2012) |
| 3 | # |
| 4 | # You probably have soundcard with one output and input |
| 5 | # Take PIR motion sensor from security system |
| 6 | # Use PIR to switch connection between left channels of output and input (tips of 3.5mm jacks) |
| 7 | # Connect grounds of these two together (maybe you will not need it - depending on your soundcard) |
| 8 | # Power up PIR |
| 9 | # Launch this script |
| 10 | # Use alsamixer and some GUI recorder (like audacity) to tune volume to some usable level |
| 11 | # Place PIR facing to your bed and go sleep |
| 12 | # Wake up |
| 13 | # Enjoy your data |
| 14 | |
| 15 | out=/tmp/sleeplog-"$(date +%F_%T)".txt |
| 16 | graphout="${out%%.*}.png" |
| 17 | |
| 18 | killall speaker-test &>/dev/null |
| 19 | speaker-test -t sine &>/dev/null & |
| 20 | |
| 21 | touch "$out" |
| 22 | bash ./sleepstats.sh "$out" &>/dev/null & |
| 23 | |
| 24 | tresh=10 |
| 25 | lastdate="$(date +%s)" |
| 26 | screen=false |
| 27 | graph=false |
| 28 | |
| 29 | export LC_ALL=C |
| 30 | |
| 31 | #trap 'kill -9 $(jobs -p);' SIGINT |
| 32 | |
| 33 | while getopts "sg" OPT; do |
| 34 | test "$OPT" == 's' && screen=true; |
| 35 | test "$OPT" == 'g' && graph=true; |
| 36 | done |
| 37 | |
| 38 | echo "Writing log to: $out"; |
| 39 | $graph && echo "Writing graph to: $graphout" |
| 40 | echo |
| 41 | arecord | ./goertzel -n i -q -l c -t $tresh -d 4 | while read line; do |
| 42 | date="$(date +%s)" |
| 43 | time="$(echo "$line" | cut -f 1)" |
| 44 | level="$(echo "$line" | cut -f 2)" |
| 45 | test "$level" -gt "$tresh" && state=false || state=true |
| 46 | $state && statenum=1 || statenum=0; |
| 47 | $state && statename='MOTION!' || statename='Nothing'; |
| 48 | |
| 49 | printf "%.2f\t %s %s %d" "$time" "$date" "$(date '+%F %T')" "$statenum" |
| 50 | |
| 51 | #Debug |
| 52 | after=$(( $date - $lastdate)) |
| 53 | printf " (%s %3d After %4d secs)\n" "$statename" "$level" "$after"; |
| 54 | |
| 55 | #Fun with values |
| 56 | $state && { |
| 57 | $screen && xset dpms force off || true; |
| 58 | } || { |
| 59 | $screen && xset dpms force on; |
| 60 | } |
| 61 | $graph && ./sleepplot.sh "$out" "$graphout" &>/dev/null & |
| 62 | |
| 63 | #Prepare invariants for next round |
| 64 | lastdate="$date"; |
| 65 | done | tee "$out" |
| 66 | kill $(jobs -p); sleep 0.2 |
| 67 | echo |
| 68 | echo "Your log: $out" |
| 69 | $graph && { |
| 70 | ./sleepplot.sh "$out" "$graphout" &>/dev/null |
| 71 | echo "Your graph: $graphout" |
| 72 | } |