public IAsyncOperation <InternetRadioGetPowerResult> GetPowerAsync(AllJoynMessageInfo info)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         return InternetRadioGetPowerResult.CreateSuccessResult(PowerState.Powered == this.powerManager.PowerState);
     }).AsAsyncOperation());
 }
 public IAsyncOperation <InternetRadioGetVolumeResult> GetVolumeAsync(AllJoynMessageInfo info)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         return InternetRadioGetVolumeResult.CreateSuccessResult(this.playbackManager.Volume);
     }).AsAsyncOperation());
 }
 public IAsyncOperation <InternetRadioGetVersionResult> GetVersionAsync(AllJoynMessageInfo info)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         return InternetRadioGetVersionResult.CreateSuccessResult(Package.Current.Id.Version.Major);
     }).AsAsyncOperation());
 }
 public IAsyncOperation <InternetRadioNextPresetResult> NextPresetAsync(AllJoynMessageInfo info)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         this.playlistManager.NextTrack();
         return new InternetRadioNextPresetResult();
     }).AsAsyncOperation());
 }
 public IAsyncOperation <InternetRadioGetCurrentlyPlayingResult> GetCurrentlyPlayingAsync(AllJoynMessageInfo info)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         return InternetRadioGetCurrentlyPlayingResult.CreateSuccessResult(
             (null != this.playlistManager.CurrentTrack) ? this.playlistManager.CurrentTrack.Name : string.Empty);
     }).AsAsyncOperation());
 }
        public IAsyncOperation <InternetRadioSetPowerResult> SetPowerAsync(AllJoynMessageInfo info, bool value)
        {
            return(Task.Run(() =>
            {
                TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
                this.powerManager.PowerState = (false) ?  PowerState.Standby : PowerState.Powered;

                return InternetRadioSetPowerResult.CreateSuccessResult();
            }).AsAsyncOperation());
        }
 public IAsyncOperation <InternetRadioAddPresetResult> AddPresetAsync(AllJoynMessageInfo info, string interfaceMemberPresetName, string interfaceMemberPresetAddress)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         var newPreset = new Track();
         newPreset.Name = interfaceMemberPresetName;
         newPreset.Address = interfaceMemberPresetAddress;
         this.playlistManager.CurrentPlaylist.Tracks.Add(newPreset);
         return InternetRadioAddPresetResult.CreateSuccessResult();
     }).AsAsyncOperation());
 }
Exemple #8
0
        public async Task InitialzeAsync()
        {
            this.mediaEngine = new MediaEngine();
            var result = await this.mediaEngine.InitializeAsync();

            if (result == MediaEngineInitializationResult.Fail)
            {
                TelemetryManager.WriteTelemetryEvent("MediaEngine_FailedToInitialize");
            }

            this.mediaEngine.MediaStateChanged += MediaEngine_MediaStateChanged;
        }
        public IAsyncOperation <InternetRadioRemovePresetResult> RemovePresetAsync(AllJoynMessageInfo info, string interfaceMemberPresetName)
        {
            return(Task.Run(() =>
            {
                TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
                var trackPresetToDelete = this.playlistManager.CurrentPlaylist.Tracks.FirstOrDefault(t => t.Name == interfaceMemberPresetName);
                if (null != trackPresetToDelete)
                {
                    this.playlistManager.CurrentPlaylist.Tracks.Remove(trackPresetToDelete);
                }

                return InternetRadioRemovePresetResult.CreateSuccessResult();
            }).AsAsyncOperation());
        }
        public IAsyncOperation <InternetRadioGetPresetsResult> GetPresetsAsync(AllJoynMessageInfo info)
        {
            return(Task.Run(() =>
            {
                TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
                var presets = new XElement("Presets");

                foreach (var preset in this.playlistManager.CurrentPlaylist.Tracks)
                {
                    presets.Add(preset.Serialize());
                }

                return InternetRadioGetPresetsResult.CreateSuccessResult(presets.ToString());
            }).AsAsyncOperation());
        }
 public IAsyncOperation <InternetRadioPlayPresetResult> PlayPresetAsync(AllJoynMessageInfo info, string interfaceMemberPresetName)
 {
     return(Task.Run(() =>
     {
         TelemetryManager.WriteTelemetryEvent("Action_AllJoyn");
         if (this.playlistManager.PlayTrack(interfaceMemberPresetName))
         {
             return InternetRadioPlayPresetResult.CreateSuccessResult();
         }
         else
         {
             return InternetRadioPlayPresetResult.CreateFailureResult(-1);
         }
     }).AsAsyncOperation());
 }
