<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://edwinjones.me.uk/feed.xml" rel="self" type="application/atom+xml" /><link href="https://edwinjones.me.uk/" rel="alternate" type="text/html" /><updated>2026-05-22T13:35:36+00:00</updated><id>https://edwinjones.me.uk/feed.xml</id><title type="html">Edwin Jones</title><subtitle>My personal website &amp; blog</subtitle><entry><title type="html">Gdc Adventures</title><link href="https://edwinjones.me.uk/gdc-adventures/" rel="alternate" type="text/html" title="Gdc Adventures" /><published>2026-05-22T00:00:00+00:00</published><updated>2026-05-22T00:00:00+00:00</updated><id>https://edwinjones.me.uk/gdc-adventures</id><content type="html" xml:base="https://edwinjones.me.uk/gdc-adventures/"><![CDATA[<p>I’ve been in the industry a long time but I have to say working on <a href="https://www.fallguys.com/">Fall Guys</a> was a dream come true in that we didn’t predict how big it would become and it smashed our wildest expectations.</p>

<p>Another long term dream of mine was 
to present at GDC. In 2024 I did exactly that with a talk about <a href="https://media.gdcvault.com/gdc2024/Slides/GDC+slide+presentations/Jones_Edwin_Terminal_Velocity_Lessons.pdf">backend services on Fall Guys</a> during 
our launch window and beyond.</p>

<p>If you fancy learning more about how to handle scaling for large amounts of players with a real life use case, please take a look at
those linked slides or watch the talk if you have <a href="https://gdcvault.com">GDC vault access.</a></p>]]></content><author><name></name></author><summary type="html"><![CDATA[I’ve been in the industry a long time but I have to say working on Fall Guys was a dream come true in that we didn’t predict how big it would become and it smashed our wildest expectations.]]></summary></entry><entry><title type="html">Steam Powered - Make your own Linux based gaming console</title><link href="https://edwinjones.me.uk/steam-powered/" rel="alternate" type="text/html" title="Steam Powered - Make your own Linux based gaming console" /><published>2023-09-22T00:00:00+00:00</published><updated>2023-09-22T00:00:00+00:00</updated><id>https://edwinjones.me.uk/steam-powered</id><content type="html" xml:base="https://edwinjones.me.uk/steam-powered/"><![CDATA[<p>I’ve been mulling moving over to <a href="https://en.wikipedia.org/wiki/Linux">Linux</a> full time for personal gaming use for quite a few years but since I got my <a href="https://store.steampowered.com/steamdeck">Steam Deck</a>
 last year, I’ve realised it’s perfectly viable now thanks to <a href="https://github.com/ValveSoftware/Proton">Proton.</a> Problem is, the Steam Deck isn’t quite powerful enough for my 4K 
TV in the living room and <a href="https://www.valvesoftware.com/en/">Valve</a> don’t actually release a desktop version of <a href="https://en.wikipedia.org/wiki/SteamOS">SteamOS</a> 
anymore. After a bit of 
searching I found that most of the popular mainstream desktop distros like <a href="https://ubuntu.com/blog/what-is-an-ubuntu-lts-release">Ubuntu LTS</a> are months to years behind 
the latest driver updates needed to run most games on launch and as such aren’t always the best choice either.</p>

<p>This left me with a few options:</p>

<ol>
  <li>Build my own <a href="https://archlinux.org/">Arch Linux</a> install with <del>blackjack and hookers</del> the latest updates.</li>
  <li>Use a gaming distro like HoloISO or ChimeraOS.</li>
  <li>Use a <a href="https://itsfoss.com/rolling-release/">rolling distribution</a> like Manjaro or openSUSE Tumbleweed to take the heavy lifting away.</li>
</ol>

<p>I opted out of option one as it seemed like a time sink. I did indeed try option 2 for a while but I chose 
<a href="https://chimeraos.org/">ChimeraOS</a> 
over <a href="https://github.com/HoloISO/holoiso">HoloISO</a> 
as it A) predates the Steam Deck/modern SteamOS incarnations and B) is more regularly updated than 
HoloISO. This worked pretty well for a while until Resident Evil 4 hit and I got the wonderful black square issue:</p>

<p><img src="/images/rantimages/RE4Issues.jpg" alt="Resident Evil 4 Bug" /></p>

<p>Urgh. That was actually caused by
<a href="https://steamdeckhq.com/tips-and-guides/how-to-fix-graphical-issues-in-the-re4-demo/">an issue with Mesa</a> that required
 an update. Neither Valve or the Chimera OS team released this for a little while but 
as soon as I upgraded, I ended up getting <a href="https://github.com/ChimeraOS/chimeraos/issues/516">this bug</a> and could 
only boot into a black screen. I chatted to the devs on their discord and they were super friendly but they couldn’t 
figure out my issue and I gave up.</p>

<p><em>NB I did try manually updating <a href="https://www.mesa3d.org/">Mesa</a> before upgrading but on an <a href="https://itsfoss.com/immutable-linux-distros/">immutable OS</a> like ChimeraOS this is difficult and such changes are often overwritten during updates anyway.</em></p>

<p>That left option 3. I wasn’t happy with some of <a href="https://github.com/arindas/manjarno">Manjaro’s known issues</a> and 
I wanted the option to use <a href="https://wiki.archlinux.org/title/Unified_Extensible_Firmware_Interface/Secure_Boot">secure boot</a> if I needed, which left <a href="https://get.opensuse.org/tumbleweed/">openSUSE Tumbleweed.</a> 
As a version of openSUSE with 
snapshotting and fast updates, it seemed the best bet. I installed it with <a href="https://www.gamingonlinux.com/2022/10/kde-steam-deck-akademy-2022/">KDE to mimic the Steam Deck’s desktop</a> 
and away I went.</p>

<p>So I finally had installed a Linux distro that could run my games well without issue but how could I make this more console like? The first thing I did was set Steam up to boot 
into <a href="https://help.steampowered.com/en/faqs/view/3725-76D3-3F31-FB63">“Big Picture” mode.</a> 
This has had a revamp and is now much more like the Steam Deck gaming mode layout but misses a few 
things - you don’t get <a href="https://wiki.archlinux.org/title/MangoHud">MangoHud</a> out of the box for instance.</p>

<p>Once I had that, I needed to make sure I could use the PC without getting up off the sofa. I updated the firmware on 
my <a href="https://www.xbox.com/en-gb/accessories/controllers/xbox-wireless-controller#white">Xbox controller</a> 
and <a href="https://www.xbox.com/en-GB/accessories/headsets/xbox-wireless-headset">Xbox wireless headset</a> then connected them <a href="https://en.opensuse.org/Bluetooth">manually via bluetooth.</a> I then configured 
<a href="https://en.wikipedia.org/wiki/Wake-on-LAN">Wake on Lan</a> 
so the PC could be remotely activated as long as it had a wired ethernet connection. I use an iPhone app called 
<a href="https://apps.apple.com/us/app/wake-me-up-wake-on-lan/id1465416032">“Wake me up”</a> to 
send the magic wake up packet to my <a href="https://www.pcmag.com/encyclopedia/term/broadcast-address">network broadcast address</a> 
which works like charm.</p>

<p>I then manually installed MangoHud and used <a href="https://github.com/benjamimgois/goverlay">GOverlay</a> 
to globally enable it but set it to hide by default. I set 
the “toggle” key to F1. I then configured Steam to change the share button on my Xbox controller to actually send 
and F1 key press and voila, a basic Steam Deck like performance overlay feature is bodged into my configuration. This is 
useful when tweaking settings to get the best performance as my RX 6700 GPU isn’t quite good enough for 4k at max 
settings for most new games.</p>

<p>I was mostly there and switching between my homebrew console and the Steam Deck without issue via <a href="https://help.steampowered.com/en/faqs/view/68D2-35AB-09A9-7678">Steam Cloud</a> but I 
suddenly noticed something odd - sometimes some games would crash to the Steam UI without warning but not on the Steam Deck, 
only my desktop PC. After a bit of reading I realised that I had to boost the 
<a href="https://www.phoronix.com/news/Fedora-39-VM-Max-Map-Count">vm.max_map_count setting</a> manually to make sure gaming processes 
didn’t crash when trying to use more memory maps than expected. This solved the problem and made me feel chuffed that I 
had fixed it myself without giving up again and hopping to a new distro.</p>

<p>I was almost there. The final problem was anytime I wanted to run updates or configure anything non gaming related I had to 
plug in a keyboard and sit by my TV which was annoying. The solution was simple: 
<a href="https://en.wikipedia.org/wiki/Virtual_Network_Computing">VNC!</a> I used <a href="https://remmina.org/">Remmina</a> 
as a client from my Ubuntu laptop. I did have to manually add a firewall exception for VNC via 
<a href="https://yast.opensuse.org/">YaST</a> which is an openSUSE tool I’d never used before but after that everything just 
worked. I’ve not needed to plug anything directly into the PC since; It just sits on the floor by the TV without
a care in the world other than the odd dust cleaning session now and then.</p>

<p>Finally, I had it - a working Linux gaming console that gets some updates faster than 
a Steam Deck does. I’ve had no compatibility issues with it either as anything the Steam Deck can run will run here as well. 
The joy of Linux means hardware upgrades are simply plug and play as long as my <a href="https://en.wikipedia.org/wiki/Linux_kernel">kernel</a> is up to date. With openSUSE tumbleweed 
this is a given as long as I remember to apply the updates themselves now and then.</p>

