Building a Sonos Controller with Vue, an iPad and a Raspberry Pi – Introduction

sonos-controller-with-vue-ipad-and-raspberry-pi-version-on-ipad

I purchased a pair of Sonos Speakers and I’m in love, however it would be cool not to use my Phone to control them, but instead mount an iPad to my wall and be able to manage it from that. I’ve decided to purchase a Raspberry Pi Zero W and use our old iPad Mini (which was just collecting dust anyway), and built a simple dashboard with enough features to be useable.

Requirements

  • A tablet, capable of browsing the internet — iPad Mini in my case
  • Any device capable of running a Node server — Raspberry Pi Zero W in my case
  • A WiFi connection or similar
  • Sonos Speaker

Design

A late evening, I launched Sketch and started drafting the initial design, featuring my dog and some very basic functionality:

  • A play queue
  • Room selector
    • And volume for each room
  • Playback controls
  • Todays weather

Building a Sonos Controller with Vue, an iPad and a Raspberry Pi

Notes

Since designing this, and after building it, I’ve realized that 3 playback buttons on top makes no sense for people with more zones/rooms, so I’ve integrated the pause/play button directly into the room icon, and made switching song possible below each icon (below the volume slider). Screenshots will come.

Keeping You Posted

This was simply an introduction post, telling you about the project. I will create 2-3 blogposts more related to this, and finally share the source code when everything is done.

Signup below and select “Sonos Controller”, and I’ll promise only to notify you about posts related to this series.

I promise, that I'll keep your e-mail safe, and only send occasional e-mails. Opt-out is super easy as well.

Getting Started in Open Source – Contributing

aGetting Started in Open Source - Contributing

I love Open Source, contributing to it especially. To me, it gives me a great feeling inside, seeing my changes or additions being merged, which is my primary reason for contributing.

Getting started, however, is strangely hard. Where do I start? How do I know where to contribute? Will they roast me? How do I do it?

I’ll try to uncover some of the questions I initially had, hoping it might help you as well.

Getting Started in Open Source

Where to Start?

I’d recommend going to Open Source repositories that you already like and use, and look at the issues. Another thing you could do is browse the “first-timers-only” label on Github, which at the time of writing contains +800 issues in various languages. “up-for-grabs” is also decent. Another resource is MunGell/awesome-for-beginners.

Will They Roast Your Code?

People are different, and some are jerks, there’s nothing to do about it.. sadly. However usually it’s unlikely that anyone will be aggressive towards you for contributing, even for small things. I’ve for example fixed a lot of readme files (minor typos) and people always respond positively about it.

You can however attempt to avoid assholes by browsing the “first-timers-only” label (people are genuinely friendly there), and follow any contribution guidelines the repository might have. If you follow their guidelines, they have absolutely no reason to be snarky.

How to Actually Contribute?

I’ll focus on pull requests, meaning actually changing the repository. A pull request is a request to change something in the code, or another file. Depending on the size of your change, there’s two typical ways of moving forward.

Edit Files Directly on Github with Forks

Browse the Git repository, and find the file you want to change. There will be a pencil icon, which will create a Fork, and open up an editor view.

Creating a Fork and Editing Files

Make your changes, and click the “Propose file change” button below, and follow the few steps to create a pull request, consider checking the box “allow edits from maintainer”, so that the maintainer(s) can edit the code in case they have some minor changes.

Cloning the Repository

Find the Open Source repository you plan to modify, and locate the “Fork” button, top right.

Fork Open Source Repository

You will now have a forked version of the repository, you can do with this as you please (respecting the license of the original repository!) Changes made are not visible in the original repository. You can now edit files directly in Github (as above) and create a pull request when you’re done. You could also clone your fork, and edit it in your favorite code editor.

Clone or Download Open Source Repository

I’ll clone using Git in my terminal:

git clone GIT_URL

Cloning using Git

You can now open the freshly created directory in your IDE or code editor, and make changes. When you’re done, you should commit your changes:

git add README.md
git commit -m "Your commit message, e.g.: Fixed typo in README"
git push origin master

Open up the fork on Github, and create a pull request.