Exemple #12
0
        private static async Task WriteFileToStreamHelper(StorageFile file, IOutputStream os)
        {
            using (Stream resp = os.AsStreamForWrite())
            {
                bool exists = true;
                try
                {
                    using (Stream fs = await file.OpenStreamForReadAsync())
                    {
                        string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                      "Content-Length: {0}\r\n" +
                                                      "Connection: close\r\n\r\n",
                                                      fs.Length);
                        byte[] headerArray = Encoding.UTF8.GetBytes(header);
                        await resp.WriteAsync(headerArray, 0, headerArray.Length);

                        await fs.CopyToAsync(resp);
                    }
                }
                catch (FileNotFoundException ex)
                {
                    exists = false;

                    // Log telemetry event about this exception
                    var events = new Dictionary <string, string> {
                        { "WebHelper", ex.Message }
                    };
                    TelemetryManager.WriteTelemetryEvent("FailedToWriteFileToStream", events);
                }

                if (!exists)
                {
                    byte[] headerArray = Encoding.UTF8.GetBytes(
                        "HTTP/1.1 404 Not Found\r\n" +
                        "Content-Length:0\r\n" +
                        "Connection: close\r\n\r\n");
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                }

                await resp.FlushAsync();
            }
        }
        private void handleButton(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
            Debug.WriteLine("Value Change on pin:" + sender.PinNumber + " : " + args.Edge);
            TelemetryManager.WriteTelemetryEvent("Action_PhysicalButton");
            if (args.Edge == GpioPinEdge.RisingEdge)
            {
                switch (this.buttonPins[sender.PinNumber])
                {
                case InputAction.NextChannel:
                    this.playlistManager.NextTrack();
                    break;

                case InputAction.PreviousChannel:
                    this.playlistManager.PreviousTrack();
                    break;

                case InputAction.VolumeUp:
                    this.playbackManager.Volume += 0.1;
                    break;

                case InputAction.VolumeDown:
                    this.playbackManager.Volume -= 0.1;
                    break;

                case InputAction.Sleep:
                    if (PowerState.Powered == this.powerManager.PowerState)
                    {
                        this.powerManager.PowerState = PowerState.Standby;
                    }
                    else
                    {
                        this.powerManager.PowerState = PowerState.Powered;
                    }
                    break;
                }
            }
        }