<p>Would I recommend this for everybody? No. Is it perfect? Far from it, I’d prefer a real desktop Steam OS release from 
Valve, but I think we all know not to wait for Valve to do things if they haven’t announced them fully by this point.
I don’t have the same ability to lock the framerate or set scaling options as you do on a Steam Deck due to not using 
<a href="https://github.com/ValveSoftware/gamescope">gamescope</a>. 
My MangoHud hack works but isn’t easily configurable while in a game like it is on a deck. Sometimes I 
get bugs that just don’t happen on the deck because I’m using an entirely different distro although like a deck I can 
“roll back” to an earlier snapshot should I need to.</p>

<p>All that aside, if you like your Steam Deck but want to game on something a bit beefier with a discrete card without leaving the Linux 
ecosystem I can heavily recommend this approach. I hope this helps you find a new way to play your PC games. The 
best part? All of this software is 100% free and most of it is open source. The year of the linux desktop is finally 
here - <em>sort of.</em></p>]]></content><author><name></name></author><summary type="html"><![CDATA[I’ve been mulling moving over to Linux full time for personal gaming use for quite a few years but since I got my Steam Deck last year, I’ve realised it’s perfectly viable now thanks to Proton. Problem is, the Steam Deck isn’t quite powerful enough for my 4K TV in the living room and Valve don’t actually release a desktop version of SteamOS anymore. After a bit of searching I found that most of the popular mainstream desktop distros like Ubuntu LTS are months to years behind the latest driver updates needed to run most games on launch and as such aren’t always the best choice either.]]></summary></entry><entry><title type="html">Games Boy - Write your own Game Boy games in C</title><link href="https://edwinjones.me.uk/games-boy/" rel="alternate" type="text/html" title="Games Boy - Write your own Game Boy games in C" /><published>2022-05-24T00:00:00+00:00</published><updated>2022-05-24T00:00:00+00:00</updated><id>https://edwinjones.me.uk/games-boy</id><content type="html" xml:base="https://edwinjones.me.uk/games-boy/"><![CDATA[<p>The game boy was my first personal home console back in the early 90s and perhaps the console that cemented my 
love of games in general. I’ve always dreamed of writing a game for it 
and now it seems I (sort of) have.</p>

<p>I’ve been playing around with the <a href="https://github.com/gbdk-2020/gbdk-2020">GBDK</a> for a while now and have managed to summarise my learnings in an article 
for Wireframe magazine. You can find the first part <a href="https://archive.org/details/Wireframe62/page/50/mode/2up">here in issue 62</a> and the second <a href="https://archive.org/details/Wireframe63/page/50/mode/2up">here in issue 63.</a> Both parts start on page 50 of their respective issues.</p>

<p>I’d like to add to the article with a little personal special thanks section. All these people and more helped me build 
what I hope is an interesting and informative read for you:</p>

<ul>
  <li><a href="https://twitter.com/ryanlambie">Ryan Lambie</a> for being an amazing person and editor.</li>
  <li><a href="https://www.youtube.com/watch?v=FzPTK91EJY8">MVG</a> and his handy GB coding quickstart.</li>
  <li><a href="https://www.gamedeveloper.com/programming/making-a-game-boy-game-in-2017-a-quot-sheep-it-up-quot-post-mortem-part-1-2-">Dr Ludos</a> with his GB game making guide.</li>
  <li><a href="https://videlais.com/2016/07/03/programming-game-boy-games-using-gbdk-part-1-configuring-programming-and-compiling/">Dan Cox</a> with his GBDK guide.</li>
  <li>The GB dev community in general for countless amazing tools like GBDK, sprite editors etc.</li>
</ul>]]></content><author><name></name></author><summary type="html"><![CDATA[The game boy was my first personal home console back in the early 90s and perhaps the console that cemented my love of games in general. I’ve always dreamed of writing a game for it and now it seems I (sort of) have.]]></summary></entry><entry><title type="html">SSH Agent Man - How does SSH agent work?</title><link href="https://edwinjones.me.uk/ssh-agent-man/" rel="alternate" type="text/html" title="SSH Agent Man - How does SSH agent work?" /><published>2022-02-18T00:00:00+00:00</published><updated>2022-02-18T00:00:00+00:00</updated><id>https://edwinjones.me.uk/ssh-agent-man</id><content type="html" xml:base="https://edwinjones.me.uk/ssh-agent-man/"><![CDATA[<p>I’ve been using <a href="https://en.wikipedia.org/wiki/Secure_Shell">SSH</a> for quite a while now and have used <a href="https://www.atlassian.com/git/tutorials/git-ssh">SSH keys</a> regularly to authenticate myself with
a variety of systems both at work and at home. I historically have been a bit lazy and avoided using passwords 
for my private keys to avoid having to remember said password and type it in every time. Eventually I learned 
of <a href="https://en.wikipedia.org/wiki/Ssh-agent">SSH Agent</a> - a tool that allows you to type your SSH password in once per session to save on repetitive password entry by storing the decrypted value of the key in memory for easy access.</p>

<p>Generally wherever I’ve installed SSH agent I tend to use some fire and forget scripts so I don’t actually follow along or remember exactly how it works, just what it does. That changed recently at work as I’ve been trying to use <a href="https://docs.microsoft.com/en-us/powershell/scripting/overview?view=powershell-7.2">Powershell</a> more at work on <a href="https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux">WSL2</a> so script snippets I learn and share around are more user friendly for my colleagues and friends on Windows systems. This lead to a bit of a snag as it didn’t have an obvious way to make SSH Agent work and I couldn’t figure out why. As I didn’t know of any simple tools to 
get things running I put my detective hat on and went to work.</p>

<p>My first step was to compare the environments of my usual daily driver shell, <a href="https://fishshell.com/">fish</a> and Powershell to see if I was missing anything obvious and it turns out I was - my powershell sessions were missing two crucial environment variables my fish shell had: <code class="language-plaintext highlighter-rouge">$SSH_AUTH_SOCK</code> and <code class="language-plaintext highlighter-rouge">$SSH_AGENT_PID</code>. If I added 
these variables to my <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-7.2#the-profile-variable">$PROFILE</a> file and started a new session everything worked normally. Without them I was still having to add my password in every time I wanted to use my SSH key. Stranger still, when I rebooted my system and went straight into a powershell session I was right back where I started and had to enter my password every time. I also noticed that when I kicked off a new fish shell session that the values of both these environment variables had changed.</p>

<p>I floundered a bit at first and tried to see if manually running <code class="language-plaintext highlighter-rouge">ssh-agent</code> would fix things - instead I just saw some strange output in the terminal. I did however notice that a new ssh agent process had started and things began to click a little. My next step was to look deeper into my fish configuration to see if I could figure out exactly what it was doing. Here I found out I’d installed <a href="https://github.com/ivakyb/fish_ssh_agent">fish_ssh_agent</a> and noticed it had easily accessible source code so I took a look at exactly what it was doing:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>function __ssh_agent_is_started -d "check if ssh agent is already started"
   if begin; test -f $SSH_ENV; and test -z "$SSH_AGENT_PID"; end
      source $SSH_ENV &gt; /dev/null
   end

   if test -z "$SSH_AGENT_PID"
      return 1
   end

   ps -ef | grep $SSH_AGENT_PID | grep -v grep | grep -q ssh-agent
   #pgrep ssh-agent
   return $status
end


function __ssh_agent_start -d "start a new ssh agent"
   ssh-agent -c | sed 's/^echo/#echo/' &gt; $SSH_ENV
   chmod 600 $SSH_ENV
   source $SSH_ENV &gt; /dev/null
   true  # suppress errors from setenv, i.e. set -gx
end


function fish_ssh_agent --description "Start ssh-agent if not started yet, or uses already started ssh-agent."
   if test -z "$SSH_ENV"
      set -xg SSH_ENV $HOME/.ssh/environment
   end

   if not __ssh_agent_is_started
      __ssh_agent_start
   end
end
</code></pre></div></div>

<p>It was a bit hard to parse at first but I could tell that it was checking if ssh-agent had been run and if not, starting it and storing the terminal output of the command in the environment variables I mentioned earlier. I couldn’t quite understand exactly what it was doing in a few places - what was <code class="language-plaintext highlighter-rouge">$SSH_ENV</code>? Why was it passing the <code class="language-plaintext highlighter-rouge">-c</code> flag to ssh-agent? It turns out both had simple answers. <code class="language-plaintext highlighter-rouge">$SSH_ENV</code> was resolving to <code class="language-plaintext highlighter-rouge">/home/username/.ssh/environment</code> - a simple text file. The script was invoking ssh-agent with the <code class="language-plaintext highlighter-rouge">-c</code> flag to force output to print in a simpler manner which according to the <a href="https://en.wikipedia.org/wiki/Man_page">man page</a> means to <em>Generate C-shell commands on stdout.</em> I wasn’t entirely sure what this meant but I could see that the output went from something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>SSH_AUTH_SOCK=/tmp/ssh-hyn2bsayp8Ot/agent.38600; export SSH_AUTH_SOCK;
SSH_AGENT_PID=38601; export SSH_AGENT_PID;
echo Agent pid 38601;
</code></pre></div></div>

<p>to</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>setenv SSH_AUTH_SOCK /tmp/ssh-myYdPLcMCmBn/agent.38914;
setenv SSH_AGENT_PID 38915;
echo Agent pid 38915;
</code></pre></div></div>

