Code: Select all
# -*- encoding: utf-8 -*-
#!/usr/bin/python
# IMPORTAMOS MÓDULOS
from Adafruit_I2C import Adafruit_I2C
from Adafruit_MCP230xx import Adafruit_MCP230XX
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from datetime import datetime
from subprocess import *
from time import sleep, strftime
from Queue import Queue
from threading import Thread
import os
import glob
import sys, pygame
from pygame.locals import *
# CONSTANTES IMAGEN
WIDTH = 493
HEIGHT = 300
# INICIALIZAMOS PLACA LCD
LCD = Adafruit_CharLCDPlate()
# DEFINIMOS VARIABLES GLOBALES
PLAYLIST_MSG = []
STATION = 1
NUM_STATIONS = 0
# BOTONES
NONE = 0x00
SELECT = 0x01
RIGHT = 0x02
DOWN = 0x04
UP = 0x08
LEFT = 0x10
UP_AND_DOWN = 0x0C
LEFT_AND_RIGHT = 0x12
# QUEUE
LCD_QUEUE = Queue()
#FUNCION IMAGEN
def load_image(filename, transparent=False):
try: image = pygame.image.load(filename)
except pygame.error, message:
raise SystemExit, message
image = image.convert()
if transparent:
color = image.get_at((0,0))
image.set_colorkey(color, RLEACCEL)
return image
# WORKER THREAD
def update_lcd(q):
while True:
msg = q.get()
while not q.empty():
q.task_done()
msg = q.get()
LCD.setCursor(0,0)
LCD.message(msg)
q.task_done()
return
# MAIN
def main():
global STATION, NUM_STATIONS, PLAYLIST_MSG
# Paramos reproductor
output = run_cmd("mpc stop" )
# Configuración AdaFruit LCD Plate
LCD.begin(16,2)
LCD.clear()
LCD.backlight(LCD.ON)
# Creamos el worker thread y lo hacemos una herramienta
worker = Thread(target=update_lcd, args=(LCD_QUEUE,))
worker.setDaemon(True)
worker.start()
# Mensaje inicial
LCD_QUEUE.put('Bienvenido a\nRPi Radio Wifi', True)
# Cargamos la playlist
load_playlist_spain()
sleep(2)
LCD.clear()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Raspberry Pi Radio Wifi")
clock = pygame.time.Clock()
background_image = load_image('fondo.jpg')
# INICIAMOS LA MÚSICA
# Iniciamos el reproductor
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
run_cmd("mpc volume +100")
mpc_play(STATION)
countdown_to_play = 0
while True:
press = read_buttons()
for eventos in pygame.event.get():
if eventos.type == QUIT:
sys.exit(0)
elif eventos.type == pygame.MOUSEBUTTONDOWN:
x, y = eventos.pos
if 283<=x<=307 and 238<=y<=264:
press=SELECT
elif 338<=x<=363 and 239<=y<=265:
press = LEFT
elif 391<=x<=416 and 223<=y<=247:
press=UP
elif 392<=x<=418 and 260<=y<=287:
press=DOWN
elif 445<=x<=468 and 242<=y<=268:
press = RIGHT
# Pulsamos botón izquierdo
if(press == LEFT):
STATION -= 1
if(STATION < 1):
STATION = NUM_STATIONS
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
countdown_to_play = 3
# Pulsamos botón derecho
if(press == RIGHT):
STATION += 1
if(STATION > NUM_STATIONS):
STATION = 1
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
countdown_to_play = 3
# Pulsamos botón de arriba
if(press == UP):
output = run_cmd("mpc volume +2")
# Pulsamos botón de abajo
if(press == DOWN):
output = run_cmd("mpc volume -2")
# Pulsamos botón select
if(press == SELECT):
menu_pressed()
if(countdown_to_play > 0):
countdown_to_play -= 1
if(countdown_to_play == 0):
mpc_play(STATION)
screen.blit(background_image, (0, 0))
pygame.display.flip()
clock.tick(3)
update_lcd.join()
return 0
# LECTURA BOTONES PULSADOS
def read_buttons():
buttons = LCD.buttons()
if(buttons != 0):
while(LCD.buttons() != 0):
delay_milliseconds(1)
return buttons
# TIEMPO DE DELAY EN MILISEGUNDOS
def delay_milliseconds(milliseconds):
seconds = milliseconds / float(1000)
sleep(seconds)
# CARGAMOS DIFERENTES PLAYLIST
def load_playlist_spain():
global STATION, NUM_STATIONS, PLAYLIST_MSG
# Añadimos todas las emisoras a la playlist
output = run_cmd("mpc clear")
output = run_cmd("/home/pi/Python-WiFi-Radio/spain.sh")
# Cargamos playlist en PLAYLIST_MSG
PLAYLIST_MSG = []
with open ("/home/pi/Python-WiFi-Radio/spain.sh", "r") as playlist:
# Salta primera línea de la playlist
for line in playlist:
if line[0:1] != '#!':
break
# Carga las siguientes líneas
for line in playlist:
if line[0] == "#" :
PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + " ")
playlist.close()
NUM_STATIONS = len(PLAYLIST_MSG)
def load_playlist_france():
global STATION, NUM_STATIONS, PLAYLIST_MSG
# Añadimos todas las emisoras a la playlist
output = run_cmd("mpc clear")
output = run_cmd("/home/pi/Python-WiFi-Radio/france.sh")
# Cargamos playlist en PLAYLIST_MSG
PLAYLIST_MSG = []
with open ("/home/pi/Python-WiFi-Radio/france.sh", "r") as playlist:
# Salta primera línea de la playlist
for line in playlist:
if line[0:1] != '#!':
break
# Carga las siguientes líneas
for line in playlist:
if line[0] == "#" :
PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + " ")
playlist.close()
NUM_STATIONS = len(PLAYLIST_MSG)
def load_playlist_germany():
global STATION, NUM_STATIONS, PLAYLIST_MSG
# Añadimos todas las emisoras a la playlist
output = run_cmd("mpc clear")
output = run_cmd("/home/pi/Python-WiFi-Radio/germany.sh")
# Cargamos playlist en PLAYLIST_MSG
PLAYLIST_MSG = []
with open ("/home/pi/Python-WiFi-Radio/germany.sh", "r") as playlist:
# Salta primera línea de la playlist
for line in playlist:
if line[0:1] != '#!':
break
# Carga las siguientes líneas
for line in playlist:
if line[0] == "#" :
PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + " ")
playlist.close()
NUM_STATIONS = len(PLAYLIST_MSG)
def load_playlist_italy():
global STATION, NUM_STATIONS, PLAYLIST_MSG
# Añadimos todas las emisoras a la playlist
output = run_cmd("mpc clear")
output = run_cmd("/home/pi/Python-WiFi-Radio/italy.sh")
# Cargamos playlist en PLAYLIST_MSG
PLAYLIST_MSG = []
with open ("/home/pi/Python-WiFi-Radio/italy.sh", "r") as playlist:
# Salta primera línea de la playlist
for line in playlist:
if line[0:1] != '#!':
break
# Carga las siguientes líneas
for line in playlist:
if line[0] == "#" :
PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + " ")
playlist.close()
NUM_STATIONS = len(PLAYLIST_MSG)
def load_playlist_united_kingdom():
global STATION, NUM_STATIONS, PLAYLIST_MSG
# Añadimos todas las emisoras a la playlist
output = run_cmd("mpc clear")
output = run_cmd("/home/pi/Python-WiFi-Radio/united_kingdom.sh")
# Cargamos playlist en PLAYLIST_MSG
PLAYLIST_MSG = []
with open ("/home/pi/Python-WiFi-Radio/united_kingdom.sh", "r") as playlist:
# Salta primera línea de la playlist
for line in playlist:
if line[0:1] != '#!':
break
# Carga las siguientes líneas
for line in playlist:
if line[0] == "#" :
PLAYLIST_MSG.append(line.replace(r'\n','\n')[1:-1] + " ")
playlist.close()
NUM_STATIONS = len(PLAYLIST_MSG)
# MENÚ DE OPCIONES
def menu_pressed():
global STATION
MENU_LIST = [
'1. Temperatura, \n fecha y hora ',
'2. Seleccionar \n Playlist ',
'3. Silenciar \n audio ',
'4. Temperatura \n Raspberry Pi ',
'5. Reiniciar \n Raspberry Pi ',
'6. Apagar \n Raspberry Pi ',
'7. Salir del \n menu ' ]
item = 0
LCD.clear()
LCD.backlight(LCD.ON)
LCD_QUEUE.put(MENU_LIST[item], True)
keep_looping = True
while (keep_looping):
press = read_buttons()
for eventos in pygame.event.get():
if eventos.type == QUIT:
sys.exit(0)
elif eventos.type == pygame.MOUSEBUTTONDOWN:
x, y = eventos.pos
if 283<=x<=307 and 238<=y<=264:
press=SELECT
elif 338<=x<=363 and 239<=y<=265:
press = LEFT
elif 391<=x<=416 and 223<=y<=247:
press=UP
elif 392<=x<=418 and 260<=y<=287:
press=DOWN
elif 445<=x<=468 and 242<=y<=268:
press = RIGHT
# Arriba
if(press == UP):
item -= 1
if(item < 0):
item = len(MENU_LIST) - 1
LCD_QUEUE.put(MENU_LIST[item], True)
# Abajo
elif(press == DOWN):
item += 1
if(item >= len(MENU_LIST)):
item = 0
LCD_QUEUE.put(MENU_LIST[item], True)
# Botón select
elif(press == SELECT):
keep_looping = False
if(item == 0):
# 1. Mostrar temperatura,fecha y hora
date_and_time()
elif(item == 1):
# 2. Seleccionar playlist
LCD_QUEUE.put("Seleccione una \nplaylist ", True)
sleep(2)
MENU_LIST = [
'1. France \n ',
'2. Germany \n ',
'3. Italy \n ',
'4. U.Kingdom \n ',
'5. Spain \n ',
'6. Salir menu \n playlist ' ]
cont = 0
LCD.clear()
LCD.backlight(LCD.ON)
LCD_QUEUE.put(MENU_LIST[cont], True)
select_country = True
while (select_country):
press = read_buttons()
for eventos in pygame.event.get():
if eventos.type == QUIT:
sys.exit(0)
elif eventos.type == pygame.MOUSEBUTTONDOWN:
x, y = eventos.pos
if 283<=x<=307 and 238<=y<=264:
press=SELECT
elif 338<=x<=363 and 239<=y<=265:
press = LEFT
elif 391<=x<=416 and 223<=y<=247:
press=UP
elif 392<=x<=418 and 260<=y<=287:
press=DOWN
elif 445<=x<=468 and 242<=y<=268:
press = RIGHT
# Izquierda
if(press == LEFT):
cont -= 1
if(cont < 0):
cont = len(MENU_LIST) - 1
LCD_QUEUE.put(MENU_LIST[cont], True)
# Derecha
elif(press == RIGHT):
cont += 1
if(cont >= len(MENU_LIST)):
cont = 0
LCD_QUEUE.put(MENU_LIST[cont], True)
# Select
elif(press == SELECT):
select_country = False
if(cont == 0):
load_playlist_france()
sleep(2)
STATION = 1
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
mpc_play(STATION)
elif(cont ==1):
load_playlist_germany()
sleep(2)
STATION = 1
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
mpc_play(STATION)
elif(cont ==2):
load_playlist_italy()
sleep(2)
STATION = 1
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
mpc_play(STATION)
elif(cont ==3):
load_playlist_united_kingdom()
sleep(2)
STATION = 1
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
mpc_play(STATION)
elif(cont ==4):
load_playlist_spain()
sleep(2)
STATION = 1
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
mpc_play(STATION)
else:
delay_milliseconds(99)
elif(item == 2):
# 3. Silenciar audio
output = run_cmd("mpc stop" )
elif(item == 3):
# 4. Temperatura Raspberry Pi
temp_rpi()
elif(item == 4):
# 5. Reiniciar Raspberry Pi
LCD_QUEUE.put('Reiniciando \nRasbperry Pi ', True)
sleep(2)
LCD_QUEUE.join()
output = run_cmd("mpc clear")
output = run_cmd("sudo shutdown now -r")
LCD.clear()
LCD.backlight(LCD.OFF)
exit(0)
elif(item == 5):
# 6. Apagar Raspberry Pi
LCD_QUEUE.put('Apagando \nRasbperry Pi ', True)
sleep(2)
LCD_QUEUE.join()
output = run_cmd("mpc clear")
output = run_cmd("sudo shutdown now -h")
LCD.clear()
LCD.backlight(LCD.OFF)
exit(0)
else:
delay_milliseconds(99)
# Restaura la pantalla
LCD.backlight(LCD.ON)
LCD_QUEUE.put(PLAYLIST_MSG[STATION - 1], True)
# TEMPERATURA,FECHA Y HORA
#Cargamos los comandos modprobe
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#Encontramos el archivo desde donde leeremos la información
directorio = '/sys/bus/w1/devices/'
carpeta = glob.glob(directorio + '28*')[0]
archivo = carpeta + '/w1_slave'
#Esta función lee la información que obtenemos del sensonr de temperatura
def read_temp_file():
f = open(archivo, 'r')
lines = f.readlines()
f.close()
return lines
#La segunda función se asegura de obtener el mensaje YES de la primera línea
#obtenida del sensor y después devuelve los valores de temperatura leídos en
#grados centígrados
def read_temp():
lines = read_temp_file()
detect = 'YES'
if detect in lines[0]:
position = lines[1].find('t=')
if position != -1:
temp_cad = lines[1][position+2:]
temp_c = float(temp_cad) / 1000.0
return temp_c
else:
lines = read_temp_file()
def date_and_time():
LCD.clear()
LCD.backlight(LCD.ON)
i = 29
keep_looping = True
while (keep_looping):
#Cada medio segundo actualizar tiempo y temperatura mostrados
i += 1
if(i % 5 == 0):
date = datetime.now().strftime("%d %b %Y \nHora: %H:%M")
LCD_QUEUE.put(date, True)
delay_milliseconds(1500)
LCD.clear()
temp = read_temp()
LCD_QUEUE.put("Temperatura: \n"+ str(temp)+" "+ chr(223)+"C", True)
delay_milliseconds(1500)
LCD.clear()
#Leemos los botones
press = read_buttons()
for eventos in pygame.event.get():
if eventos.type == QUIT:
sys.exit(0)
elif eventos.type == pygame.MOUSEBUTTONDOWN:
x, y = eventos.pos
if 283<=x<=307 and 238<=y<=264:
press=SELECT
if(press == SELECT):
keep_looping = False
delay_milliseconds(99)
# TEMPERATURA RPI
def temp_rpi():
LCD.clear()
tempC = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1000
LCD_QUEUE.put("Temperatura RPi:\n"+ str(tempC)+" "+ chr(223)+"C", True)
delay_milliseconds(3000)
LCD.clear()
def run_cmd(cmd):
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
output = p.communicate()[0]
return output
def mpc_play(STATION):
pid = Popen(["/usr/bin/mpc", "play", '%d' % ( STATION )]).pid
if __name__ == '__main__':
main()
pygame.init()
I want to display the content of LCD_QUEUE.put in my gui when is shown in my LCD.
Thanks very much for your reply.