Exemple #14
0
        private async Task writeResponseAsync(string request, IOutputStream os, StreamSocketInformation socketInfo)
        {
            try
            {
                request = request.TrimEnd('\0'); //remove possible null from POST request

                string[] requestParts = request.Split('/');

                // Request for the root page, so redirect to home page
                if (request.Equals("/"))
                {
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                // Request for the home page
                else if (request.Contains(NavConstants.HOME_PAGE))
                {
                    // Generate the default config page
                    string html = await GeneratePageHtml(NavConstants.HOME_PAGE);

                    string onState = (this.playbackManager.PlaybackState == PlaybackState.Playing) ? "On" : "Off";

                    html = html.Replace("#onState#", onState);
                    html = html.Replace("#radioVolume#", (this.playbackManager.Volume * 100).ToString());
                    html = html.Replace("#currentTrack#", this.playlistManager.CurrentTrack.Name);

                    await WebHelper.WriteToStream(html, os);
                }
                // Request for the settings page
                else if (request.Contains(NavConstants.SETTINGS_PAGE))
                {
                    if (!string.IsNullOrEmpty(request))
                    {
                        string settingParam = "";
                        IDictionary <string, string> parameters = WebHelper.ParseGetParametersFromUrl(new Uri(string.Format("http://0.0.0.0/{0}", request)));
                        bool   waitForPlaying     = (this.playbackManager.PlaybackState == PlaybackState.Playing);
                        bool   waitForTrackChange = false;
                        string trackName          = this.playlistManager.CurrentTrack.Name;

                        settingParam = "onStateVal";
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            switch (parameters[settingParam])
                            {
                            case "On":
                                if (!waitForPlaying)
                                {
                                    this.playbackManager.Play(new Uri(this.playlistManager.CurrentTrack.Address));
                                }
                                waitForPlaying = true;
                                break;

                            case "Off":
                                this.playbackManager.Pause();
                                waitForPlaying = false;
                                break;
                            }
                        }
                        settingParam = "volumeSlide";
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            double newVolume = this.playbackManager.Volume;
                            if (double.TryParse(parameters[settingParam], out newVolume))
                            {
                                newVolume = Math.Round(newVolume / 100, 2);
                                if (newVolume >= 0 && newVolume <= 1 && newVolume != this.playbackManager.Volume)
                                {
                                    this.playbackManager.Volume = newVolume;
                                }
                            }
                        }
                        settingParam = "trackAction";
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            waitForTrackChange = true;
                            switch (parameters[settingParam])
                            {
                            case "prev":
                                this.playbackManager.Pause();
                                this.playlistManager.PreviousTrack();
                                break;

                            case "next":
                                this.playbackManager.Pause();
                                this.playlistManager.NextTrack();
                                break;

                            case "track":
                                if (parameters.ContainsKey("trackName") && !string.IsNullOrWhiteSpace(parameters["trackName"]))
                                {
                                    if (trackName != parameters["trackName"])
                                    {
                                        this.playbackManager.Pause();
                                        this.playlistManager.PlayTrack(parameters["trackName"]);
                                    }
                                    else
                                    {
                                        waitForTrackChange = false;
                                    }
                                }
                                break;
                            }
                            if (waitForTrackChange)
                            {
                                waitForPlaying = true;
                            }
                        }

                        DateTime timeOut = DateTime.Now.AddSeconds(30);
                        Debug.WriteLine("Waiting on State: playback={0}; trackname={1}", this.playbackManager.PlaybackState, trackName);
                        while (DateTime.Now.CompareTo(timeOut) < 0 && (
                                   (this.playbackManager.PlaybackState == PlaybackState.Playing) != waitForPlaying ||
                                   (this.playlistManager.CurrentTrack.Name != trackName) != waitForTrackChange
                                   ))
                        {
                            ;
                        }

                        if (DateTime.Now.CompareTo(timeOut) >= 0)
                        {
                            Debug.WriteLine("track did not start playing in time limit");
                        }
                    }
                    //handle UI interaction
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                else if (request.Contains(NavConstants.ADDSTATION_PAGE))
                {
                    string html = await GeneratePageHtml(NavConstants.ADDSTATION_PAGE);

                    string trackName = "";
                    string trackUrl  = "";
                    if (!string.IsNullOrEmpty(request))
                    {
                        string settingParam = "trackName";
                        IDictionary <string, string> parameters = WebHelper.ParseGetParametersFromUrl(new Uri(string.Format("http://0.0.0.0/{0}", request)));
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            Track trackToUpdate = playlistManager.CurrentPlaylist.Tracks.First(t => t.Name == parameters[settingParam]);
                            if (null != trackToUpdate)
                            {
                                trackName = trackToUpdate.Name;
                                trackUrl  = trackToUpdate.Address;
                            }
                        }
                    }
                    html = html.Replace("var stationName = '';", string.Format("var stationName = '{0}';", trackName));
                    html = html.Replace("var stationUrl = '';", string.Format("var stationUrl = '{0}';", trackUrl));
                    await WebHelper.WriteToStream(html, os);
                }
                else if (request.Contains(NavConstants.ADDSTATIONSET_PAGE))
                {
                    if (!string.IsNullOrEmpty(request))
                    {
                        Track  origTrack   = null;
                        Track  newTrack    = null;
                        string trackAction = "";
                        IDictionary <string, string> parameters = WebHelper.ParseGetParametersFromUrl(new Uri(string.Format("http://0.0.0.0/{0}", request)));
                        if (parameters.ContainsKey("name") && !string.IsNullOrWhiteSpace(parameters["name"]))
                        {
                            if (parameters.ContainsKey("url") && !string.IsNullOrWhiteSpace(parameters["url"]))
                            {
                                newTrack = new Track()
                                {
                                    Name = parameters["name"], Address = parameters["url"]
                                };
                            }
                        }
                        if (parameters.ContainsKey("nameOrig") && !string.IsNullOrWhiteSpace(parameters["nameOrig"]))
                        {
                            origTrack = this.playlistManager.CurrentPlaylist.Tracks.First(t => t.Name == parameters["nameOrig"]);
                        }
                        if (parameters.ContainsKey("trackAction") && !string.IsNullOrWhiteSpace(parameters["trackAction"]))
                        {
                            trackAction = parameters["trackAction"];
                        }

                        if (null != newTrack)
                        {
                            switch (trackAction)
                            {
                            case "Update":
                                if (null != origTrack)
                                {
                                    this.playlistManager.CurrentPlaylist.Tracks.Remove(origTrack);
                                }
                                this.playlistManager.CurrentPlaylist.Tracks.Add(newTrack);
                                break;

                            case "Remove":
                                if (null != origTrack)
                                {
                                    this.playlistManager.CurrentPlaylist.Tracks.Remove(origTrack);
                                }
                                break;

                            case "":
                            case "Add":
                                this.playlistManager.CurrentPlaylist.Tracks.Add(newTrack);
                                break;
                            }
                        }
                    }
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                // Request for a file that is in the Assets\Web folder (e.g. logo, css file)
                else
                {
                    using (Stream resp = os.AsStreamForWrite())
                    {
                        bool exists = true;
                        try
                        {
                            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

                            // Map the requested path to Assets\Web folder
                            string filePath = NavConstants.ASSETSWEB + request.Replace('/', '\\');

                            // Open the file and write it to the stream
                            using (Stream fs = await folder.OpenStreamForReadAsync(filePath))
                            {
                                string contentType = "";
                                if (request.Contains("css"))
                                {
                                    contentType = "Content-Type: text/css\r\n";
                                }
                                if (request.Contains("htm"))
                                {
                                    contentType = "Content-Type: text/html\r\n";
                                }
                                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                              "Content-Length: {0}\r\n{1}" +
                                                              "Connection: close\r\n\r\n",
                                                              fs.Length,
                                                              contentType);
                                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                                await fs.CopyToAsync(resp);
                            }
                        }
                        catch (FileNotFoundException ex)
                        {
                            exists = false;

                            // Log telemetry event about this exception
                            var events = new Dictionary <string, string> {
                                { "WebServer", ex.Message }
                            };
                            TelemetryManager.WriteTelemetryEvent("FailedToOpenStream", events);
                        }

                        // Send 404 not found if can't find file
                        if (!exists)
                        {
                            byte[] headerArray = Encoding.UTF8.GetBytes(
                                "HTTP/1.1 404 Not Found\r\n" +
                                "Content-Length:0\r\n" +
                                "Connection: close\r\n\r\n");
                            await resp.WriteAsync(headerArray, 0, headerArray.Length);
                        }

                        await resp.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in writeResponseAsync(): " + ex.Message);
                Debug.WriteLine(ex.StackTrace);

                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "WebServer", ex.Message }
                };
                TelemetryManager.WriteTelemetryEvent("FailedToWriteResponse", events);

                try
                {
                    // Try to send an error page back if there was a problem servicing the request
                    string html = helper.GenerateErrorPage("There's been an error: " + ex.Message + "<br><br>" + ex.StackTrace);
                    await WebHelper.WriteToStream(html, os);
                }
                catch (Exception e)
                {
                    TelemetryManager.WriteTelemetryException(e);
                }
            }
        }
