Example #1
0
        public Main(Arguments args)
        {
            this.log             = Log.Logger;
            this.fileStoragePath = args.FileStoragePath;

            // Clean up temp folder
            string tempFolder = Path.Combine(this.fileStoragePath, "tmp");

            Directory.CreateDirectory(tempFolder);
            Directory.GetDirectories(tempFolder).ToList().ForEach(x => Directory.Delete(x, true));

            if (!string.IsNullOrEmpty(args.VideoSystem))
            {
                switch (args.VideoSystem.ToLower())
                {
                case "omx":
                    this.videoSystem = VideoSystems.OMX;
                    break;

                default:
                    throw new ArgumentException("Invalid video system type");
                }
            }
            else
            {
                this.videoSystem = VideoSystems.None;
            }

            if (args.AudioSystem && this.videoSystem != VideoSystems.None)
            {
                throw new ArgumentException("Cannot support both audio and video system concurrently");
            }

            if (this.videoSystem != VideoSystems.None)
            {
                // Disable console log output
                this.log.Information("Video System, turning off console logging and cursor");

                //FIXME
                //var logConfig = LogManager.Configuration;
                //var consoleTargets = new List<string>();
                //consoleTargets.AddRange(logConfig.AllTargets
                //    .OfType<NLog.Targets.ColoredConsoleTarget>()
                //    .Select(x => x.Name));
                //consoleTargets.AddRange(logConfig.AllTargets
                //    .OfType<NLog.Targets.ConsoleTarget>()
                //    .Select(x => x.Name));
                //foreach (var loggingRule in logConfig.LoggingRules)
                //{
                //    loggingRule.Targets
                //        .Where(x => consoleTargets.Contains(x.Name) || consoleTargets.Contains(x.Name + "_wrapped"))
                //        .ToList()
                //        .ForEach(x => loggingRule.Targets.Remove(x));
                //}
                //LogManager.Configuration = logConfig;

                Console.CursorVisible = false;
                Console.Clear();
            }

            this.loadedSounds   = new Dictionary <string, Sound>();
            this.currentBgTrack = -1;
            this.random         = new Random();
            this.disposeList    = new List <IDisposable>();
            this.serialPorts    = new Dictionary <int, SerialPort>();

            string fileStoragePath = Path.GetFullPath(args.FileStoragePath);

            Directory.CreateDirectory(fileStoragePath);

            this.soundEffectPath = Path.Combine(fileStoragePath, FileTypes.AudioEffect.ToString());
            this.trackPath       = Path.Combine(fileStoragePath, FileTypes.AudioTrack.ToString());
            this.videoPath       = Path.Combine(fileStoragePath, FileTypes.Video.ToString());

            this.autoStartBackgroundTrack = args.BackgroundTrackAutoStart;

            // Try to read instance id from disk
            try
            {
                using (var f = File.OpenText(Path.Combine(fileStoragePath, "MonoExpander_InstanceId.txt")))
                {
                    this.instanceId = f.ReadLine();
                }
            }
            catch
            {
                // Generate new
                this.instanceId = Guid.NewGuid().ToString("n");

                using (var f = File.CreateText(Path.Combine(fileStoragePath, "MonoExpander_InstanceId.txt")))
                {
                    f.WriteLine(this.instanceId);
                    f.Flush();
                }
            }

            this.log.Information("Instance Id {0}", this.instanceId);
            this.log.Information("Video Path {0}", this.videoPath);
            this.log.Information("Track Path {0}", this.trackPath);
            this.log.Information("FX Path {0}", this.soundEffectPath);

            this.backgroundAudioTracks = new List <string>();
            if (!string.IsNullOrEmpty(args.BackgroundTracksPath))
            {
                this.backgroundAudioTracks.AddRange(Directory.GetFiles(args.BackgroundTracksPath, "*.wav"));
                this.backgroundAudioTracks.AddRange(Directory.GetFiles(args.BackgroundTracksPath, "*.mp3"));
            }

            if (args.AudioSystem)
            {
                this.log.Information("Initializing FMOD sound system");
                this.fmodSystem = new LowLevelSystem();

                this.fxGroup  = this.fmodSystem.CreateChannelGroup("FX");
                this.trkGroup = this.fmodSystem.CreateChannelGroup("Track");
                this.bgGroup  = this.fmodSystem.CreateChannelGroup("Background");
            }

            if (SupersonicSound.Wrapper.Util.IsUnix)
            {
                this.log.Information("Initializing PiFace");

                try
                {
                    this.piFace = new PiFaceDigitalDevice();

                    // Setup events
                    foreach (var ip in this.piFace.InputPins)
                    {
                        ip.OnStateChanged += (s, e) =>
                        {
                            SendInputMessage(e.pin.Id, e.pin.State);
                        };

                        // Send current state
                        SendInputMessage(ip.Id, ip.State);
                    }
                }
                catch (Exception ex)
                {
                    this.log.Warning(ex, "Failed to initialize PiFace");
                }
            }

            if (!string.IsNullOrEmpty(args.SerialPort0) && args.SerialPort0BaudRate > 0)
            {
                this.log.Information("Initialize serial port 0 ({0}) for {1} bps", args.SerialPort0, args.SerialPort0BaudRate);

                var serialPort = new SerialPort(args.SerialPort0, args.SerialPort0BaudRate);

                serialPort.Open();

                this.serialPorts.Add(0, serialPort);
            }

            this.log.Information("Initializing ExpanderCommunication client");

            this.connections = new List <Tuple <IClientCommunication, MonoExpanderClient> >();
            foreach (var server in args.Servers)
            {
                var client = new MonoExpanderClient(this);

#if SIGNALR
                var communication = new SignalRClient(
                    host: server.Host,
                    port: server.Port,
                    instanceId: InstanceId,
                    dataReceivedAction: (t, d) => DataReceived(client, t, d));
#endif
#if NETTY
                var communication = new NettyClient(
                    logger: this.log,
                    host: server.Host,
                    port: server.Port,
                    instanceId: InstanceId,
                    dataReceivedAction: (t, d) => DataReceived(client, t, d),
                    connectedAction: () => SendMessage(new Ping()));
#endif
                this.connections.Add(Tuple.Create((IClientCommunication)communication, client));

                Task.Run(async() => await communication.StartAsync()).Wait();
            }
        }