<p>Finally, I noticed it was using <a href="https://en.wikipedia.org/wiki/Sed">sed</a> to comment out the <a href="https://en.wikipedia.org/wiki/Echo_(command)">echo</a> command that would otherwise print the process id of the running instance of ssh agent to the screen each time that part of the script ran.</p>

<p>I was almost there, but I couldn’t quite figure out how fish was taking this output and using it. I finally twigged that it was <a href="https://superuser.com/questions/46139/what-does-source-do">sourcing</a> the environment text file as script, exporting those environment variables to the current session.</p>

<p>It all made sense. The script was using the environment file to check if it had been run before. If it had it checked to see if the process id recorded in the script was currently in use. If it wasn’t it ran ssh-agent and exported the output to the current session. If was, it exported the existing variables in the file. This meant that anything trying to use ssh agent in a shell session could know what socket ssh-agent was already listening to and communicate with it. This would allow use of the decrypted ssh key any time it was required.</p>

<p>I was almost there. The next step was to make it work in powershell where bash style commands don’t always work. I took the brute force approach of rewriting the script and sticking it into my $PROFILE file like so:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Stick this in your "$profile" file.
# Rough explanation of ssh-agent output here: http://blog.joncairns.com/2013/12/understanding-ssh-agent-and-ssh-add/
# Note, https://github.com/ivakyb/fish_ssh_agent/blob/master/functions/fish_ssh_agent.fish takes a similar approach.

# Resolve SSH agent details by starting ssh-agent if it's not already running
# and storing current run details in $HOME/.ssh/environment
$environmentfile = "$HOME/.ssh/environment"
if(Test-Path -path $environmentfile -pathtype leaf)
{
  Write-Output "ssh agent file exists"
}
else
{
  Write-Output "creating ssh agent file"
  ssh-agent -c | Select-Object -first 2 | Out-File $environmentfile
}

$sshdetails = Get-Content $environmentFile
$env:SSH_AUTH_SOCK = $sshdetails[0].split(' ')[-1].split(';')[0]
$env:SSH_AGENT_PID = $sshdetails[1] -replace "[^0-9]" , ''

if(-not (Get-Process -id $env:SSH_AGENT_PID -ea silentlycontinue))
{
  Write-Output "updating ssh agent file"
  ssh-agent -c | Select-Object -first 2 | Out-File $environmentfile
  $sshdetails = Get-Content $environmentfile
  $env:SSH_AUTH_SOCK = $sshdetails[0].split(' ')[-1].split(';')[0]
  $env:SSH_AGENT_PID = $sshdetails[1] -replace "[^0-9]" , ''
}
</code></pre></div></div>

<p>Hopefully you can see the script is doing mostly the same as the fish equivalent but with a few extra steps. To get the socket value I split the first line of the ssh agent output to find the right token. To find the process id I just use a <a href="https://en.wikipedia.org/wiki/Regular_expression">regex</a> to strip out everything on the second line that’s not a number. I only take the first two lines of the output so I don’t need to do anything funky with sed to comment out the echo command.</p>

<p>I restarted my computer to be sure nothing was hanging over from previous sessions and loaded up a new terminal. I tried to run an ssh command and entered the key when prompted. I then ran the same command a second time and it worked as expected. I then opened a new terminal instance and ran the same command a third time with complete success. I was quite pleased I’d managed to solve my problem with a little digging and didn’t need to switch away from powershell to enjoy using the utility of ssh agent.</p>

<p>I hope this helps you - I find knowing what your tools are doing under the hood lets you adapt them for other usages and workflows like I have here. Learning a bit about ssh-agent means I get to keep using powershell where I want to and now have the tools I need to solve any related problems in the future.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[I’ve been using SSH for quite a while now and have used SSH keys regularly to authenticate myself with a variety of systems both at work and at home. I historically have been a bit lazy and avoided using passwords for my private keys to avoid having to remember said password and type it in every time. Eventually I learned of SSH Agent - a tool that allows you to type your SSH password in once per session to save on repetitive password entry by storing the decrypted value of the key in memory for easy access.]]></summary></entry><entry><title type="html">Cleaning up my site</title><link href="https://edwinjones.me.uk/cleaning-up-my-site/" rel="alternate" type="text/html" title="Cleaning up my site" /><published>2021-06-02T00:00:00+00:00</published><updated>2021-06-02T00:00:00+00:00</updated><id>https://edwinjones.me.uk/cleaning-up-my-site</id><content type="html" xml:base="https://edwinjones.me.uk/cleaning-up-my-site/"><![CDATA[<p>Since I started my own blog around 10 years ago to learn HTML and web tech in general, a lot has changed. I originally relied heavily on external tech such as <a href="https://developers.facebook.com/docs/plugins/comments/">facebook comments</a>, <a href="https://analytics.google.com/analytics/web/">google analytics</a> and <a href="https://disqus.com/">disqus</a> to host comments and track activity on my page. Sadly, things haven’t exactly gone well in terms of privacy on the internet for a variety of reasons and I think it’s time to clean this page up.</p>

<p>Therefore as of right now this page is free of all trackers, social media widgets and ad tech I don’t directly need to keep this site running. I’m still using <a href="https://pages.github.com/">github pages</a> for hosting, <a href="http://youtube.com">youtube</a> for video storage and <a href="https://aws.amazon.com/route53/">AWS</a> as a domain registrar so I can’t guarantee this site is entirely tracker free but I’ll endeavour to keep this page as clean as I can going forward.</p>

<p>Most of the web is full of pop ups, adverts and other annoyances that make the experience less pleasant than it could be. I can’t fix those problems at scale but I can at least try to make people feel more at ease on my site. I hope in some small way this helps.</p>

<p>I’ll work towards removing more trackers as and when I can find replacement tech. If you find something you think should be removed, please send me a message at <script type="text/javascript">printEmailAddress();</script>.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Since I started my own blog around 10 years ago to learn HTML and web tech in general, a lot has changed. I originally relied heavily on external tech such as facebook comments, google analytics and disqus to host comments and track activity on my page. Sadly, things haven’t exactly gone well in terms of privacy on the internet for a variety of reasons and I think it’s time to clean this page up.]]></summary></entry><entry><title type="html">Make your own Raspberry Pi webcam</title><link href="https://edwinjones.me.uk/make-your-own-raspberry-pi-webcam/" rel="alternate" type="text/html" title="Make your own Raspberry Pi webcam" /><published>2020-08-26T00:00:00+00:00</published><updated>2020-08-26T00:00:00+00:00</updated><id>https://edwinjones.me.uk/make-your-own-raspberry-pi-webcam</id><content type="html" xml:base="https://edwinjones.me.uk/make-your-own-raspberry-pi-webcam/"><![CDATA[<p>2020 has been an <em>interesting</em> year to say the least, but one of the oddest side effects of coronavirus is the fact that USB webcams 
have been much harder to come by and generally cost a lot more than they used to. 
The oft lauded <a href="https://www.logitech.com/en-us/product/hd-pro-webcam-c920">Logitech c920</a> goes for the best part of £100 if not more, 
and that’s if you can find one in stock.</p>

<p>I had the idea a few months ago that I could probably jury-rig <a href="https://www.raspberrypi.org/products/raspberry-pi-zero-w/">a Raspberry Pi Zero</a> 
with a <a href="https://www.raspberrypi.org/products/camera-module-v2/">camera module</a> to be a USB webcam but I didn’t know enough about how to configure one 
to make it work. I was following <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=38&amp;t=148361">this thread</a> on the official forums but 
it seemed that people far smarter than me weren’t having any luck, so I gave up for the meanwhile. 
Recently I came across a post by <a href="http://www.davidhunt.ie/raspberry-pi-zero-with-pi-camera-as-usb-webcam">David Hunt</a> 
that made my heart skip a beat - he’d cracked the remaining steps and created a detailed post about how to configure everything.</p>

<p>I realised that this probably wouldn’t work if I needed to quickly unplug the Pi as power cuts can cause SD card corruption - then I remembered that you can configure the Pi to have a read only operating system. 
As this would only be plugged in via USB without any network access, I wouldn’t need OS or software updates! 
I’d done this years before but long since forgotten how, 
thankfully another post by <a href="https://medium.com/swlh/make-your-raspberry-pi-file-system-read-only-raspbian-buster-c558694de79">Andreas Schallwig</a> 
had me covered with a detailed guide for the latest version of the Raspberry Pi OS, <a href="https://www.raspberrypi.org/blog/buster-the-new-version-of-raspbian/">Buster.</a></p>

<p>I followed both guides and added some customisations of my own to turn off the wifi of my Pi. 
I couldn’t quite figure out why the image appeared blurry at this stage. Turns out yet another blogger had me covered - Jeff Gerling’s <a href="https://www.jeffgeerling.com/blog/2017/fixing-blurry-focus-on-some-raspberry-pi-camera-v2-models">post about the camera</a> 
explained what was wrong and more importantly that <em>you can manually focus a v2 camera with some tweezers!</em> 
One awkward and fiddly step later this was the result:</p>

<p><br />
<img src="/images/rantimages/pi-webcam-image.png" alt="webcam-example" />
<br /></p>

<p>Impressive no? David’s configuration sets up the camera to act as a generic <a href="https://en.wikipedia.org/wiki/USB_video_device_class">UVC</a> 1080p/30fps webcam that should work on most desktop operating systems. I set mine up on <a href="https://pop.system76.com/">Pop OS</a> and it worked just fine. 
It looks significantly better than my laptop camera at 720p and matches the spec of the c920 I mentioned earlier. 
Considering the c920 costs so much, I saw this as a significant win.</p>