New pull request in Open Source

Remember to add descriptive messages, and for visual changes add some before and after screenshots (recommended to me by Joanne, make your pull requests visual for frontend changes)

Where to Help, and What to Do?

Of cause, Github issues are low-hanging fruits, but simple things like fixing a typo in the README file, or even adding a new feature are things you can do. Writing some more tests can rarely ever hurt. Try increasing code coverage.

Not sure how to write good tests? Try the video course “Test Driven Laravel“.

Another thing is look for “Failing” badges on the readme, e.g. “StyleCI: Failing”, click it and find the reason for it failing.

Alternatives to Contributing

An other way of helping Open Source maintainers is reporting bugs, or even supporting them financially through Patreon or Open Collective (Example: Preact).

You Don’t Have To Contribute

Contributing to Open Source is far from necessary to work as a developer, but it can work as practice for working in teams, or just improving your skills. If you use a lot of Open Source libraries in your work, you should consider giving back in some manner.

Making PHPUnit Amazing with Emojis

PHPUnit is great as is, but what if you could replace the ordinary dots and letters, with emojis?! I know you want to.

Coderabbi, Yitzchok Willroth, has created a project that goes under the name “phpumoji“, which does this exact thing. You can even customize the emojis, and I’ve heard he’s working on more customizability. It’s hard not to love it.

You can check out phpumoji here.

It’s quite amazing.

To be honest, I’d probably not use it for large test suites (I can already imagine 2000 emojis flooding my console.. Lol.. Maybe I should 🤔)

However, when doing some smaller projects, I’d probably find myself setting this up, to make testing visually cooler.

Emoji in PHPUnit

Images stolen directly from Coderabbi’s Twitter.

Test-Driven Development (TDD) and Laravel – the Definitive Video Course

Test-Driven Development - Test-Driven Laravel

I’ve never been good at writing tests, I mean.. I was horribly bad at writing real tests. Sure, I knew how to write a test that ensured that a User model had a email attribute, but not actually real-world tests. Also, I’ve underestimated tests a lot:

Which I shouldn’t have, testing is the most efficient to ensure that your code works, after a large refactor or a new feature.

I’m sharing this because I think there are a lot of people like myself, that aren’t really writing real-world tests, but instead writes no tests, or useless tests.

Test-Driven Laravel, by Adam Wathan

Adam, has created this amazing video course where he goes from nothing to final product, doing it entirely by the TDD principle. You’ll be creating a ticket-platform (TicketBeast) in Laravel, which is of cause fully tested. Interestingly, I also learned some great concepts and methods for creating applications through watching this.

My favorite part of the courses, is the way Adam describes how to continue forward, in a manner that makes sense; even for someone who might not be as experienced in testing.

You will be granted access to a very active GitHub repository, containing the entire project, should you want to look at the final code.

This course is still in early access, which means its still under development, hence more content is added over time.

It may not be for you, but you can get a preview of the course, before spending any money, to decide if you’ll benefit from it.

Go grab the course

Final thoughts

I’m not done watching this course (how could I, it has not been completed.) and I’m learning something in almost every episode. Currently, I’m building a larger application, and before this course it had no tests at all. Now, almost every endpoint, event and command is fully tested. I’m not working towards 100% code coverage, but if I did, I’d almost be done soon.

This is somewhat of a odd post, usually I wouldn’t just be advertising products, this course however.. really worth it.

Note: This is NOT sponsored. I just really like the course.

Great Tech Podcasts and Blogs

Great Tech Podcasts and Blogs

Whenever I go for a walk with my dog, I tend to pull out my phone, and listen to different tech podcasts (Usually Five-Minute Geek Show with Matt Stauffer, link below). However I often find it difficult to find great podcast about stuff that I care about. The discovery-features in iTunes/Podcasts on iOS really does nothing for me, haven’t found a single thing that I wanted to listen to. I’ve decided to create a collection here, and keep it somewhat updated as I discover more sources.

Tech Podcasts

Five-Minute Geek Show, by Matt Stauffer

