def __init__(self): Radio.__init__(self) self.playing_list_url = "http://139.198.14.56/ls.php" self.next_play_url = "http://139.198.14.56/ls.php" self.file_url = "http://139.198.14.56/phpfiles/" self.play_info_url = "http://139.198.14.56/play2.php" self.change_status_url = "http://139.198.14.56/change2.php"
def __init__(self, servaddr, servport, device_args="", rx_txrx=False): self.pipe = None self.conproc = None self.logger = None self.setup_logger() self.radio = Radio(self.logger, device_args, rx_txrx) self.connector = ClientConnector(servaddr, servport)
def __init__(self): super(Main, self).__init__() ## initialize sensors self.sensorThread = False self.radioThread = False self.cameraThread = False try: self.sensorThread = Sensors() except: print("error initing sensor thread") try: pass #self.cameraThread = Camera('Mini') except: print("error initializing camera thread") try: self.radioThread = Radio(self) except: print("error initing radio thread") #self.numberGen = RandomThread() self.daemon = True self.fileLocation = str(os.getcwd()) + '/' self.data_file = self.fileLocation + str(datetime.now().replace(microsecond=0)) print("initialized") print(self.data_file)
class MyPlayer(xbmc.Player): def __init__(self, playerCore=0): self.radio = None self.urls = [] self.valid = True self.started = False xbmc.Player.__init__(self, playerCore=playerCore) def start(self, station_id, station_from): log("Yandex.Radio::start") self.radio = Radio(client, station_id, station_from) self.radio.start_radio(self.__on_start) def __on_start(self, track, next_track): log("Yandex.Radio::__on_start") self.add_next_track(track) self.add_next_track(next_track) self.play(pl, startpos=0) self.started = True def __on_play_next(self, track): log("Yandex.Radio::__on_play_next") self.add_next_track(track) def queue_next(self): log("Yandex.Radio::queue_next") self.radio.play_next(self.__on_play_next) def add_next_track(self, track): log("Yandex.Radio::add_next_track") track, url = track li = create_track_list_item(track) li.setPath(url) playIndex = pl.size() pl.add(url, li, playIndex) self.urls.append(url) def onPlayBackStopped(self): log("Yandex.Radio::onPlayBackStopped") self.queue_next() def onQueueNextItem(self): log("Yandex.Radio::onQueueNextItem") self.queue_next() def check(self): if not self.started: return try: url = self.getPlayingFile() self.valid = (url in self.urls) and pl.size() == len(self.urls) log("check valid: %s" % self.valid) except BaseException as ex: self.valid = False log("can't get current: %s" % ex)
def start_receiving(self, loop_sleep): self._receive_loop_sleep = loop_sleep if self._radio is None: self._radio = Radio(self._is_second_comms) self._is_receiving = True self._receiving_thread = threading.Thread(target=self.receiving_loop) # set to daemon mode so it will be easily killed self._receiving_thread.daemon = True self._receiving_thread.start()
async def init_radio(self): if not self.neighbourhood[1:]: self.srecovery = datetime.now().time() self.radio = Radio(RADIO_PORT, self.neighbourhood_watch) self.radio_started.set() print( f"1 Radio Started {self.port}, self id: {self.neighbourhood[0]}, neighbour list: {self.neighbourhood[1:]}" ) await self.radio.start()
def __init__(self, path, lst, port, id): self.path = path self.lst = lst self.port = port self.id = id self.radio = Radio(port, print) self.pub = Pub(port) self.sub = Sub(port) self.heartbeat_started = asyncio.Event() self.neigh_hood_check_started = asyncio.Event() self.sub_started = asyncio.Event()
def start_sending(self, loop_sleep): self._loop_sleep = loop_sleep if self._loop_sleep < Radio.MESSAGE_DELAY: print("WARNING: Comms loop sending faster than Radio can send") if self._radio is None: self._radio = Radio(self._is_second_comms) self._is_sending = True self._sending_thread = threading.Thread(target=self.sending_loop) # set to daemon mode so it will be easily killed self._sending_thread.daemon = True self._sending_thread.start()
class Comms(Provider): """Comms class spins a thread to repeated send the commands stored in gamestate to the robots via radio""" def __init__(self, team, is_second_comms=False): super().__init__() assert (team in ['blue', 'yellow']) self._team = team self._is_second_comms = is_second_comms self._radio = None self._owned_fields = [ '_blue_robot_status', '_yellow_robot_status', ] # self._receive_loop_sleep = Radio.MESSAGE_DELAY # self._messages_received = [] # self._last_receive_loop_time = None def pre_run(self): if self._radio is None: self._radio = Radio(self._is_second_comms) def run(self): team_commands = self.gs.get_team_commands(self._team) for robot_id, commands in team_commands.items(): # self.logger.info(commands) if self.gs.is_robot_lost(self._team, robot_id): self.logger.debug(f"Robot {robot_id} is lost") commands.set_speeds(0, 0, 0) else: # recalculate the speed the robot should be commanded at pos = self.gs.get_robot_position(self._team, robot_id) commands.derive_speeds(pos) # send serialized message for whole team message = RobotCommands.get_serialized_team_command(team_commands) self._radio.send(message) for robot_id, commands in team_commands.items(): robot_status = self.gs.get_robot_status(self._team, robot_id) # simulate charge of capacitors according to commands if commands.is_charging: robot_status.simulate_charge(self.delta_time) # TODO: UNTESTED if commands.is_kicking: robot_status.charge_level = 0 # sleep to avoid spamming the xbee radio time.sleep(Radio.MESSAGE_DELAY) def post_run(self): if self._radio is not None: self._radio.close()
def main(): stations = [ Station( "https://wdr-1live-live.sslcast.addradio.de/wdr/1live/live/mp3/128/stream.mp3", "1Live"), Station("http://www.ndr.de/resources/metadaten/audio/m3u/ndr2_hh.m3u", "Ndr2"), Station( "https://swr-dasding-live.sslcast.addradio.de/swr/dasding/live/aac/96/stream.aac", "Das Ding") ] radio_inst = Radio(stations) radio_inst.listen_to_station(0) menue(radio_inst)
def __init__(self): self.about_dialog = None self.icon = os.path.abspath('./tabletop_radio_.png') self.active_icon = None self.attention_icon = None self.radio = Radio() self.notification = Notify.Notification.new('', '', None) self.indicator = appindicator.Indicator.new( "DoubanRadio-Indicator", self.icon, appindicator.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_attention_icon(self.icon) self.menu = self.get_menu() self.indicator.set_menu(self.menu) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
def main(radio_idx): radio = Radio(int(radio_idx), mic_threshold=MIC_THRESHOLD, input_rate=INPUT_RATE, input_id=INPUT_ID, output_id=OUTPUT_ID) radio.connect(server=0) radio.start_speaker_stream() while True: radio.stream_mic_segment_to_server()
def __init__(self, jid, password, rooms, nick, token, groups): # XMPP super(Jabbergram, self).__init__(jid, password) self.add_event_handler('session_start', self.start) self.add_event_handler('groupchat_message', self.muc_message) self.muc_rooms = rooms.split() self.nick = nick self.token = token self.xmpp_users = {} self.jid = jid self.radio = Radio() for muc in self.muc_rooms: self.add_event_handler("muc::%s::got_online" % muc, self.muc_online) self.add_event_handler("muc::%s::got_offline" % muc, self.muc_offline) # Telegram self.groups = groups.split() self.bot = telegram.Bot(self.token) self.telegram_users = {} # put tg connector in a thread def start_read_tg_loop(): t = Thread(target=self.read_tg) t.daemon = True t.start() self.radio.once('http-upload-initialized', start_read_tg_loop) # initialize http upload on a thread since its needed to be connected # to xmpp t = Thread(target=self.init_http) t.daemon = True t.start() log('Please wait a couple of minutes until it\'s correctly ' 'connected.')
def main(): pa = Parser() naam, url, comm = pa.zendervinden() print naam, url, comm cursor.hide() fa = Fabriek() co = fa.returnCommunicatorObject(comm) rd = Radio() t = threading.Thread(target=rd.afspelen, args=(naam, url, co)) t.start() ## Afspelen stoppen na drukken op één van de EXITKEYS kp = Keypress() while kp.getexitkeypress() == False: time.sleep(0.2) cursor.show() rd.stoppen() return 0
def __init__(self): self.about_dialog = None self.icon = os.path.abspath('./tabletop_radio_.png') self.active_icon = None self.attention_icon = None self.radio = Radio() self.notification = Notify.Notification.new('', '', None) self.indicator = appindicator.Indicator.new("DoubanRadio-Indicator", self.icon, appindicator.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_attention_icon(self.icon) self.menu = self.get_menu() self.indicator.set_menu(self.menu) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
def element_wyposazenia(self, typ: str) -> Wyposazenie: if typ == 'fotele': wyposazenie = Fotele({'typ': 'skorzane'}) elif typ == 'kierownica': wyposazenie = Kierownica({'typ': 'skorzana'}) elif typ == 'nawigacja': wyposazenie = Nawigacja() elif typ == 'radio': wyposazenie = Radio() elif typ == 'tapicerka': wyposazenie = Tapicerka({'typ': 'welurowa'}) else: wyposazenie = None return wyposazenie
def __init__(self): """ Instantiate the AUV object """ self.mc = MotorController() # Connection to onboard radio. try: # Jack Silberman's radio #self.radio = Radio('/dev/serial/by-id/usb-FTDI_FT230X_Basic_UART_DN038PQU-if00-port0') # Yonder's radio self.radio = Radio( '/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0') except Exception, e: print("Radio not found. Exception is: ", e) print("Exiting") exit(1)
def main(): """Runs the gateway""" loop = asyncio.get_event_loop() router = Router() loop.run_until_complete(router.connect_to_message_queue()) initialize_gpio() radio = Radio() router.set_send_packet(radio.send_packet) poll(loop, radio, router) try: loop.run_forever() finally: loop.close()
def test_normal(self): radio = Radio() t1 = SenderTerminal("t1", "00:00:00:00:00:01", "192.168.0.1", radio) t1.x = 100 t1.y = 40 radio.add_node(t1) t2 = ReceiverTerminal("t2", "00:00:00:00:00:02", "192.168.0.2", radio) t2.x = 100 t2.y = -40 radio.add_node(t2) globals.now = 0 globals.events = sorted(globals.events, key=lambda x: x.time) while True: if len(globals.events) == 0: break globals.events = sorted(globals.events, key=lambda x: x.time) events_work = copy.copy(globals.events) event = globals.events[0] globals.now = event.time if globals.now > 10: break break for event in events_work: if event.time <= globals.now: event.call() globals.events.pop(0) else: break self.assertEqual(250000, t2.total_received_byte * 8 / globals.now)
if inky_display.HEIGHT == 300: img = Image.open(os.path.join(current_dir, "whatnow.png")).resize(inky_display.resolution) font_size = 32 margin = 40 else: img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT)) font_size = 20 margin = 0 draw = ImageDraw.Draw(img) font = ImageFont.truetype(FredokaOne, font_size) lines = [] track = Radio.fetchTrack() if not track: sys.exit() composer = Radio.getComposer(track) title = Radio.getTitle(track) cache_file = '/tmp/cache' last_track = '' if os.path.exists(cache_file): cache = open(cache_file, 'rt') play_history = json.loads(cache.readline()) cache.close()
from radio import Radio Mradio= Radio("Pioner") DeseaContinuar=True while DeseaContinuar: if Mradio.encendido: op=int(input("1.Apagar \n2.Subir/Bajar Volumen \n3.Subir/Bajar Emisora \n4.AM/FM \n\n")) if op==1: Mradio.encendido=False if op==2: opcvol=int(input("1.subir 2.bajar ")) if opcvol==1: Mradio.subir_volumen() else: Mradio.bajar_volumen() if op==3: opcEsta=int(input("1.subir estacion 2.bajar estacion ")) if opcEsta==1: Mradio.subir_estacion() else: Mradio.bajar_estacion() if op==4: Mradio.cambio_emisora() else: opc=int(input("1.Encender \n2.Salir \n\n")) if opc==1: Mradio.encendido=True else: DeseaContinuar=False print("Bai Bai") print(Mradio.en_FM) print(Mradio.volumen)
from radio import Radio rad=Radio("sony") desea_contunuar=True while desea_contunuar: if rad.encendido: print(" 1.subir volumen \n 2.bajar volumen\n 3.subir emisora\n 4.bajar emisora\n 5.cambiar frecuencia\n 6.apagar") opc=int(input("que opcion quiere? ")) if opc == 1: rad.subir_volumen() if opc == 2: rad.bajar_volumen() if opc == 3: rad.subir_emisora() if opc == 4: rad.bajar_emisora() if opc == 5: rad.cambiar() if opc == 6: rad.apagar() else : print(" 1.salir \n 2.encender ") opc=int(input("que opcion quiere? ")) if opc == 1: desea_contunuar=False if opc == 2: rad.encender() print("marca" ,rad.marca) print("estado" ,rad.encendido) print("volumen" ,rad.volumen) print("emisora AM" ,rad.emisora_AM)
slots = jsonIntent["slots"] for i in range(len(slots)): if slots[i]['slotName'] == slot_name: return slots[i]['value']['value'] return default_value def end_session(intent, sentence): print('session: ' + intent + ': ' + sentence) return EndSession(sentence) @app.on_intent("PlayInternetRadio") async def startListening(intent: NluIntent): radio_station = get_slot_value_by_slot_name(intent, 'radio_station', None) sentence = radio.play_radio_station(radio_station) return end_session('Start Listening to Internet Radio', sentence) @app.on_intent("Stop") async def stopListening(intent: NluIntent): sentence = radio.stop_radio() return end_session('Stop Listening to Internet Radio', sentence) if __name__ == "__main__": config = read_configuration_file() language = read_language_file(config['setup']['language']) radio = Radio({"config": config, "language": language}) app.run()
def experiment_cicles(cicles=5, set_size=500): weight_df = pd.DataFrame(columns=list([])) evaluate_df = pd.DataFrame(columns=list([])) similarity_df = pd.DataFrame(columns=list()) for i in range(cicles): print('- * - Iniciando o Ciclo: ', str(i)) if set_size > 0: print("+ Extraindo " + str(set_size) + " músicas") extractSet(set_size=set_size) print('+ Carregando dados no sistema') groot = Radio(load_data_songs(), load_data_users()) print('+ Processando dados') groot.post_preference_set( preference_set=make_set_to_process( song_set=groot.get_song_set(), dict_set=statisticalOverview( songSet=groot.get_song_set(), preferenceSet=groot.get_preference_set(), DEBUG=False ), DEBUG=False ) ) print('+ Treinando a árvore') classifier, evaluate_results = plant_the_tree( set_to_process=preprocessing_data( data_set=groot.get_preference_set(), all_features=groot.get_all_features(), DEBUG=False ), features=groot.get_song_features(), important_feature=groot.get_important_feature(), DEBUG=False, ADMIN=False ) groot.post_classifier( new_classifier=classifier ) print('+ Obtendo similaridade entre as músicas') groot.post_distance_matrix( new_distance_matrix=get_song_distance( song_set=groot.get_song_set(), song_features=groot.get_song_features(), classifier_important=groot.get_feature_weight(), DEBUG=False ) ) print('+ Iniciando a busca') similarity = environment( groot=groot, song_stages=random_choice(groot=groot), DEBUG=False ) print('+ Busca Terminada') print('Salvando informações') # weight_df = pd.concat([weight_df, pd.DataFrame( [[i for i in list(groot.get_classifier().feature_importances_)]], columns=[i for i in list(groot.get_song_features())], )], sort=False) # evaluate_df = pd.concat([evaluate_df, pd.DataFrame( [[i for i in evaluate_results.values()]], columns=[x for x in evaluate_results], )], sort=False) # similarity_df = pd.concat([similarity_df, pd.DataFrame( [[i for i in similarity.values()]], columns=[x for x in similarity], )], sort=False) plot_feature_importance(weight_df) plot_evaluations(evaluate_df) plot_similarity(similarity_df['similaridade'].tolist()) plot_final_state(similarity_df['final_state'].tolist()) plot_nodes(similarity_df['total_visitas'].tolist())
def user_experiment(set_size=2000): if set_size > 0: print("+ Extraindo " + str(set_size) + " músicas") extractSet(set_size=set_size) print('+ Carregando dados no sistema') groot = Radio(load_data_songs(), load_data_users()) print('+ Carregando Dados') groot.post_preference_set( preference_set=make_set_to_process( song_set=groot.get_song_set(), dict_set=statisticalOverview( songSet=groot.get_song_set(), preferenceSet=groot.get_preference_set(), DEBUG=False ), DEBUG=False ) ) print('+ Treinando a árvore') classifier, evaluate_results = plant_the_tree( set_to_process=preprocessing_data( data_set=groot.get_preference_set(), all_features=groot.get_all_features(), DEBUG=False ), features=groot.get_song_features(), important_feature=groot.get_important_feature(), DEBUG=True, ADMIN=False ) groot.post_classifier( new_classifier=classifier ) print('+ Obtendo similaridade entre as músicas') groot.post_distance_matrix( new_distance_matrix=get_song_distance( song_set=groot.get_song_set(), song_features=groot.get_song_features(), classifier_important=groot.get_feature_weight(), DEBUG=False ) ) print('+ Rádio Groot - Iniciando') time.sleep(3) os.system('clear||cls') start_and_end = interface_menu(groot) environment( groot=groot, song_stages=start_and_end )
from radio import Radio radio1 = Radio("Sony") continuar = int(input("Quieres usar el radio? \n 1. Si \n 2. No ")) if continuar == 1: continuar = True else: continuar = False print ("Adios!") radio1.encendido = False while continuar == True: if radio1.encendido == True: des = int(input(" 1. Subir volumen \n 2. Bajar volumen \n 3. Subir estacion \n 4. Bajar estacion \n 5. Cambiar frecuencia \n 6. Apagar ")) if des == 1: radio1.subir_volumen elif des == 2: radio.bajar_volumen elif des == 3: radio1.subir_estacion elif des == 4: radio1.bajar_estacion elif des == 5: if en_FM == True: radio1.en_AM else: radio1.en_FM
args = parser.parse_args() if args.custom_coords is not None: lat, lon = args.custom_coords.strip().split(',') utils.REF_LAT, utils.REF_LON = float(lat), float(lon) else: utils.set_loc_ip() print(f'Using reference coordinates of: {utils.REF_LAT}, {utils.REF_LON}') msg_que = Queue() if args.input is not None: print(f"Using MockRadio with {args.input}") radio = MockRadio(msg_que, args.input, args.repeat, args.delay, args.delay) else: print('Setting up radio') radio = Radio(msg_que) print('Done') if args.gui: run_gui(radio, args.debug) else: while True: msgs = radio.get_all_queue() for m in msgs: if m.valid: print(m) if args.output is not None and (m.valid or args.output_invalid): args.output.write(f'{round(time.time())} {m.bin_msg}\n')
class OspreyNcurses(object): freezeDisplay = False def __init__(self, blockDevice, baudRate): signal.signal(signal.SIGALRM, ncursesSignalHandler) self.radio = Radio(blockDevice, baudRate) def start(self): curses.wrapper(self.run) def stop(self): curses.endwin() def run(self, screen): self.screen = screen (self.height, self.width) = self.screen.getmaxyx() self.drawUI() self.sendThread = CursesSendThread(self) self.sendThread.start() self.read() def read(self): self.displayLines(['Waiting for data...']) while True: try: curData = self.radio.read() lines = [] lines.append('Time: %s' % curData['timestamp']) lines.append('Delta: %ds' % curData['delta']) lines.append('Coordinates: %s' % (curData['coordinates'])) lines.append('Roll: %.2f\xb0' % curData['roll']) lines.append('Pitch: %.2f\xb0' % curData['pitch']) lines.append('Heading: %.2f\xb0' % curData['heading']) lines.append('Acceleration: %.2fg' % curData['acceleration']) lines.append('Raw Acceleration: %.2fg' % curData['raw_acceleration']) lines.append('Pressure Altitude: %.2fm' % curData['pressure_altitude']) lines.append('GPS Altitude: %.2fm' % curData['gps_altitude']) lines.append('Above Ground Level: %.2fm' % curData['agl']) lines.append('Pressure Setting: %.2f\" Hg' % curData['pressure_setting']) lines.append('Temperature: %.2f\xb0C' % curData['temp']) lines.append('GPS Speed: %.2fkt' % curData['speed']) lines.append('GPS Quality: %d' % curData['gps_quality']) lines.append('Previous Command: %s' % curData['previous_command']) lines.append('Command Status: %s' % ('ACK' if curData['command_status'] == constants.COMMAND_ACK else 'ERR')) lines.append('Logging: %d' % curData['logging']) lines.append('Battery: %.2fV' % curData['battery']) lines.append('Phase: %d' % curData['phase']) lines.append('Armed: %d' % curData['armed']) lines.append('Apogee Fired: %d' % curData['apogee_fired']) lines.append('Main Fired: %d' % curData['main_fired']) lines.append('Main Altitude: %d' % curData['main_alt']) self.displayLines(lines) except exceptions.RadioReceiveError as exception: self.displayLines([str(exception)]) continue def drawUI(self): self.setColors() self.screen.clear() self.screen.border(0) self.makeOutputWindow() self.makeInputWindow() self.makeStatusWindow() self.screen.refresh() def displayLines(self, lines, minTime=None): # Don't display anything while the freeze display flag is set if OspreyNcurses.freezeDisplay: return self.outputWindow.erase() for index, line in enumerate(lines): self.outputWindow.addstr(index, 1, line, 1) self.outputWindow.refresh() self.inputWindow.refresh() # Set the freeze display flag and set an alarm to disable it if minTime: OspreyNcurses.freezeDisplay = True signal.alarm(minTime) def setColors(self): if not curses.has_colors(): return curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) self.screen.bkgd(curses.color_pair(1)) def makeOutputWindow(self): self.outputWindow = self.screen.subwin(self.height-4, self.width-2, 1, 1) self.outputWindow.scrollok(True) def makeInputWindow(self): self.inputWindow = self.screen.subwin(1, self.width-26, self.height-2, 1) self.input = curses.textpad.Textbox(self.inputWindow, insert_mode=True) curses.textpad.rectangle(self.screen, self.height-3, 0, self.height-1, self.width-25) self.inputWindow.move(0, 0) def makeStatusWindow(self): status = 'Osprey Debug Console' self.statusWindow = self.screen.subwin(self.height-3, self.width-24) self.statusWindow.border(0) self.statusWindow.addstr(1, 2, status)
def __init__(self, blockDevice, baudRate): signal.signal(signal.SIGALRM, ncursesSignalHandler) self.radio = Radio(blockDevice, baudRate)
from radio import Radio mi_radio = Radio("Sony") desea_continuar = True while desea_continuar == True: if not mi_radio.encendido: print("") print( """SU RADIO ESTA APAGADO. 1. Encenderlo 2. Salir.""") encender_salir= int(input("Ingrese opcion elegida: ")) if encender_salir == 1: mi_radio.encender() elif encender_salir == 2: print("Gracias por utilizar Radio, Adios.") desea_continuar = False else: print("") print("Opcion invalida.") else: print("") print("ESTADO ACTUAL DE RADIO") print("Marca del radio: " , mi_radio.marca) print("Encendido: " , mi_radio.encendido) if mi_radio.en_FM == True:
from radio import Radio mi_radio=Radio("a") desea_continuar=True while desea_continuar: if mi_radio.encendido: opcion=input("1)apagar radio 2)elejir emisora3)subir volumen4)bajar volumen") if opcion==1: mi_radio.encendido=False else: mi_radio.encendido() if opcion==2 canal=input("elija una emisora") if canal=fm: mi_radio.en_fm else: mi_radio.en_am=True
from radio import Radio objeto_radio = Radio(input("Ingrese una marca: ")) desea_continuar = True while desea_continuar: print("Marca: ", objeto_radio.marca) print("Encendido: ", objeto_radio.encendido) print("Volumen: ", objeto_radio.volumen) print("Fm: ", objeto_radio.en_fm) print("Emisora AM: ", objeto_radio.emisora_am) print("Emisora FM: ", objeto_radio.emisora_fm) if objeto_radio.encendido == False: opcion = int(input(("1. Encender: "))) if opcion == 1: objeto_radio.encender() if objeto_radio.encendido == True: opcion2 = int( input((""" 1. Apagar 2. Subir Volumen 3. Bajar Volumen 4. Cambiar Frecuencia 5. Subir Emisora 6. Bajar Emisora """))) if opcion2 == 1: objeto_radio.apagar()
from math import floor from random import random from time import sleep from yandex_music import Client from radio import Radio # API instance client = Client(token="YOUR_TOKEN_HERE") # Get random station _stations = client.rotor_stations_list() _station_random_index = floor(len(_stations) * random()) _station = _stations[_station_random_index].station _station_id = f'{_station.id.type}:{_station.id.tag}' _station_from = _station.id_for_from # Radio instance radio = Radio(client) # start radio and get first track first_track = radio.start_radio(_station_id, _station_from) print("[Radio] First track is:", first_track) # get new track every 5 sec while True: sleep(5) next_track = radio.play_next() print("[Radio] Next track is:", next_track)
from radio import Channel, Radio # The FM broadcast band, used for FM broadcast radio by radio stations, # differs between different parts of the world. # In Europe, Australia[1] and Africa - from 87.5 to 108 megahertz (MHz) # A Channel has a frequency (between 87.5 and 108), a name, and a playlist ch1 = Channel("VGOLOS", 107.2, ["Susy", "Without You", "That's Enough"]) assert(ch1.getFrequency() == 107.2) assert(str(ch1) == \ """Channel VGOLOS on 107.2, playlist: ['Susy', 'Without You', "That's Enough"]""") ch2 = Channel("Oles FM", 91.1, ["911"]) assert(str(ch2) == "Channel Oles FM on 91.1, playlist: ['911']") assert(ch2.playlist == ['911']) assert(ch2 == Channel("Oles FM", 91.1, ["911"])) assert(ch2 != ch1) assert(ch2 != "Oles FM") s = set() assert(ch2 not in s) s.add(ch2) assert(Channel("Oles FM", 91.1, ["911"]) in s) assert(ch1 not in s) # A Radio (FM Radio) can be tuned to receive channels # based on some different frequencies channels = { 107.2 : ch1, 91.1 : ch2 } radio = Radio(channels, 107.25) assert(radio.getCurrentFrequency() == 107.25) # A Radio receives a channel if it’s tuned within 0.05 Hz of that channel’s # frequency. You’re guaranteed that channel frequencies will always be # at least 0.05 Hz apart. assert(radio.getCurrentChannel() == ch1)
class IndicatorDoubanRadio(): def __init__(self): self.about_dialog = None self.icon = os.path.abspath('./tabletop_radio_.png') self.active_icon = None self.attention_icon = None self.radio = Radio() self.notification = Notify.Notification.new('', '', None) self.indicator = appindicator.Indicator.new( "DoubanRadio-Indicator", self.icon, appindicator.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_attention_icon(self.icon) self.menu = self.get_menu() self.indicator.set_menu(self.menu) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE) def get_menu(self): """ Create and populate the menu """ menu = Gtk.Menu() self.img_item = add2menu(menu, icon=os.path.abspath("./tabletop_radio_.png")) self.song_info = add2menu(menu, text="song_name") self.next_song = add2menu(menu, text="next", conector_event='activate', conector_action=self.play_next) menu.show() return menu def play_next(self, nouse): self.radio.next() def main(self): self.radio.next() chls = self.radio.get_channels() self.show_chls(chls) self.exit_item = add2menu(self.menu, text="quit", conector_event='activate', conector_action=self._on_quit_clicked) Gtk.main() exit(0) def show_chls(self, chls): chls = json.loads(chls) groups = chls['groups'] for group in groups: group_item = add2menu(self.menu, group['group_name']) if group['group_id'] is 0: for chl in group['chls']: add_chl(self.menu, 'activate', self._on_switch_channel, chl) add2menu(self.menu) else: #group_item = Gtk.ImageMenuItem.new_with_label(group['group_name']) subchl = Gtk.Menu() for chl in group['chls']: add_chl(subchl, 'activate', self._on_switch_channel, chl) subchl.show() group_item.set_submenu(subchl) #group_item.show() #self.menu.append(group_item) def _on_switch_channel(self, nouse, chl): self.radio.channel = chl['id'] self.radio.skip() def _on_quit_clicked(self, widget): exit(0)
def parse_config_file(self): """ This method parses the configuration file and check that all parameters follow the prerequisites. """ with open(self._filename) as f: # Opening configuration file tree = json.load(f) # Parsing json content # Closing file f.close() # First, let's load the list of radios for radio in tree['radios']: # Load attributes long_name = radio['long_name'] short_name = radio['short_name'] stream_url = radio['stream_url'] media_type = radio['type'] module_name = None if 'module_name' in radio: module_name = radio['module_name'] # Check radio attributes type if not isinstance(long_name, str): raise ConfigurationFileException( "radios.radio.long_name must be a string") if not isinstance(short_name, str): raise ConfigurationFileException( "radios.radio.short_name must be a string") if not isinstance(stream_url, str): raise ConfigurationFileException( "radios.radio.stream_url must be a string") if not isinstance(media_type, str): raise ConfigurationFileException( "radios.radio.type must be a string") if module_name is not None and not isinstance(module_name, str): raise ConfigurationFileException( "radios.radio.module_name must be a string") # Check attribute value and size if len(long_name) > 32: raise ConfigurationFileException( "radios.radio.long_name must not exceed 32 characters") if len(short_name) > 16: raise ConfigurationFileException( "radios.radio.short_name must not exceed 16 characters") if media_type != "stream" and media_type != "folder": raise ConfigurationFileException( "radios.radio.type must be either 'stream' or 'folder'") # Register new radio r = Radio(long_name, short_name, stream_url, media_type, module_name) self._radios.append(r) if len(self._radios) <= 0: raise ConfigurationFileException("No radio available.") # Then, load other mandatory properties self._name = tree['general']['name'] self._halt_message = tree['general']['halt_message'] self._default_volume = tree['general']['default_volume'] self._volume_step = tree['general']['volume_step'] self._volume_timer = tree['display']['volume_timer'] self._scroll_time_interval = tree['display']['scroll_time_interval'] self._scroll_time_pause = tree['display']['scroll_time_pause'] self._serial_device = tree['display']['serial_device'] self._serial_baud_rate = tree['display']['serial_baud_rate'] self._radio_info_check_interval = tree['general'][ 'radio_info_check_interval'] self._full_radio_name_pause = tree['general']['full_radio_name_pause'] self._save_file_path = tree['general']['save_file_path'] # Check var type if not isinstance(self._name, str): raise ConfigurationFileException( "general.name parameter must be a string") if not isinstance(self._halt_message, str): raise ConfigurationFileException( "general.halt_message parameter must be a string") if not isinstance(self._default_volume, numbers.Number): raise ConfigurationFileException( "general.default_volume parameter must be a number") if not isinstance(self._volume_step, numbers.Number): raise ConfigurationFileException( "general.volume_step parameter must be a number") if not isinstance(self._volume_timer, numbers.Number): raise ConfigurationFileException( "display.volume_timer parameter must be a number") if not isinstance(self._scroll_time_interval, numbers.Number): raise ConfigurationFileException( "display.scroll_time_interval parameter must be a number") if not isinstance(self._scroll_time_pause, numbers.Number): raise ConfigurationFileException( "display.scroll_time_pause parameter must be a number") if not isinstance(self._serial_device, str): raise ConfigurationFileException( "display.serial_device parameter must be a string") if not isinstance(self._serial_baud_rate, numbers.Number): raise ConfigurationFileException( "display.serial_baud_rate parameter must be a number") if not isinstance(self._radio_info_check_interval, numbers.Number): raise ConfigurationFileException( "general.radio_info_check_interval parameter must be a number") if not isinstance(self._full_radio_name_pause, numbers.Number): raise ConfigurationFileException( "general.full_radio_name_pause parameter must be a number") if not isinstance(self._save_file_path, str): raise ConfigurationFileException( "general.save_file_path parameter must be a string") # Check var value and size if len(self._name) > 32: raise ConfigurationFileException( "general.name must not exceed 32 characters") if len(self._halt_message) > 32: raise ConfigurationFileException( "general.halt_message must not exceed 32 characters") if self._default_volume > 100 or self._default_volume < 0: raise ConfigurationFileException( "general.default_volume must be between 0 and 100") if self._volume_step > 40 or self._volume_step <= 0: raise ConfigurationFileException( "general.volume_step must be between 1 and 40") if self._volume_timer < 0: raise ConfigurationFileException( "display.volume_timer must be a positive value (in seconds)") if self._scroll_time_interval <= 0: raise ConfigurationFileException( "display.scroll_time_interval must be a non-null positive value (in seconds)" ) if self._scroll_time_pause < 0: raise ConfigurationFileException( "display.scroll_time_pause must be a positive value (in seconds)" ) if self._serial_baud_rate <= 0: raise ConfigurationFileException( "display.serial_baud_rate must be a non-null positive value") if self._radio_info_check_interval <= 0: raise ConfigurationFileException( "general.radio_info_check_interval must be a non-null positive value (in seconds)" ) if self._full_radio_name_pause < 0: raise ConfigurationFileException( "general.full_radio_name_pause must be a positive value (in seconds)" ) # Now, let's try to load cached settings if exist self.load_cached_settings(self._save_file_path)
radio.decreaseVolume() else: radio.increaseVolume() def powerOffButtonCallback(): radio.stop() display.disable() os.system("shutdown -h now") config = configparser.ConfigParser() config.read("tube.cfg") display = LCD(config["display"]["address"]) display.enable() radio = Radio(config["radio"]["stations"].splitlines()) trackDataThread = _thread.start_new_thread(updateTrackData, ()) powerOffButton = Button(int(config["button"]["pinNumber"]),config["button"]["pinName"],int(config["button"]["pullupNumber"]),config["button"]["pullupName"], powerOffButtonCallback) powerOffButton.enable() stationRotary = RotaryEncoder(int(config["rightRotary"]["aPinNumber"]),config["rightRotary"]["aPinName"],int(config["rightRotary"]["aPullupNumber"]),config["rightRotary"]["aPullupName"],int(config["rightRotary"]["bPinNumber"]),config["rightRotary"]["bPinName"],int(config["rightRotary"]["bPullupNumber"]),config["rightRotary"]["bPullupName"],stationCallback) stationRotary.enable() volumeRotary = RotaryEncoder(int(config["leftRotary"]["aPinNumber"]),config["leftRotary"]["aPinName"],int(config["leftRotary"]["aPullupNumber"]),config["leftRotary"]["aPullupName"],int(config["leftRotary"]["bPinNumber"]),config["leftRotary"]["bPinName"],int(config["leftRotary"]["bPullupNumber"]),config["leftRotary"]["bPullupName"],volumeCallback) volumeRotary.enable() radio.play() while True: sleep(1000000)
def admin_experiment(set_size=2000): if set_size > 0: print("+ Extraindo " + str(set_size) + " músicas") extractSet(set_size=set_size) print('+ Carregando dados no sistema') groot = Radio(load_data_songs(), load_data_users()) print('+ Processando dados') groot.post_preference_set( preference_set=make_set_to_process( song_set=groot.get_song_set(), dict_set=statisticalOverview( songSet=groot.get_song_set(), preferenceSet=groot.get_preference_set(), DEBUG=True ), DEBUG=True ) ) print('+ Treinando a árvore') classifier, evaluate_results = plant_the_tree( set_to_process=preprocessing_data( data_set=groot.get_preference_set(), all_features=groot.get_all_features(), DEBUG=True ), features=groot.get_song_features(), important_feature=groot.get_important_feature(), DEBUG=True, ADMIN=True ) groot.post_classifier( new_classifier=classifier ) print('+ Obtendo similaridade entre as músicas') groot.post_distance_matrix( new_distance_matrix=get_song_distance( song_set=groot.get_song_set(), song_features=groot.get_song_features(), classifier_important=groot.get_feature_weight(), DEBUG=True ) ) print('+ Iniciando a busca') similarity = environment( groot=groot, song_stages=random_choice(groot=groot), DEBUG=True ) print('+ Busca Terminada')
class IndicatorDoubanRadio(): def __init__(self): self.about_dialog = None self.icon = os.path.abspath('./tabletop_radio_.png') self.active_icon = None self.attention_icon = None self.radio = Radio() self.notification = Notify.Notification.new('', '', None) self.indicator = appindicator.Indicator.new("DoubanRadio-Indicator", self.icon, appindicator.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_attention_icon(self.icon) self.menu = self.get_menu() self.indicator.set_menu(self.menu) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE) def get_menu(self): """ Create and populate the menu """ menu = Gtk.Menu() self.img_item = add2menu(menu, icon=os.path.abspath("./tabletop_radio_.png")) self.song_info = add2menu(menu, text="song_name") self.next_song = add2menu(menu, text="next", conector_event='activate', conector_action=self.play_next) menu.show() return menu def play_next(self, nouse): self.radio.next() def main(self): self.radio.next() chls = self.radio.get_channels() self.show_chls(chls) self.exit_item = add2menu(self.menu, text="quit", conector_event='activate', conector_action=self._on_quit_clicked) Gtk.main() exit(0) def show_chls(self,chls): chls = json.loads(chls) groups = chls['groups'] for group in groups: group_item = add2menu(self.menu, group['group_name']) if group['group_id'] is 0: for chl in group['chls']: add_chl(self.menu, 'activate', self._on_switch_channel, chl) add2menu(self.menu) else: #group_item = Gtk.ImageMenuItem.new_with_label(group['group_name']) subchl = Gtk.Menu() for chl in group['chls']: add_chl(subchl, 'activate', self._on_switch_channel, chl) subchl.show() group_item.set_submenu(subchl) #group_item.show() #self.menu.append(group_item) def _on_switch_channel(self, nouse, chl): self.radio.channel = chl['id'] self.radio.skip() def _on_quit_clicked(self, widget): exit(0)
import sys sys.path.append("libs") import http.server import urllib.parse, json from myglobals import MyGlobals from checkbox import Checkbox from scatter import Scatter from radio import Radio from chart import Chart from excel import Excel from table import Table checkbox = Checkbox() scatter = Scatter() radio = Radio() chart = Chart() xl = Excel() table = Table() class Handler(http.server.BaseHTTPRequestHandler): def do_POST(self): jsonResponse = self.rfile.read(int(self.headers['Content-Length'])) self.send_response(200) self.end_headers() jsonAsString = jsonResponse.decode("UTF-8") results = json.loads(jsonAsString)
for conn in self.connections: if conn != connection: new_connections.append(conn) if len(new_connections) == len(self.connections): raise Exception('Connection not found to unregister') elif len(new_connections) != len(self.connections) - 1: raise Exception('More than one connection to unregister') else: self.connections = new_connections def get_connections_count(self): return len(self.connections) radio = Radio() btns = BtnsThread(radio) btns.start() conn_handler = ConnectionsHandler(radio) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(CONNECTIONS_LIMIT) try: print('Starting listening for socket connections…') while True: conn, addr = s.accept()
from radio import Radio Pradio= Radio("Pioner") desea_continuar=True print(Pradio.marca) print(Pradio.encendido) print(Pradio.en_FM) print(Pradio.volumen) while desea_continuar: if Pradio.encendido: opc=int(input("1.Apagar\n2.Subir/Bajar Volumen\n3.Subir/Bajar Estacion\n4.Cambiar Emisora\n \n")) if opc==1: Pradio.encendido=False if opc==2: res=int(input("1.Subir volumen\n 2.Bajar volumen ")) if res==1: Pradio.subir_volumen() if res==2: Pradio.baja_volumen() if opc==3: vol=int(input("1.Subir estacion\n 2.Bajar estacion ")) if vol==1: Pradio.subir_estacion() if vol==2: Pradio.bajar_estacion() else: opc=int(input("1.Encender:\n2.Salir:\n\n")) if opc==1: Pradio.encendido=True else: desea_continuar=False print(Pradio.marca)
from radio import Radio ra= Radio ("Sony") desea_continuar = True while desea_continuar: if ra.encendido: print("1.subir volumen\n 2.bajar volumen\n 3.subir emisora\n 4.bajar emisora\n 5.cambiar estacion\n 6.apagar") opc= int(input("elija una opcion: ")) if opc==1: ra.subir_volumen() if opc==2: ra.bajar_volumen() if opc==3: ra.subir_estacion() if opc==4: ra.bajar_estacion() if opc==5: ra.cambiar() if opc==6: ra.apagar() else: print("1.encender\n 2.salir\n") opc= int(input("elija una opcion: ")) if opc==1: ra.encender() if opc==2: desea_continuar=False print("marca:",ra.marca) print("esta encendido :",ra.encendido) print("volumen:",ra.volumen)