def run(printFREQ=60, port=8888): ''' Initialize stream and print constants, then process data for packet loss. :param int printFREQ: Value in seconds denoting the frequency with which this program will report packets lost :param int port: Local port to listen on ''' global DPtime, DPttlLoss printM("Initializing...") raspberryshake.initRSlib( dport=port, rsstn='Z0000' ) # runs in quiet mode; suppresses needless output but shows errors add_debug_handler() # now start console output # initialize data stream constants printM('Opened data port successfully.') DP = raspberryshake.getDATA() CHAN = raspberryshake.getCHN( DP) # first channel - doesn't matter which, used to stop looping TR = raspberryshake.tf # transmission rate - in milliseconds TRE = (TR + TR * .5) / 1000. # time diff / error to identify a missed packet SR = raspberryshake.sps # sample / second ttlCHN = raspberryshake.getTTLCHN() # total number of channels printM(" Total Channels: %s" % ttlCHN) printM(" Sample Rate: %s samples / second" % SR) printM(" TX Rate: Every %s milliseconds" % TR) # start processing data packets for packet loss detection # initialize chnNum = 0 while chnNum < ttlCHN: DP = raspberryshake.getDATA() CHAN = raspberryshake.getCHN(DP) DPtime[CHAN] = raspberryshake.getTIME(DP) timeStart[CHAN] = DPtime[CHAN] DPttlLoss[CHAN] = 0 chnNum += 1 printM('Data Packet reading begun.') printM( 'Will report any DP loss as it happens and totals every %s seconds.' % printFREQ) while 1: # loop forever DP = raspberryshake.getDATA() CHAN = raspberryshake.getCHN(DP) timeS = raspberryshake.getTIME(DP) timeD = timeS - DPtime[CHAN] if abs(timeD) > TRE: printM("DP loss of %s second(s) Current TS: %s, Previous TS: %s" % (round(timeD, 3), timeS, DPtime[CHAN])) DPttlLoss[CHAN] += abs(int(timeD * TR)) DPtime[CHAN] = timeS if int(timeS) % printFREQ == 0: if printTTLS(CHAN, TR): timeStart[CHAN] = timeS DPttlLoss[CHAN] = 0
def run(settings, debug): ''' Main setup function. Takes configuration values and passes them to the appropriate threads and functions. :param dict settings: settings dictionary (see :ref:`defaults` for guidance) :param bool debug: whether or not to show debug output (should be turned off if starting as daemon) ''' global PLOTTER, SOUND # handler for the exit signal signal.signal(signal.SIGINT, handler) if TESTING: global TESTQUEUE # initialize the test data to read information from file and put it on the port TESTQUEUE = Queue( ) # separate from client library because this is not downstream of the producer tdata = TestData(q=TESTQUEUE, data_file=TESTFILE, port=settings['settings']['port']) tdata.start() # initialize the central library rs.initRSlib(dport=settings['settings']['port'], rsstn=settings['settings']['station']) H.conn_stats(TESTING) if TESTING: T.TEST['n_port'][1] = True # port has been opened if rs.sps == 0: printE( 'There is already a Raspberry Shake sending data to this port.', sender=SENDER) printE( 'For testing, please change the port in your settings file to an unused one.', sender=SENDER, spaces=True) _xit(1) output_dir = settings['settings']['output_dir'] if settings['printdata']['enabled']: # set up queue and process q = mk_q() prnt = PrintRaw(q, testing=TESTING) mk_p(prnt) if settings['write']['enabled']: global WRITER # set up queue and process cha = settings['write']['channels'] q = mk_q() WRITER = Write(q=q, data_dir=output_dir, cha=cha, testing=TESTING) mk_p(WRITER) if settings['plot']['enabled'] and MPL: while True: if rs.numchns == 0: time.sleep(0.01) continue else: break cha = settings['plot']['channels'] sec = settings['plot']['duration'] spec = settings['plot']['spectrogram'] full = settings['plot']['fullscreen'] kiosk = settings['plot']['kiosk'] screencap = settings['plot']['eq_screenshots'] alert = settings['alert']['enabled'] if settings['plot']['deconvolve']: if settings['plot']['units'].upper() in rs.UNITS: deconv = settings['plot']['units'].upper() else: deconv = 'CHAN' else: deconv = False pq = mk_q() PLOTTER = Plot(cha=cha, seconds=sec, spectrogram=spec, fullscreen=full, kiosk=kiosk, deconv=deconv, q=pq, screencap=screencap, alert=alert, testing=TESTING) # no mk_p() here because the plotter must be controlled by the main thread (this one) if settings['forward']['enabled']: # put settings in namespace addr = settings['forward']['address'] port = settings['forward']['port'] cha = settings['forward']['channels'] fwd_data = settings['forward']['fwd_data'] fwd_alarms = settings['forward']['fwd_alarms'] # set up queue and process if len(addr) == len(port): printM('Initializing %s Forward threads' % (len(addr)), sender=SENDER) for i in range(len(addr)): q = mk_q() forward = Forward(num=i, addr=addr[i], port=int(port[i]), cha=cha, fwd_data=fwd_data, fwd_alarms=fwd_alarms, q=q, testing=TESTING) mk_p(forward) else: printE( 'List length mismatch: %s addresses and %s ports in forward section of settings file' % (len(addr), len(port)), sender=SENDER) _xit(1) if settings['alert']['enabled']: # put settings in namespace sta = settings['alert']['sta'] lta = settings['alert']['lta'] thresh = settings['alert']['threshold'] reset = settings['alert']['reset'] bp = [settings['alert']['highpass'], settings['alert']['lowpass']] cha = settings['alert']['channel'] if settings['alert']['deconvolve']: if settings['alert']['units'].upper() in rs.UNITS: deconv = settings['alert']['units'].upper() else: deconv = 'CHAN' else: deconv = False # set up queue and process q = mk_q() alrt = Alert(sta=sta, lta=lta, thresh=thresh, reset=reset, bp=bp, cha=cha, debug=debug, q=q, testing=TESTING, deconv=deconv) mk_p(alrt) if settings['alertsound']['enabled']: soundloc = os.path.expanduser( os.path.expanduser(settings['alertsound']['mp3file'])) if soundloc in ['doorbell', 'alarm', 'beeps', 'sonar']: soundloc = pr.resource_filename( 'rsudp', os.path.join('rs_sounds', '%s.mp3' % soundloc)) q = mk_q() alsnd = AlertSound(q=q, testing=TESTING, soundloc=soundloc) mk_p(alsnd) runcustom = False try: f = False win_ovr = False if settings['custom']['enabled']: # put settings in namespace f = settings['custom']['codefile'] win_ovr = settings['custom']['win_override'] if f == 'n/a': f = False runcustom = True except KeyError as e: if settings['alert']['exec'] != 'eqAlert': printW( 'the custom code function has moved to its own module (rsudp.c_custom)', sender='Custom') f = settings['alert']['exec'] win_ovr = settings['alert']['win_override'] runcustom = True else: raise KeyError(e) if runcustom: # set up queue and process q = mk_q() cstm = Custom(q=q, codefile=f, win_ovr=win_ovr, testing=TESTING) mk_p(cstm) if settings['tweets']['enabled']: global TWITTER consumer_key = settings['tweets']['api_key'] consumer_secret = settings['tweets']['api_secret'] access_token = settings['tweets']['access_token'] access_token_secret = settings['tweets']['access_secret'] tweet_images = settings['tweets']['tweet_images'] extra_text = settings['tweets']['extra_text'] q = mk_q() TWITTER = Tweeter(q=q, consumer_key=consumer_key, consumer_secret=consumer_secret, access_token=access_token, access_token_secret=access_token_secret, tweet_images=tweet_images, extra_text=extra_text, testing=TESTING) mk_p(TWITTER) if settings['telegram']['enabled']: global TELEGRAM token = settings['telegram']['token'] chat_ids = settings['telegram']['chat_id'].strip(' ').split(',') send_images = settings['telegram']['send_images'] extra_text = settings['telegram']['extra_text'] for chat_id in chat_ids: sender = "Telegram id %s" % (chat_id) q = mk_q() TELEGRAM = Telegrammer(q=q, token=token, chat_id=chat_id, send_images=send_images, extra_text=extra_text, sender=sender, testing=TESTING) mk_p(TELEGRAM) if settings['rsam']['enabled']: # put settings in namespace fwaddr = settings['rsam']['fwaddr'] fwport = settings['rsam']['fwport'] fwformat = settings['rsam']['fwformat'] interval = settings['rsam']['interval'] cha = settings['rsam']['channel'] quiet = settings['rsam']['quiet'] if settings['rsam']['deconvolve']: if settings['rsam']['units'].upper() in rs.UNITS: deconv = settings['rsam']['units'].upper() else: deconv = 'CHAN' else: deconv = False # set up queue and process q = mk_q() rsam = RSAM(q=q, interval=interval, cha=cha, deconv=deconv, fwaddr=fwaddr, fwport=fwport, fwformat=fwformat, quiet=quiet, testing=TESTING) mk_p(rsam) # start additional modules here! ################################ ################################ if TESTING: # initialize test consumer q = mk_q() test = Testing(q=q) mk_p(test) # start the producer, consumer, and activated modules start() PLOTTER = False if not TESTING: _xit() else: printW('Client has exited, ending tests...', sender=SENDER, announce=False)
import rsudp.raspberryshake as RS port = 8888 # Port to bind to with open('/opt/settings/sys/ip.txt', 'r') as file: host = file.read().strip() RS.initRSlib(dport=port) RS.openSOCK(host) def main(): try: while 1: # loop forever print(RS.getDATA()) except KeyboardInterrupt: print('') RS.printM('Quitting...') exit(0) if __name__ == '__main__': main()
def run(settings, debug): ''' Main setup function. Takes configuration values and passes them to the appropriate threads and functions. :param dict settings: settings dictionary (see :ref:`defaults` for guidance) :param bool debug: whether or not to show debug output (should be turned off if starting as daemon) ''' global PLOTTER, SOUND # handler for the exit signal signal.signal(signal.SIGINT, handler) if TESTING: global TESTQUEUE # initialize the test data to read information from file and put it on the port TESTQUEUE = Queue() # separate from client library because this is not downstream of the producer tdata = TestData(q=TESTQUEUE, data_file=TESTFILE, port=settings['settings']['port']) tdata.start() # initialize the central library rs.initRSlib(dport=settings['settings']['port'], rsstn=settings['settings']['station']) H.conn_stats(TESTING) if TESTING: T.TEST['n_port'][1] = True # port has been opened if rs.sps == 0: printE('There is already a Raspberry Shake sending data to this port.', sender=SENDER) printE('For testing, please change the port in your settings file to an unused one.', sender=SENDER, spaces=True) _xit(1) output_dir = settings['settings']['output_dir'] if settings['printdata']['enabled']: # set up queue and process q = mk_q() prnt = PrintRaw(q) mk_p(prnt) if settings['write']['enabled']: # set up queue and process cha = settings['write']['channels'] q = mk_q() writer = Write(q=q, cha=cha) mk_p(writer) if settings['plot']['enabled'] and MPL: while True: if rs.numchns == 0: time.sleep(0.01) continue else: break cha = settings['plot']['channels'] sec = settings['plot']['duration'] spec = settings['plot']['spectrogram'] full = settings['plot']['fullscreen'] kiosk = settings['plot']['kiosk'] screencap = settings['plot']['eq_screenshots'] alert = settings['alert']['enabled'] if settings['plot']['deconvolve']: if settings['plot']['units'].upper() in rs.UNITS: deconv = settings['plot']['units'].upper() else: deconv = 'CHAN' else: deconv = False pq = mk_q() PLOTTER = Plot(cha=cha, seconds=sec, spectrogram=spec, fullscreen=full, kiosk=kiosk, deconv=deconv, q=pq, screencap=screencap, alert=alert) # no mk_p() here because the plotter must be controlled by the main thread (this one) if settings['forward']['enabled']: # put settings in namespace addr = settings['forward']['address'] port = settings['forward']['port'] cha = settings['forward']['channels'] # set up queue and process q = mk_q() forward = Forward(addr=addr, port=port, cha=cha, q=q) mk_p(forward) if settings['alert']['enabled']: # put settings in namespace sta = settings['alert']['sta'] lta = settings['alert']['lta'] thresh = settings['alert']['threshold'] reset = settings['alert']['reset'] bp = [settings['alert']['highpass'], settings['alert']['lowpass']] cha = settings['alert']['channel'] if settings['alert']['deconvolve']: if settings['alert']['units'].upper() in rs.UNITS: deconv = settings['alert']['units'].upper() else: deconv = 'CHAN' else: deconv = False # set up queue and process q = mk_q() alrt = Alert(sta=sta, lta=lta, thresh=thresh, reset=reset, bp=bp, cha=cha, debug=debug, q=q, deconv=deconv) mk_p(alrt) if settings['alertsound']['enabled']: sender = 'AlertSound' SOUND = False soundloc = False if PYDUB_EXISTS: soundloc = os.path.expanduser(os.path.expanduser(settings['alertsound']['mp3file'])) if soundloc in ['doorbell', 'alarm', 'beeps', 'sonar']: soundloc = pr.resource_filename('rsudp', os.path.join('rs_sounds', '%s.mp3' % soundloc)) if os.path.exists(soundloc): try: SOUND = AudioSegment.from_file(soundloc, format="mp3") printM('Loaded %.2f sec alert sound from %s' % (len(SOUND)/1000., soundloc), sender='AlertSound') except FileNotFoundError as e: printW("You have chosen to play a sound, but don't have ffmpeg or libav installed.", sender='AlertSound') printW('Sound playback requires one of these dependencies.', sender='AlertSound', spaces=True) printW("To install either dependency, follow the instructions at:", sender='AlertSound', spaces=True) printW('https://github.com/jiaaro/pydub#playback', sender='AlertSound', spaces=True) printW('The program will now continue without sound playback.', sender='AlertSound', spaces=True) SOUND = False else: printW("The file %s could not be found." % (soundloc), sender='AlertSound') printW('The program will now continue without sound playback.', sender='AlertSound', spaces=True) else: printW("You don't have pydub installed, so no sound will play.", sender='AlertSound') printW('To install pydub, follow the instructions at:', sender='AlertSound', spaces=True) printW('https://github.com/jiaaro/pydub#installation', sender='AlertSound', spaces=True) printW('Sound playback also requires you to install either ffmpeg or libav.', sender='AlertSound', spaces=True) q = mk_q() alsnd = AlertSound(q=q, sound=SOUND, soundloc=soundloc) mk_p(alsnd) runcustom = False try: f = False win_ovr = False if settings['custom']['enabled']: # put settings in namespace f = settings['custom']['codefile'] win_ovr = settings['custom']['win_override'] if f == 'n/a': f = False runcustom = True except KeyError as e: if settings['alert']['exec'] != 'eqAlert': printW('the custom code function has moved to its own module (rsudp.c_custom)', sender='Custom') f = settings['alert']['exec'] win_ovr = settings['alert']['win_override'] runcustom = True else: raise KeyError(e) if runcustom: # set up queue and process q = mk_q() cstm = Custom(q=q, codefile=f, win_ovr=win_ovr) mk_p(cstm) if settings['tweets']['enabled']: consumer_key = settings['tweets']['api_key'] consumer_secret = settings['tweets']['api_secret'] access_token = settings['tweets']['access_token'] access_token_secret = settings['tweets']['access_secret'] tweet_images = settings['tweets']['tweet_images'] q = mk_q() tweet = Tweeter(q=q, consumer_key=consumer_key, consumer_secret=consumer_secret, access_token=access_token, access_token_secret=access_token_secret, tweet_images=tweet_images) mk_p(tweet) if settings['telegram']['enabled']: token = settings['telegram']['token'] chat_ids = settings['telegram']['chat_id'].strip(' ').split(',') send_images = settings['telegram']['send_images'] for chat_id in chat_ids: sender = "Telegram id %s" % (chat_id) q = mk_q() telegram = Telegrammer(q=q, token=token, chat_id=chat_id, send_images=send_images, sender=sender) mk_p(telegram) if settings['rsam']['enabled']: # put settings in namespace fwaddr = settings['rsam']['fwaddr'] fwport = settings['rsam']['fwport'] fwformat = settings['rsam']['fwformat'] interval = settings['rsam']['interval'] cha = settings['rsam']['channel'] if settings['rsam']['deconvolve']: if settings['rsam']['units'].upper() in rs.UNITS: deconv = settings['rsam']['units'].upper() else: deconv = 'CHAN' else: deconv = False # set up queue and process q = mk_q() rsam = RSAM(q=q, debug=debug, interval=interval, cha=cha, deconv=deconv, fwaddr=fwaddr, fwport=fwport, fwformat=fwformat) mk_p(rsam) # start additional modules here! ################################ ################################ if TESTING: # initialize test consumer q = mk_q() test = Testing(q=q) mk_p(test) # start the producer, consumer, and activated modules start() PLOTTER = False if not TESTING: _xit() else: printW('Client has exited, ending tests...', sender=SENDER, announce=False) if SOUND: T.TEST['d_pydub'][1] = True
def run(settings, debug): # handler for the exit signal signal.signal(signal.SIGINT, handler) RS.initRSlib(dport=settings['settings']['port'], rsstn=settings['settings']['station']) output_dir = settings['settings']['output_dir'] destinations, threads = [], [] def mk_q(): q = Queue(RS.qsize) destinations.append(q) return q def mk_p(proc): threads.append(proc) if settings['printdata']['enabled']: # set up queue and process q = mk_q() prnt = PrintRaw(q) mk_p(prnt) if settings['write']['enabled']: # set up queue and process q = mk_q() writer = Write(q=q) mk_p(writer) if settings['plot']['enabled'] and mpl: while True: if RS.numchns == 0: time.sleep(0.01) continue else: break cha = settings['plot']['channels'] sec = settings['plot']['duration'] spec = settings['plot']['spectrogram'] full = settings['plot']['fullscreen'] kiosk = settings['plot']['kiosk'] screencap = settings['plot']['eq_screenshots'] alert = settings['alert']['enabled'] if settings['plot']['deconvolve']: deconv = settings['plot']['units'] else: deconv = False pq = mk_q() Plotter = Plot(cha=cha, seconds=sec, spectrogram=spec, fullscreen=full, kiosk=kiosk, deconv=deconv, q=pq, screencap=screencap, alert=alert) if settings['forward']['enabled']: # put settings in namespace addr = settings['forward']['address'] port = settings['forward']['port'] cha = settings['forward']['channels'] # set up queue and process q = mk_q() forward = Forward(addr=addr, port=port, cha=cha, q=q) mk_p(forward) if settings['alert']['enabled']: # put settings in namespace sta = settings['alert']['sta'] lta = settings['alert']['lta'] thresh = settings['alert']['threshold'] reset = settings['alert']['reset'] bp = [settings['alert']['highpass'], settings['alert']['lowpass']] cha = settings['alert']['channel'] win_ovr = settings['alert']['win_override'] ex = eqAlert if settings['alert']['exec'] in 'eqAlert' else settings[ 'alert']['exec'] if settings['alert']['deconvolve']: deconv = settings['alert']['units'] else: deconv = False # set up queue and process q = mk_q() alrt = Alert(sta=sta, lta=lta, thresh=thresh, reset=reset, bp=bp, func=ex, cha=cha, win_ovr=win_ovr, debug=debug, q=q, deconv=deconv) mk_p(alrt) if settings['alertsound']['enabled']: sender = 'AlertSound' sound = False if pydub_exists: soundloc = os.path.expanduser( os.path.expanduser(settings['alertsound']['mp3file'])) if soundloc in ['doorbell', 'alarm', 'beeps', 'sonar']: soundloc = pr.resource_filename( 'rsudp', os.path.join('rs_sounds', '%s.mp3' % soundloc)) try: sound = AudioSegment.from_file(soundloc, format="mp3") printM('Loaded %.2f sec alert sound from %s' % (len(sound) / 1000., soundloc), sender='AlertSound') except FileNotFoundError as e: if ['ffprobe' in str(e)] or ['avprobe' in str(e)]: printM( "WARNING: You have chosen to play a sound, but don't have ffmpeg or libav installed.", sender='AlertSound') printM( ' Sound playback requires one of these dependencies.', sender='AlertSound') printM( " To install either dependency, follow the instructions at:", sender='AlertSound') printM(' https://github.com/jiaaro/pydub#playback', sender='AlertSound') printM( ' The program will now continue without sound playback.', sender='AlertSound') else: raise FileNotFoundError('MP3 file could not be found') sound = False else: sound = False printM( "WARNING: You don't have pydub installed, so no sound will play.", sender='AlertSound') printM(' To install pydub, follow the instructions at:', sender='AlertSound') printM(' https://github.com/jiaaro/pydub#installation', sender='AlertSound') printM( ' Sound playback also requires you to install either ffmpeg or libav.', sender='AlertSound') q = mk_q() alsnd = AlertSound(q=q, sound=sound) mk_p(alsnd) # master queue and consumer queue = Queue(RS.qsize) cons = Consumer(queue, destinations) cons.start() for thread in threads: thread.start() prod = Producer(queue, threads) prod.start() if settings['plot']['enabled'] and mpl: Plotter.run() else: while not prod.stop: time.sleep(0.1) time.sleep(0.5) print() printM('Shutdown successful.', 'Main') sys.exit()