backup tgids master
[scannr.git] / scannr.py
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import logging
 
logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s\t%(levelname)s\t%(message)s')
 
import snd
import time
from datetime import date
import threading
from pydispatch import dispatcher
import wave
import serial
#python -m serial.tools.miniterm -p COM20 -e -b 115200 --cr
import psycopg2
import csv
import sys
import os
 
 
sys.path.insert(0, os.path.join(os.path.dirname(__file__) or '.', 'pynma'))
import pynma
 
filename = "demo.wav"
last_call = (None, None, None)
MIN_LENGTH = 90000
lock = threading.RLock()
 
 
def get_call():
    global lock
    with lock:
        ser.write("GLG\r")
        line = ser.readline()   # read a '\n' terminated line
        print line
        reader = csv.reader([line])
        for row in reader:
            #GLG,40078,NFM,0,0,CanberraBlackMnt,AustralianCapita,SES Ops 1,1,0
            #,NONE,NONE,NONE
            if (row[0] != 'GLG' or row[1] == ''):
                print "uh oh"
                return (None, None, None)
            if (row[1] != ''):
                tgid = row[1]
                #nma.push("scannr", "ping", filename, "http://www.google.com")
                tgname = row[7]
                sitename = row[5]
                return (tgid, tgname, sitename)
 
 
def log_recording(tgid, tgname, sitename, filename, length):
    cur = conn.cursor()
    cur.execute("INSERT INTO recordings \
    (tgid, tgname, sitename, filename, length)\
     VALUES (%s, %s, %s, %s, %s)", ( tgid, tgname, sitename, filename, length))
    conn.commit()
    cur.close()
 
 
def tgid_worker():
    global last_call
    last_call = get_call()
 
 
def save_worker(filename, length):
    global last_call
    """thread worker function
    http://www.doughellmann.com/PyMOTW/threading/
    https://github.com/uskr/pynma
ffmpeg -i 2012-09-29-1348911268.34-demo.wav -ar 8000 -ab 4.75k test.3gp
http://stackoverflow.com/questions/2559746/getting-error-while-converting-
wav-to-amr-using-ffmpeg
"""
    print 'Worker for ' + filename
    (oldtgid, oldtgname, oldsitename) = last_call
    (tgid, tgname, sitename) = get_call()
    if oldtgid == tgid:
        if tgid is None or tgid == '':
            print filename + " has no TGID"
        else:
            log_recording(tgid, tgname, sitename, filename, length)
    else:
        if tgid is None or tgid == '':
            print filename + " has no TGID"
        else:
            log_recording(tgid, tgname, sitename, filename, length)
        if oldtgid is None or oldtgid == '':
            print filename + " has no old TGID"
        else:
            log_recording(oldtgid, oldtgname, oldsitename, filename, length)
    return
 
 
def filenameMaker():
    global filename
    filename = date.today().isoformat() + '-' + str(time.time()) + '-demo.wav'
 
 
def do_record():
    #global filename
    sample_width, data = snd.record()
    thr = threading.Thread(target=record_to_async_file, args=(sample_width, data, filename))
    thr.start()
 
 
def record_to_async_file(sample_width, data, filename):
    "Records from the microphone and outputs the resulting data to `filename`"
    print "Recording complete"
    if len(data) > MIN_LENGTH:
        print "Recording being saved..."
        dispatcher.send(signal='FILE_CREATED', sender=filename, filename=filename, length=len(data))
        print str(len(data))
        data = snd.pack('<' + ('h' * len(data)), *data)
        path = "./data/" + filename
        wf = wave.open(path, 'wb')
        wf.setnchannels(2)
        wf.setsampwidth(sample_width)
        wf.setframerate(snd.RATE)
        wf.writeframes(data)
        wf.close()
        del wf
        print("done - result " + str(len(data)) + " frames written to " + path)
    del data
 
dispatcher.connect(filenameMaker, signal='SND_STARTED', sender=dispatcher.Any)
dispatcher.connect(tgid_worker, signal='SND_STARTED', sender=dispatcher.Any)
dispatcher.connect(save_worker, signal='FILE_CREATED', sender=dispatcher.Any)
 
print "Opening serial port..."
if sys.platform.startswith('darwin'):
    ser = serial.Serial('/dev/tty.usbserial-FTB3VL83', 112500, timeout=1)
elif sys.platform.startswith('win32'):
    ser = serial.Serial('COM20', 112500, timeout=1)
print "Loading notifymyandroid..."
nma = pynma.PyNMA("a6f50f76119eda33befe4325b4b9e1dd25eef7bad2868e4f")
print "Connecting database..."
conn = psycopg2.connect("dbname=scannr user=postgres password=snmc")
print "Scannr started."
while True:
    print "ready to record again"
    do_record()
ser.close()