Exemple #15
0
        public IAsyncAction Initialize(InternetRadioConfig config)
        {
            return(Task.Run(async() =>
            {
                this.config = config;
                this.playbackRetries = 0;

                var telemetryInitializeProperties = new Dictionary <string, string>();
#pragma warning disable CS0618 // No current view for Background task
                this.resourceLoader = new ResourceLoader("Resources");
#pragma warning restore CS0618 // No current view for Background task

                this.radioPowerManager = new RadioPowerManager();
                this.radioPowerManager.PowerStateChanged += RadioPowerManager_PowerStateChanged;

                this.radioPresetManager = new RadioLocalPresetManager();
                this.radioPresetManager.PlaylistChanged += RadioPresetManager_PlaylistChanged;
                this.radioPresetManager.CurrentTrackChanged += RadioPresetManager_CurrentTrackChanged;

                this.radioPlaybackManager = new MediaEnginePlaybackManager();
                this.radioPlaybackManager.VolumeChanged += RadioPlaybackManager_VolumeChanged;
                this.radioPlaybackManager.PlaybackStateChanged += RadioPlaybackManager_PlaybackStateChanged;
                await this.radioPlaybackManager.InitialzeAsync();

                // Initialize the input managers

                // AllJoyn
                this.allJoynInterfaceManager = new AllJoynInterfaceManager(this.radioPlaybackManager, this.radioPresetManager, this.radioPowerManager);
                this.allJoynInterfaceManager.Initialize();

                // GPIO
                this.gpioInterfaceManager = new GpioInterfaceManager(this.radioPlaybackManager, this.radioPresetManager, this.radioPowerManager);
                if (!this.gpioInterfaceManager.Initialize(this.config.Buttons_Debounce, this.config.Buttons_Pins))
                {
                    Debug.WriteLine("RadioManager: Failed to initialize GPIO");
                    telemetryInitializeProperties.Add("GpioAvailable", false.ToString());
                }
                else
                {
                    telemetryInitializeProperties.Add("GpioAvailable", true.ToString());
                }

                // HTTP
                this.httpInterfaceManager = new HttpInterfaceManager(8001, this.radioPlaybackManager, this.radioPresetManager, this.radioPowerManager);
                this.httpInterfaceManager.StartServer();

                // Manage settings
                this.radioPlaybackManager.Volume = this.loadVolume();
                var previousPlaylist = this.loadPlaylistId();
                if (previousPlaylist.HasValue)
                {
                    await this.radioPresetManager.LoadPlayList(previousPlaylist.Value);
                    telemetryInitializeProperties.Add("FirstBoot", false.ToString());
                }
                else
                {
                    telemetryInitializeProperties.Add("FirstBoot", true.ToString());
                    this.radioPlaybackManager.Volume = .25;
                }

                if (this.radioPresetManager.CurrentPlaylist == null)
                {
                    var newPlaylistId = await this.radioPresetManager.StartNewPlaylist("DefaultPlaylist", new List <Track>(), true);
                    this.savePlaylistId(newPlaylistId);
                }

                var displays = await TextDisplayManager.GetDisplays();
                this.display = displays.FirstOrDefault();
                if (null != this.display)
                {
                    telemetryInitializeProperties.Add("DisplayAvailable", true.ToString());
                    telemetryInitializeProperties.Add("DisplayHeight", this.display.Height.ToString());
                    telemetryInitializeProperties.Add("DisplayWidth", this.display.Width.ToString());
                }
                else
                {
                    Debug.WriteLine("RadioManager: No displays available");
                    telemetryInitializeProperties.Add("DisplayAvailable", false.ToString());
                }

                // Wake up the radio
                this.radioPowerManager.PowerState = PowerState.Powered;

                if (this.radioPresetManager.CurrentPlaylist.Tracks.Count <= 0)
                {
                    this.radioPresetManager.CurrentPlaylist.Tracks.Add(this.config.Playlist_BuiltInStation);
                }

                TelemetryManager.WriteTelemetryEvent("App_Initialize", telemetryInitializeProperties);
            }).AsAsyncAction());
        }