If you’re interested in anything geeky, this is for you. Matt talks about business, personal health, development, community, workplaces and so much more. It’s my go-to source for mind-changing thoughts.

Full Stack Radio, by Adam Wathan

Interested in building great software products? This is for you. Hosted by Adam Wathan, this podcast is about product design, UX, unit testing and more. He’s joined by guests to talk about the subjects that they know best. You should really check this one out!

The Laravel Podcast, by Matt Stauffer

Another one by Matt, co-hosted by the creator of Laravel (Taylor Otwell) and Jeffrey Way, creator of Laracasts. Sitting at +50 episodes, with great guests and a length of usually +45 minutes, you can get some great insight, primarily about Laravel.

Bootstrapped, by Ian Landsman & Andrey Butov

+90 episodes of software bootstrapping and interesting guests, whats not to love? If you’re remotely interested in business strategies, startups, tech, development and similar topics, this is something I’d recommend you check out.

Dev Discussions, by Shawn McCool

Don’t let the amount of episodes scare you away from listening, this is still a great source of content related to primarily web development.

PHP Roundtable, by Sammy Kaye Powers

I really dig this format, because it features so many sources of input. You can easily find episodes featuring 3, 4 and even +5 guests. This is everything PHP, mixed with great guests and long episodes. Its amazing! They put it best themselves:

The PHP podcast where everyone chimes in.

Tech Blogs

Laravel News, by Eric L. Barnes

For anyone using Laravel, this is a absolute must to follow and read. It’s the official news site for Laravel. The content is great, created often and you won’t need to look for Laravel related news anymore if you subscribe to their newsletter.

Laravel Daily, by Web Coder Pro

Okay, I’m a little biased towards Laravel, I’m sorry. But this is another great source for Laravel related content. I’m aware that its a company rather than just a blog, but  this site has a lot of great tutorials for Laravel and PHP in general. +100 (~9*21 pages) articles and they keep on coming.

Matt Stauffer’s Blog

I’ve already featured something by Matt (Five-Minute Geek Show) and it’s hard not to also give his blog a visit, especially if you’re into Laravel. Most of the content is based on Laravel, and its mostly tutorials and news.

Adam Wathan’s blog

Adam Wathan is the creator of the TDD Laravel course, the Refactoring to Collections book and videos, and host of the podcast Full Stack Radio (also featured above). If you’re interested in getting better at writing tests, this is absolutely the place to start.

Taylor Otwell on Medium

Taylor, the creator of Laravel, shares some great content about Laravel, PHP and related. You can get the latest news about Laravel directly from the creator himself and generally pick his mind, whenever he shares content about his thoughts and new releases.

Final thoughts

To me, podcasts in particular, can be a great learning platform. Not for deep and heavy content, but for insight and thoughts. It’s a great way to get some information about a subject, from another perspective.

Have any recommendations for a source of great content? Shoot a comment, or tweet me @lasserafn, and I’ll look into adding it here. Thanks!

Speeding up Laravel in Simple Steps

Speeding up Laravel in Simple Steps

Speeding up Laravel applications can be done fairly simple. This guide will only cover the absolute surface and won’t dig deep into specific applications.

Using Cookie for Sessions Instead of Files

Changing a config/environment variable can improve web-performance a bit. It’s very different depending on your site, but usually I’ve found that it gave a little boost. It’s quite fast to switch your session driver:

  1. Open up your .env file
  2. Find the SESSION_DRIVER
  3. Change it to `cookie` Like so:
SESSION_DRIVER=cookie

So, Why Does Using Cookies Instead of Files, Boost Performance?

Reading from cookies is usually way faster than reading from a file.

Cookies and Assets

Another thing to think about, if you’re interested in shaving off every millisecond possible, is serving assets (images, js, styles,..) from a cookieless domain; hence serving your assets from another domain, where you’re not using cookies.

Remember if you’re using Google Analytics, it may a cookie for subdomains as well.

Benchmarks

I’ll be using a local site, completely fresh Laravel instance (with a logged in user, reading from and writing to the session), and the following command to benchmark:

ab -n 1000 -c 25 "http://laravel-file-vs-cookie.dev/"

File