Example #2
0
        public Main(Arguments args)
        {
            this.log = LogManager.GetLogger("Main");
            this.fileStoragePath = args.FileStoragePath;

            // Clean up temp folder
            string tempFolder = Path.Combine(this.fileStoragePath, "tmp");
            Directory.CreateDirectory(tempFolder);
            Directory.GetDirectories(tempFolder).ToList().ForEach(x => Directory.Delete(x, true));

            if (!string.IsNullOrEmpty(args.VideoSystem))
            {
                switch (args.VideoSystem.ToLower())
                {
                    case "omx":
                        this.videoSystem = VideoSystems.OMX;
                        break;

                    default:
                        throw new ArgumentException("Invalid video system type");
                }
            }
            else
                this.videoSystem = VideoSystems.None;

            if (args.AudioSystem && this.videoSystem != VideoSystems.None)
                throw new ArgumentException("Cannot support both audio and video system concurrently");

            if (this.videoSystem != VideoSystems.None)
            {
                // Disable console log output
                this.log.Info("Video System, turning off console logging and cursor");

                var logConfig = LogManager.Configuration;
                var consoleTargets = new List<string>();
                consoleTargets.AddRange(logConfig.AllTargets
                    .OfType<NLog.Targets.ColoredConsoleTarget>()
                    .Select(x => x.Name));
                consoleTargets.AddRange(logConfig.AllTargets
                    .OfType<NLog.Targets.ConsoleTarget>()
                    .Select(x => x.Name));
                foreach (var loggingRule in logConfig.LoggingRules)
                {
                    loggingRule.Targets
                        .Where(x => consoleTargets.Contains(x.Name) || consoleTargets.Contains(x.Name + "_wrapped"))
                        .ToList()
                        .ForEach(x => loggingRule.Targets.Remove(x));
                }
                LogManager.Configuration = logConfig;

                Console.CursorVisible = false;
                Console.Clear();
            }

            this.loadedSounds = new Dictionary<string, Sound>();
            this.currentBgTrack = -1;
            this.random = new Random();
            this.disposeList = new List<IDisposable>();
            this.serialPorts = new Dictionary<int, SerialPort>();

            string fileStoragePath = Path.GetFullPath(args.FileStoragePath);
            Directory.CreateDirectory(fileStoragePath);

            this.soundEffectPath = Path.Combine(fileStoragePath, FileTypes.AudioEffect.ToString());
            this.trackPath = Path.Combine(fileStoragePath, FileTypes.AudioTrack.ToString());
            this.videoPath = Path.Combine(fileStoragePath, FileTypes.Video.ToString());

            this.autoStartBackgroundTrack = args.BackgroundTrackAutoStart;

            // Try to read instance id from disk
            try
            {
                using (var f = File.OpenText(Path.Combine(fileStoragePath, "MonoExpander_InstanceId.txt")))
                {
                    this.instanceId = f.ReadLine();
                }
            }
            catch
            {
                // Generate new
                this.instanceId = Guid.NewGuid().ToString("n");

                using (var f = File.CreateText(Path.Combine(fileStoragePath, "MonoExpander_InstanceId.txt")))
                {
                    f.WriteLine(this.instanceId);
                    f.Flush();
                }
            }

            this.log.Info("Instance Id {0}", this.instanceId);
            this.log.Info("Video Path {0}", this.videoPath);
            this.log.Info("Track Path {0}", this.trackPath);
            this.log.Info("FX Path {0}", this.soundEffectPath);

            this.backgroundAudioTracks = new List<string>();
            if (!string.IsNullOrEmpty(args.BackgroundTracksPath))
            {
                this.backgroundAudioTracks.AddRange(Directory.GetFiles(args.BackgroundTracksPath, "*.wav"));
                this.backgroundAudioTracks.AddRange(Directory.GetFiles(args.BackgroundTracksPath, "*.mp3"));
            }

            if (args.AudioSystem)
            {
                this.log.Info("Initializing FMOD sound system");
                this.fmodSystem = new LowLevelSystem();

                this.fxGroup = this.fmodSystem.CreateChannelGroup("FX");
                this.trkGroup = this.fmodSystem.CreateChannelGroup("Track");
                this.bgGroup = this.fmodSystem.CreateChannelGroup("Background");
            }

            if (SupersonicSound.Wrapper.Util.IsUnix)
            {
                this.log.Info("Initializing PiFace");

                try
                {
                    this.piFace = new PiFaceDigitalDevice();

                    // Setup events
                    foreach (var ip in this.piFace.InputPins)
                    {
                        ip.OnStateChanged += (s, e) =>
                        {
                            SendInputMessage(e.pin.Id, e.pin.State);
                        };

                        // Send current state
                        SendInputMessage(ip.Id, ip.State);
                    }
                }
                catch (Exception ex)
                {
                    this.log.Warn(ex, "Failed to initialize PiFace");
                }
            }

            if (!string.IsNullOrEmpty(args.SerialPort0) && args.SerialPort0BaudRate > 0)
            {
                this.log.Info("Initialize serial port 0 ({0}) for {1} bps", args.SerialPort0, args.SerialPort0BaudRate);

                var serialPort = new SerialPort(args.SerialPort0, args.SerialPort0BaudRate);

                serialPort.Open();

                this.serialPorts.Add(0, serialPort);
            }

            this.log.Info("Initializing ExpanderCommunication client");

            this.connections = new List<Tuple<IClientCommunication, MonoExpanderClient>>();
            foreach (var server in args.Servers)
            {
                var client = new MonoExpanderClient(this);

#if SIGNALR
                var communication = new SignalRClient(
                    host: server.Host,
                    port: server.Port,
                    instanceId: InstanceId,
                    dataReceivedAction: (t, d) => DataReceived(client, t, d));
#endif
#if NETTY
                var communication = new NettyClient(
                    host: server.Host,
                    port: server.Port,
                    instanceId: InstanceId,
                    dataReceivedAction: (t, d) => DataReceived(client, t, d),
                    connectedAction: () => SendMessage(new Ping()));
#endif
                this.connections.Add(Tuple.Create((IClientCommunication)communication, client));

                Task.Run(async () => await communication.StartAsync()).Wait();
            }
        }