How to control a switch by audio

Copy the following files into a directory (e.g. /opt/audio-switch)

rx-audio-adapter.sh

#!/bin/bash

rm rx.log

while true
do
        rm in.wav
        rec in.wav silence 1 0.1 3% 1 3.0 3%
        rx=$(./dtmf2num in.wav | tail -n 1 | cut -c 18-)
        echo $rx >> rx.log
        if [ "$rx" == "1" ]; then
                echo switch ON >> rx.log
                curl http://localhost:8080/on
        elif [ "$rx" == "D" ]; then
                echo switch OFF >> rx.log
                curl http://localhost:8080/off
        else
                echo unknown command >> rx.log
        fi
        sleep 1
done

 

usb-switch-service.py

Python dependencies: pyserial, web.py

import serial
import time
import json
import web

# /status       -> return the status of the switch (on/off)
# /on           -> turn ON the switch and return the status (on/off)
# /off          -> turn OFF the switch and return the status (on/off)
urls = (
    '/(.*)', 'ActionController'
)

app = web.application(urls, globals())

ser = serial.Serial('/dev/ttyUSB0')

class ActionController:
    def GET(self, action):
        status = ""
        if action == 'status':
            print "status"
            status = ser.dsr
        elif action == 'on':
            print "on"
            ser.dtr = True
            time.sleep(0.1)
            status = ser.dsr
        elif action == 'off':
            print "off"
            ser.dtr = False
            time.sleep(0.1)
            status = ser.dsr
        else:
            print "unknown command"
            status = ser.dsr
        return json.dumps(status)
      
if __name__ == "__main__":
    app.run()

 

start-switch.sh

#!/bin/bash

pushd /opt/audio-switch

# start usb-switch-service
python usb-switch-service.py > /tmp/usb-switch-service.log &
sleep 5
curl http://localhost:8080/off

# start rx-audio-adapter
rm in.wav
nohup ./rx-audio-adapter.sh > /dev/null 2>&1 &

popd

 

dtmf2num

wget http://aluigi.altervista.org/mytoolz/dtmf2num.zip

then compile it (make).

 

DTMF tones

The DTMF tone files can be generated from here:

http://www.audiocheck.net/audiocheck_dtmf.php

The rx-audio-adapter can be tested with the following script:

loop.sh

#!/bin/bash

while true
do
        aplay audiocheck.net_dtmf_1.wav
        sleep 10
        aplay audiocheck.net_dtmf_D.wav
        sleep 10
done

 

Advertisements