def pick_day(date): t0_code = ''.join(str(date.date).split('-')) t1_code = ''.join(str((date + 86400).date).split('-')) out_name = '{}-{}.ppk'.format(t0_code, t1_code) fout = open(os.path.join(out_root, out_name), 'w') print('picking %s' % date) data_dict = get_data_dict(date, data_root) for data_paths in data_dict.values(): st = read(data_paths[0]) st += read(data_paths[1]) st += read(data_paths[2]) picker.pick(st, fout) fout.close()
def alternating(ser, gui, channel, color, speed, size, moving, direction): global initial for array in initial: ser.write(array) out = ser.read() pass if gui != 0: color = [] gui = 2 for i in range(2): color.append(picker.pick("Color " + str(i + 1) + " of " + str(gui))) if moving: if direction: option = size * 8 + speed | 192 else: option = size * 8 + speed | 128 else: option = size * 8 + speed ser.write( bytearray.fromhex("4B0" + str(channel) + "C8" + color[0] + format(option, '02x'))) out = ser.read() ser.write( bytearray.fromhex("4B0" + str(channel) + "C8" + color[1] + format(option + 32, '02x'))) out = ser.read()
def pulse(ser, gui, channel, color, speed): global initial for array in initial: ser.write(array) out = ser.read() pass if 1 <= gui <= 8: color = [] for i in range(gui): color.append(picker.pick("Color " + str(i + 1) + " of " + str(gui))) ser.write( bytearray.fromhex("4B0" + str(channel) + "C9" + color[0] + "0" + str(speed))) out = ser.read() last_byte = speed for other_color in color[1:]: last_byte = last_byte + 20 ser.write( bytearray.fromhex("4B0" + str(channel) + "C9" + other_color + str(last_byte))) out = ser.read() print("DONE!")
def fixed(ser, gui, channel, color): if gui != 0: color = picker.pick("Color") command = create_command(ser, channel, [color], "fixed", 0, 0, 0, 2) outputs = previous.get_colors(channel, command) write(ser, outputs)
def wings(ser, gui, channel, color, speed): if gui != 0: color = picker.pick("Color") command = create_command(ser, channel, [color], "wings", 0, 0, 0, speed) outputs = previous.get_colors(channel, command) write(ser, outputs)
def candlelight(ser, gui, channel, color): if gui != 0: color = picker.pick("Color") command = create_command(ser, channel, [color], "candlelight", 0, 0, 0, 0) outputs = previous.get_colors(channel, command) write(ser, outputs)
def getMode(self): title = 'Please select which mode you would like to play:' opts = { 'Name the Tune': 'title', 'Name the Artist': 'artist', 'Name the Album': 'album' } choice, idx = pick(list(opts.keys()), title, indicator='->') self.mode = opts[choice]
def marquee(ser, gui, channel, color, speed, size, direction): if gui != 0: gui = 1 for i in range(1): color = picker.pick("Color "+str(i+1) + " of "+str(gui)) command = create_command(ser, channel, [color], "marquee", direction, 0, size, speed) outputs = previous.get_colors(channel, command) write(ser, outputs)
def cover_marquee(ser, gui, channel, color, speed, direction): if 1 <= gui <= 8: color = [] for i in range(gui): color.append(picker.pick("Color "+str(i+1) + " of "+str(gui))) command = create_command(ser, channel, color, "cover_marquee", direction, 0, 0, speed) outputs = previous.get_colors(channel, command) write(ser, outputs)
def pulse(ser, gui, channel, color, speed): if 1 <= gui <= 8: color = [] for i in range(gui): color.append(picker.pick("Color "+str(i+1) + " of "+str(gui))) command = create_command(ser, channel, color, "pulse", 0, 0, 0, speed) outputs = previous.get_colors(channel, command) write(ser, outputs)
def fixed(ser, gui, channel, color): if gui != 0: color = picker.pick("Color") print("Creating command...") command = create_command(ser, channel, [color], "fixed", 0, 0, 0, 2) print("Doing this weird previous thing") outputs = previous.get_colors(channel, command) print("Write final command.") write(ser, outputs) print("Done")
def candlelight(ser, gui, channel, color): global initial for array in initial: ser.write(array) out = ser.read() pass if gui != 0: color = picker.pick("Color") ser.write(bytearray.fromhex("4B0" + str(channel) + "CC" + color + "00")) out = ser.read()
def fixed(ser, gui, channel, color): global initial for array in initial: ser.write(array) out = ser.read() pass if gui != 0: color = picker.pick("Color") ser.write(bytearray.fromhex("4B0" + str(channel) + "C0" + color + "00")) out = ser.read() print("DONE!")
def custom(ser, gui, channel, colors, mode, speed): strips = [strips_info(ser, 1), strips_info(ser, 2)] if mode not in ['fixed', 'breathing', 'wave']: raise InvalidCommand("No such mode for custom") if 1 <= gui <= 40: colors = [] for i in range(gui): colors.append(picker.pick("Color "+str(i+1) + " of "+str(gui))) command = create_custom(ser, channel, colors, mode, 0, 0, 0, speed, strips) outputs = previous.get_colors(channel, command) write(ser, outputs)
def alternating(ser, gui, channel, color, speed, size, moving, direction): if gui != 0: color = [] gui = 2 for i in range(2): color.append(picker.pick("Color "+str(i+1) + " of "+str(gui))) if moving: option = 1 else: option = 0 command = create_command(ser, channel, color, "alternating", direction, option, size, speed) outputs = previous.get_colors(channel, command) write(ser, outputs)
def cover_marquee(ser, gui, channel, color, speed, direction): global initial for array in initial: ser.write(array) out = ser.read() pass if 1 <= gui <= 8: color = [] for i in range(gui): color.append(picker.pick("Color " + str(i + 1) + " of " + str(gui))) option = speed | 0 if direction: first_option = format(option, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C7" + color[0] + first_option)) out = ser.read() last_byte = option for other_color in color[1:]: last_byte = last_byte + 32 loop_option = format(last_byte, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C7" + other_color + loop_option)) out = ser.read() else: first_option = format(option, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C6" + color[0] + first_option)) out = ser.read() last_byte = option for other_color in color[1:]: last_byte = last_byte + 32 loop_option = format(last_byte, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C6" + other_color + loop_option)) out = ser.read() print("DONE!")
def marquee(ser, gui, channel, color, speed, size, comet, direction): global initial for array in initial: ser.write(array) out = ser.read() pass if gui != 0: color = [] gui = 2 for i in range(2): color.append(picker.pick("Color " + str(i + 1) + " of " + str(gui))) if comet: option = size * 8 + speed | 128 else: option = size * 8 + speed | 0 if direction: first_option = format(option, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C5" + color[0] + first_option)) out = ser.read() second_option = format(option + 32, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C5" + color[1] + second_option)) out = ser.read() else: first_option = format(option, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C4" + color[0] + first_option)) out = ser.read() second_option = format(option + 32, '02x') ser.write( bytearray.fromhex("4B0" + str(channel) + "C4" + color[1] + second_option)) out = ser.read() print("DONE!")
def playRound(self): self.genOptions(self.optcount, self.mode) realpick = self.song_list[0] realfname = self.song_fnames[0] realdata = getSongData(realfname) random.shuffle(self.song_list) playSong(realfname) starttime = time.time() title = f'Round {self.round}: Guess the {self.mode}!' choice = None while choice != realpick: choice, idx = pick(self.song_list, title, indicator='->') self.song_list.remove(choice) elapsedtime = time.time() - starttime score = max( 100 * (1 - elapsedtime / realdata['length']) - (self.optcount - 1 - len(self.song_list)) * (100 / self.optcount), 0) print('You guessed it!') print(f'Your score was {score:0.2f}') input('Press enter to continue to next round...') self.totalscore += score self.round += 1
def audio_level(ser, gui, channel, colors, tolerance, smooth): try: if os.geteuid() == 0: raise InvalidUser( "Audio won't work with root. Login as a normal user, add your user to the group of /dev/ttyACM0 and retry without root" ) except: pass if not inspect.isclass(ser): ser = serial.Serial(ser, 256000) if 1 <= gui <= 8: colors = [] for i in range(gui): colors.append( picker.pick("Color " + str(i + 1) + " of " + str(gui))) strips = [strips_info(ser, 1), strips_info(ser, 2)] if channel == 0: channel = [1, 2] else: channel = [channel] init(ser) import pyaudio import wave chunk = 2048 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 500000 WAVE_OUTPUT_FILENAME = "output.wav" p = pyaudio.PyAudio() if os.name == 'nt': chunk = 1024 # Windows doesn't like 2048 for some reason index = p.get_default_input_device_info()['index'] for i in range(p.get_device_count()): if 'Stereo Mix' in p.get_device_info_by_index(i)['name']: index = i stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=chunk, input_device_index=index) else: stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=chunk) alls = [] s = [] try: while True: try: data = stream.read(chunk) except IOError: continue alls.append(data) if len(alls) > 1: data = b''.join(alls) wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(data) wf.close() w = wave.open(WAVE_OUTPUT_FILENAME, 'rb') summ = 0 value = 1 delta = 1 amps = [] for i in range(0, w.getnframes()): data = struct.unpack('<h', w.readframes(1)) summ += (data[0] * data[0]) / 2 if (i != 0 and (i % 1470) == 0): value = int(math.sqrt(summ / 1470.0) / 10) amps.append(value - delta) summ = 0 if delta == 0: tarW = 0.0 else: tarW = float(amps[0] * 1.0 / delta / 100) s.append(tarW) if len(s) >= smooth: out = sum(s) / len(s) for c in channel: write_audio(ser, c, colors, tolerance, out, strips) s = [] delta = value alls = [] except: stream.close() p.terminate() os.remove(WAVE_OUTPUT_FILENAME) raise
def main(): """ Input file fields galactic (ephem.Galactic): galactic coordinates ra (ephem.Angle): right ascension (RA) of the point to observe dec (ephem.Angle): declination (DEC) of the point to observe epoch (ephem.Date): epoch with which RA and DEC were calculated t_obs(float): seconds observed """ parser = argparse.ArgumentParser(description='Record data from the Leuschner dish.') parser.add_argument('pointings_log', help='path to .npz file of points to observe') parser.add_argument('--time', type=float, default=150, help='integration time in seconds (defaults to 150s') parser.add_argument('--repoint', type=float, default=30, help='frequency of dish position updates') parser.add_argument('--margin', type=float, default=2, help='record point if it is within MARGIN degrees of the altitude limit') parser.add_argument('--verbose', action='store_true', default=False, help='additional debugging output') parser.add_argument('--endtime', type=str, help='datetime string in form "mm-dd-yyyy hh:mm:ss"') args = parser.parse_args() if not os.path.exists(os.path.join(PATH, "raw")): os.mkdir(os.path.join(PATH, "raw")) if not os.path.exists(os.path.join(PATH, "logs")): os.mkdir(os.path.join(PATH, "logs")) if not os.path.exists(os.path.join(PATH, "data")): os.mkdir(os.path.join(PATH, "data")) if args.repoint <= 12: raise argparse.ArgumentTypeError("Can't repoint more often than every 12 seconds.") if args.time <= 0: raise argparse.ArgumentTypeError("Can't record for 0 seconds.") if not args.endtime: raise argparse.ArgumentError("Need to specify an endtime in the form 'mm-dd-yyyy hh:mm:ss'") logger = logging.getLogger('leuschner') init_log() pointings = np.load(os.path.join(PATH, args.pointings_log)) logger.debug('Date: %s', str(OBS.date)) logger.debug('Observer Latitude: %s', str(OBS.lat)) logger.debug('Observer Long: %s', str(OBS.long)) logger.debug('LO frequency: %s', str(LO_ON)) logger.debug('LO off frequency: %s', str(LO_OFF)) endtime = datetime.datetime.strptime(args.endtime, "%m-%d-%Y %H:%M:%S") # Create dish and synthesizer interfaces d = init_dish(verbose=args.verbose) s = init_synth(freq=LO_ON, amp=10.0, verbose=args.verbose) while datetime.datetime.now() + datetime.timedelta(seconds=2*args.time+10) <= endtime: in_range = False skip = 0 max_N = 1 while not in_range: if (datetime.datetime.now() + datetime.timedelta(seconds=2*args.time+10) > endtime): break # TODO (uh): the max_N=1 obvsiouly only works on the first run... what should we do? new_point = picker.pick(max_N=max_N, skip=skip) if type(new_point) == int: skip = 0 max_N += 1 continue ra = new_point['ra'] dec = new_point['dec'] # epoch = pointings['epoch'] glat = new_point['lat'] glon = new_point['lon'] point = ephem.FixedBody() point._ra = np.deg2rad(ra) point._dec = np.deg2rad(dec) point._epoch = ephem.J2000 # kevin: Hardcoding this because I don't wanna deal with it OBS.date = ephem.now() point.compute(OBS) try: dish.pointing.az_alt_to_xy(np.rad2deg(point.az), np.rad2deg(point.alt) - args.margin) except ValueError: in_range = False logger.debug("Skipping (%s, %s) for due to reasons." % (np.rad2deg(point.az), np.rad2deg(point.alt))) skip += 1 continue # Skip pointing if it isn't within the observing limits if (np.rad2deg(point.alt)-args.margin) <= ALT_LIMITS[int(np.rad2deg(point.az))]: in_range = False logger.debug("Skipping (%s, %s) for the greater good." % (np.rad2deg(point.az), np.rad2deg(point.alt))) skip += 1 else: in_range = True if not in_range: break logger.debug("Picked next point %s" % new_point) logger.debug("Picked next point (alt, az): (%.4f, %.4f)" % (np.rad2deg(point.alt), np.rad2deg(point.az))) # CANT LAUNCH SEPARATE THREAD BECAUSE 2 THREADS CANT USE DISH # Create a thread that periodically re-points the telescope # Set the thread to run for 2*integration time + 5 seconds for initial # pointing # controller = threading.Thread(target = repoint, # args = (d, point, args.time*2+5, args.repoint)) # controller.daemon = True # controller.start() status = record_pointing(d, s, glon, glat, point, file_name=os.path.join(PATH, 'raw', 'l%.4f_b%.4f_%s' % (glon, glat, time.strftime("%m-%d-%Y_%H%M%S"))), int_time=args.time, repoint_freq=args.repoint) # controller.join() #TODO(Kevin): status will be -1 if data was not successfully saved picker.update(glon, glat, N=1, t_obs=args.time) logger.debug('Exiting')