<p>If you want to try this out yourself, you’ll need the following parts:</p>

<ul>
  <li><a href="https://www.quora.com/What-is-the-difference-between-a-USB-charging-cable-and-a-data-cable">A micro usb data cable</a>.</li>
  <li><a href="https://www.jeffgeerling.com/blog/2019/raspberry-pi-microsd-card-performance-comparison-2019">A decent micro SD card.</a></li>
  <li><a href="https://www.raspberrypi.org/products/raspberry-pi-zero-w/">A Pi Zero W.</a></li>
  <li><a href="https://thepihut.com/products/official-raspberry-pi-zero-case">A case.</a></li>
  <li><a href="https://shop.pimoroni.com/products/camera-cable-raspberry-pi-zero-edition?variant=32092803891283">A Ribbon cable for the camera module.</a> (This comes with the official case.)</li>
  <li><a href="https://www.raspberrypi.org/products/camera-module-v2/">A v2 camera module.</a></li>
  <li>Something to hold the Pi with so the camera can aim at your face.</li>
  <li>A computer to flash the micro SD card and use SSH with.</li>
</ul>

<p>Assuming you already have a computer, the cost of all of the above is only around £45. If you have any of the parts already you’ll save even more. 
Who needs a £100 webcam? David uses the <a href="https://www.raspberrypi.org/products/raspberry-pi-high-quality-camera/">Pi HQ camera</a> but 
this is overkill for a webcam and costs a lot more than the v2. 
The Pi Camera V1 should also work but those are no longer in production so I couldn’t verify this myself.</p>

<p>To get started, you’ll need to download the latest version of the Raspberry Pi OS and flash it onto your SD card. 
The easiest way to do this I’ve found is to use the <a href="https://www.raspberrypi.org/blog/raspberry-pi-imager-imaging-utility/">official Raspberry Pi Imager tool</a> 
and choose <em>Rasbian Lite</em> as the OS image - we’re not going to be using a desktop on our webcam!</p>

<p>Once you’ve flashed the SD card you need to open up the <code class="language-plaintext highlighter-rouge">boot</code> partition in your file explorer and add two files. 
Add one called <code class="language-plaintext highlighter-rouge">ssh</code> with <em>no</em> file extension - we’ll need this to enable SSH access for later. Add a second one called <code class="language-plaintext highlighter-rouge">wpa_supplicant.conf</code> 
and give it the following content:</p>

<p><br /></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>country=gb
update_config=1
ctrl_interface=/var/run/wpa_supplicant

network={
 scan_ssid=1
 ssid="MyNetworkSSID"
 psk="MyWifiPassword"
}
</code></pre></div></div>
<p><br /></p>

<p>You can change the country code if you live outside of the UK - acceptable values are <code class="language-plaintext highlighter-rouge">us, de, fr</code> etc. depending on your country.</p>

<p>Plug your SD card into your Pi and attach the v2 Camera inside of the case. 
<a href="https://www.youtube.com/watch?v=xjRFtqHAztA">There’s a handy guide here</a> if you’ve never done this before. 
Connect a micro USB cable to the Pi’s USB <em>data</em> port and plug it into your PC. The data port is the one in the middle, 
not the one near the edge of the board. Once assembled you should have something that looks similar to mine, which is currently mounted on my monitor stand:</p>

<p><br />
<img src="/images/rantimages/pi-webcam.jpg" alt="webcam-in-stand" />
<br /></p>

<p>Give it a minute or so to boot up. We should now be able to see our Pi on the local network. 
There’s a few ways to do this but I’ve found it best to use the official guide to find the correct 
<a href="https://www.raspberrypi.org/documentation/remote-access/ip-address.md">IP address</a>. 
Once we have this we can remote into the Pi via <a href="https://www.raspberrypi.org/documentation/remote-access/ssh/">SSH</a> with the default username of <code class="language-plaintext highlighter-rouge">pi</code> 
and the password of <code class="language-plaintext highlighter-rouge">raspberry</code>.</p>

<p>Once we’re at the command line, we’re ready to set the camera up as a 
USB gadget via <a href="http://www.davidhunt.ie/raspberry-pi-zero-with-pi-camera-as-usb-webcam">David’s guide.</a> A major problem I had was that I tried to edit only the <code class="language-plaintext highlighter-rouge">/boot/cmdline.txt</code> file by adding <code class="language-plaintext highlighter-rouge">modules-load=dwc2,libcomposite</code> at the 
end of the <code class="language-plaintext highlighter-rouge">console</code> line. You <em>must</em> make changes to the config file as well and it’s easy to miss this in the guide. Add these lines 
to the bottom of the <code class="language-plaintext highlighter-rouge">/boot/config.txt</code> file:</p>

<p><br /></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Enable usb gadget mode
dtoverlay=dwc2
</code></pre></div></div>
<p><br /></p>

<p>Once you’ve run through the above, you can reboot the Pi and start accessing the system via TTY over USB. 
If you’re comfortable doing this and want to disable wifi for security, add the following lines to end of the <code class="language-plaintext highlighter-rouge">/boot/config.txt</code> file, 
under the <code class="language-plaintext highlighter-rouge">dtoverlay=dwc2</code> line:</p>

<p><br /></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Disable wifi and bluetooth (we use TTY connections over usb)
dtoverlay=pi3-disable-wifi
dtoverlay=pi3-disable-bt
</code></pre></div></div>
<p><br /></p>

<p>This is completely optional and if you’d rather just use wifi, that’s fine as well! If you do want to do it and you’re using Linux make sure to add yourself to the <code class="language-plaintext highlighter-rouge">dialout</code> and <code class="language-plaintext highlighter-rouge">tty</code> groups as I couldn’t connect without doing this first.</p>

<p>We should now be able to see the raspberry pi show up as a webcam now in a variety of applications. 
If you can’t see yours you might want to double check you’ve done all the steps above. 
You can adjust the camera brightness, contrast and rotation by adding these lines to your <code class="language-plaintext highlighter-rouge">/etc/rc.local</code> file, 
just above the <code class="language-plaintext highlighter-rouge">exit 0</code> line:</p>

<p><br /></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># set camera settings
v4l2-ctl -c brightness=(0-100, pick a number! Starts at 50)
v4l2-ctl -c contrast=(0-100, pick a number! Starts at 20)
v4l2-ctl -c horizontal_flip=(1 or 0, 1 is on 0 is off)
v4l2-ctl -c vertical_flip=(1 or 0, 1 is on 0 is off)
</code></pre></div></div>
<p><br /></p>

<p>If the camera appears fuzzy remember you can manually focus the lens with a pair of tweezers as demonstrated 
<a href="https://www.youtube.com/watch?v=xjRFtqHAztA">in this video.</a> 
You will probably see a little noise in the image but this is normal for the Pi camera V1/V2 as their sensors can be a slightly noisy in certain situations.</p>

<p>Once you’re happy with the video quality, it’s time to set the Pi into read only mode so we can switch off our PC whenever and 
not have to worry about corrupting the SD card. Follow <a href="https://medium.com/swlh/make-your-raspberry-pi-file-system-read-only-raspbian-buster-c558694de79">Andreas’ guide here</a> then reboot your Pi. 
Once the Pi comes back online you’re ready to show your friends and co-workers your webcam 
that cost a fraction of what theirs did and is likely better. Congratulations!</p>]]></content><author><name></name></author><summary type="html"><![CDATA[2020 has been an interesting year to say the least, but one of the oddest side effects of coronavirus is the fact that USB webcams have been much harder to come by and generally cost a lot more than they used to. The oft lauded Logitech c920 goes for the best part of £100 if not more, and that’s if you can find one in stock.]]></summary></entry><entry><title type="html">Powerful Powershell Passwords</title><link href="https://edwinjones.me.uk/powerful-powershell-passwords/" rel="alternate" type="text/html" title="Powerful Powershell Passwords" /><published>2020-07-27T00:00:00+00:00</published><updated>2020-07-27T00:00:00+00:00</updated><id>https://edwinjones.me.uk/powerful-powershell-passwords</id><content type="html" xml:base="https://edwinjones.me.uk/powerful-powershell-passwords/"><![CDATA[<p><em>Tl;dr - For all of you doing some googling to find out how to make a secure password with any modern powershell version (i.e. Powershell 5 and above) the code snippet you want is at the bottom of this article.</em></p>

<p>We’ve all been there - we’ve got a new website to sign up for or some credentials to generate for a work account. For most people a password manager is a viable option for generating secure passwords but in many cases you want to automate this flow - ideally in a way that will work on any given platform. Many people work with windows as their OS but others use Mac OS or a variety of linux. While there are a variety of approaches for each, most people I expect would prefer something simple that would work on all of them. I’ve recently spent some time searching for a good solution for this myself but as I couldn’t find one easily  I’ve written this article in the hopes of sparing somebody else the time it took me to come to these conclusions.</p>

<p><a href="https://docs.microsoft.com/en-us/powershell/scripting/overview?view=powershell-7">Powershell</a> has made leaps and bounds since it originally started as a windows only scripting language. It now runs on all your favourite desktop operating systems and makes a perfect candidate for finding a simple command that the majority of people can just run without installing anything else. The old way to generate a password in powershell is as follows:</p>

<pre><code class="language-pwsh">Add-Type -AssemblyName 'System.Web'
$length = 32
[System.Web.Security.Membership]::GeneratePassword($length, 0)
</code></pre>

