Friday, 17 June 2016

PowerShell as a web application interface

As a web developer I sometimes use PowerShell to aid development and to automate tasks.

With most applications, especially complex ones, it can be handy to have a PowerShell build script to build the application without having to load Visual Studio. I've written scripts in the past to create deployment packages for release to remote servers. I've also used scripts to unzip the packages, create sites in IIS and deploy the website and database to the remote server.

So PowerShell can be extremely useful as a developer to speed up common development tasks.
Recently I've been looking at expanding my PowerShell knowledge and have looked at how to create own binary PowerShell modules in C#.

The process of creating a C# binary module is relatively simple, and there's a good guide here on how to create them, but I wondered how easy it would be to create PowerShell modules to allow me to administer my own web applications, if that's something that I should do, and if that's something that even makes sense.

I have a sample application which is relatively well designed. The application layer and data layer are separated out, and there is a simple MVC web front end which uses this application layer. The database dependencies are injected using Unity.

The application doesn't really do a lot, it has a couple of different entities which are stored in a LocalDB database and accessed using Entity Framework. The MVC front end lists these entities and allows basic add/update/delete actions on these entities.

Creating the modules

I added a new Class Library project to my application solution, and imported the System.Management.Automation package to allow PowerShell modules to be created.

I wanted to create a couple of modules which would be able to perform simple List and Add operations on the database entities, reusing as much of the existing application code as possible.

To start, I created a base class which my modules would inherit from. This would hold the basic database connection settings, so I wouldn't have to write this for every module.

namespace Solution.PS
{
    using System.Management.Automation;
    using Data;
    using Services;
 
    public class PsModuleBase : PSCmdlet
    { 
        protected EntityService EntityService { getset; }
 
        protected override void BeginProcessing()
        {
            var fac = new ApplicationDbContextFactory(@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=C:\Source\Samples\Solution\Solution.Web\App_Data\aspnet-Solution-20160510123834.mdf;Initial Catalog=aspnet-Solution-20160510123834;Integrated Security=True");
            this.EntityService = new EntityService(fac);
        }
    }
}

Then, for my modules, I inherited this base class, and used the already existing Query and Add methods, which are part of my Services project to access the database.

namespace Solution.PS
{
    using System.Linq;
    using System.Management.Automation;
    using Data.Entities;
 
    public class PsModules
    {
        [Cmdlet(VerbsCommon.Get, "AppEntity")]
        public class GetAppEntity : PsModuleBase
        {
            protected override void ProcessRecord()
            {
                this.WriteObject(this.EntityService.Query().ToList());
            }
        }
 
        [Cmdlet(VerbsCommon.Add, "AppEntity")]
        public class AddAppEntity : PsModuleBase
        {
            [Parameter(Mandatory = true)]
            [Alias("EntityName")]
            public string Name { getset; }
 
