#!/usr/bin/env python

# Example program to interface the Volumio media player running on a Raspberry Pi
# with the serial console on the Djuke Preamplifier, this gives endless possibilities, like:
# - switching on the amplifier when the media player starts playing
# - automatically choose the correct input when the media player starts playing
# - display the song title on the Preamplifier display
# - switch off the amplifier when the media player stops playing
# - etc.
#
# The Volumio media player can be accessed from Python using mpd2 (Music Player Daemon)
# https://pypi.python.org/pypi/python-mpd2
#
# To install it on the Volumio raspbian distribution, connect using ssh to it and run these commands:
#
# (apt-get update)
# apt-get install python-pip
# pip install python-mpd2
#
# The connection to the Djuke preamplifier uses python-serial, if it is not already installed, install it with
#
# apt-get install python-serial
# 

import logging
import logging.handlers
import time
import sys
import threading

# Logging parameter
LOG_FILENAME = "/var/log/DjukePreamp.log"
LOG_LEVEL = logging.INFO  # Could be e.g. "DEBUG" or "WARNING"

# Configure logging to log to a file, making a new file at midnight and keeping the last 3 day's data
# Give the logger a unique name (good practice)
logger = logging.getLogger(__name__)
# Set the log level to LOG_LEVEL
logger.setLevel(LOG_LEVEL)
# Make a handler that writes to a file, making a new file at midnight and keeping 3 backups
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight", backupCount=3)
# Format each log message like this
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
# Attach the formatter to the handler
handler.setFormatter(formatter)
# Attach the handler to the logger
logger.addHandler(handler)

# Make a class we can use to capture stdout and sterr in the log
class MyLogger(object):
        def __init__(self, logger, level):
                """Needs a logger and a logger level."""
                self.logger = logger
                self.level = level

        def write(self, message):
                # Only log if there is a message (not just a new line)
                if message.rstrip() != "":
                        self.logger.log(self.level, message.rstrip())

# Replace stdout with logging to file at INFO level
sys.stdout = MyLogger(logger, logging.INFO)
# Replace stderr with logging to file at ERROR level
sys.stderr = MyLogger(logger, logging.ERROR)

# Volumio connection
from mpd import MPDClient, MPDError, CommandError
class VolumioClient(object):
    def __init__(self, host="localhost", port="6600", password=None):
        self._host = host
        self._port = port
        self._password = password
        self._client = MPDClient()

    def connect(self):
        try:
            self._client.connect(self._host, self._port)
            logger.info("Connected to Volumio on '%s'" % self._host)
            logger.info("Volumio status: " + str(self._client.status()))
            logger.info("Volumio client version: " + str(self._client.mpd_version))

        # Catch socket errors
        except IOError:
            logger.warning("Could not connect to '%s'" %
                              (self._host))
            logger.info("Retry after 5s")
            time.sleep(5);
            self.connect()

        # Catch all other possible errors
        except MPDError as e:
            raise Exception("Could not connect to '%s': %s" %
                              (self._host, e))
    def disconnect(self):
        # Try to tell MPD we're closing the connection first
        try:
            self._client.close()

        # If that fails, don't worry, just ignore it and disconnect
        except (MPDError, IOError):
            pass

        try:
            self._client.disconnect()

        # Disconnecting failed, so use a new client object instead
        # This should never happen.  If it does, something is seriously broken,
        # and the client object shouldn't be trusted to be re-used.
        except (MPDError, IOError):
            self._client = MPDClient()

    def reconnect(self):
         self.disconnect()

         try:
             self.connect()

         # Reconnecting failed
         except Exception as e:
             raise Exception("Reconnecting failed: %s" % e)

    def idle(self):
        try:
            result = self._client.idle()

        # Couldn't get the current song, so try reconnecting and retrying
        except (MPDError, IOError):
            # No error handling required here
            # Our disconnect function catches all exceptions, and therefore
            # should never raise any.
            self.reconnect()

            try:
                result = self._client.idle()

            # Failed again, just give up
            except (MPDError, IOError) as e:
                raise Exception("Couldn't retrieve current song: %s" % e)

        return result

# Serial read thread
SERIAL_LOG_FILENAME = "/var/log/DjukePreamp-serial.log"
def read_serial_data(ser):
   serial_log=open(SERIAL_LOG_FILENAME, 'ab')
   serial_log.write("\nDjuke Preamp log file\n".encode());

   ser.flushInput()

   while True:
      reading = ser.read()
      serial_log.write(reading)
      serial_log.flush()

# DjukePreamp serial connection
import serial
class PreampClient(object):
    def __init__(self, port="/dev/ttyAMA0", baudrate="115200", timeout=1):
        self._ser = serial.Serial()
        self._ser.port = port
        self._ser.baudrate = baudrate
        self._ser.timeout = timeout

    def open(self):
        self._ser.open()

        if (self._ser.isOpen()):
            logger.info("Serial port: " + self._ser.port + " opened")
            thread = threading.Thread(target=read_serial_data, args=(self._ser,))
            thread.start()
            preamp.write("")
            preamp.version()

    def close(self):
        self._ser.close()
        
    def write(self, command):
        self._ser.flushOutput()
        time.sleep(0.05)
        self._ser.write((command + "\n").encode())
        time.sleep(0.05)

    # Request preamp version
    def version(self):
        self.write("ver")

if __name__ == "__main__":
    import sys

    try:
        preamp = PreampClient()
        preamp.open()

        volumio = VolumioClient()
        volumio.connect()

        while True:
            last_state = volumio._client.status()
            result = volumio.idle()
            new_state = volumio._client.status()
            #logger.info("Volumio result: " + str(result))

            if result == ['player']:
             if last_state['state'] != 'stop' and new_state['state'] == 'stop':
                logger.info("player stopped, remove preamp title")
                preamp.write("input set 9")
             if last_state['state'] != 'pause' and new_state['state'] == 'pause':
                logger.info("player paused, remove preamp title")
                preamp.write("input set 9")
             if last_state['state'] == 'stop' or last_state['state'] == 'pause' and new_state['state'] == 'play':
                logger.info("Player started, power on preamp")
                preamp.write("power on")
                time.sleep(2);
                logger.info("Set preamp input to Raspberry Pi")
                preamp.write("input set 9")
                time.sleep(1);
             if new_state['state'] == 'play':
                currentsong = volumio._client.currentsong()
                logger.info("Set preamp title to: " + str(currentsong['title']))
                preamp.write("title 9 " + str(currentsong['title']))

    except (KeyboardInterrupt, SystemExit):
        logger.info("Keyboard or system exit interrupt");
        volumio.disconnect();
        preamp.close();
        sys.exit();

    # Catch all other non-exit errors
    except Exception as e:
        logger.error(e)
        sys.exit(1)

    except:
        sys.exit(0)