<p>This works by using a static method we borrow from C# to generate a password of the given length. It’s the top find on most “generate a password in powershell” searches and still works to this day on Windows. Sadly, <code class="language-plaintext highlighter-rouge">System.Web.Security.Membership</code> <a href="https://github.com/PowerShell/PowerShell/issues/5352">is not available outside of windows.</a> Ideally, we want a solution that will work on any operating system you end up using so we need to keep searching.</p>

<p>Google fu can take us some interesting places, usually with multi line scripts that are hard to confirm are crytopgraphically sound. The smallest gist I’ve found so far is <a href="https://gist.github.com/marcgeld/4891bbb6e72d7fdb577920a6420c1dfb">this one</a>. It looks pretty promising, but ideally I think we’d all like to use a one liner we can easily share with our peers. Looking at the code in that gist, we can take one line of it and use that:</p>

<pre><code class="language-pwsh">Write-Output ( -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count 32 | % {[char]$_}) )
</code></pre>

<p>This works and generates something that looks correct but…what on earth is that code doing? It’s actually pretty simple - it’s putting the ASCII characters <code class="language-plaintext highlighter-rouge">a-z</code>, <code class="language-plaintext highlighter-rouge">A-Z</code> and <code class="language-plaintext highlighter-rouge">0-9</code> into a set, selecting a random character from that set 32 times and dumping that out on your console. Good luck remembering that in a few months let alone editing that command without breaking it. What if we simplified it a bit with:</p>

<pre><code class="language-pwsh">Write-Output "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray() | Get-Random -Count 32 | Join-String
</code></pre>

<p>That’s much easier to understand right? The best part of this approach is it’s obvious to anybody new what’s going on and we can easily customise the alphabet used for the random passwords. We could remove numbers entirely or add different characters etc.</p>

<p>As for the <code class="language-plaintext highlighter-rouge">Get-Random</code> cmdlet, how can we be sure it’s actually secure? Via the <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-random?view=powershell-7">documentation!</a> Reading the documentation tells us that as long as we do not set a manual seed the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator?view=netcore-3.1">RandomNumberGenerator</a> class is used and that’s cryptographically secure. If you’re still unconvinced you can check the source code itself to confirm what is going on <a href="https://github.com/PowerShell/PowerShell/blob/master/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs#L583">under the hood.</a></p>

<p>I hope this helps you generate passwords and api keys more easily during your day to day workflows - please let me know if this is of use to you!</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Tl;dr - For all of you doing some googling to find out how to make a secure password with any modern powershell version (i.e. Powershell 5 and above) the code snippet you want is at the bottom of this article.]]></summary></entry><entry><title type="html">Write your own browser extension</title><link href="https://edwinjones.me.uk/write-your-own-browser-extension/" rel="alternate" type="text/html" title="Write your own browser extension" /><published>2019-12-04T00:00:00+00:00</published><updated>2019-12-04T00:00:00+00:00</updated><id>https://edwinjones.me.uk/write-your-own-browser-extension</id><content type="html" xml:base="https://edwinjones.me.uk/write-your-own-browser-extension/"><![CDATA[<p>In my day to day work I’m often reading a lot of database records that are sorted by time, usually using <a href="https://www.unixtimestamp.com/">unix timestamps</a>. The problem I usually have with this is when I view these records via some sort of web portal the numbers are a bit meaningless - I can’t tell by eye if <code class="language-plaintext highlighter-rouge">1575468821</code> is an older date than <code class="language-plaintext highlighter-rouge">1575598821</code> without a little reading. Realising that I could do with a tool that automatically converted these for me I decided to bite the bullet and write a simple extension called stampy for <a href="https://chrome.google.com/webstore/detail/stampy/ccicllkpedpkilncdaololajfojgaodg">Chrome</a> (and <a href="https://addons.mozilla.org/en-GB/firefox/addon/stampy/">Firefox</a>). It turns out writing one is easy and this post details how I wrote mine.</p>

<p>A chrome extension at heart consists of a folder that contains a <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> file and one to many <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a> files. The JSON file is known as the <a href="https://developer.chrome.com/extensions/manifest">manifest</a> and just contains some details about your application such as its name, description, version number and which JavaScript files the extension uses. These broadly fall into two categories, <a href="https://developer.chrome.com/extensions/background_pages">background scripts</a> and <a href="https://developer.chrome.com/extensions/content_scripts">content scripts</a>.</p>

<p>Content scripts are similar to website scripts you may have written before and can read or modify the contents of a page as you’d expect. They are basically standard JavaScript with the proviso that what you have access to may be controlled by the permissions you’ve configured your extension to have in the manifest.</p>

<p>Background scripts are more interesting, these represent the “host” of your extension. This is the place you would write code to hook into browser events such as somebody opening a new tab or clicking your extension’s button. You can think of these as contexts that run inside the browser itself, extending how it functions. In my extension I use a background script to listen for any events that occur when somebody clicks the extension’s button and then invoke a custom content script on the currently active browse tab with the following short snippet of code:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">chrome</span><span class="p">.</span><span class="nx">browserAction</span><span class="p">.</span><span class="nx">onClicked</span><span class="p">.</span><span class="nx">addListener</span><span class="p">(</span>
    <span class="kd">function</span> <span class="p">(</span><span class="nx">tab</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">chrome</span><span class="p">.</span><span class="nx">tabs</span><span class="p">.</span><span class="nx">executeScript</span><span class="p">(</span><span class="nx">tab</span><span class="p">.</span><span class="nx">id</span><span class="p">,</span> <span class="p">{</span> <span class="na">file</span><span class="p">:</span> <span class="dl">"</span><span class="s2">content.js</span><span class="dl">"</span> <span class="p">});</span>
    <span class="p">});</span>

</code></pre></div></div>

<p>As you can see, the <code class="language-plaintext highlighter-rouge">chrome</code> object and its associated APIs are not what you would normally be able to access inside of a JavaScript browser context or console. This is the place where you can glue together the internal workings of a web browser with custom logic to change how your browser works. For reference, this is what <code class="language-plaintext highlighter-rouge">content.js</code> looks like:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// use an anon function to avoid polluting the environment after the script is run</span>
<span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">info</span><span class="p">(</span><span class="dl">"</span><span class="s2">stampy - running unix timestamp conversion for page</span><span class="dl">"</span><span class="p">);</span>

    <span class="kd">const</span> <span class="nx">timerName</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">stampy - document body parsing took</span><span class="dl">"</span><span class="p">;</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">time</span><span class="p">(</span><span class="nx">timerName</span><span class="p">);</span>

    <span class="kd">function</span> <span class="nx">replaceTimestamp</span><span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
        <span class="kd">let</span> <span class="nx">date</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Date</span><span class="p">(</span><span class="nx">value</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">);</span>
        <span class="kd">let</span> <span class="nx">locale</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nb">navigator</span><span class="p">.</span><span class="nx">language</span><span class="p">;</span>
        <span class="kd">let</span> <span class="nx">replacement</span> <span class="o">=</span> <span class="s2">`</span><span class="p">${</span><span class="nx">date</span><span class="p">.</span><span class="nx">toLocaleDateString</span><span class="p">(</span><span class="nx">locale</span><span class="p">)}</span><span class="s2"> @ </span><span class="p">${</span><span class="nx">date</span><span class="p">.</span><span class="nx">toLocaleTimeString</span><span class="p">(</span><span class="nx">locale</span><span class="p">)}</span><span class="s2"> (UTC)`</span><span class="p">;</span>

        <span class="k">return</span> <span class="nx">replacement</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="kd">function</span> <span class="nx">filterInvalidTextNodes</span><span class="p">(</span><span class="nx">node</span><span class="p">)</span> <span class="p">{</span>

        <span class="c1">// invisible elements should not be considered for timestamp conversion</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">node</span><span class="p">.</span><span class="nx">parentElement</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">display</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">none</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">return</span> <span class="nx">NodeFilter</span><span class="p">.</span><span class="nx">FILTER_SKIP</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="k">return</span> <span class="nx">NodeFilter</span><span class="p">.</span><span class="nx">FILTER_ACCEPT</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="kd">const</span> <span class="nx">timestampRegex</span> <span class="o">=</span> <span class="nb">RegExp</span><span class="p">(</span><span class="dl">"</span><span class="s2">[0-9]{10}</span><span class="dl">"</span><span class="p">);</span>
    <span class="kd">const</span> <span class="nx">nodeIterator</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createNodeIterator</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">,</span> <span class="nx">NodeFilter</span><span class="p">.</span><span class="nx">SHOW_TEXT</span><span class="p">,</span> <span class="nx">filterInvalidTextNodes</span><span class="p">);</span>

    <span class="kd">let</span> <span class="nx">node</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="nx">node</span> <span class="o">=</span> <span class="nx">nodeIterator</span><span class="p">.</span><span class="nx">nextNode</span><span class="p">())</span> <span class="p">{</span>
        <span class="nx">node</span><span class="p">.</span><span class="nx">textContent</span> <span class="o">=</span> <span class="nx">node</span><span class="p">.</span><span class="nx">textContent</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="nx">timestampRegex</span><span class="p">,</span> <span class="nx">replaceTimestamp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="nx">console</span><span class="p">.</span><span class="nx">timeEnd</span><span class="p">(</span><span class="nx">timerName</span><span class="p">);</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">info</span><span class="p">(</span><span class="dl">"</span><span class="s2">stampy - timestamp conversion completed</span><span class="dl">"</span><span class="p">);</span>
<span class="p">})();</span>
</code></pre></div></div>