            protected override async void ProcessRecord()
            {
                var e = new Entity { Name = this.Name };
                await this.EntityService.AddAsync(e);
            }
        }
    }
}

Running the application

Building and importing the module into PowerShell means I can now query the Entity list and Add new entity records using PowerShell modules.

>Add-AppEntity -Name NewEntity
>Get-AppEntity

Id             : 1
Name           : NewEntity
_entityWrapper : System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships`1[System.Data.Entity.DynamicProxies.Entity_752509F5469DFFCA653EEAEA813AD30DFAE5B07E9F73172F775CB059AB13ABAB]

I could also see via the web interface that the entities were being correctly created as planned.

So, the code worked. I know it's not perfect code, I'd like to see how easy it would be to use Unity to add the same dependency injection to this. I obviously hard coded the full path to the Database file in the PowerShell base class, so this would be nicer if I was using DI, potentially passing this connection information as a parameter to the modules.

The main thing I wanted to test was if this was possible and how easy it would be. The code here is relatively simple, and I could re-use much of the existing logic and classes I already have.

As for whether this approach is sensible? I'm still not sure.

It seems like a good approach to administering web applications, it could allow people familiar with PowerShell scripting to easily import data into a new deployment of a web application. It would only take a few simple commands to import a CSV file of entities straight into the application using the application's own methods, so any internal business logic can still be used.
It could also allow quick queries of the application to check the status of the data.

So to me, it seems to make a certain amount of sense to create an interface like this for some web applications. Part of the reason for questioning this approach was that I couldn't find any similar examples of this on the web, so it doesn't seem like a common practice.

It would be interesting to see some other examples where people have done something similar, or a best-practice approach to extending web applications in this way.

Friday, 29 April 2016

An update to Nano Server


Last month I posted an article about the upcoming version of Nano Server which is to be released as part of Windows Server 2016.

I was attempting to make the process of creating a new Virtual Nano Server instance as quickly and easy as possible for testing out ASP.Net Core Websites.
Although I'd managed to script most of the work in PowerShell, so creating a new image only took a few commands, I still knew that improvements could be made.

Creating the image was relatively painless, but once the image was created and started there were some additional commands which needed to be run directly on the Nano server machine to configure IIS. Even though I'd scripted this, it still seemed messy, and something that could potentially be improved.

Thankfully, Microsoft have just announced the latest release of Windows Server 2016, which is Technical Preview 5. Creating images using this new technical preview is still very similar to Technical Preview 4, but there are a few additional improvements which make this initial configuration easier.

The new  -SetupCompleteCommands parameter allows additional setup commands to be passed into the image, which automatically become included in the SetupComplete.cmd script which is automatically executed when the Server first starts up.

Using the process I'd described in my previous article, I can now pass the command to run my setup.ps1 script as a Setup complete command, which means it will automatically be run on first boot, so I don't have to manually login to the server to run this command.

Setting up the files

I'm setting up my local files for creating Nano server images in a very similar way to my previous post, so I'm not going to go into the same level of detail, but only explain the additional steps here.

Previously I'd created a c:\nano folder containing a number of folders with the setup files. For the new version, you're going to need mostly the same files.

I've started by creating a new c:\nano5 (for Technical Preview 5), and I've created an ISO folder in there, into which I coped the entire contents of the Windows Server 2016 Technical Preview 5 ISO.

Also from the ISO's NanoServer folder you'll need to copy the NanoServerImageGenerator folder into c:\nano5.

I've also copied my Tools folder from my previous c:\nano folder into c:\nano5. The tools folder contains the HTTPPlatformHandler files, the output folder for your ASP.Net Core website, and the setup.ps1 script which we created in the previous post.

So in my c:\nano5 folder now, I've got an ISO, NanoServerImageGenerator and Tools folder.

Creating a Nano Server VM

The creation of the VM is very similar to how it was previously, but some of the command parameters have changed slightly. The previous -GuestDrivers parameter has been replaced by -DeploymentType Guest, and the -ReverseForwarders command is no-longer needed as this is done automatically. Also -MergeFiles has been replaced by -CopyFiles.

First we need to import the NanoServerImageGenerator module.

>Import-Module \NanoServerImageGenerator

Then we can execute the new command to create the VM, with the additional parameter which will add our startup script to the SetupComplete tasks.

>New-NanoServerImage -Edition Standard -DeploymentType Guest -MediaPath .\ISO
-BasePath .\Base -TargetPath c:\Nano5\Nano1\Nano.vhdx
-ComputerName Nano1 -Packages Microsoft-NanoServer-IIS-Package
-EnableRemoteManagement -CopyFiles .\Tools 
-SetupCompleteCommands 'powershell "& ""C:\Tools\Setup.ps1"""'

Note that the additional quotation marks around the path in the SetupCompeteCommands are needed.

This command will prompt you for an admin password, and after a couple of minutes you'll have a new Nano server VM hard drive image. A new Virtual machine can easily be created from this image with the same PowerShell commands as I'd use previously or using the Hyper-V Manager.

When the machine first starts the C:\Tools\Setup.ps1 setup script will automatically be run, which creates the necessary IIS configuration and firewall rules for your ASP.Net Core website to run, and then once the machine has fully started you should be able to browse the website by pointing your browser to the IP of the new server on port 8000.

This is a much nicer and neater method of creating a new Nano Server VM, and doesn't require any of the remoting into the server to execute scripts.

Windows Server 2016 is still a Technical Preview so some of this will probably change again, but hopefully it'll make this process even easier. Also .Net Core still hasn't shipped, so more changes are coming which may mean this works slightly differently in future.

I've added a new script on GitHub to streamline this new process. Nano-CreateTP5 can be executed as one command for creating, configuring and starting the VM.

Saturday, 12 March 2016

Running .NET Core websites on Nano Server

I've recently been looking into the new Windows Nano Server, which is still in Technical Preview, but is due to launch alongside Windows Server 2016 later this year.

I'm not going to go into too much detail about what Nano Server is and what it's benefits are generally, but for me, as a developer it means I should be able to quickly setup a new virtual web server, running IIS to test websites on. The setup and configuration time should be vastly reduced, as it's a much simpler server. This has a potential to make development and testing of sites easier without relying specific PC setup potentially causing problems.

Since the full .NET Framework isn't available for Nano Server, you can only test websites created for .NET Core.

After investigating how Nano server works and is setup, I've managed to simplify much of the setup process so new virtual servers can be created and ASP.Net Core websites deployed with only a few commands.

To make the process of deploying the Nano Servers and sites simpler, there's a small amount of setup to do on your local machine, but this is just getting files in the right places, there's no installation to do and this only has to be done once to make the creation of the servers much simpler.

Creating the Nano Server image in PowerShell

Setting up the files

To start with, you'll need a copy of the Windows Server 2016 Technical preview ISO image.

Getting the files from the ISO

Double clicking the ISO image in Windows 8.1 or Windows 10 will mount it as a virtual disk drive.
With this mounted, create a new folder on your computer (I'm using c:\nano), and from the NanoServer folder on the disk copy the Convert-WindowsImage.ps1 and NanoServerImageGenerator.psm1 files into your new folder.

Inside your nano folder, create a new folder called ISO, and copy the entire contents of the ISO image into this folder. This step isn't strictly necessary, as you can point the setup process at the mounted ISO directly, but doing this means you can un-mount the ISO disk and you won't need it again.

Creating the Tools directory

In your nano folder, create a new Tools folder. This will hold some additional files we're going to copy to our Nano Server when we create the image.

Get the HTTPPlatformHandler files

Inside the Tools folder, create a new folder named HTTPPlatformHandler. The HTTPPlatformHandler is a module which essentially allows .NET Core sites to run under IIS. You'll need to also install the HTTPPlatformHandler on a non-nano machine first, so you can access a couple of the files to copy to your Nano Server.

After it is installed, locate the following two files and copy them to your new HTTPPlatformHandler folder.
%windir%\System32\inetsrv\HttpPlatformHandler.dll
%windir%\System32\inetsrv\config\schema\httpplatform_schema.xml

Publish the Web Application

You'll need to create a published build of your website to be able to deploy it. To do this, find the folder where your website application source code is stored, and run the following publish command.
dnu publish --runtime dnx-coreclr-win-x64.1.0.0-rc1-update1
This will create a published version of the site using the 64-bit version of the Core CLR. The resulting files will be copied to the bin\output\ folder.

Copy the entire Output folder from it's current location to your Tools folder.


Copy the setup script

There are a few commands which need to be executed on the Nano server the first time it starts up. These commands setup IIS to serve up the ASP.Net Core website, and open the relevant firewall ports. The setup script only needs to be run once.

Copy the script.ps1 script into the Tools folder.

The Tools folder should now contain the HTTPPlatformHandler, and Output folders, and the setup.ps1 script.

The main Nano folder should contain ISO and Tools folders, and the Convert-WindowsImage.ps1 and NanoServerImageGenerator.psm1 files.

If these files are all present, then the initial setup is complete.

Creating a Nano Server VM

With the initial setup complete, the process of creating each new Nano server VM only takes a few commands.

In PowerShell enter the following commands to Import the Image Generator module and generate the VHDX hard drive image. The second command will take a few minutes to run.

This will create a new Nano Server image named Nano1 and install the IIS package, and copy your Tools folder to c:\Tools on the new VM. This command will also set some configuration so that you can connect to the VM remotely via PowerShell.
>Import-Module .\NanoServerImageGenerator.psm1

>New-NanoServerImage -MediaPath .\ISO -BasePath .\Base -TargetPath c:\Nano\Nano1\Nano.vhdx
-ComputerName Nano1 –GuestDrivers -ReverseForwarders
-Packages Microsoft-NanoServer-IIS-Package
-Language en-us -EnableRemoteManagementPort -MergePath .\Tools
Once this is done, the following commands will create a new Hyper-V virtual machine using this VHDX image, and start the VM. The commands set defaults for the memory used by the VM, and the network switch it will use. You can alter the values here, or change them once the machine is created in the Hyper-V manager.
>New-VM -Name Nano1 -Generation 2 -MemoryStartupBytes 256MB -VHDPath c:\Nano\Nano1\Nano.vhdx
-SwitchName "Internal Virtual Switch"

>Set-VMMemory Nano1 -DynamicMemoryEnabled $true -MinimumBytes 256MB -StartupBytes 256MB
-MaximumBytes 2GB -Priority 50 -Buffer 20

>Start-VM Nano1
The first time the VM starts up, it takes a few minutes to get fully up and running. Once it is fully running, all that is left is to find the IP address of the new VM, connect to it, and execute the startup.ps1 script we copied to the VM.

You can do that with the following commands.
>$serverIP = (Get-VMNetworkAdapter Nano1).IPAddresses[0]

>Set-Item WSMan:\localhost\Client\TrustedHosts $serverIP -force -concatenate

>Invoke-Command -Computername $serverIP -ScriptBlock { C:\Tools\Setup.ps1 }
-Credential "~\Administrator"
The last command should prompt you for the Administrator password you first used when you created the VM. Enter this, and the setup.ps1 script should execute on the remote VM.
Once this script has executed, you should be able to view the published ASP.NET Core web application in your browser.

This will be accessible on the same IP address found by running
(Get-VMNetworkAdapter Nano1).IPAddresses[0], using port 8000

You can also view the default IIS startup page by just browsing to the IP address without the port number.

So as you can see, once the initial setup is done, the creation of new Nano servers with your deployed ASP.Net Core web application is very simple, and only takes a few minutes.

To save even more time, and as I'm a fan of automation, I've even condensed these PowerShell commands into a couple of scripts which are available on GitHub.

There are two scripts, Nano-Create.ps1 will create and start the VM, and Nano-Setup.ps1 will run the one-time setup of the VM. Both scripts will prompt for the Nano server name you wish to use.

Friday, 26 February 2016

Music player: The case

Over the past few weeks, I've been building a music player using a Raspberry Pi and a number of components to power and amplify the project.

In my last post, I completed the soldering I needed to do, and completed the circuit. There are still improvements that can be made to the system overall, but for now I've got a complete, working system. I just need to fit it into a case.

I've always liked the combination of old fashioned style and modern technology, and while browsing a vintage shop I came across an old Bush radio from the late 1950's.

The Bush DAC70

The model is a Bush DAC70 which was built in London around 1957. It only picks up Long-wave and Medium-wave transmissions, so in working condition would be fairly limited in what can be picked up with today's radio broadcasts, especially since I don't listen to LW or MW.

The inspection card found inside the case
This unit was not functional, but was only used to make a nice display in the shop. The light inside the dial worked, but the radio itself didn't work.
This wasn't a problem for me, since I only needed the case, and I know that to radio enthusiasts that destroying a perfectly functional radio would be a crime.
Since this unit isn't working, and I'm planning on restoring it in a fashion, so it can be used again, it feels a better use for the radio than just being sat unused on a display.


The case needed a bit of a clean, so I removed the back, and unscrewed the side-knobs so they could be removed. I removed the screws holding the central panel in the case in position, but found that it couldn't be removed easily. The front dial was connected to the tuner inside the case, so I'd have to disconnect this before I could take the components out.

The inside of the radio
I didn't want to break the front dial as the plastic seemed that it would be quite brittle, but with some gentle twisting and pulling I eventually managed to remove the dial in it's entirety from the tuning mechanism. With the dial removed, the rest of the components came out easily and I gave the case and the controls a good clean.

I used an old toothbrush and some soapy water to clean the dials I'd removed from the radio, and they looked much better. For the case itself, I just wiped this down with a damp cloth, there were quire a few cobwebs inside the case before I started cleaning so clearly it hadn't been cleaned in a while.

Case with dials removed and cleaned
With the parts of the case clean and dry, I first installed my speakers into the case. The existing speaker was a single, larger speaker which was fitted inside the left side of the case. I managed to use some of the existing mountings to attach my own speakers.

Inside of the case with new speakers fitted
I then needed something to attach my components to inside the case. I found a piece of old wooden shelf which was lying around and seemed to be about the right size. I had to trim and shape it slightly to make it fit properly in place of the previous metal centre panel.

With this fitted, I screwed my components to the inside of this to stop them moving around inside the case. I'd managed to pick up some small 2.5mm screws which were the right size to fit through the mounting holes of the Raspberry Pi and the other circuits.

The Raspberry Pi and components inside the case
With all the components installed, I checked the connections were fitted correctly, and powered up the radio. I'm still using the simple On/Off switch.

I connected to the Pi MusicBox browser interface from my phone. I also connected to the Pi using SSH from my pc, to check everything was running correctly.

Since the project is using a Raspberry Pi and it's built inside a Bush radio. I've decided to call it The Raspberry Bush.

The Raspberry Bush playing music using Pi MusicBox
I played some radio stations via the TuneIn radio feature of the software, and this seemed to work with no problems.
The volume is loud enough even with the relatively small speakers I used. The sound quality is also great, it might not be as good as a full Hi-Fi system, but for the size of the speakers I don't think it could really sound any better.
If I was to build a system with large speakers, then I expect the built in audio direct from the Pi wouldn't be good enough and I'd need an external DAC add-on, but for this setup it's perfect.


Using the Pi MusicBox software from a mobile phone

There's a number of improvements I plan to make, but for now the project is essentially complete.  It's a fully working system.

The original radio's dial was illuminated with a bulb, which looks really nice when it's working, so i'd like to recreate that by adding some LED's inside the dial. The LED's can be powered and controlled directly from the Pi, so they should be fairly straightforward to add.

I also want to restore the function of the volume control dial and create a better power switch. I'm planning on using a rotary encoder behind one of the dials to allow it to instruct the software to increase or decrease the volume, rather than using something like a variable resistor or potentiometer. This way the system only has a single volume which can be controlled via the software or the dial.
I plan to somehow mount the second dial so it can be used as a simple push switch to turn the system on. I don't have any plans for the front tuning dial currently.

I've mounted the charging circuit in a position where it cannot be very easily accessed at the moment, so I'd have to remove the back to charge it, or feed a micro USB cable through one of the gaps in the rear of the case. It's not a problem for now, but I'd like to improve this.

I also want to try out some different variations and configurations of software. I plan to try those out on my old Raspberry Pi until I've got a setup I'm happy with.

Overall, I'm very happy with the outcome of the project. It's the first project I've done of this type. I've not built any circuits since school, and not used the Raspberry Pi for anything more complicated than a simple media player connected to a TV.

I'd say that most people would be able to tackle a project like this, just be sure to do your research and take your time.

Sunday, 21 February 2016

Music player: Finalising the hardware

I'd tested out my breadboard prototype of the whole music player, and everything worked well. So I needed to do some final soldering to make the connections more permanent.

I didn't want to solder directly onto the Pi and I wanted the other components to be easy to remove in the event I wanted to make any changes to the setup of the hardware.


Making the connectors


I opted to use some of the breadboard jumpers I already had along with some AdaFriut Pig-Tail cables to make the pluggable wires I needed.

The power cable to the Raspberry Pi needed to be stable so it didn't come loose, to make this, I decided to use three female breadboard jumper connectors to make a three-pin connector. Only the first and third pin actually needed wires, the middle pin is just for stability.

Three breadboard jumper connectors
I super-glued the three connectors together to make one, more stable connector, and plugged it into some spare headers to allow it to dry.

The glued power connector
I also needed a two-pin power connection from the PowerBoost to the amplifier. For this I used one of the pig-tail connectors, and soldered this directly to the output USB connections on the PowerBoost so this could plug into the amplifier.

The PowerBoost and pig-tail cable
I needed a better way to connect the audio pig-tail cable to the amplifier. The audio cable connects to four pins on the amplifier board, so for this I created a four-pin cable, soldering the inner two pins to the ground of the audio cable, and the outer two pins separately to the L and R connections of the audio cable.

Soldering the audio cable


Raspberry Pi model A+


I decided to pick up a new Raspberry Pi model A+. I'd previously looked into the power consumption on the different models, and since I only had the old original B model I knew I could reduce the power consumption a reasonable amount by simply swapping to the model A+.

Since the model A+ doesn't have a network connection, and the project was intended to be wireless anyway, I ordered one of the official Raspberry Pi WiFi dongles. I know smaller dongles are available, but I selected this one hoping the larger size would give better WiFi reception. The physical size of the project wasn't my main concern, and since the official dongles are a good price and I know they are fully compatible, it seemed like a good option.

Raspberry Pi model B and model A+ (with WiFi dongle) side-by-side
I knew the model A+ would be smaller than the model B, but seeing the two side-by-side, it's still impressive to see how small these devices are.


Putting it all together


So with all the pieces built, I put the project back together without the breadboard.

Completed hardware. Battery disconnected
I plan to look into which software I want to use with the music player properly later on. I know there are a number of options available, but for now I'm using a basic install of Pi MusicBox.
Since this is easy to set up out of the box and the configuration can be done by changing a few settings in a text file on the SD card before you put it into the Pi, this seemed an easy way to get the WiFi working and music playing with minimal effort.

The completed project, playing music
The PiMusicBox software supports playing of music via multiple methods, but I tested it out with some music playing from an iPod over AirPlay.




For now, I am using a simple SPDT slide switch to control the power on and off, but I am working on a better solution for when the music player is installed into a case.

So that's the main soldering and circuit completed. Next, I plan to build the circuit into a suitable case.

Monday, 1 February 2016

Music player: First prototype

After purchasing the parts I needed from my previous post, my next task was to start building a prototype to test if they would all work together.

The PowerBoost and amplifier circuits would need some soldering before I could use them with my breadboard. I purchased a soldering iron in a starter kit from Amazon, which included a soldering iron stand and some helping hands to hold the component while it is being soldered. The kit also included pliers, solder and some tweezers. Everything I needed to get started.

I soldered the headers and jumpers into the amplifier, and the terminal blocks for the speakers.

MAX98306 Amplifier with soldered headers

I also soldered the headers onto the PowerBoost and some wires onto the power output to power the amplifier.

PowerBoost 500c with soldered headers and power wires

I also needed to solder some lengths of wire onto the speakers.

Speakers with soldered wires

I've not soldered since school, but it didn't take me long to get back into it. Some of the headers weren't perfectly straight, but the connection seemed solid enough.

With an the soldering complete, I assembled the prototype on the breadboard. I aligned a switch with the BAT, EN and GND pins of the PowerBoost on the breadboard, so I could turn the whole circuit on and off more easily. I connected the battery to the PowerBoost using the JST connector and tested that it powered on and off with the switch.

I then added the amplifier to the breadboard and connected the speakers. I temporarily connected the red, black and ground wires from the audio pigtail cable to some male-female breadboard wires, and plugged the red into the R+ pin on the amp and the black into the L+ pin. The ground needed connecting to both the R- and L- pins, so to achieve this I connected the ground from the pigtail to L- and bridged the L- and R- connections with another breadboard wire.

Completed amplifier prototype circuit
I set the amplifier jumper; then connected the two power wires from the PowerBoost to the amp. I initially tested the circuit by connecting the audio cable to a phone to play music. This will eventually connect to the Raspberry Pi, but the principle is the same with any audio device. I powered on the circuit and played some music on the phone.

It worked!

Prototype circuit playing amplified music from phone

The sound quality was impressive and at a reasonable volume. It sounded like it should be loud enough to work as a small music player in the corner of a room, like a small radio. It wouldn't replace a full HiFi system, but that wasn't my intention.

I then tested the circuit powering the Raspberry Pi as well as the as amp, by connecting a wire from the 5V pin on the PowerBoost to GPIO pin 2 on the Pi and from the GND pin on the PowerBoost to GPIO pin 6.

I also plugged the audio cable into the Pi, though I'm not testing the Pi audio here, just the power.

Raspberry Pi and amp powered from the PowerBoost and battery

I also connected the Pi to a monitor to check it was working. Turning the circuit on, the Pi booted normally, and displayed the Desktop on the monitor.

Raspberry Pi fully booted running on battery

Overall this was a successful test of all the parts required. I'd tested that the PowerBoost worked well running on battery, that the PowerBoost could power the amp and the Raspberry Pi, and that the amp played audio at a reasonable volume through the speakers.

The next stage is to make the wiring a little more permanent, removing the need for the breadboard. I'd still like to keep the circuit relatively modular, in case I decide to swap out any parts. I'm going to investigate a number of different options for semi-permanent connections, something like the battery's JST connector or the speaker terminal blocks would be good, but I'll see what I can find.

I'm also keeping in mind that I'd like to make the shutdown friendlier. Currently turning the circuit on is fine, but when it comes to turning off, the Pi ideally needs to be shutdown first, otherwise I'd risk corrupting the SD card. I'm not planning on storing any music on the SD card, so it would only be the OS I'd risk corrupting, which could easily be restored, but still it's not ideal.

So, some sort of method for safely shutting down the Pi before turning off the power would be ideal. If I could also detect a low battery and shutdown the Pi safely that would be even better.

I'll investigate these options and write about my findings in a future post.

Wednesday, 13 January 2016

Music player: Choosing the components

Continuing from my previous post, I'm building a music player using a Raspberry Pi.  This left me a number of things to consider:
  • How to power the project?
  • How to amplify the audio from the Pi?
  • How good would the sound quality be?

I'd seen a number of pre-built amplifiers which can be just plugged into the Pi, like the HiFiBerry AMP+. Using this would easily answer the second and third questions, as these are marketed as high quality audio products. This would also be easy to use, and could be powered by an external 12-18V power supply which would also power the Pi, also potentially answering the first question, but another factor I want to consider is cost.

The HiFi Berry Amp+

This amp costs just under £40, although it's not too expensive when you consider the price of an off-the-shelf streaming audio player. As this is a hobby project, I want to keep things small, simple and relatively inexpensive to start with, and potentially build up to something more powerful later.

As I'd mentioned previously, the Adafruit website has been invaluable for guides in how to use the components they sell and build circuits with them. One of the projects I found most useful was their Super Game Pi handheld games console, which was also built with the Raspberry Pi at it's core.

This project also answers some of my questions, the first two. It uses an amplifier circuit from Adafruit, which will essentially amplify anything with a headphone socket, and powers the amplifier and the Pi from a rechargeable battery and includes a circuit which handles the charging of the battery seamlessly.

This sounds ideal, a battery powered music player which can be plugged in via micro-USB to recharge it. Obviously the Raspberry Pi also uses the ubiquitous micro-USB for power, and I should be able to power the amp from the Pi, but having the ability to have the solution totally wireless was an appealing option.

The only unanswered question with this set-up would be the sound quality. The general opinion of the Raspberry Pi sound is that it is quite poor. I listened to music from the Pi over headphones and found that the quality seemed reasonable for what I'd need, providing amplifying this over speakers didn't sound any worse.

With these design decisions made, I found many of the items I'd need on Adafruit, but needed to order them from a UK stockist. Thankfully online stores like Pimoroni, Makersify, Pi Supply and Amazon stocked the items I needed.

This is the list of Adafruit components I ordered, or similar equivalents.


I already have an old Raspberry Pi model B which I am planning to use to prototype the project, but I am also considering that as the project is to be battery powered, keeping the power consumption down would be beneficial.

The newer Raspberry Pi A+ and B+ models have improved power management, and also use less power overall than the original model B. If my initial tests go well, I am planning on using a model A+ in my music player, as this has similar specs to my old model B, but is smaller and uses less power. The newer + models also boast improved sound quality, so this would also be an improvement.

According to RasPi.tv, the original model B uses around 360mA when idling, compared to around 100mA for the model A+.

With the 2500mAh battery I'm using, that could be as much as 25 hours of battery life, although when the music player is in use, I'd expect a greater power draw. If the music player is playing music over Wi-Fi, this will also draw more power.

RasPi.tv suggests that high processor usage (shooting 1080p video) uses 230mA, so even if my project used this much power, I could estimate around 10 hours of battery life. At the moment I don't know exactly how much power my project will draw, so currently these figures are nothing more than estimates.

I now have all the components I need to start building a working prototype. In my next post I will go into how I put this together.

Thursday, 7 January 2016

Starting something

I've taken an interest in the Raspberry Pi since it first launched, and have read a number of articles on possible uses and seen many interesting creations people have made with it.

I picked up one of the early model B editions of the Pi some time ago, and have done a small amount of tinkering with it, using it as a XBMC/Kodi/OSMC machine for watching videos, and trying out other similar applications. I always felt I should try a more ambitious project.

I didn't really need another device to play videos on, and have seen a number of really nice looking custom music players, so I started looking into the possibilities of creating my own.

I should start by mentioning that my electronics and soldering skills are fairly basic, so I wanted to start simple, with a view to adding to the project as I became more familiar and more confident with some of the electronics required.

Having read a lot about other peoples projects and how they had built them, I picked up an electronics starter kit for the Raspberry Pi.  The kit was aimed mainly at kids, but it had a solder-less breadboard, and a number of basic electronic components, wires, and instructions on building basic circuits, so thought this would be a good start.

Basic LED circuit controlled by the Raspberry Pi

I built some basic circuits with this kit, and as I'm a software developer I was happy enough hacking around with some of the python code to alter the function of the circuits slightly.
The projects are a good introduction to what can be achieved, but I mainly wanted the kit for the breadboard and the starter set of components and wires that should prove helpful when prototyping my music player.

Having gained a good idea of what I wanted to build and what components I'd need, I put a list together using Adafruit as a valuable resource for many of the components and also excellent guides on how to use the components and build projects with them.

I'll go into more detail on the components I'm using to build my music player in my next post.

Do a thing!

I've been considering for a while writing a blog, and a number of things recently have given me the push to finally start.

I've recently started a small electronics project, so I'll be writing about that soon, but really that was just a first article to get me started.

I'm a software developer by trade and have been for over 15 years. I read a lot of articles and blogs and have done a fair amount of training on the Internet. I've reached a point now where I've accumulated a fair amount of knowledge over the years and perhaps should start writing some of it down.

I also realised recently that I've not really started anything brand new for a while. I learn new things everyday as part of my job, but this is just an extension of things I already do, so here's something new.

Also, as I read a lot of blogs a lot of my knowledge and problem solving have come from other people's blogs, so perhaps one day my blog may impart knowledge to someone else learning something new.

It might inspire someone else to Do a Thing!


The design is basic to start with, and I'll tweak the design as I go, but I wanted to make a start and get something online, so here it is.