Concurrency Level:      25
Time taken for tests:   15.264 seconds
Complete requests:      1000
Requests per second:    65.51 [#/sec] (mean)

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:    80  377  45.5    366     537
Waiting:       80  377  45.5    366     537
Total:         81  377  45.4    366     537

Cookie

Concurrency Level:      25
Time taken for tests:   13.880 seconds
Complete requests:      1000
Requests per second:    72.05 [#/sec] (mean)

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:    77  343  26.7    342     477
Waiting:       77  343  26.7    342     477
Total:         78  343  26.7    342     478

Difference

Of cause, as mentioned, results may vary. However, looking at the results above, we we’re able to server ~6.54 requests more per second.

Route and Config Cache

Another way to boost performance is using config and route caching. But please be aware, you can only cache routes if all routes point to a controller.

  1. Locate your project root in your terminal.
  2. Type in php artisan config:cache
  3. And php artisan route:cache

Benchmarks

I’ve setup another application with 10 resource controllers and did not touch anything else.

I’ll be using a variation of the same command as before (pointing to one of the controllers.

ab -n 1000 -c 25 "http://laravel-route-config-cache.dev/posts"

Before

Concurrency Level:      25
Time taken for tests:   16.139 seconds
Complete requests:      1000
Requests per second:    61.96 [#/sec] (mean)

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:    79  399  52.1    390     581
Waiting:       79  399  52.1    390     581
Total:         80  399  52.1    390     581

After

Concurrency Level:      25
Time taken for tests:   11.931 seconds
Complete requests:      1000
Requests per second:    83.81 [#/sec] (mean)

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:    58  295  45.5    287     531
Waiting:       58  295  45.5    287     531
Total:         59  295  45.4    287     531

Difference

Remember, results may vary a lot, however again, we see a difference. This time, we were able to handle ~21,85 more requests per second, which I’d say is worth it.

The reason for the large difference, is mainly that routes are expensive, they’re heavy to generate, and if they’re not cached; will generate on each request.

Remember, to change your config or routes afterwards, you’ll have to use these commands:

php artisan route:clear
php artisan config:clear

Artisan Optimize

You can also use php artisan optimize which will optimize your class loader and generally just optimize your application a bit. It likely won’t provide a huge boost, but its work trying.

I won’t be showing a benchmark for this, as I could not see any real difference for a clean installation of Laravel. You should experiment with this, but its unlikely to provide a negative result.

Speeding up Laravel Even Further

I will be creating more posts regarding Laravel and performance, so stay tuned, however meanwhile you could checkout this video course: Performant Laravel, by Chris Fidao, which covers these tips, and much more.

Validating Max Length in Laravel – Also for Integers and Digits

Validating Max Length in Laravel

I recently figured that Laravel does not have a validation rule for max length. Sure, you could use “max”, but if you also use the “integer” validation, this will cause “max” to be the max value, not length.

I recently tweeted this:

It’s quite simple, you specify a custom validation rule that checks the length of the value.

Add this to your service providers (Eg. AppServiceProvider) boot() method

\Validator::extend( 'maxlength', function ( $attribute, $value, $parameters, $validator )
{
   return mb_strlen( $value ) <= (int) $parameters[0];
} );

Validation messages

You’ll probably want to have a fitting validation message as well, which is also quite simple. First, you’ll want to add another block of content to your boot() method.

\Validator::replacer( 'maxlength', function ( $message, $attribute, $rule, $parameters )
{
   return str_replace( ':maxlength', $parameters[0], $message );
} );

And in your resources/lang/{LOCALE}/validation.php file, add this line to the first level of the array:

'maxlength' => 'The :attribute field may not be more than :maxlength characters of length.',

Of cause, you can fit this to your liking. Doing this, will return something like:

The number field may not be more than 10 characters of length.

Final thought

To me, this should be core functionality, and I might also submit a PR for this, but until then, using a custom rule is a great solution.

More useful snippets

If you’re interested in great snippets, not only for Laravel, but also Vue, JavaScript, PHP and much much more, you should checkout Tweetsnippet, a curated collection of snippets from tweets.