<p>The basic flow of the script is basically that I search through all the text nodes of the page that are children of <em>visible</em> html elements (so I don’t risk modifying <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script">script</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style">style</a> elements) and check to see if they contain a certain timestamp-eske pattern with a regex. This pattern is 10 consecutive numerical digits which usually represents a unix timestamp between 2001 and 2286. I feel this is a broad enough range to be useful and a fair enough concession to make to avoid accidentally converting <em>every</em> number on a page. Any strings that match this pattern are then replaced with a string representation of the associated date and time in <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time">UTC</a>, the formatting of which is controlled by the user’s locale settings for their browser. I invoke this all via an <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE</a> so I don’t pollute the environment for any other running scripts.</p>

<p>Once I’d tried this out via <a href="https://support.google.com/chrome/a/answer/2714278?hl=en">chrome’s development tools</a> all I had to do was log in to the <a href="https://chrome.google.com/webstore/developer/dashboard">chrome developer dashboard</a> and register it by uploading a zip file containing the source code. There was a small sign up fee of $5 but other than that it was trivial to get my extension published.</p>

<p>I wondered how hard it would be to convert the extension to Firefox but I really should not have. Not only does Firefox support most of the <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities">chrome extension apis</a>, Mozilla don’t charge to publish an extension! It was even less work to get my extension published for Firefox than it was for Chrome.</p>

<p>All in all it was good fun and quite educational to write my own browser extension. The source code is available on <a href="https://github.com/edwin-jones/stampy">GitHub.</a> If you’re interested in writing your own I’d recommend using <a href="https://developer.chrome.com/extensions/getstarted">google’s free developer guide</a> and go from there. Who knows what you might come up with?</p>]]></content><author><name></name></author><summary type="html"><![CDATA[In my day to day work I’m often reading a lot of database records that are sorted by time, usually using unix timestamps. The problem I usually have with this is when I view these records via some sort of web portal the numbers are a bit meaningless - I can’t tell by eye if 1575468821 is an older date than 1575598821 without a little reading. Realising that I could do with a tool that automatically converted these for me I decided to bite the bullet and write a simple extension called stampy for Chrome (and Firefox). It turns out writing one is easy and this post details how I wrote mine.]]></summary></entry><entry><title type="html">Python Packaging is in a Pickle</title><link href="https://edwinjones.me.uk/python-packaging-is-in-a-pickle/" rel="alternate" type="text/html" title="Python Packaging is in a Pickle" /><published>2019-10-26T00:00:00+00:00</published><updated>2019-10-26T00:00:00+00:00</updated><id>https://edwinjones.me.uk/python-packaging-is-in-a-pickle</id><content type="html" xml:base="https://edwinjones.me.uk/python-packaging-is-in-a-pickle/"><![CDATA[<p>This post is my attempt to summarize my learnings about the basics of how to manage <a href="https://www.python.org/">python</a> packages with different tools and commands. I’ve spent a while collecting this information, hopefully it helps a few people searching for the same thing via google too.</p>

<p>The tl;dr of this post is: <em>Python packaging is a bit of a mess.</em></p>

<p><img src="https://imgs.xkcd.com/comics/standards.png" alt="standards" title="There's always a relevant XKCD comic." /></p>

<p>The three most popular solutions I have found for managing python packages are as follows:</p>

<h2 id="pip">Pip</h2>

<p><a href="https://pypi.org/project/pip/">Pip</a> is the default way to install modules in python and one you’ve probably used before as it comes by default in most modern installations. The basic usage of pip is along the lines of <code class="language-plaintext highlighter-rouge">pip install {module name}</code>. The main issue with pip is that it installs <em>globally</em> and not locally inside of the folder you invoked the command from like say, <a href="https://www.npmjs.com/">npm.</a> This means you can encounter dependency problems where two packages need different versions of the same package but as it’s installed globally, you end up in a bit of a pickle.</p>

<p>A <a href="https://pip.readthedocs.io/en/1.1/requirements.html">requirements file</a> can be used with pip for loose requirements, such as <em>“I need some version of pygame”</em> and is used by pip. It tends to be used as a <em>dev requirements</em> file that is shared between developers of a package. You can simply create a file named <code class="language-plaintext highlighter-rouge">requirements.txt</code> in the directory of your choosing with content like so:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
</code></pre></div></div>

<p>Then install those requirements (again, globally) with the <code class="language-plaintext highlighter-rouge">pip install -r requirements.txt</code> command.</p>

<p>Another way to share pip dependencies is with a <a href="https://docs.python.org/3/distutils/setupscript.html">setup.py</a> file. This is a more involved requirements installation mechanism and is required to deploy a python module to the <a href="https://pypi.org/">python package index</a>. This is the place you’d want to put your python code if you wanted other people to be able to <code class="language-plaintext highlighter-rouge">pip install</code> it. <code class="language-plaintext highlighter-rouge">setup.py</code> is what actually gets used to install requirements whenever you run <code class="language-plaintext highlighter-rouge">pip install {module name}</code>. Both this and requirement.txt files tend to get used in a python project so developers can install dependencies slightly differently to how end users do.</p>

<h2 id="venv">Venv</h2>

<p><a href="https://docs.python.org/3/library/venv.html">Venv</a> allows you to create <em>virtual environments</em> and works around the global pip install issues by creating an environment inside a directory that you can install packages directly into. It can be a bit unwieldy however. It comes with modern python installations by default. You can run it with the following command: <code class="language-plaintext highlighter-rouge">python -m venv {folder path}</code>. To exit a running venv session you can usually just use the <code class="language-plaintext highlighter-rouge">deactivate</code> command.</p>

<h2 id="pipenv">Pipenv</h2>
<p><a href="https://github.com/pypa/pipenv">Pipenv</a> is an abstraction layer around venv and uses it and pip under the hood to extend pip. Instead of <code class="language-plaintext highlighter-rouge">pip install</code> you’d run <code class="language-plaintext highlighter-rouge">pipenv install</code> etc. It installs the dependencies to a folder inside your user directory. It greatly simplifies things at the cost of abstraction as you are less involved with how <code class="language-plaintext highlighter-rouge">venv</code> is being invoked. One thing to note is that while <code class="language-plaintext highlighter-rouge">venv</code> and <code class="language-plaintext highlighter-rouge">pip</code> are usually included with python, <code class="language-plaintext highlighter-rouge">pipenv</code> is not! Pipenv has richer package metadata and dependency tree data than a requirements.txt file. It is good at installing dev dependencies as well as your main dependencies. You can consider using it to be similar to <code class="language-plaintext highlighter-rouge">npm install</code> in a way.</p>

<h2 id="summary">Summary</h2>

<p>The reason there isn’t one single default tool to manage python packaging appears to be because python is a mature, open source language. It does not have direct oversight from a single large corporation like Microsoft has over <a href="https://docs.microsoft.com/en-us/dotnet/csharp/">C#</a> or Google has over <a href="https://golang.org/">Go</a>. Several groups have developed different methods to try to solve the packaging problem but there is no one single accepted way of doing things.</p>

<p>I myself prefer just to use pip with a requirements.txt file if required but it’s probably worth looking to <code class="language-plaintext highlighter-rouge">venv</code> at the very least if you have a large deployment environment to manage.</p>

<p><em>PS: To turn python applications into exes/binaries, use the <a href="https://www.pyinstaller.org/">pyinstaller</a> module. It’s very easy to make  binaries from tons of python code, even for windowed apps! This means you can avoid all the pain described above if your deployment environment allows you to share and run binaries. It does bundle the entire python runtime alongside your package, so it might not be the most efficient solution depending on your use case.</em></p>]]></content><author><name></name></author><summary type="html"><![CDATA[This post is my attempt to summarize my learnings about the basics of how to manage python packages with different tools and commands. I’ve spent a while collecting this information, hopefully it helps a few people searching for the same thing via google too.]]></summary></entry><entry><title type="html">How I stopped worrying and learned to love emulation</title><link href="https://edwinjones.me.uk/how-I-stopped-worrying-and-learned-to-love-emulation/" rel="alternate" type="text/html" title="How I stopped worrying and learned to love emulation" /><published>2018-09-18T00:00:00+00:00</published><updated>2018-09-18T00:00:00+00:00</updated><id>https://edwinjones.me.uk/how-I-stopped-worrying-and-learned-to-love-emulation</id><content type="html" xml:base="https://edwinjones.me.uk/how-I-stopped-worrying-and-learned-to-love-emulation/"><![CDATA[<p><strong><em>UPDATE 2022: This post has now been rewritten for issue 54 of Wireframe magazine and is available <a href="https://archive.org/details/Wireframe54/page/48/mode/2up">here on page 48.</a></em></strong></p>

<p>Emulators fancinate me. The idea that you could run a computer within another computer feels like some sort of arcane vodoo magic. <a href="https://www.google.co.uk/search?q=dolphin+emulator&amp;oq=dolphin+emulator&amp;aqs=chrome..69i57.1996j0j7&amp;sourceid=chrome&amp;ie=UTF-8">Playing Gamecube games on a PC?</a> <a href="https://en.wikipedia.org/wiki/Sonic%27s_Ultimate_Genesis_Collection">MegaDrive games on an Xbox 360</a>? Insanity, but awesome nonetheless.</p>

<p>I’ve wanted to dabble in writing my own emulator for a long time but in earlier years I lacked confidence and more recently I just didn’t feel like I had the time. After watching a colleague of mine at <a href="https://www.mediatonicgames.com/">Mediatonic</a> write his own working <a href="https://bitbucket.org/gamezer0/nesemu/raw/64d3b73167568a391e69ef189fc1dc9b4eb395e9/doc/Kike%20Alcor%20-%20Creating%20a%20NES%20emulator%20v2.pdf">NES emulator from scratch</a> I felt I needed to try again. After, <em>ahem</em>, gentle encouragement from other colleagues I thought what the heck, I’d give it a try.</p>

<p>The next question was…what to emulate? The NES project was quite daunting and I wanted something simpler and compact so I wouldn’t be tempted to give up. It turns out that there is a really good starter project for everybody who wants to try their hand and emulation and it’s called the <a href="https://en.wikipedia.org/wiki/CHIP-8">CHIP-8</a>.</p>

<p>The CHIP-8 was never a real computer but that’s what makes it fascinating. Long before most other games systems it was a virtual machine for 8 bit computers way back in the 1970s. This means there is no real hardware to attempt to emulate and quite a simple specification to implement as the CHIP-8 only has 35 <a href="https://en.wikipedia.org/wiki/Opcode">opcodes</a>, one of which is generally ignored anyway as it’s a hardware specific one for the <a href="https://en.wikipedia.org/wiki/RCA_1802">RCA 1802</a>. You still have all the usual problems to solve of loading binary files, parsing opcodes and then running them on virtual hardware but you don’t have the other baggage that comes with trying to write emulators for real hardware. The game was afoot.</p>

<p>Next, I needed to choose some tech to help me build my own version of the CHIP-8. I read tutorials that used <a href="https://blog.dantup.com/2016/06/building-a-chip-8-interpreter-in-csharp/">C#</a> and <a href="http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/">C++</a> but both seemed a bit heavy weight for what I wanted to do and seemed to be platform specific. I wanted something simple that would handle drawing to screen and work on platforms other than a windows PC with a minimum of fuss. The most sensible option stood out from the rest: <a href="https://www.pygame.org/wiki/about">Pygame.</a></p>

<p>For simple projects there is no easier way I have found to draw things on your monitor. I was going to find however, that dynamic languages have a few drawbacks when it comes to emulating things like <a href="https://en.wikipedia.org/wiki/Processor_register">registers</a> and <a href="https://en.wikipedia.org/wiki/Framebuffer">framebuffers</a>. The most obvious problem was that Python has no byte type available by default. <del>Thankfully the <a href="http://www.numpy.org/">NumPy</a> library does define such types, so I decided to use that.</del> <em>It turns out the simplest way to deal with this is a bitmask to restrict integer values to the range of one or two bytes where required.</em></p>

<p>Next I had to break down and understand the basic CHIP-8 specifications:</p>

<ul>
  <li>4K of total memory</li>
  <li>16 general purpose 8 bit registers (the 16th is also used as a special arithmetic flag at times)</li>
  <li>A 64 pixel wide and 32 pixel high framebuffer</li>
  <li>A stack that stores return addresses for function calls and nothing else</li>
  <li>Some way to store the pressed state of a 16 button keypad (0-F)</li>
  <li>An 8 bit index register</li>
  <li>An 8 bit program counter</li>
  <li>An 8 bit stack pointer</li>
  <li>An 8 bit delay timer register</li>
  <li>An 8 bit sound timer register (when above zero, a beep is made)</li>
</ul>

<p>This part is pretty simple and was easy to set up. The next step was figuring out how to parse the raw binary from a rom file and turn that into instructions for the CPU. The CHIP-8 has a strange opcode definition in that each opcode is a 16 bit/2 byte value that contains the instruction and the data for that instruction. This would be simple enough were it not for the fact that apart from the first four bits, each following <a href="https://en.wikipedia.org/wiki/Nibble">nibble</a> can be part of an instruction <em>or</em> data - depending on the instruction in question. For instance, the opcode <strong>0x00E0</strong> means <em>clear the screen</em> but opcode <strong>0x1234</strong> means <em>jump to address 0x234.</em></p>

<p>I had to write a parsing system that would map each opcode to a corresponding logical operation. The first part of the problem was how to turn a set of bytes into separate values so that if an opcode contained data, I could get at that data. I could have used binary operators every time but it seemed cleaner to make a class that took in the byte value and exposed the associated nibbles as attributes, like so:</p>

<p><br /></p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="s">"""
This module defines an opcode class for parsing
raw words into instructions and data
"""</span>

<span class="k">class</span> <span class="nc">Opcode</span><span class="p">:</span>
    <span class="s">"""
    This class represents the instructions and data of an opcode
    """</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">word</span><span class="p">):</span>
        <span class="s">"""
        This class takes in a 2 byte value/word and parses the bytes
        to store them in different attributes for later use
        Args:
            word: a 2 byte/16 bit value representing an opcode.
        """</span>

        <span class="c1"># We use bitwise AND with a mask to extract specific nibbles.
</span>
        <span class="c1"># a word should be no more than 16 bits
</span>        <span class="bp">self</span><span class="p">.</span><span class="n">word</span> <span class="o">=</span> <span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0xFFFF</span>

        <span class="c1"># we just want the most significant bits/nibble
</span>        <span class="c1"># here so we bitshift right
</span>        <span class="bp">self</span><span class="p">.</span><span class="n">a</span> <span class="o">=</span> <span class="p">(</span><span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0xF000</span><span class="p">)</span> <span class="o">&gt;&gt;</span> <span class="mi">12</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">nnn</span> <span class="o">=</span> <span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0x0FFF</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">nn</span> <span class="o">=</span> <span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0x00FF</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">n</span> <span class="o">=</span> <span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0x000F</span>

        <span class="c1"># Where don't use the lower nibbles, bitshift
</span>        <span class="c1"># right to get just the raw value
</span>        <span class="bp">self</span><span class="p">.</span><span class="n">x</span> <span class="o">=</span> <span class="p">(</span><span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0x0F00</span><span class="p">)</span> <span class="o">&gt;&gt;</span> <span class="mi">8</span>

        <span class="c1"># Eg. we want 0x4 not 0x40
</span>        <span class="bp">self</span><span class="p">.</span><span class="n">y</span> <span class="o">=</span> <span class="p">(</span><span class="n">word</span> <span class="o">&amp;</span> <span class="mh">0x00F0</span><span class="p">)</span> <span class="o">&gt;&gt;</span> <span class="mi">4</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">hex</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">word</span><span class="p">)</span>
</code></pre></div></div>
<p><br /></p>

<p>Pretty simple eh? I wish I could take credit for this one but many CHIP-8 emulators solve the problem in a similar way.</p>

<p>The next issue was how to map an <em>opcode</em> to an <em>operation</em>. Most other emulators I had looked at just used a giant switch statement, which seemed inelegant. Some blog posts suggested that function lookups would be a good idea but I felt that would be hard to test and a bit ugly. I decided to write a class for each opcode that would change the state of the (virtual) cpu as required.</p>

<p>I then wrote a mapper class that would take in the raw byte value of an opcode and return the related operation object. It looks like this:</p>

<p><br /></p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="s">"""
This module defines a class that handles
mapping a 16 bit opcode value to an operation object
"""</span>

<span class="kn">from</span> <span class="nn">pychip8.operations</span> <span class="kn">import</span> <span class="o">*</span>
<span class="kn">from</span> <span class="nn">pychip8.opcode</span> <span class="kn">import</span> <span class="n">Opcode</span>

<span class="k">class</span> <span class="nc">OperationMapper</span><span class="p">():</span>
    <span class="s">"""
    This class handles mapping a 16 bit opcode
    value to an operation object
    """</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span> <span class="o">=</span> <span class="p">{}</span>

        <span class="c1"># opcode 0NNN (call RCA 1802 program) is NOT SUPPORTED!
</span>        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x00E0</span><span class="p">]</span> <span class="o">=</span> <span class="n">ClearDisplay</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x00EE</span><span class="p">]</span> <span class="o">=</span> <span class="n">ReturnFromFunction</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x1</span><span class="p">]</span> <span class="o">=</span> <span class="n">Goto</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x2</span><span class="p">]</span> <span class="o">=</span> <span class="n">CallFunction</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x3</span><span class="p">]</span> <span class="o">=</span> <span class="n">SkipIfEqual</span><span class="p">()</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x4</span><span class="p">]</span> <span class="o">=</span> <span class="n">SkipIfNotEqual</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x6</span><span class="p">]</span> <span class="o">=</span> <span class="n">SetX</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x7</span><span class="p">]</span> <span class="o">=</span> <span class="n">AddToX</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xA</span><span class="p">]</span> <span class="o">=</span> <span class="n">SetI</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xB</span><span class="p">]</span> <span class="o">=</span> <span class="n">GotoPlus</span><span class="p">()</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xC</span><span class="p">]</span> <span class="o">=</span> <span class="n">Random</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xD</span><span class="p">]</span> <span class="o">=</span> <span class="n">DrawSprite</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x50</span><span class="p">]</span> <span class="o">=</span> <span class="n">SkipIfXyEqual</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x80</span><span class="p">]</span> <span class="o">=</span> <span class="n">SetXToY</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x81</span><span class="p">]</span> <span class="o">=</span> <span class="n">BitwiseOr</span><span class="p">()</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x82</span><span class="p">]</span> <span class="o">=</span> <span class="n">BitwiseAnd</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x83</span><span class="p">]</span> <span class="o">=</span> <span class="n">BitwiseXor</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x84</span><span class="p">]</span> <span class="o">=</span> <span class="n">AddYToX</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x85</span><span class="p">]</span> <span class="o">=</span> <span class="n">TakeYFromX</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x86</span><span class="p">]</span> <span class="o">=</span> <span class="n">ShiftXRight</span><span class="p">()</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x87</span><span class="p">]</span> <span class="o">=</span> <span class="n">TakeXFromY</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x8E</span><span class="p">]</span> <span class="o">=</span> <span class="n">ShiftXLeft</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0x90</span><span class="p">]</span> <span class="o">=</span> <span class="n">SkipIfXyNotEqual</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xE9E</span><span class="p">]</span> <span class="o">=</span> <span class="n">SkipIfKeyPressed</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xEA1</span><span class="p">]</span> <span class="o">=</span> <span class="n">SkipIfKeyNotPressed</span><span class="p">()</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF07</span><span class="p">]</span> <span class="o">=</span> <span class="n">SetXToDelayTimer</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF0A</span><span class="p">]</span> <span class="o">=</span> <span class="n">WaitForKeyPress</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF15</span><span class="p">]</span> <span class="o">=</span> <span class="n">SetDelayTimer</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF18</span><span class="p">]</span> <span class="o">=</span> <span class="n">SetSoundTimer</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF1E</span><span class="p">]</span> <span class="o">=</span> <span class="n">AddXToI</span><span class="p">()</span>

        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF29</span><span class="p">]</span> <span class="o">=</span> <span class="n">LoadCharacterAddress</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF33</span><span class="p">]</span> <span class="o">=</span> <span class="n">SaveXAsBcd</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF55</span><span class="p">]</span> <span class="o">=</span> <span class="n">SaveRegistersZeroToX</span><span class="p">()</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="mh">0xF65</span><span class="p">]</span> <span class="o">=</span> <span class="n">LoadRegistersZeroToX</span><span class="p">()</span>


    <span class="k">def</span> <span class="nf">find_operation</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">word</span><span class="p">):</span>
        <span class="s">"""
        This method takes a 16 bit value representing an
        opcode and returns the related operation
        """</span>

        <span class="n">opcode</span> <span class="o">=</span> <span class="n">Opcode</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>

        <span class="c1"># make a key of a + n + n so that 0xA123 becomes 0xA23
</span>        <span class="n">twelve_bit_key</span> <span class="o">=</span> <span class="nb">int</span><span class="p">((</span><span class="n">opcode</span><span class="p">.</span><span class="n">a</span> <span class="o">&lt;&lt;</span> <span class="mi">8</span><span class="p">)</span> <span class="o">+</span> <span class="n">opcode</span><span class="p">.</span><span class="n">nn</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">twelve_bit_key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="n">twelve_bit_key</span><span class="p">]</span>

        <span class="c1"># make a key of a + n so that 0xA123 becomes 0xA3
</span>        <span class="n">eight_bit_key</span> <span class="o">=</span> <span class="nb">int</span><span class="p">((</span><span class="n">opcode</span><span class="p">.</span><span class="n">a</span> <span class="o">&lt;&lt;</span> <span class="mi">4</span><span class="p">)</span> <span class="o">+</span> <span class="n">opcode</span><span class="p">.</span><span class="n">n</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">eight_bit_key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="n">eight_bit_key</span><span class="p">]</span>

        <span class="n">four_bit_key</span> <span class="o">=</span> <span class="n">opcode</span><span class="p">.</span><span class="n">a</span>
        <span class="k">if</span> <span class="n">four_bit_key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">_operations</span><span class="p">[</span><span class="n">four_bit_key</span><span class="p">]</span>

        <span class="k">raise</span> <span class="nb">KeyError</span><span class="p">(</span><span class="sa">f</span><span class="s">"Opcode </span><span class="si">{</span><span class="n">word</span><span class="si">:</span><span class="c1">#06x</span><span class="si">}</span><span class="s"> is invalid"</span><span class="p">)</span>
</code></pre></div></div>
<p><br /></p>

<p>The trick with this is the parsing that happens in <code class="language-plaintext highlighter-rouge">find_operation</code> - I try to find the opcodes with the most nibbles that are identifiers first, then I slowly go through to more simple ones that may only use two nibbles and finally check the ones that are only identified by their leading nibble. If an operation can’t be found I throw an exception. This is important as I spent the early period of the project mostly just writing opcodes with no working emulator to run them on. Instead, I wrote several tests to confirm the opcodes did what they said they did and also that the mapper found the expected operation when given an opcode. I also had tests to make sure that invalid codes that should not map to an operation, didn’t.</p>

<p>Writing the unit tests doubled the time it took to write a class for each operation, but the amount of bugs they caught made them invaluable. They also meant that I could be sure that any change I made did not break the functionality of existing code elsewhere. If you want to write your own CHIP-8 emulator I would very much recommend testing your code in a similar fashion.</p>

<p>Now I had a way to read binary data from roms, a virtual cpu, and working opcodes. What I needed next was a renderer. Writing a simple renderer in pygame that drew an all black screen and then drew white sprites over that was easy enough, but sadly I hadn’t quite implemented the single draw opcode properly. I figured this out by creating a test pattern shown below:</p>

<p><br />
<img src="/images/rantimages/chip8_render_test.png" alt="renderer test" />
<br /></p>

<p>It didn’t look like this at first as I had incorrectly implemented the opcode. Among other things I had used the raw values in the opcode as the “start drawing at x and y co-ordinates” rather than using the values in the registers they pointed to. Yes, the good old <em>forgot to dereference a pointer</em> error. Sigh.</p>

<p>The good news is that by writing the renderer test it was easier to track down the bug and I soon had the emulator partially working. I found a useful <a href="https://slack-files.com/T3CH37TNX-F3RF5KT43-0fb93dbd1f">test ROM</a> to confirm that the emulator was working correctly <a href="https://slack-files.com/T3CH37TNX-F3RKEUKL4-b05ab4930d">(you can see the documentation for it here)</a> but I was getting strange output like shown below:</p>

<p><br />
<img src="/images/rantimages/chip-8-failing-test.png" alt="failing tests" />
<br /></p>

<p>I was scratching my head for a while but after looking at the documentation I could see which opcodes were failing but I wasn’t sure why. To fix this, I had to take a step back and write my own debugger that allowed me to run the program step by step and print all the register values on screen so I could see where things were going wrong. It looks like this:</p>

<p><br />
<img src="/images/rantimages/chip8_debugger.png" alt="renderer test" />
<br /></p>

<p>It took a little time to figure out the simplest way to write a debugger and implement it but it was more than worth the effort. Like my unit tests and the test rom, I consider the debugger a crucial part of building the emulator and it sped fixing errors up immeasurably.</p>

<p>After stepping through each error the test rom threw up I found that the basic font of the CHIP-8 wasn’t working. I hand crafted a fresh test rom byte by byte with a hex editor to print each character stored in the font, then used my debugger to loop through it. It turned out my font loading code was broken and looking at the wrong addresses. Once this was fixed, the test ROM started working. It’s hard to explain how happy just seeing this made me:</p>

<p><br />
<img src="/images/rantimages/bon-by-best-coder.png" alt="très bon" />
<br /></p>

<p>It’s silly, but it meant the emulator was mostly working! In my excitement I immediately booted up a full phat game <a href="https://en.wikipedia.org/wiki/Space_Invaders">(space invaders)</a> and was overjoyed to see the awesome title screen run.</p>

<p>Sadly, in my haste I hadn’t actually implemented input or sound yet so I couldn’t move any further than the menu screen. I was also confused as the screen appeared to flicker slightly. This was due to me running my emulator far too slowly <em>(a CHIP-8 runs best at roughly ~500hz and I was running it at 60hz)</em> and the drawing operation being rather slow to begin with. I looked up some footage of other CHIP-8 emulators and when I saw the same oddness I breathed a sigh of relief.</p>

<p><br /></p>
<iframe width="480" height="360" src="https://www.youtube.com/embed/NVd5vOiGhNU" frameborder="0" allow="encrypted-media" allowfullscreen="">
</iframe>
<p><br /></p>

<p>Input was slightly more complicated so I ended up just using the existing pygame api to handle that. Once I put it all together I could finally play space invaders and other CHIP-8 games like <a href="https://en.wikipedia.org/wiki/Pong">pong</a> and <a href="https://en.wikipedia.org/wiki/Tetris">tetris</a>. Old and well known they may be but there was something very novel about playing them on a system I had crafted for myself. For reference, this is how my emulator looks playing pong:</p>

<p><br />
<img src="/images/rantimages/pong.gif" alt="pong" />
<br /></p>

<p>I showed off my project to a few people at work and they were pretty awesome in providing feedback and genuine interest. The only downside is they are now egging me on to build a <a href="https://en.wikipedia.org/wiki/Game_Boy">game boy</a> emulator which I am seriously considering doing if I can find the time.</p>

<p>Building this emulator might seem like a simple enough task but it’s one of the biggest projects I’ve done outside of my day job for a long time and was good fun. I had to spend some time planning and reading before coding so I felt this was a nice way to stretch my engineering legs. If you’re interested in emulation even a little bit I would recommend this as a fun project to learn the basics. <a href="https://github.com/edwin-jones/pychip8">You can find the source code for my emulator on github.</a></p>]]></content><author><name></name></author><summary type="html"><![CDATA[UPDATE 2022: This post has now been rewritten for issue 54 of Wireframe magazine and is available here on page 48.]]></summary></entry></feed>