<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Brian Candler on Medium]]></title>
        <description><![CDATA[Stories by Brian Candler on Medium]]></description>
        <link>https://medium.com/@brian-candler?source=rss-85f9051accd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Brian Candler on Medium</title>
            <link>https://medium.com/@brian-candler?source=rss-85f9051accd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:11:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brian-candler/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Roland S-1 “Tweak” Synthesizer]]></title>
            <link>https://brian-candler.medium.com/roland-s-1-tweak-synthesizer-816e0c2b9660?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/816e0c2b9660</guid>
            <category><![CDATA[keyboard]]></category>
            <category><![CDATA[roland]]></category>
            <category><![CDATA[electronic-music]]></category>
            <category><![CDATA[digital-audio-workstation]]></category>
            <category><![CDATA[synthesizers]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 17:07:36 GMT</pubDate>
            <atom:updated>2023-06-13T07:50:24.182Z</atom:updated>
            <content:encoded><![CDATA[<h4>A pocket-sized poly that packs a punch</h4><figure><img alt="Roland S-1 next to a teacup and teaspoon for scale" src="https://cdn-images-1.medium.com/max/1024/0*JL9rb6v6xTTu_oQN" /></figure><p>When searching for something to introduce my daughter to the world of synthesizers, I stumbled across the new <a href="https://www.roland.com/uk/products/s-1/">Roland S-1</a>. It’s the size and weight of a paperback book, runs off its own rechargeable battery, sounds amazing, and costs about a third of the other options I was looking at (such as the Korg <a href="https://www.korg.com/uk/products/synthesizers/minilogue_xd/">Minilogue XD</a>). What’s not to like?</p><h3>Overview</h3><p>The S-1 is a shrunk-down copy of the slightly larger SH-01A, which in turn is a digital recreation of the monophonic, analogue <a href="https://en.wikipedia.org/wiki/Roland_SH-101">SH-101</a> which was sold from 1982 to 1986. Compared to its venerable ancestor it adds a host of features including 4-note polyphony, a sequencer and arpeggiator, and chorus/delay/reverb effects. Being a digital emulation, it never goes out of tune. What’s more, it can send and receive audio digitally via its USB-C port (which appears as an audio in/out interface on the host computer); the same port also doubles up for MIDI and charging.</p><p>It can store 64 “patterns” each containing both synth presets and sequencer data. The first 16 contain factory-set examples that you can overwrite, and the remaining 48 are blank.</p><p>Out of the box it comes with a USB-A to USB-C lead, and nothing else. A padded carry case is sold as an optional extra. There is no internal speaker, so to get started you’ll need to plug headphones into the 3.5mm output jack (unless you connect to a PC and take digital audio over USB). There’s not even a printed manual included — it’s a <a href="https://www.roland.com/uk/support/by_product/s-1/owners_manuals/">PDF download</a>.</p><h3>Keyboard</h3><p>The S-1 has 25 small buttons serving as a two-octave keyboard, and which double up with other functions when used in conjunction with the Shift key. For example, Shift and Oct-/Oct+ (which are two of the black notes) can be used to move the keyboard up and down in octaves.</p><p>The keyboard is quite playable and certainly fine for setting up riffs in the sequencer; and of course you can always play it over MIDI. There’s a MIDI interface in the USB-C port, as well as MIDI in/out on 3.5mm jacks (a format I’ve never seen before, but you can get adapters to convert this to regular MIDI ports)</p><p>There are no pitch bend or modulation wheels. Instead, there is a feature called “D-MOTION”: press a button, then tilt the whole device front-to-back or side-to-side. It makes the unit behave like a large joystick, and is lots of fun to use. The two directions can be separately routed to a range of different controls¹.</p><h3>Audio path</h3><p>Here is a simplified block diagram. It’s part of a 4-page “quick reference” that I created, which you can download from <a href="https://github.com/candlerb/roland-s1-quick-reference/releases/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ntCVfXlrZWM-VFjgya28g.png" /><figcaption>Roland S-1 Main Controls — simplified block diagram</figcaption></figure><p>There are the traditional synthesizer components you’d expect:</p><ul><li>Three oscillators (square/pulse, triangle, and a square/pulse sub-oscillator which is 1 or 2 octaves below) plus a pink/white noise generator.</li><li>A low-pass filter, with adjustable cutoff and resonance</li><li>An ADSR envelope generator, which can control amplitude, filter cutoff, and/or pulse width modulation of the main square/pulse oscillator</li><li>A low-frequency oscillator (modulation source) which can affect pitch, filter cutoff, and/or pulse width modulation. It includes a “random” shape for sample-and-hold-like effects.</li></ul><p>These are followed by digital chorus, delay (echo) and reverb effects.</p><p>There’s no ring modulation, oscillator sync or FM synthesis, but you can run the LFO in high-speed mode which allows a range of effects to be achieved.</p><p>There are four polyphony modes: polyphonic, monophonic, unison (where all four voices play the same note for a rich layered sound), and chord (where you configure the intervals between the voices).</p><p>The filter is low-pass only and has a very peaky resonance, which can go into self-oscillation if you crank it all the way up — effectively giving you another sine-wave source. You can set up keyboard tracking so that the filter cutoff follows the input note — and incidentally, in polyphonic mode this demonstrates that there are 4 separate filters, rather than all four voices going into a shared filter, as some synths have.</p><p>However, this is the point where you realise the issues with the S-1’s small form factor.</p><h3>Control surface</h3><p>Due to the tiny size of the S-1, there are a limited number of control knobs which are directly available on the surface . They are quite fiddly, although still much more tactile and immediate than using a mouse with a software synth emulator.</p><p>Some other controls are available² using Shift+knob combinations: for example, Shift + Filter Env knob (normally “filter envelope tracking”) controls filter keyboard tracking. These are not marked, so you have to learn where they are.</p><p>Other options are available using Shift + note keys, which are labelled. For example, Shift + AMP (one of the black notes) switches the amplifier section from envelope tracking to simple gate on/off control and back again.</p><p>But many other options are buried in menus, which you access using Shift + 15 (Menu), then use the Tempo/Value knob to select a menu, then hit Enter to go into that menu, adjust with Tempo/Value again, hit Exit to leave that setting and Exit again to leave the menus. Ugh. Chorus and LFO key sync are two examples which can only be controlled via menus.</p><p>And this is where the most unwelcome throwback to the 1980’s comes in: the 4-digit, 7-segment display, like an old alarm clock. It <em>tries</em> to display text here, and fails miserably. For example, what do you think this menu item is?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*NBAfNw-hsVbv8Af8MHcO7A.png" /></figure><p>It’s actually trying to say “Mod.d” for “(LFO) Modulation Depth”. But that’s an easy one. How about this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*y08y6-tav17TnCaT6r5Qtg.png" /></figure><p>That’s “Reload Sequence” — restore the sequencer notes (but not the sound settings) from the saved pattern. How about these?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*HUm46NNiQbGQRTVHguRBiQ.png" /></figure><p>These are used when setting up chord mode. They are “v2.SW” (voice 2 switch on/off), and “v2.KS” (key shift, i.e. note offset) respectively.</p><p>Roland could easily have fitted a dot matrix display in the space available. You can either see this as a ludicrous cost-saving measure to shave a few pence off the price; or you can see it as benefit, increasing its retro “nerd appeal”. But it certainly doesn’t help if you’re trying to use the S-1 to introduce synthesizers to a newcomer. After a brief demo, my daughter gave a very succinct summary: <em>“it’s complicated”</em>.</p><p>The <a href="https://www.roland.com/uk/support/by_product/s-1/owners_manuals/">manual</a> covers everything, but you really need to work through it all and keep referring to the tables in the back. That’s why I ended up making the <a href="https://github.com/candlerb/roland-s1-quick-reference/releases/">quick-reference card</a>.</p><p>The lack of a dot-matrix display becomes a further drawback when you use some of the S-1&#39;s more advanced features. The square oscillator can be switched into an “Osc Draw” mode, which lets you plot your own waveform from scratch; and “Osc Chop” allows chopping an existing waveform to add extra harmonics. But these are very hard to use without a waveform display to see what you’re doing.</p><p>Fortunately, the USB audio capability provides a solution: you can connect to a PC and run a software oscilloscope, such as “Oscilloppoi” (99p from the Mac app store)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*2b6AOgfzQb8TaTi1_j40Kg.png" /><figcaption>Oscilloppoi display of a triangle wave in Oscillator Draw “Step” mode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*51B8s3Zb60dpT0cItpehsQ.png" /><figcaption>“Slope” mode smooths the edges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*c_z34RBa1uNPNKHFmotn1Q.png" /><figcaption>Adding some gritty “Chop” to the waveform</figcaption></figure><h3>It it worth it?</h3><p>The S-1 retails for around £180, and at this price it’s got to be one of the cheapest introductions to the world of “real” synthesizers you can get. It’s small enough to throw in a bag, and yet it’s a fully fledged instrument that wouldn’t be out of place in a professional studio. The MIDI, USB audio and Clock Sync connectivity means it can integrate into a digital audio workstation or any larger studio setup.</p><p>The <a href="https://www.korg.com/uk/products/synthesizers/">Korg</a> range of Monologue / Minilogue / Minilogue XD would, in my opinion, be much better for teaching and learning. They all have much better laid out control surfaces, and a built-in oscilloscope display. However, the Monologue is over 40% more expensive than the S-1, whilst only being a monophonic synth; and the other two are far more expensive, although you do get a proper 3 octave keyboard with these. They still have menus that you have to navigate for hidden settings. For example, only the Minilogue XD has a dedicated Portamento knob.</p><p>On the whole, the set of features you get from the S-1 in a compact and low-cost package is compelling.</p><p>If you want a more detailed look, I recommend <a href="https://www.youtube.com/watch?v=b5sQMMKn2FU">this video</a> by “Jorb”, a genuine synthesizer nerd. Just be warned that he covers it at break-neck speed!</p><p>¹Roland refers to the two directions as “Pitch” and “Roll”, like movements on an aeroplane. That’s technically correct but a bit confusing, as “Pitch” means the front-to back movement, not musical pitch — although you can route this movement to pitch bend, should you wish.</p><p>²The range of shift controls has been expanded in firmware version 1.02. The unit I bought came with version 1.01, so I upgraded it over the USB port. This is a <a href="https://www.roland.com/uk/support/by_product/s-1/updates_drivers/">fairly straightforward operation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816e0c2b9660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monads in 10 minutes!]]></title>
            <link>https://brian-candler.medium.com/monads-in-10-minutes-7640ac25f4da?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7640ac25f4da</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 11:40:59 GMT</pubDate>
            <atom:updated>2023-03-27T07:52:41.598Z</atom:updated>
            <content:encoded><![CDATA[<h4>I challenged myself to explain Monads whilst keeping it within a Medium “10 min read”</h4><p>In lockdown, I wrote a rambling <a href="https://brian-candler.medium.com/functional-programming-illustrated-5974586a8cf0">series</a> of articles, where in reality I was just trying to get my own head around monads once and for all. Now I’m going to try to explain the concept more succinctly.</p><h3>Function application</h3><p>I’m going to assume you understand two concepts already. The first one is <em>applying a function </em><strong><em>f</em></strong><em> to a value </em><strong><em>v</em></strong>. In mathematics, and many programming languages, it’s written like this:</p><pre><em>f(v)</em></pre><p>If <em>f</em> is a <em>pure function</em>, then the returned value depends only on its internal logic and the supplied argument value <em>v</em>. It is not affected by any other state in the system, nor does it have any side-effects which modify the state of the system. Applying the same <em>f</em> to the same <em>v</em> always gives the same result.</p><p>Apart from that, you can perform whatever calculation you like inside <em>f.</em></p><h3>Higher order functions</h3><p>The second concept is a <em>higher-order function:</em> one which accepts another function as a value.</p><p>The simplest, non-trivial¹ higher-order function looks like this:</p><pre><em>g(f, v)</em></pre><p>Function <em>g</em> accepts another function <em>(f)</em> and a value <em>(v)</em>, does some calculations, and returns a value.</p><p>As part of its internal logic, <em>g </em>may choose to apply function <em>f</em> to some values. Note that <em>g</em> doesn’t necessarily have to apply <em>f</em> at all: for example, it might choose to apply it only for certain values of <em>v</em> but not for others. Or it might apply it repeatedly, with the number of applications depending on the value of <em>v</em>. It’s all down to what you decide to write into the behaviour of <em>g</em>: again, that’s entirely up to you<em>.</em></p><p>OK, that’s it!</p><h3>What’s a monad then?</h3><p>A monad consists of:</p><ul><li>A Type (or Class) of values: let’s call that type T</li><li>A function which acts on values of that type, of the form:</li></ul><pre>bind(f, v)</pre><p>…where <em>v</em> is of type T, and <em>f</em> is some other function you pass in. You can see that <em>bind</em> is just a simple higher-order function like <em>g</em> I showed above.</p><p>The <em>bind</em> function is part of the implementation of a particular monad. If the class was written by someone else, and you are just using it, then you don’t touch it: it’s already been written for you. You have to provide your own function <em>f</em> at each place where <em>bind</em> is invoked though.</p><p>When I say “Class”, yes, that does correspond to what object-oriented programmers think of as a “class”, where every <em>v</em> is an <em>instance</em> of that class. Since the <em>bind</em> function accepts a single instance of type T as one of its arguments, this could also be written in OOP form as an <em>instance method</em> like this:</p><pre>v.bind(f)</pre><p>Alternatively, if your language supports operator overloading, then you can make this an operator instead: if <em>bind</em> is renamed to be the operator &gt;&gt;= (as in Haskell) then it becomes:</p><pre>v &gt;&gt;= f</pre><p>Choose whichever representation makes most sense to you.</p><p>That’s almost it. There are a few additional constraints that must be followed to make this type+function qualify as a monad.</p><p>An important one is that whatever function <em>f</em> you supply, the value it returns must be of type T, in other words the same type as <em>v</em>. (However, the argument passed to <em>f</em> can be of any plain type)</p><p>There needs to be a constructor function:</p><pre>unit(x)</pre><p>takes some plain value <em>x</em> and returns a corresponding value of type T.</p><p>There are a few more rules, but I’ll skip those for now².</p><p>In short, you can see that a monad is fundamentally nothing more than a class of values, and a supplied higher-order function which acts on those values and follows a few rules.</p><h3>How can you use monads?</h3><p>In lots of ways. But the one you are most likely to come across first is performing I/O in a functional language.</p><p>A pure function cannot have any side-effects, which definitely excludes things like writing to the terminal, or executing SQL statements.</p><p>If you think about it, there’s only one possible way to approach this with a pure function: it has to return a value which is a <em>request</em> to perform an impure action, such as “please output this particular string to the terminal”, or “please execute this SQL statement”. The request is just a value, so the function is still pure when it returns such a value.</p><p>Some of those actions, when executed, may in turn yield results (for example, reading a line of text from the terminal results in a string that the user typed), and those values will then have to be passed as the arguments to some other function.</p><p>Since monads already existed as a mathematical concept, they were co-opted into implementing this behaviour in functional languages.</p><ul><li>The IO Monad is a class</li><li>Each value (each instance of that class) represents a request to do something, like “please print this string to the terminal”, or “please read a line of text from the terminal”</li><li>The <em>bind</em> function/method actually performs the requested action.</li><li>It then passes the result of that action to some other function <em>f</em>, which is the function you passed as the other argument to <em>bind</em>.</li><li>The value returned by <em>f</em>, which is another instance of the IO Monad, is passed back as the return value of <em>bind</em>.</li></ul><p>All the impure behaviour is encapsulated in IO’s <em>bind</em> function. Everything else is just values being passed around.</p><p>So, let’s say that getLine is an instance of the IO Monad which represents the request “please read a line of text from the terminal”. If you write, in a Python-esque style:</p><pre>getLine.bind(f)</pre><p>then the <em>bind</em> function will perform the action of reading a line from the terminal, and pass the string value as the argument to <em>f</em>. The return value from <em>bind</em> is the value which <em>f</em> itself returned.</p><p>Here, <em>f</em> represents “the rest of the program” which consumes the value. You can write the body of <em>f</em> inline, as a “lambda” or anonymous function like this:</p><pre>getLine.bind(lambda text:<br>    ... rest of program goes here ...<br>)</pre><p>which means that the argument <em>text</em> receives the line which was typed.</p><p>In Haskell, with its operator overloading, that could be written:</p><pre>getLine &gt;&gt;= (\text -&gt; ......)</pre><p>But Haskell also provides some syntactic sugar, so you more commonly see it written as:</p><pre>text &lt;- getLine</pre><p>Underneath it’s exactly the same though.</p><p>When you want to print text to the console, you have to construct a value saying specifically what you want to print, using a helper function. Reverting to a Python-esque syntax:</p><pre>putStrLn(&quot;Hello, world!&quot;)</pre><p>That function doesn’t actually print anything though: it just creates an IO value wrapping the request. You have to <em>bind</em> that value to perform the action.</p><p>A program with multiple actions ends up as a series of nested functions:</p><pre>putStrLn(&quot;What&#39;s your name?&quot;).bind(lambda _:<br>    getLine.bind(lambda name:<br>        putStrLn(&quot;Hello &quot; + name).bind(lambda _:<br>            ... rest of program goes here ...<br>        )<br>    )<br>)</pre><p>That’s where the syntactic sugar really helps, but the messy form above shows what’s really going on.</p><h3>Other uses of monads</h3><p>Given that f(v) is direct function application, then you can think of v.bind(f) as <strong>indirect function application</strong>. It does use <em>f</em> and <em>v, </em>but depending on how the <em>bind</em> function is written, it could also do any of the following:</p><ul><li><strong>Pre-processing</strong>: preparing the value to be passed as an argument to <em>f</em></li><li><strong>Post-processing</strong>: taking the return value from <em>f</em> and performing additional computation, such as combining it with the initial value of <em>v</em>, before returning the final answer</li><li><strong>Conditional behaviour</strong>: deciding whether or not to call the function <em>f</em>, or calling it multiple times with different arguments and combining the results.</li></ul><p>This makes it a flexible building block. Examples of other monads include:</p><ul><li>the <strong>State</strong> monad (wrapping a value which is modified and carried forward between successive invocations of <em>bind</em>)</li><li>the <strong>Maybe</strong> monad (wrapping a value which may be present or absent, and skipping computation if it is absent)</li></ul><h3>Further reading</h3><p>If you want to see the nuts and bolts of exactly how I/O is performed using monads, see <a href="https://brian-candler.medium.com/function-programming-illustrated-in-python-part-5-90c4882b21b7">part 5</a> of my series.</p><p>If you want to know more about the structure of a monad and the rules it must follow, see <a href="https://brian-candler.medium.com/function-programming-illustrated-in-python-part-4-bc8948ec6433">part 4</a>. It also goes into some more detail around the Maybe monad, and has links to other recommended reading.</p><p>¹I could have written <em>g(f)</em> but it’s not that useful. <em>g</em> would have to apply <em>f</em> to a hard-coded static argument, say 0; or return another function value.</p><p>²One of the laws that a monad must follow is unit(x).bind(f) is the same as f(x). Another is that v.bind(unit) is the same as v. Finally there’s an associativity rule. These are mathematical properties of a monad that you can rely on, in a similar sense that x+0 and 0+x are always x for addition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7640ac25f4da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things I wish my music teacher had taught me at school: Part 2]]></title>
            <link>https://brian-candler.medium.com/things-i-wish-my-music-teacher-had-taught-me-at-school-part-2-8d1cad203d51?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d1cad203d51</guid>
            <category><![CDATA[music-theory]]></category>
            <category><![CDATA[chords]]></category>
            <category><![CDATA[musical-scales]]></category>
            <category><![CDATA[music-composition]]></category>
            <category><![CDATA[jazz]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 14:56:41 GMT</pubDate>
            <atom:updated>2023-08-15T16:53:48.966Z</atom:updated>
            <content:encoded><![CDATA[<h4>Scales</h4><p>In <a href="https://brian-candler.medium.com/things-i-wish-my-music-teacher-had-taught-me-at-school-part-1-b8ed65ba92a1">part 1</a>, I looked at how chords are constructed, in particular the importance of the <em>third</em> and the <em>seventh.</em> This leads to four very important chord shapes: if the root note is C, then you get:</p><ul><li>C∆ (major 3rd, major 7th)</li><li>C7 (major 3rd, minor 7th)</li><li>Cm7 (minor 3rd, minor 7th)</li><li>Cm∆ (minor 3rd, major 7th)</li></ul><p>But what are the other notes of the scale that we can use with these?</p><h3>7-note scales</h3><p>Most of the interesting scales, and the ones you are almost certainly familiar with, have 7 notes. Since there are 12 semitones in an octave, this means there are five intervals of a full tone, and two intervals of a semitone. Here is how a standard C major is constructed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*DvD9r4MGuoxPxbYs973TAQ.png" /><figcaption>C major, showing the semitones with slurs</figcaption></figure><p>But given a root note, a third and a seventh, that’s not the only way we can fit notes in between to make a 7-note scale.</p><p>In the previous article, I observed that the perfect fourth over a major chord has a jarring sound. Can we fix that? Yes we can, by sharpening the fourth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*DgSagS5LHcBVr92Pbg2puQ.png" /><figcaption>C major with sharpened fourth (Lydian)</figcaption></figure><p>This scale even has a special name: the <em>Lydian</em>. It’s different to the normal major scale, but still has a major third and major seventh, so it fits with our C∆ (Cmaj7) chord shape.</p><p>Now, this might seem weird when you first hear it. And definitely <em>don’t</em> try to play <em>“Twinkle Twinkle Little Star”</em> with a Lydian scale: it sounds completely wrong.</p><p>But in many contexts this is an extremely natural scale. In fact, the sharpened fourth is perhaps the most beautiful note you can put over a major chord. Try it.</p><h3>Modes</h3><p>The next question you might have is, “is this a new scale I have to learn to play”? Well, look at the C Lydian scale again carefully. Have you seen a scale before, which has all natural notes except an F sharp?</p><p>Trust me, you have.</p><p>It’s just the G major scale — starting on the 4th note!</p><p>In fact, you can get a whole series of scales, just by starting major scales on different notes. These different variations are known as <em>modes. </em>They have been known for millennia, and they were named by the ancient Greeks. Here is the full set:</p><pre>+------------+-------+-------+---------+----------------------+<br>|    Name    | Start | Third | Seventh |       Comments       |<br>+============+=======+=======+=========+======================+<br>| Ionian     |     1 | Major | Major   | Standard major scale |<br>| Dorian     |     2 | Minor | Minor   | Major 6th            |<br>| Phrygian   |     3 | Minor | Minor   | Minor 2nd            |<br>| Lydian     |     4 | Major | Major   | Augmented 4th        |<br>| Mixolydian |     5 | Major | Minor   |                      |<br>| Aeolian    |     6 | Minor | Minor   | Minor 6th            |<br>| Locrian    |     7 | Minor | Minor   | Diminished 5th       |<br>+------------+-------+-------+---------+----------------------+</pre><p>Some of these scales are major (that is, they have a major third), and some are minor.</p><p>For example, if you play a C major scale starting on the second note (the D), you get the <em>Dorian</em> mode. This has a minor 3rd and minor 7th, and a major 6th. It’s the scale you use when playing <em>“What shall we do with the drunken sailor?”</em></p><p>The Dorian mode just gives the pattern of notes and intervals: it doesn’t have to start on a D. If you want to make a Dorian scale that starts on a C, you have to work out which major scale has C as its second note (that’s B flat), and then play a B flat scale starting on C:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*VtKsu5NN_dFBLBsIz7BXXA.png" /><figcaption>Dorian mode on C</figcaption></figure><h3>Seventh chords</h3><p>Things get more interesting when you look at a chord like C7, which has a major 3rd and a minor 7th. (Technically that’s a “dominant seventh” chord, but if someone just says “seventh”, that’s probably what they mean).</p><p>In the tables of modes above, there’s only one which has a major third and a minor seventh: the <em>Mixolydian</em>. It is the same as the obvious solution: take the major scale and flatten the 7th.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*KlduW0l2nV5DbERAYv0Qvw.png" /><figcaption>C major with flattened 7th (Mixolydian)</figcaption></figure><p>(Pop quiz: what scale do you already know that has all naturals but a B flat?)</p><p>But it turns out there are lots of other, really interesting scales to connect the major third to the minor seventh: this is where much popular and jazz music gets it rich harmonies from.</p><p>If you take the Mixolydian and sharpen the fourth, as we did with the Lydian, then you get my favourite scale of all time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*zsr1PLz_BqBgBcHIF882Gw.png" /></figure><p>This scale doesn’t have an official name like the Greek modes, but “Lydian Dominant” is commonly used. It pops up in all kinds of places, like the theme tune to <em>The Simpsons:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELHJMIgQlNnpujpwfkrDqQ.png" /><figcaption>Bart!</figcaption></figure><p>At first glance, that’s a really weird scale. It has both a sharp and a flat. Surely you can’t have seen <em>this</em> scale before?</p><p>In fact, I bet you have! But you might have to look carefully to work it out.</p><p>Answer: this is actually the same notes as the G melodic minor scale, but starting on the fourth note — that is, the fourth <em>mode</em> of the melodic minor scale.</p><p>Therefore, in principle, we have also have seven modes of melodic minor to work with. In practice, there are two others that are commonly used. One of these is the seventh mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*jIzCgFpF8L5NPwrbZLufsA.png" /><figcaption>C7 alt scale (Db melodic minor in disguise)</figcaption></figure><p>Sometimes called “Super Locrian” (because it’s the same notes as the Locrian but with flattened 4th), this is more commonly known as the “altered scale”, since <em>every note</em> apart from the root and third is different to the major scale.</p><p>From a classical theory background, I found this astonishing at first. This scale has<em> </em><a href="https://www.youtube.com/watch?v=uMPEUcVyJsc&amp;t=86s"><em>all the wrong notes!</em></a> Not only that, but it seems to have <em>both</em> a minor third and a major third at the same time!¹</p><p>Is it possible that you can use this to build chords and music that sound right? Yes: it works great². Funky even. Just make sure, as I said earlier, to keep either the third or the seventh as the lowest note of the chord.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*qcabhQc-OjTk_VpYARufPQ.png" /></figure><p>Of course, this chord and the associated melody or improvisation will probably want to be using the same scale, to avoid sounding discordant. (But anything goes, if you play it with enough conviction).</p><p>The other is the sixth mode, which works over a minor 7th chord with a flattened fifth — also called “half-diminished” and given the shorthand symbol ø.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*8Wz_JoD3Mvt_4fD90L3RdQ.png" /><figcaption>Cø = Cm7b5</figcaption></figure><p>This one is also similar to Locrian, but with a major 2nd instead of a minor 2nd. You’ll find this commonly in sequences such as Cø — F7 — Bbm.</p><h3>Other scales</h3><p>Although I said that the most interesting scales were 7-note, I’ll mention a few others briefly.</p><p>There is one 6-note scale: the whole tone scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*0HkLVYFvjqoMi03fmFTZ7A.png" /><figcaption>Whole tone scale</figcaption></figure><p>This does also fit the seventh chord: it has a major third and minor seventh. But it has a weird, alien feel, with all those dissonant tritone³ intervals, and doesn’t get used very much. It’s the scale that <a href="https://www.youtube.com/watch?v=-Rj-CQ39e_c&amp;t=176s">the Clangers</a> would use when walking downstairs.</p><p>There are two 8-note scales: the diminished scale (“whole-half”), and its second mode (“half-whole”). They have alternating tones and semitones; the names tell you which way round they go.</p><p>These are actually quite useful. The half-whole scale is yet another option for seventh chords: the lower half is like the altered scale, and the upper half is like the Lydian Dominant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*5O_Yos8LnCLLtmE9w2LXKg.png" /><figcaption>Half-whole, or second mode of diminished (octatonic) scale</figcaption></figure><p>If you remove the limitation that scales can only consist of tones and semitones, then you get more possibilities. These include the <em>pentatonic</em> scale and its <em>minor pentatonic</em> mode. Add a note to the latter, and you get the infamous <em>blues scale:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*8ankvoMmy8m39C2mut8SaQ.png" /><figcaption>C blues scale</figcaption></figure><p>Try playing it over this chord⁴:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*DVJWrMu8SUcPJNvEWo55VA.png" /></figure><p>If this has piqued your interest, there are plenty of books and online resources which go into more detail.</p><h3>Conclusion</h3><p>This was a whistle-stop tour, and I necessarily left some things out (there <em>are</em> some other chord shapes, like diminished chords and major 6th).</p><p>But in short, here are the two things I wish I’d known earlier in my life:</p><ul><li>Chords are fundamentally built from the root, third and seventh. Then you can add any other notes from the scale (apart from Aunt Dolly).</li><li>For a given root, third and seventh, there are many more scales that work with them than the ones I learned in classical music theory.</li></ul><p>Thanks again for reading!</p><p>¹Observe that D sharp and E flat are essentially the same note. There are real problems when “spelling out” the notes in this scale: the way I chose has two D’s (a “flattened 9th” and “sharpened 9th”) and no F — but maybe I should have put F-sharp instead of G-flat. A true 7-note scale would have D-flat, E-flat and F-flat, but that would have looked even weirder, since the major third would turn into a flattened 4th. Or should I have used C-sharp and D-sharp (as it’s a mode of C# melodic minor)? Then I’d have A-sharp for the 7th, and either two C’s, or a B-sharp for the root. It’s messy.</p><p>²If you’re interested, there’s a reason it works so well. Try playing the C7alt chord I showed, but with F# as the bass note instead of C. The C7alt scale has the same notes as the F# Lydian Dominant — my favourite scale. The 3rd and 7th notes of C7 are the same as the 7th and 3rd notes of F#7, and the root note of one is the sharpened 4th of the other.</p><p>³Also known as augmented fourth, or diminished fifth.</p><p>⁴You can hear this in <em>Kelly Blue</em>, from the album of the same name by Wynton Kelly, when the opening head is played for the second time (at 0:45 <a href="https://www.youtube.com/watch?v=gK4uJe0xwYA">here</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1cad203d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things I wish my music teacher had taught me at school: Part 1]]></title>
            <link>https://brian-candler.medium.com/things-i-wish-my-music-teacher-had-taught-me-at-school-part-1-b8ed65ba92a1?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8ed65ba92a1</guid>
            <category><![CDATA[jazz]]></category>
            <category><![CDATA[musical-scales]]></category>
            <category><![CDATA[chords]]></category>
            <category><![CDATA[music-composition]]></category>
            <category><![CDATA[music-theory]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 15:23:59 GMT</pubDate>
            <atom:updated>2023-08-21T19:22:43.923Z</atom:updated>
            <content:encoded><![CDATA[<h4>Chords</h4><p>When I was growing up, my musical education was entirely classical: classical piano, classical violin (played very poorly I should add!) and classical music theory.</p><p>All that time, I could <em>hear</em> the harmonies in pop music and jazz, and they sounded great, but I wasn’t able to make sense of them. This made them hard to copy and to build on; I didn’t really even try.</p><p>Many years later, I think I finally got to grips with it. It turns out that just a couple of small pieces of knowledge would have made a huge difference. In these short articles, I’d like pass on those small nuggets which I wish I had known earlier.</p><h3>How do you build a chord?</h3><p>Suppose you were sitting down at a piano right now, and I asked you to play a C major chord. What would you play?</p><p>As teenage me, this is what I would have given you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*Y2augh2mCunXBJSSSAtCbA.png" /><figcaption>C major</figcaption></figure><p>That’s C, E and G: the root, third and fifth of C major. This chord structure even has a special name, derived from having three notes: the <em>triad¹</em>.</p><p>That’s all fine and dandy, and it all makes perfect theoretical sense.</p><p>The problem is: it sounds, to put it politely, lame.</p><p>Why does it sound lame? Well, there are two reasons.</p><p>Firstly, the bass note is too high. But if you play it down an octave, it sounds muddy: the notes are too close together for this low pitch, and your ear can’t distinguish them properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*l-oyQDVL4r0oHEFgsoN1pg.png" /><figcaption>C major triad (low down)</figcaption></figure><p>The second reason is the presence of the C-G interval, the <em>perfect fifth</em>. For reasons of physics, the perfect fifth contains many of the same harmonic frequencies as the root. Therefore, it just reinforces the root, whilst hardly adding any colour of its own. Try playing the fifth by itself, and then the octave, then both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*OMLZxPMoHygVSDJ7AIyI3Q.png" /><figcaption>Fifth and octave</figcaption></figure><p>They sound almost identical. The perfect fifth doesn’t add any character to the chord, making it superfluous.</p><h3>A different approach to chords</h3><p>So, if that’s not a great way to build chords, what’s a better way? Here is the simple solution I learned from jazz courses years later.</p><ol><li>Put the root low down in the bass.</li><li>Add the <em>third</em> and the <em>seventh</em> note higher up (in either order).</li></ol><p>In order not to sound muddy, the lower of those two notes shouldn’t really go any lower than the E flat below middle C.</p><p>And that’s it. Really? Really.</p><p>Given that there are two types of third (minor and major), and two types of seventh (ditto), this gives four fundamental chord shapes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*V9__iXCitE_F5wxt53nIPA.png" /><figcaption>Four types of C chord</figcaption></figure><p>In jazz scores, you may see these as C∆, C7, Cm7 and Cm∆ respectively.</p><p>As I said before, you are free to make the seventh lower than the third. Try it: they work just as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ZE0FlNoKiZVKI0BcN3J-1w.png" /><figcaption>Swapping thirds and sevenths</figcaption></figure><h3>Guide tones and voice leading</h3><p>The third and seventh are known as <em>guide tones</em>, and they work remarkably well just on their own, with a spacious and airy feel. Take a bass line, add a piano or two solo instruments playing nothing but guide tones, a lead instrument and some rhythm, and you have the basis of a real and satisfying arrangement.</p><p>One reason it works so well is when you see how the thirds and sevenths can follow each other. Take the chord sequence Dm7 — G7 — C (which will be recognisable as a <em>cadence</em> to all you music theoretics out there). Write it out using guide tones, but choose the thirds and sevenths which are as close to each other as you can. One possibility looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*24lj4z4LuQxXwjw4TaxZnw.png" /><figcaption>2–5–1 cadence</figcaption></figure><p>The first chord is Dm7 with the seventh below the third; the second is G7 with the third below the seventh. This gives a pleasant “descending-in-semitones” path to the inner voices, in effect a simple inner melody, known as <em>voice leading</em>. It’s very natural and satisfying.</p><p>If you’re playing a piano without a bass, you can even get away with just the root note and the third or seventh in your left hand (that is, the lower two notes of the voicings shown above) — known as “Bud Powell” voicings.</p><h3>Building up chords</h3><p>Although these simple chords work really well, there’s more you can do and more interesting sounds to be had. How do you build up richer and more complex chords?</p><p>That turns out to be extremely easy too:</p><ol><li>Start with the guide tones.</li><li>Add as many of the other notes of the scale as you like, in whatever way you like. (Keep either the third or the seventh as the lowest note though).</li></ol><p>It’s really that simple, and it really works!</p><p>There’s just one exception: <strong>don’t play the perfect fourth over a major chord</strong>. You can find out why if you try it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*DDuPFKC8U0D3d4HlnpEuVw.png" /></figure><p>Add the 6th over a major chord — nice. Add the 2nd (or the 9th if you prefer to think of it that way) — nice. Add the perfect fourth: OUCH! It’s that octave-plus-a-semitone interval which grates².</p><p>I also had this sound described³ to me using the story of “Aunt Dolly”. Aunt Dolly is one of those relations you don’t see very often. She’s not very musical, but when she comes around at Christmas and has had a few drinks, she sits down at the piano to play her rendition of “Jingle Bells”. Here’s how it goes: note the repeated major triad in the left hand. You need to play it to get the full effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbVeszoSOMFuvxjKgQzTRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYeFboLB_mUpJMg2ivhr0A.png" /><figcaption>Aunt Dolly after a few drinks</figcaption></figure><p>By this point, everyone is yelling “Aunt Dolly, STOP!”</p><p>Anyway, returning to that simple Dm7-G7-C cadence from before: by adding more notes from the scale to the third and seventh, you can build scrunchy chords like these that fit into one hand (perfect for your left hand when improvising with the right):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*bVGwkQRrTx-q2YLTI_i6rA.png" /></figure><p>Or you can build wide, spaced-out chords with four or five notes or more, spread across two hands. The possibilities are endless.</p><h3>What’s a scale?</h3><p>Just now, I said you can use “any notes of the scale” in your chords. But what scales are there, and what notes do they contain?</p><p>That will be the subject for <a href="https://brian-candler.medium.com/things-i-wish-my-music-teacher-had-taught-me-at-school-part-2-8d1cad203d51">part two</a> of this series. Thanks for reading.</p><p>¹I could have gone into more theory, like the triad “inversions” — putting the third or fifth as the bottom note. It’s not really relevant here.</p><p>²Still, tastes do change over the years. A century or two ago, the minor 7th over a major chord was considered dissonant, but now our ears are accustomed to it. Maybe this will sound fine to future generations.</p><p>³Heard from the late, great <a href="https://en.wikipedia.org/wiki/Michael_Garrick">Michael Garrick</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8ed65ba92a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rediscovering the Power Factor]]></title>
            <link>https://brian-candler.medium.com/rediscovering-the-power-factor-9dbf4187c311?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dbf4187c311</guid>
            <category><![CDATA[solar-power]]></category>
            <category><![CDATA[energy-meter]]></category>
            <category><![CDATA[power-measurement]]></category>
            <category><![CDATA[home-energy]]></category>
            <category><![CDATA[power-factor]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Sun, 22 May 2022 21:28:24 GMT</pubDate>
            <atom:updated>2023-01-10T06:42:03.391Z</atom:updated>
            <content:encoded><![CDATA[<h4>…or, why clip-on power meters can give wildly misleading readings</h4><p>Before I installed my <a href="https://brian-candler.medium.com/living-with-solar-part-1-9037739cad6d">solar PV system</a> I wanted to get an accurate idea of how much background power I was using, to decide how big a battery I needed to cover overnight usage. I also wanted to know where in the house it was going; and whether there were any quick wins I could get by turning off power-hungry devices.</p><p>This turned out to be a longer voyage of discovery than I was expecting. Eventually some long-forgotten electronics knowledge saved the day!</p><p><strong>TL;DR: power meters that clip onto your incoming electricity supply can give wildly misleading readings.</strong></p><h3>The starting point</h3><p>I knew from my utility meter readings that I use around 3,600kWh per year, or 10kWh per day.</p><p>Dividing by 24 gives 0.417 kilowatt-hours per hour — or more simply, 417 watts. That’s my <em>average</em> power consumption. That seems quite high, given that devices on standby ought to use only 1 or 2 watts each.</p><p>We use electricity for cooking, so I know that will account for a big chunk of it (although hot water and central heating are gas). The kettle is used many times per day, for drinking tea. Then there are the washing machine and tumble drier and so on. All of these things consume a lot of power when running, but nothing when idle.</p><p>I wanted to find out how much of the usage is continuous background power drain, also known as “vampire power”, and whether there was anything I could do to reduce it.</p><h3>Take 1: The clip-on power meter</h3><p>Many years ago, I bought an “<a href="http://www.reuk.co.uk/wordpress/shopping/electrisave-review/">ElectriSave</a>” wireless power meter, a model which is no longer on sale. This has a sensor that clips onto the incoming mains feed at the consumer unit, and plugs into a transmitter. There is a separate display which shows your usage. Both parts are battery powered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/0*9p0RQ5CaLqOq8eOO.jpg" /><figcaption>ElectriSave: what comes in the box (image: <a href="http://www.reuk.co.uk/wordpress/shopping/electrisave-review/">REUK</a>)</figcaption></figure><p>I decided to dig this out and give it another go.</p><p>Firstly, I switched off the fridge and freezer. These are things which turn off and on intermittently, so would make accurate measurements difficult. I reasoned that I can make separate measurements for these later. In any case, we can’t live without them, so they’re not really “vampire” power.</p><p>Under these conditions, the power meter told me that the house was using: 310 watts!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*ONsFYvykaD6RXIaK2XVBpw.png" /><figcaption>Background power as measured by ElectriSave</figcaption></figure><p>Hmm, that’s more than I was expecting. 300 watts is a significant amount of power ultimately ending up as heat, and indeed not far off my total usage. That’s excluding big consumers like the oven. Could it really be that the majority of my usage is down to vampire power? I wanted to find out where this was power was going.</p><p>I switched off all the breakers in the consumer unit, and switched them on one by one. There was no obvious single circuit which could account for all this usage.</p><ul><li>Many circuits used nothing (e.g. oven, hob, garage, doorbell)</li><li>One downstairs lighting circuit used 120W — with no lights on! However this circuit also has the TV amplifier in the loft, and the bathroom extractor fan</li><li>Switching on a couple of rings used 120W — despite only having a few things on standby.</li></ul><p>Something odd was going on. But if nothing else, it was clear that the resolution of the ElectriSave was poor: although it displays increments of 0.01kW (10W), I only ever saw it jump up in increments of 30W or 40W. And it only updates a few times per minute, making it very hard to pin down the source.</p><p>Time to get a better device.</p><h3>Take 2: The current clamp meter</h3><p>My ancient Maplin multimeter has a dodgy switch, so I decided to treat myself to a <a href="https://www.amazon.co.uk/gp/product/B00O1Q2HOQ">new meter</a>, one with a current clamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*z4Xexs89-RQb-clfwnHdGw.png" /><figcaption><a href="https://www.amazon.co.uk/gp/product/B00O1Q2HOQ">UNI-T mini clamp multimeter</a></figcaption></figure><p>This fits around the incoming mains wire, just like the ElectriSave.</p><p>Under the same conditions, here’s the measurement I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*VnAYiFMIxS-twOOMiJpIQA.png" /></figure><p>That’s 1.344 amps. The supply is 240 volts, so we get</p><blockquote>Power = volts x amps = 240 x 1.344 = 322 watts</blockquote><p>So the ElectriSave was right all along! Or so I thought.</p><h3>Take 3: Measuring individual devices</h3><p>One benefit of the clamp meter, though, is that it has extremely fine resolution, down to 0.001A (1 milliamp), as well as refreshing several times per second. This meant I could turn individual devices off and on, and see how that affected the power in real time¹.</p><p>Taking one example: with just the kitchen socket ring active, I measured 0.146A. By turning things off one at a time, and seeing how much the current dropped, I was able to break this down into:</p><ul><li>Fridge: 0.053A (it was plugged in at this point)</li><li>Microwave: 0.012A (it has a built-in clock)</li><li>Sonos Play 1: 0.062A</li><li>Everything else: 0.019A</li></ul><p>The Sonos, which was sitting there connected to the wireless network but otherwise not doing anything, appeared to account for 0.062 x 240 = 15 watts. This is an old model, but that’s pretty bad for a device which is more or less on “standby”.</p><p>The same story was repeated on other rings and with other kinds of devices I tried. 10 watts here, 15 watts there, and it soon adds up to the 310 watts of background.</p><p>I wasn’t happy. I was missing something.</p><h3>Take 4: The Plug-in Power Meter</h3><p>The next step was to directly measure the power consumption of individual devices, rather than the total power on a ring. That meant buying a <a href="https://www.amazon.co.uk/gp/product/B085S7Q1T4">plug-in power meter</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*rP6dmZFTqmA9-UXk46puLg.png" /><figcaption><a href="https://www.amazon.co.uk/gp/product/B085S7Q1T4">Plug-in power monitor</a></figcaption></figure><p>Then I went round trying some of the same devices as before.</p><p>Strangely, each individual device seemed to be using much less power. I couldn’t get them to add up to what I had found before. Was the plug-in meter inaccurate?</p><p>Let’s take the Sonos Play 1 again. Previously I thought it was using 15 watts. But the power meter says only 3.7 watts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*4UsF_rh_9c9t5I-L1v02lg.png" /><figcaption>Power meter showing watts</figcaption></figure><p>That’s odd, although it’s a more reasonable value for background power usage. Anything else it can tell me? Pressing the “Function” button, another screen shows me the voltage and frequency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*3WAGV_P9gXQVGycqgHFwlg.png" /><figcaption>Voltage and Frequency</figcaption></figure><p>That’s what I was expecting. The next screen shows me the current:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*u5A1RrXnvygXbIcavOkD1Q.png" /><figcaption>Current and…?</figcaption></figure><p>0.070A is close to what I had measured indirectly before (0.062A), simply by turning the Sonos off and seeing how much the current measured by the clamp meter fell.</p><p>But then the penny dropped. The answer was staring me in the face — right underneath the current reading.</p><h3>The Power Factor</h3><p>All along, I had been using this well-known formula:</p><blockquote>Power = Voltage x Current</blockquote><p>And you can hardly blame me, because the ElectriSave was doing this as well.</p><p>This formula works for Direct Current (DC). But as it turns out, it doesn’t necessarily work for Alternating Current (AC). For AC, the real formula is:</p><blockquote>Power = Voltage x Current x Power Factor</blockquote><p>I had learned about the power factor many years ago, but partly I had forgotten about it, and partly I thought it wouldn’t be relevant in a small domestic environment. I was wrong.</p><p>I’ll try to explain it properly later. But in short:</p><ul><li>Multiplying the voltage and current gives you the “apparent power”. This is measured in volt-amps (VA) rather than watts (W)</li><li>Multiplying this by the power factor gives you the “true power”</li><li>The true power represents the real work that the electricity is doing</li></ul><h4>Why the clip-on meter is wrong</h4><p>The clamp sensor on the clip-on meter measures only <em>current</em>, using the magnetic field emitted by the mains wire as current flows through it — just like my clamp multimeter.</p><p>In order to display a power reading, it has to <em>assume</em> that the voltage is 240 volts, and the power factor is 1.</p><p>For many large consumers of electricity in the house, particularly those devices which mainly convert electricity to heat or light, the power factor is indeed 1 or very close to it, and so this assumption is fair.</p><p>But for small devices this isn’t always true. What the ElectriSave shows is apparent power, not true power.</p><h3>Take 5: The utility meter</h3><p>What’s really important here is what I’m charged for. Does the utility company charge me for apparent power, or true power?</p><p>I read online that it’s true power, but I wanted to convince myself of this.</p><p>If you have a smart meter, this is easy (and you wouldn’t have bothered doing any of the things I’ve done in this article). But even without one, you can watch the meter itself to get a near real-time reading of power.</p><p>Old meters have a disc which rotates. Modern meters have a light which pulses periodically, and a label will say how many pulses it generates per kWh of energy usage — mine is 1,000 pulses per kWh.</p><p>What you do is watch the pulses (or disc rotations), and measure the average time between them.</p><p>There are smartphone apps available which use the camera to watch the LED pulses and perform the above calculation for you — if you can be bothered to hold your phone in the right place for long enough. I just used a stopwatch instead.</p><p>Here’s what I found, when trying it under the same conditions (fridge and freezer turned off):</p><ul><li>There are 26 seconds between pulses</li><li>This means there are 3600/26 = 138 pulses per hour</li><li>Each pulse is 1/1000 of a kWh</li><li>Therefore I am using 0.138kWh of energy per hour. Or equivalently, my power consumption is 138W.</li></ul><p>That’s <em>way</em> less than the ElectriSave was telling me. This implies that all of these devices together have an average power factor of about 0.43 (138W true power, divided by 322W apparent power)</p><p>Or put it another way: the ElectriSave was showing a value which was nearly 250% of the true power value. That’s grossly misleading.</p><h3>Take 6: The true-reading CT meter</h3><p>Unfortunately, the power factor is not constant. It varies from device to device, and how active that device is.</p><p>Always wanting to get to the bottom of a problem, I needed to know if there was a way to measure the true power to the house, using a clamp meter (so I didn’t have to touch the wiring) but which was also able to compensate for the power factor.</p><p>It turns out there is. What you need is a meter which plugs into a mains socket, so it can sense the voltage and phase, <em>and</em> has a clamp connection, also known as a CT (Current Transformer).</p><p>Some of these are <a href="https://www.amazon.co.uk/dp/B017DV3URS">expensive</a>, and I didn’t want to spend a lot of money just to confirm a theory, but I found a really cheap <a href="https://www.amazon.co.uk/gp/product/B092VYQ697">module</a> which can do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*A5cqOemp7Tov9P23Xa_msw.png" /><figcaption><a href="https://www.amazon.co.uk/gp/product/B092VYQ697">DollaTek power meter with CT</a></figcaption></figure><p>BEWARE! This is not a piece of consumer electronics. It has four screw terminals at the back. Two of them are where the CT connects, and two of them need to be connected to Live and Neutral of a mains supply. I connected them to a cable with a mains plug, and then I stuck some insulating tape over the back, and took care not to let my fingers go near that end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*R34bpPsHMmOTZMKBtq-Shw.png" /><figcaption>The power meter module, wired up</figcaption></figure><p>Don’t attempt this unless you’re sure you know what you’re doing. This is designed to be installed by an electrician, and really it’s a module that should be installed inside a permanent panel.</p><p>Anyway, when plugged into a nearby socket, and with the clamp applied to the main feed into my consumer unit, this is what I saw:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*bJ9-dE3A6OZhNwz3HbyIGg.png" /></figure><p>There you go. A true reading of 134 watts, matching the utility meter, and showing the power factor of 0.42. Success at last!</p><p>If it stays like this all day, then over 24 hours this background usage accounts for 0.134 x 24 = 3.2kWh of electricity — about a third of my total usage. And as I said before, the rest comes from things like the fridge, freezer, cooking and so on.</p><p>The module, by the way, is surplus to requirements now. It can’t tell the difference between power imported and exported, so it’s not any use with a solar PV system.</p><h3>Measuring the fridge</h3><p>The plug-in power meter that I bought (see “Take 4” above) also allowed me to find out how much the fridge uses.</p><p>The fridge is something that switches off and on intermittently, so watching its instantaneous power draw is not useful. But the plug-in power meter also counts units of energy used, just like a utility meter.</p><p>So I simply left the fridge plugged into it for about a week. From this, I was able to determine that the fridge used 7.840kWh over 7 days and 18 hours. That works out as</p><blockquote>7.840 / (7x24 + 18) = 0.042 kWh per hour</blockquote><p>… or more simply, 42 watts on average. (Exactly what any Douglas Adams fan would expect).</p><p>A similar exercises for our standalone freezer came up with 25 watts — presumably because its door is opened less frequently.</p><h3>Conclusion</h3><p>Clip-on power meters are still useful, and will give accurate readings for your use of electricity for lighting, heating, cooking, and laundry: these sorts of devices typically have a power factor of 1, as well as high power consumption.</p><p>But for small devices, a clip-on meter may give you an exaggerated idea of how much you could save by switching them off. It’s much better to get a plug-in power meter to find out what these devices are really using, and therefore, what they are really costing to run.</p><p>The rest of this article is to explain where the Power Factor comes from. If you’re not interested in that, please feel free to end here.</p><h3>Postscript: Understanding the Power Factor</h3><p>So what exactly is this Power Factor, and from where does it arise? I’ll try to explain it in simplistic terms.</p><p>The electricity supply in your house is Alternating Current (AC), which switches directions repeatedly — in a UK household it’s 50 cycles per second (50Hz). AC power naturally arises from the rotation of generators in power stations. It’s also convenient because it allows <em>transformers</em> to be used to step up and step down the voltage.</p><p>Over a cycle the voltage rises and falls, and then switches direction, following a sine wave.</p><p>With a normal “resistive” load, as the voltage rises and falls it causes a corresponding rise and fall in current — in accordance with Ohms Law. Hence the current is in phase with the voltage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dFUz38GrddiX2JRdV_4sIw.png" /></figure><p>When the voltage reverses, the current reverses too. At all times, power is going into the load, and is consumed by that load.</p><p>However there are other types of load, called “reactive” loads, which temporarily store and return energy. There are two kinds of reactive load: <em>capacitors</em> store energy in an electric field, and <em>inductors</em> store energy in a magnetic field.</p><p>Real devices have a combination of resistive and reactive behaviour. Power is consumed by the resistive part, but stored and returned by the reactive part.</p><p>In practice, what you see is that the current is out of phase with the voltage: it either leads or lags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2l7fEoAT7eSlM20u0ExQxg.png" /></figure><p>During certain parts of the cycle (highlighted in blue), the voltage is positive but the current is negative, or vice versa. During those parts of the cycle, energy is being returned <em>from</em> the load.</p><p>This explains why the true power consumed is less than the apparent power. When the voltage and current are out of phase, sometimes energy is being transferred to the load, and sometimes energy is being returned from the load. The true power is the net power which the load consumes. Your electricity meter doesn’t penalise you for “lending” some energy briefly, if you get it back in the same cycle.</p><h4>The role of transformers</h4><p>Many devices in the home need low voltages to operate, and have transformers inside them.</p><p>A transformer consists of two coils of wire wound together so as to be magnetically coupled. The primary coil creates an alternating magnetic field from the incoming supply, and the secondary coil turns that magnetic field back into a voltage (which may be higher or lower than the original, depending on the number of turns in each coil).</p><p>A transformer winding is inductive, so if the device isn’t drawing much power from the secondary coil, it appears as a reactive load.</p><h4>What effect does the Power Factor have?</h4><p>Resistive loads have a Power Factor of 1, so the true power and apparent power are the same. You can calculate the power using “voltage x current” as normal².</p><p>Devices with a reactive part have a power factor less than 1. As described above, power flows into them during part of the AC cycle but flows back out again during another part of the cycle. So overall, the power consumed is less than you’d expect just by looking at the current alone.</p><p>Or looking at it the other way: the current is higher than you would expect, when transferring the same amount of power into the load.</p><h4>If you’re charged only for true power, does Power Factor matter?</h4><p>The answer is, not much.</p><p>Most of the power you use is consumed by the devices themselves, but a small amount is wasted in the wires that deliver power to them. The wires have some resistance, and the current flowing through them makes them heat up a little.</p><p>With a power factor less than 1, the current flowing through the wires to your device is higher than it would otherwise be. So whilst the device may be using the same amount of power, the amount of power lost to heating the wires is increased.</p><p>In practice, this is usually tiny, compared to the power consumption of the device itself. If you notice the cables to your devices feeling warm, then you have a problem, and you should speak to an electrician immediately.</p><h4>Power Factor Correction?</h4><p>It’s possible to correct for the power factor, by adding extra components to bring the current and voltage into phase.</p><p>There are some devices with high power draw where power factor <em>is</em> important, primarily those with electric motors. Any devices you have like this will most likely have power factor correction built in. Without power factor correction, the increased current could cause your circuit breakers to trip.</p><p>Some people will try to sell you home power factor correction systems. <strong>Don’t buy them.</strong> At best, they will reduce the current flowing through your wires, but they will not reduce the true power consumed by your devices, and hence they won’t reduce your energy bills. The reduction in resistive heating from your home wiring will be negligible.</p><p>Such devices might be able to make the power shown by an ElectriSave-style clamp meter drop dramatically — but now you know why that’s not a true reflection of the power you are consuming.</p><p>¹You can’t just put the clamp meter around an appliance cable, because the live and neutral currents are in opposite directions and the magnetic fields cancel each other out. You have to put it around the live wire <em>or</em> the neutral wire only. In my case, I was using one of the thick cables coming into the consumer unit.</p><p>²The voltage and current are also varying throughout the cycle. But by using a special kind of average, called the Root Mean Square (RMS), you can multiply the RMS voltage by the RMS current to get the average power.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dbf4187c311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Living with Solar: part 4]]></title>
            <link>https://brian-candler.medium.com/living-with-solar-part-4-55a3f6a759b3?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a3f6a759b3</guid>
            <category><![CDATA[solar-panel-installation]]></category>
            <category><![CDATA[solar-power]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Sat, 21 May 2022 07:20:28 GMT</pubDate>
            <atom:updated>2023-03-13T16:20:48.813Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is it worth it?</h4><p>In this final part, I discuss the economics of solar, the various optional extras you can choose, and whether it’s worth the investment.</p><h3>How much does it cost?</h3><p>The total cost of the system will depend on a number of factors, most obviously the number of panels, but also the optional extras you buy. Interestingly, the panels themselves will likely not represent the largest proportion of the total. This how my quote broke down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*2QhGKS0l9Cvu2Q7Bu-PiFQ.png" /></figure><p>A system with batteries and other optional extras can easily cost 50% more than a plain panel-only system. So which options should you take?</p><h4>Batteries</h4><p>Until a couple of years ago this was a difficult decision, but in my opinion it’s now easy.</p><p>Over the last few years, the capacity has doubled and the price has halved. A 3.5kWh lithium-ion battery is now under £1,000 <em>(Pylontech US3000c)</em>. This has a claimed life of 6,000 cycles, or around 15 years, with “deep discharge” that lets you use 95% of the stated capacity.</p><p>Choosing batteries at the time of installation means you will need a hybrid inverter, which will add around another £500, but this is cheaper than getting a separate battery charger later. Furthermore, any batteries you buy when the system is installed are now free of VAT in the UK.</p><p>Adding £1,500 to your system to get 3kWh of extra energy every day could nearly double the solar electricity you can use instead of returning to the grid, making it a no-brainer in my opinion. The capacity will reduce as the batteries age, but even if the average is only half, 6,000 cycles amounts to about 10,000kWh of electricity stored and used. At current pricing, that’s a return of about £3,000 (versus, at best, £750 for returning that energy to the grid).</p><p>The next question is, how many batteries should you buy? These Pylontech batteries allow up to 5 to be connected together. But it’s not easy to know in advance how many will give you the best return.</p><p>The system designer recommended one battery, but I went for two, giving a 7kWh total capacity. Why did I make this choice? I made a simple calculation: if I use 10kWh per day, and let’s say there’s only 8 hours of usable sunlight, then I need to power the house for the remaining 16 hours, meaning I need to store two-thirds of 10kWh for use overnight.</p><p>This calculation is overly simplistic. Overnight usage is lower than average; and in winter, I expect there will be many days where there won’t be 8 hours of daylight sufficient both to power the house and charge that amount of battery.</p><p>However, based on the initial usage patterns I see in late spring, I already think I made the right decision.</p><p>Firstly, when the battery fills to 100% in the daytime, overnight it drops to around 45% by the time is starts charging again the next morning¹, or 35% if the oven or hob have been used for cooking. This means that if I’d bought a single battery, it would be completely empty and I’d be using grid power for part of the night.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*olCVspn6blNHFCxxodVXbQ.png" /><figcaption>Battery State Of Charge (%) on 13th May 2022, with 6 panels. There was enough sunlight on this day, and the previous one, to charge to 100%. Times in UTC. The drop at 17:15 (6.15pm local time) is due to electric cooking.</figcaption></figure><p>Secondly, when the battery drops to 20%, it stops discharging. So in practice, the usable capacity is not quite as high as I’d thought. (This is something that I believe can be configured on the inverter; I suspect it has been set to keep some charge for emergency use).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*454ylG6KzAPFXkulYIcYcg.png" /><figcaption>11th May 2022 — discharging to 20%, again with only 6 panels.</figcaption></figure><p>Thirdly, each battery has a limited rate at which it can charge and discharge. By having two batteries, I can discharge at double the rate — meaning that when there is peak usage, there is less that needs to be pulled from the grid.</p><p>Here’s an example where there are several appliances running in the kitchen, and the sun is obscured by cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*d-lHiz2IH-4_ExBuCNIa8w.gif" /><figcaption>High power consumption, mostly covered by the batteries</figcaption></figure><p>Looking at the <a href="https://en.pylontech.com.cn/pro_detail.aspx?id=121&amp;cid=23">specifications</a> of the US3000c, I see:</p><ul><li>Continuous charge/discharge: 37A (= 1.78kW at nominal 48V)</li><li>Peak for 60 seconds: 74–89A (= 3.55–4.27kW)</li></ul><p>Hence one battery may be able to support a short burst for kettle and toaster, say; but it won’t be able to power the oven and hob together for an extended period.</p><p>With two batteries, the continuous discharge rate is doubled to around 3.5kW, which matches what I see in the graphic above. It means less power is required from the grid under peak loads.</p><p>Three batteries could increase this further, but then I’d hit the inverter’s own limit of 5kW, and such high peaks are rarely reached anyway.</p><p>For me, in a household that has an electric oven and hob, two batteries appear to be the sweet spot, and I estimate that the second battery will save me 1–2 units per day, at least in the sunny parts of the year; I believe I’ll recoup the cost of the second battery in a similar timeframe to the rest of the system. But if you cook with gas, there may be less benefit.</p><p>Eliminating every last drop of grid electricity can become an obsession, but unless you’re building a completely off-grid system, it doesn’t make sense to buy more battery capacity than you need. In the next few years, I expect the technology to improve and prices to fall further.</p><h4>Bird netting</h4><p>This one is a no-brainer too, and my panel installers said I had made the right decision to install it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*ttFtAhBvwLA9Yga9Iiok_A.png" /><figcaption>Bird netting at edge of panels</figcaption></figure><p>If birds decide to nest behind your panels, it will get very messy and expensive to clean up. Although my neighbour has had a solar PV system for many years, and hasn’t suffered from birds, I would rather be sure there’s no chance of this happening.</p><h4>Optimizers</h4><p>My system has two strings of PV panels: one of six panels and one of eight. This matches how the panels are laid out across two roof surfaces.</p><p>Since they are connected in series, the same amount of current passes through all the panels in a string. If one panel is generating less power than the others — due to partial shading, or bird muck on one panel, or even just manufacturing variations — then the current through the other panels is reduced too, which reduces the total power they can generate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*lRkHoQl6okN0Kkc52w11Dw.png" /><figcaption>Afternoon tree shading—taken before the panels were fitted</figcaption></figure><p>The solution is to install electronic “optimizers” behind each panel, which adjust the panel output to match the others. Some manufacturers claim that even in normal operation, optimizers can increase the whole system output by up to 5%. That’s nice to have, although it would be cheaper just to add another panel (if you have the space). They cost £40-£50 per panel.</p><p>I decided to fit them because of a high tree line to the west, which means shading is an issue in the late afternoon. Without them, power could drop off more rapidly when some panels are shaded and others not. In practice, the shade covers the whole roof within the space of about half an hour, so I suspect it doesn’t make a great deal of difference. I still like the idea that I’m getting maximum output from the panels though.</p><p>If you have panels oriented in different directions across multiple roof surfaces, then they should be on different strings, feeding separate inverter inputs. If you have to combine them onto the same string, then you really do need optimizers.</p><p>Micro-inverters have also provide this benefit, as well as some other features relating to monitoring and system safety. But they have their own downsides: for a system with battery, power is converted from DC to AC and back to DC again, which is less efficient. Also, if they fail, they can be harder to replace individually than a monolithic inverter.</p><h4>Solar diverter (iBoost)</h4><p>If you have a gas boiler with a hot water storage tank, and that tank also has an electric immersion heater element, you can divert your spare solar energy to heat the water instead of exporting it to the grid².</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*3yOEyD5MlE8XMMi7jJ3Reg.png" /><figcaption>iBoost controller (image from <a href="https://www.marlec.co.uk/product/solar-iboost-controller/">Marlec</a>)</figcaption></figure><p>The <a href="https://www.marlec.co.uk/product/solar-iboost/">iBoost</a> has a sensor which clips on the main power cable into the consumer unit, and signals wirelessly to a main unit connected to the immersion heater. When it senses that energy is being exported to the grid, it energises the immersion heater. It varies the power delivered into the heating element in response to the amount of energy being exported. When the tank reaches its maximum temperature, the immersion heater’s thermostat turns it off, so any more excess power is exported again.</p><p>The iBoost has its own energy usage meter, which is important because otherwise you can’t tell the difference between your regular household usage and the iBoost’s opportunistic consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*oZ0844dbqTli2SPkE6Xtvg.png" /><figcaption>iBoost in action on a sunny day. Green = battery charging; Orange = consumption, including iBoost; Blue = grid export</figcaption></figure><p>It certainly works, and is relatively cheap at £300-£350 when installed with your system, but I’m not sure whether I’d take this option again.</p><p>If it picks up most of my excess generation, I reckon the iBoost could pay for itself in 3 or 4 years via reduced gas usage. However the cost of 1kWh of gas, currently 7.32p for me, is much less than 1kWh of electricity³. If I get a smart meter⁴ <em>and</em> can get a good SEG tariff like Octopus Fixed, I could earn 7.5p per kWh just by selling it back to the grid.</p><p>An iBoost (or similar device) certainly makes sense if you have a very large PV system that runs completely off-grid, and you have nothing better to use the excess power for.</p><p>There is one undeniable benefit though, which is that it reduces my personal carbon emissions. Every kWh of PV electric water heating is one less kWh of gas that I burn. One kWh fed back into the grid <em>may</em> reduce carbon use somewhere else, but it depends on how much is being generated by renewables that day.</p><blockquote><strong>UPDATE</strong>: in February 2023, Octopus launched a new tariff called <a href="https://octopus.energy/smart/flux/">Flux</a>, for owners of PV systems with battery. It pays 25p/unit export during the day, and 40p/unit export during the 4pm-7pm peak slot. As a result, the iBoost is now a white elephant: with gas at 10.3p per unit, it’s always cheaper to export surplus electricity, and use gas to heat water.</blockquote><h4>Emergency consumer unit</h4><p>Given a PV system with battery, you might expect that it can power the house in the event of a grid power outage. However, it turns out that many systems cannot do that. They are designed to shut down completely in the event of a power outage, so as not to energise the outside power cables and create a safety hazard for workers trying to fix the lines.</p><p>If you do want to power your house this way, you need to have a system which can isolate itself from the grid — with either a manual or automatic changeover switch. However, it seems to me that this is not as useful as you might think. After switching over to battery power, you are likely to end up running around your house switching off as many devices as possible, just to preserve the battery energy.</p><p>There is another option though: the Solis hybrid inverter in my system has a second AC output which remains continuously powered. By hooking this up to a second consumer unit, you can have one socket ring (16A) and one lighting circuit (6A) which are continuously powered.</p><p>I took this option and used it to power a double socket next to my Internet router, acting as a large uninterruptible power supply. The low power draw of the router should result in many hours of run time in the event of a power outage, without the need for a separate UPS.</p><h4>EV charger</h4><p>I don’t have an electric vehicle, so I didn’t take an EV charger. I was told to expect to pay around £700-£750 for a basic car charger, or just over £1,000 for an intelligent one (such as “<a href="https://myenergi.com/product/zappi/">Myenergi Zappi</a>”) which I believe can divert spare solar power to car charging, similar to the iBoost for hot water. Note that a home EV charger will require a 32A dedicated breaker from the consumer unit, which might have to be upgraded.</p><p>If you have an EV and it can be connected at home during the day, then this could be a valuable way to use spare solar generation capacity. If you drive to work, and the EV is only parked at home in the evenings, then this doesn’t help you much. You will still most likely want a home EV charger, but you’ll probably rely on an EV tariff which lets you charge your vehicle from the grid cheaply overnight.</p><h4>Installation and scaffolding</h4><p>You can’t avoid professional installation, and this is likely to be the largest part of the cost — but is also why it’s worth getting quotes from several suppliers.</p><p>My property is a bungalow, and in the end the installers decided that scaffolding was not necessary. They deducted it from the final bill.</p><h4>No VAT!</h4><p>Until recently, solar installations were subject to a reduced rate of VAT of 5% (except for batteries which were still 20%), with the proviso that the installation charge had to account for at least 40% of the total cost.</p><p>From April 2022, the VAT rate has dropped to zero, including batteries installed at the same time as the rest of the system. This gives a small but welcome reduction in the cost.</p><h4>Fixing your roof</h4><p>Finally, your roof needs to be in good condition, because repairing it <em>after</em> the system has been installed will be expensive. So if you’re not sure, get it checked by a professional roofer, and do any necessary repairs first. If you want to get moss removed, this is the time to do it as well.</p><h3>How long will it last?</h3><p>On my system the panels have a 12 year warranty, but should easily last 20 or 25 years. They do degrade over time, and their generation capacity is expected to drop by 0.5%-1% per year. The manufacturer warrants that after 20 years, they will still produce at least 80% of their original output.</p><p>The inverter has a warranty of 10 years (5 years manufacturer warranty plus 5 years extension purchased by the installer). I’m expecting to replace it after 10–15 years, at a cost today of around £1,250 plus installation.</p><p>The batteries have a design life of 15 years and 6,000 cycles, and a 10 year warranty. When it comes to replacing them, they are likely to be cheaper and better than today.</p><p>There shouldn’t be any ongoing maintenance costs. A slight increase in output may be obtained by professional cleaning, although the cost is likely to outweigh the benefits.</p><p>In addition there is a risk of unexpected repair bills, for example if a panel or optimizer completely dies and disables an entire string.</p><h3>Will it pay for itself?</h3><h4>Electricity usage</h4><p>Subtract two meter readings one year apart, to determine your annual electricity usage. You can get this information from your bills. You’ll need this figure to work out your potential savings, and the designer of your system will also want you to provide it.</p><p>My household annual usage is about 3,600kWh.</p><p>Note that usage in winter tends to be higher than in summer, due to increased use of lighting, indoor entertainment like TVs, and other appliances like clothes driers. I have LED lights so this effect is less pronounced.</p><h4>System yield</h4><p>There are a number of things which can affect the system yield, most importantly:</p><ul><li>Location. I am in Kent, which is one of the sunniest parts of the UK; if you live further north then yields will be lower.</li><li>The type and number of panels, which in turn is limited by the size and shape of your roof, and what you can afford.</li><li>The slope of your roof (“elevation”) and its orientation (“azimuth”). A south-facing roof is optimal; mine faces south-west which is still good.</li><li>Shading due to hills, nearby trees, or other obstructions.</li></ul><p>Your system designer should take all this into account and give you a predicted system annual yield figure in kWh, separated into self-use (electricity you generate and consume yourself) and grid feed-in values. Multiply the first by your electricity unit cost to get your annual saving through reduced electricity bills. If you are eligible for the Smart Export Guarantee then multiply the second figure by your SEG rate to see how much income you will earn from that. (Beware: SEG values are tiny, in some cases as low as 1.5p per kWh)</p><p>My predicted figures, for the initial design with 4kWh of battery storage, were:</p><ul><li>Total yield: 4,902 kWh</li><li>Self-use: 2,257 kWh [includes energy stored in battery and released later]</li><li>Grid feed-in: 2,645 kWh</li></ul><p>These figures are estimates, based on modelling. Until I have run the system over a full year, especially over winter, I won’t know the true results. Also, the larger battery I have should mean more self-use and less grid feed-in.</p><h4>Calculating the savings</h4><p>Given that my annual usage is 3,600 kWh, the prediction is that 2257/3600 = 62.7% of my electricity should come from solar. At the current exorbitant rate of 29.5p per unit, this amounts to £665 per year saved.</p><p>When I get a smart meter, on Octopus fixed SEG tariff I could receive 7.5p per unit for grid feed-in, bringing in potentially another £198 per year.</p><p>Since I have an iBoost, much of this may get diverted to hot water heating instead, but my current gas price is very similar at 7.32p per kWh.</p><h3>What about environmental benefits?</h3><p>This is hard for me to quantify.</p><p>Firstly, any electricity you generate and use or export means a corresponding reduction in centrally generated electricity. A proportion of that, however, is already renewable. You can find the UK’s power mix figures <a href="https://grid.iamkate.com/">here</a>, updated in real time. Over time, the benefit of a personal PV system will decrease as the UK moves towards more non-carbon based central generation.</p><p>Secondly, the system itself, particularly the panels and batteries, will have generated CO₂ from their manufacturing process, together with the mining and refining of the raw materials.</p><p>Estimates I have found <a href="https://www.renewableenergyhub.co.uk/main/solar-panels/solar-panels-carbon-analysis/">online</a> suggest that the panels will pay back their initial carbon debt in around 2.5–3 years.</p><p>Finally, with a solar PV system, there’s little incentive to conserve energy. Wash the laundry at 40°C instead of 30°C? Sure, why not — as long as the sun is shining or the batteries are full. This won’t change until metered export tariffs rise from their current paltry rates⁵.</p><h3>Conclusion</h3><p>It will be a year before I’ll know the true performance and benefits of the system; and in that time, the price of grid electricity may have gone up or down.</p><p>But I’m very happy to have a system which can reduce my reliance on the grid, and still very excited to watch all that “free” energy I’m generating.</p><p>Based on my experience, if you decide to go with solar my advice is:</p><ul><li>Get as many panels as you can fit. Panels are a mature technology and a relatively small proportion of the total cost; nobody complained about having too much power. (However, above 6kWp you may need a more expensive inverter, and anything above 7.5kWp may be difficult to integrate into a domestic wiring system).</li><li>Get a battery system with 3–8kWh capacity. Go for the higher end if you use electricity for cooking, or you tend to do your laundry in the evenings.</li><li>Get bird netting.</li><li>Think carefully whether any other extras are useful enough to you to justify the cost.</li></ul><p>¹Those figures were with only 6 panels in early May. With 14 panels in late May, more power is generated in the late afternoon and early morning, and I found the battery only dropped to 55% without cooking. Still, the experience with fewer panels shows what things might be like when the days are shorter.</p><p>²My hot water tank has a 200 litre capacity. Each 1°C rise in temperate requires approximately 200 x 4.1 kJ of energy, or 0.23 kWh. To heat from 20°C to 60°C will use approximately 9.2 kWh. I have now set my gas timer only to heat water in the evenings, so that after our morning showers, the iBoost still has work to do.</p><p>The heating element draws power up to 2.85kW, so anything above that, plus normal household usage, is still exported to the grid.</p><p>³Gas meters don’t count kWh: they measure the volume of gas used. The conversion factor varies depending on your location, and you can find it on your gas bill.</p><p>⁴I’ve requested one, but am still waiting. Apparently they install them on an area-by-area basis. <strong>UPDATE</strong>: I got it installed in September 2022 — sadly just as export for the year was tailing off!</p><p>⁵Those people who were lucky enough to get the old Feed-In Tariff scheme are paid handsomely for their generation. But under that scheme, they were paid for their entire solar generation, whether they used it or exported it. So they also are incentivised to use as much as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a3f6a759b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Living with Solar: part 3]]></title>
            <link>https://brian-candler.medium.com/living-with-solar-part-3-c1031fa44a4?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1031fa44a4</guid>
            <category><![CDATA[solar-panel-installation]]></category>
            <category><![CDATA[solar-power]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Sat, 21 May 2022 07:16:39 GMT</pubDate>
            <atom:updated>2022-05-22T07:44:37.442Z</atom:updated>
            <content:encoded><![CDATA[<h4>System Performance and Troubleshooting</h4><p>Once my solar PV system was up and running, I was able to watch how it performed.</p><h3>Inverter monitoring</h3><p>This system has a <a href="https://www.ginlong.com/rhi_inverter1/1952.html">6kW hybrid inverter</a> from Ginlong Solis — a mid-range, work-horse Chinese brand — and includes a wifi module that connects to the Internet. It uploads data to the “Solis Cloud” every 5 minutes, where it can be inspected using an app (iOS/Android) or a web browser.</p><p>Since it’s a hybrid system, all the information about both solar and battery state is available in a single interface.</p><p>The most important information is shown in two graphs: <em>generation</em> and <em>consumption</em>. Here are my graphs for the first full day after installation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZh_syndQLQQBVRH3RcfJg.png" /></figure><h4>Generation data</h4><p>The generation graph has one line showing the overall solar power generated by the panels (in <em>yellow</em>). It then has three more lines showing where this power has been sent to:</p><ul><li>“Self-use”, i.e. directly powering the house (<em>orange</em>)</li><li>Battery charging (<em>light green</em>)</li><li>Export to grid (<em>blue</em>)</li></ul><p>The sum of these three lines equals the yellow one¹.</p><p>In the top graph, you can see that the solar generation was mostly used for battery charging (the green area) until 14:00 UTC, or 3pm local summer time, when the battery was full. After that, self-use jumped up (the orange area): this was my iBoost kicking in, using all the spare electricity for heating the water tank. If I didn’t have the iBoost then it would have been exported to the grid instead.</p><h4>Consumption data</h4><p>The consumption graph has one line for the overall power consumed by the house (<em>dark green</em>). It has three other lines for where this power has come from:</p><ul><li>“Self-use”, i.e. direct from solar panels (<em>orange</em>; this line is identical to the one in the generation graph)</li><li>Battery discharging (<em>purple</em>)</li><li>Import from grid (<em>red</em>)</li></ul><p>Again, the sum of these three lines equals the dark green one.</p><p>In the lower graph, you can see consumption spikes at various times of day, most likely for boiling the kettle. And happily, almost nothing was coming from the grid.</p><p>This all makes sense, once it clicks. It’s obvious really that the power you use in the house at any particular instant is always going to be different from the amount that the panels are generating at that time.</p><p>Therefore, if the panels are providing <em>more</em> power than you are consuming, the extra goes either to battery charging or to the grid. That’s what the top graph shows. On the other hand, if the panels are generating <em>less</em> power than you are consuming, the shortfall has to be made up from either battery discharging or by drawing from the grid. The bottom graph shows this happening.</p><h4>Battery state</h4><p>This system has two Pylontech US3000c batteries, with a total storage capacity of 7kWh. I wanted to see how the energy stored in the battery varied over the day — also called its State Of Charge (SOC).</p><p>This isn’t available in the default “plant overview” screen, but can be found by switching to “device” view. In fact, there are very many inverter parameters available here, and you can combine multiple ones onto the same graph.</p><p>Here is the power generation graph (orange), combined with the battery state of charge (grey), for the same day as above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JofEIoWKmHoeoxQS7k4K6w.png" /></figure><p>The battery SOC fell to 21% overnight (having reached 79% the previous day), but climbed right up to 100% by mid-afternoon.</p><p>The graph has finer resolution in this view, and you can more clearly see the sun going in and out of clouds for much of the day.</p><h3>An unexpected problem</h3><p>This was all very exciting. It was early May, the weather was good, I could see the battery charging up and discharging as expected — although some days the battery didn’t manage to fill to 100%, I was not using grid power.</p><p>But then there was one perfect, cloudless sunny day. This let me see the system as it should be performing at its absolute best. Here is the generation graph for that day, with all lines turned off except for the total power:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9it4s6lc7sZX-TwvfRzJ0w.png" /><figcaption>8th May 2022</figcaption></figure><p>The maximum value was 2.09kW, at 13:00 UTC (2pm), as expected for a south-westerly facing system. You can see a sharp drop-off starting 17:00 UTC, when shade falls across the roof due to tall trees nearby.</p><p>But hang on. My system has 14 panels, with a design capacity of 5.18kWp. Even in these perfect conditions, I wasn’t getting anywhere near that!</p><p>Time to dig down further.</p><h4>String voltages</h4><p>Again by switching from the “plant overview” to the “device” view in Solis Cloud, there are many more measurements to inspect.</p><p>My system was designed with two strings, of 6 and 8 panels, connected to two separate DC inputs on the inverter, PV1 and PV2. I could check the voltages on both these strings independently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBHXpJ0ex8ZwlsSAYBilgA.png" /></figure><p>PV1 has a healthy 200V DC, staying mostly flat thanks to the optimizers. But PV2 has zero volts! It’s clear that the whole string is not working.</p><p>According to the panel specs (JA Solar), they have an optimum operating voltage of 34V. Seeing 200V suggests that there are six panels in the working string (200/34 = 5.9).</p><p>These are 370Wp panels, so six panels are 370x6 = 2.22kWp, and I was achieving very close to that.</p><p>Further observations on another sunny day confirmed this theory. When shade from nearby trees fell across the rear set of 8 panels, the power output did not drop. But as soon as shade fell across the front 6 panels, it dropped.</p><p>It was time to call back the installers to fix the system. Maybe they hadn’t plugged a cable in? Maybe one of the panels or optimizers was bad? Maybe the inverter itself was bad? It was their job, not mine, to sort it out.</p><p>Unfortunately I had to go away, and it was nearly two weeks before they were able to come.</p><h4>After the fix</h4><p>When the electrician arrived, it took only a few minutes to find and fix the problem. A cable had not been crimped properly.</p><p>Here’s the graph for the first few hours, showing the power from PV1 and PV2 separately, plus the battery charge. You can see exactly when it was fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaZEk8D3w8taef2--Btn1Q.png" /></figure><p>It was a miserable rainy morning. But still, I was getting about 150W combined from the panels, which was enough to reduce the battery drain to a trickle — and sometimes up to 400W.</p><p>It remained overcast, but as the rain cleared, generation briefly spiked at 1kW, and then at 2.5kW as the cloud thinned, and then to an astonishing 6.3kW as the sun broke through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*LqsuYGn5Vyv96-DjNm7JYw.gif" /><figcaption>Warp factor 10, Mr Sulu!</figcaption></figure><p>I had read about this phenomenon before. When the sun lights up a nearby area of thin cloud, it can briefly result in more light reaching the panels than from direct illumination alone. The thirsty batteries were lapping it up as fast as they could², and there was even excess available for the iBoost.</p><p>Fortunately this didn’t last long, as the inverter is only rated for 6kW, although it allows short excursions above this (and can protect itself).</p><p>Here’s the complete power and battery graph for the whole of that day. Since we spiked above the inverter’s rated capacity 6kW, the software has added warning lines for rated power and 1.2 times rated power (ignore these for the battery charge, which has its own axis).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHdPucpp7hMrWlzwQAnpzw.png" /></figure><p>Despite raining heavily for the first half of the day, and then mostly grey with a few bursts of sunshine, the battery managed to charge up to 100% (just).</p><p>The next morning was sunny with light cloud, turning to heavier scattered cloud in the afternoon. The battery had dropped to 59% overnight, but by 10.45am (local time) it was fully charged and the iBoost kicked in. By 12:40pm the tank was hot, and for most of the rest of the day we were exporting substantial amounts of power³. The graphs show all this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJ5xWUNKOLCPO-xGfQLoAA.png" /><figcaption>Power generated and consumed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awmOBu7YHJEgUBTOeIcStQ.png" /><figcaption>Power generated and battery SOC</figcaption></figure><p>(The sharp drop in battery charge from 99% to 81%, starting around 6.15pm local time, is due to using both the oven and hob for cooking. The time we cook is usually just after the sun has gone behind the trees, so the battery really helps out with this)</p><p>Suffice to say, I’m extremely happy with the results. Of course, this is late May; the days are bright and long, and getting longer. No doubt things will be very different in December. But it’s good to see that the full system can generate useful amounts of electricity in cloudy conditions, and even a little when it’s raining.</p><h3>Living with mini-solar</h3><p>An unexpected benefit of this episode is that I was able to experience what it was like to live with a much smaller, 6-panel system. This gives me a hint as to how things may be when winter approaches.</p><p>Perhaps surprisingly in retrospect, on most days the battery managed to charge up fully. However on 10th May it only reached 90%. On the next day, here’s what happened:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0EHYweB5G781QM0GSloMQ.png" /><figcaption>11th May 2022</figcaption></figure><p>When the battery discharged to 20%, we were switched to grid power for two hours in the early morning. The charge crept up only to 57%, so it was back down to 20% later that evening. We were then on grid throughout the night, until the next morning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*geTpfo7eGFUrq7TP_9ihyg.png" /><figcaption>12th May 2022</figcaption></figure><p>Notice how the battery discharges <em>very</em> slowly once it hits 20%. It was supplying only about 35 watts — the rest came from the grid⁴. In the day though, intermittent sun was enough to charge it back to 90%.</p><p>The worst day of all was this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r57LyizoYVJgtRl0OYmEbw.png" /><figcaption>15th May 2022</figcaption></figure><p>The vertical power scale has changed. The peak output was less than 600 watts, and only 3 units of electricity were generated all day. There was just enough to stop the battery discharging for part of the day, and after that it soon drained away, leaving us on grid overnight again.</p><p>But despite this: over a 15-day period, and using readings from my “real” utility electricity meter, I can see that I used only 18 units in total, whereas normally I would expect to use about 150.</p><p>That’s a short period of time, and I don’t know if it was unseasonably sunny. Certainly there were some scorching days.</p><p>I think this experience shows that even a small solar PV system <em>can</em> produce beneficial results, at the right time of year. However, the panels themselves are only a small fraction of the cost. Put another way: a 6-panel system costs almost as much as a 14-panel system, and yet will have much less benefit, particularly when conditions are poor.</p><p>That leads me on to the <a href="https://brian-candler.medium.com/living-with-solar-part-4-55a3f6a759b3">fourth and final part</a> of this series, where I’ll look at the available choices, costs and benefits.</p><p>¹Maybe it would be clearer if it were shown as three bands of colour stacked on top of each other, rather than side by side. If this is already possible, I couldn’t see how to do it.</p><p>²Each battery has a maximum sustained charge and discharge rate of about 1.8kW, so it’s 3.6kW when there are two. They can burst higher for very short periods.</p><p>³Unfortunately I’m not being paid for this yet, until the DNO has registered my system and I get a smart meter. However, afternoons are a good time to be exporting power, since demand is high. A variable export tariff like Agile Octopus pays high rates from about 4pm to 7pm.</p><p>⁴35W is about right for the the router and two <a href="https://ark.intel.com/content/www/us/en/ark/products/78953/intel-nuc-kit-dn2820fykh.html">NUC</a> servers I have connected to the backup power output on the inverter. That is: I believe the inverter may be choosing to power these from the battery rather than from the grid, even when the rest of the house is on grid.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1031fa44a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Living with Solar: part 2]]></title>
            <link>https://brian-candler.medium.com/living-with-solar-part-2-dcb2adc7612b?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcb2adc7612b</guid>
            <category><![CDATA[solar-panel-installation]]></category>
            <category><![CDATA[solar-power]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Thu, 19 May 2022 09:23:44 GMT</pubDate>
            <atom:updated>2022-05-21T08:01:16.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Installation</h4><p>Getting the system installed by a professional installer was straightforward. These are the steps involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yn85pnFRMo1SUyhcMVhcCw.png" /><figcaption>The completed installation</figcaption></figure><h3>Outline design</h3><p>You should contact several installers — I recommend at least three. Ensure they are registered with the relevant trade bodies, such as the <a href="https://www.recc.org.uk/">Renewable Energy Consumer Code</a>.</p><p>Tell them your outline requirements and get them to provide an indicative quote for the system cost.</p><p>Installers can quickly look at your property’s roof elevation on Google Earth and make a good estimate of how many panels can fit. If you already have an idea how many you think will fit, perhaps because a neighbour in a similar house already has a system, let them know. Also say if you want batteries, or any other specific features like an EV charger. (In part 4 I’ll discuss the available options and how they affect the price).</p><p>Talk to them on the phone, take the opportunity to ask any questions you have, and ask about installation lead times.</p><p>One of the installers I talked to — the one who eventually got my business — used a computer package to create a detailed PDF design document, which included things like the sun’s path across the sky at my location, predicted system yields, and system payback time.</p><p>Another installer took several weeks to get back to me with just a basic cost figure for panels only. Another one quoted me for a Tesla Powerwall-based system, with a price tag almost double what I ended up paying.</p><p>It definitely pays to shop around to find the system that suits you best, and an installer who is responsive.</p><h3>Survey</h3><p>Once you have chosen your installer, they will visit your property to inspect and measure your roof, look for obstructions, check how your existing electrics are laid out, and discuss with you details such as the best place to install the inverter. This is another opportunity to discuss any questions you have with the surveyor.</p><p>After this, the design and the quotation can be finalised, and you will likely have to sign contracts and pay a deposit before proceeding.</p><h3>DNO application</h3><p>In the UK, microgeneration systems with a capacity of more than 3.68kW (e.g. 4kW of panels with a 92% efficient inverter) are required to get <a href="https://energysavingtrust.org.uk/sites/default/files/reports/Solar%20pv%20connection%20to%20the%20grid.pdf">approval</a> from the Distribution Network Operator before connection, to ensure that the local power network is not overloaded.</p><p>The application will be made on your behalf by your installer, but you will have to sign and submit the documents. This can take 4 to 6 weeks.</p><p>I was told that in the unlikely event that the DNO did not approve the application, a clamp dummy load would be fitted to limit the amount of power which could be exported to the grid (at no cost to myself).</p><h3>Installation</h3><p>Installation can be completed in a day, although in my case it wasn’t.</p><p>I was visited by two teams of two people. The first team fitted the panels to the roof. They installed the mounting system, which consisted of brackets that screwed into the roof rafters, and replaced some tiles with rubber ones for the brackets to rest on.</p><p>Here they are part way through mounting 6 panels to one roof surface: the brackets and supporting rubber tiles are clearly visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*4GTvwGF8CDAGGJyjc_2P1w.png" /></figure><p>They also fitted another 8 panels to a roof surface further back along the house, the optimizers (which clip into place behind the panels), and the bird netting. The whole job was completed in a morning.</p><p>The second team were the electricians, who were delayed by an earlier job over-running, and didn’t arrive until 3pm. They got the inverter and batteries in place that afternoon, but had to come back the next day to wire everything up and sort out some problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*Pz3ezAaA2VheQbyjgJMH1w.png" /><figcaption>The inverter and batteries, installed in the loft</figcaption></figure><p>By about 2.30pm on the second day, I was generating electricity!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T3HrI1gl3cgt7KhBXUviQ.png" /><figcaption>First graphs. Times are in UTC, so 13:25 UTC is 14:25 British Summer Time.</figcaption></figure><p>In <a href="https://brian-candler.medium.com/living-with-solar-part-3-c1031fa44a4">part 3</a>, I’ll show what these graphs mean — and how they showed me that the system had a problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcb2adc7612b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Living with Solar: part 1]]></title>
            <link>https://brian-candler.medium.com/living-with-solar-part-1-9037739cad6d?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9037739cad6d</guid>
            <category><![CDATA[solar-power]]></category>
            <category><![CDATA[solar-panel-installation]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Thu, 19 May 2022 08:54:51 GMT</pubDate>
            <atom:updated>2022-06-25T11:15:50.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>I’ve recently had a solar panel system with batteries installed — and I’m very pleased with it. In the following series of articles I’ll note some of the things I learned along the way.</p><h3>How it works</h3><p>There are now three sources of electricity for our house: the sun, energy stored in the batteries, and the incoming grid. These are automatically combined as required.</p><p>If solar power by itself is enough to cover the household usage, any excess is used to charge the batteries. And any excess after that (for example, if the batteries are already full) is exported to the grid, where it can be used to power neighbouring houses.</p><p>Conversely, when there’s insufficient solar generation to power the house, the remainder is made up by discharging the batteries, and if necessary by drawing from the grid.</p><p>With the system I have, the monitoring app shows in close to real time how the power is flowing. In the following diagram, it’s a bright day, and there’s plenty of excess power to charge the battery, as well as power the house:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*zFXUbmzwe9XnroCtd2OZLw.gif" /><figcaption>Example graphic from Solis Cloud</figcaption></figure><p>This picture is available via an app or web page, and is updated every 5 minutes. Data is also stored for generating historical graphs.</p><h3>Terminology: kW, kWh and kWp</h3><p>When you have a system design drawn up for you, it’s very helpful to understand the terms being used.</p><h4>Power: kW</h4><p><strong>Power</strong> is a measure of how quickly you are using or generating energy. The units are <strong>watts</strong> (<strong>W</strong>) or <strong>kilowatts</strong> (<strong>kW</strong>), where 1kW = 1,000W. An electric kettle, for example, might use 2kW of power while it is switched on; this is an indication of how quickly it is transferring energy into the water to heat it up. A modern TV might only use 50W, or 0.05kW, while it’s running, and only 1–2W on standby.</p><h4>Energy: kWh</h4><p><strong>Energy</strong> is the total amount of work done by the electricity you have consumed or generated, and this is what you are actually charged for.</p><p>Technically, the standard unit of energy is the <em>joule</em> (J): one watt of power means one joule of energy per second.</p><p>However, joules are too small¹ to be conveniently used in household applications, so instead the utility companies measure energy in <strong>kilowatt-hours</strong> (<strong>kWh</strong>), often simply called “<strong>units</strong>”. This is the amount of energy which is used by an appliance drawing 1 kilowatt when left running for 1 hour. It’s the same as an appliance drawing 2kW for half an hour, or 0.1kW for 10 hours, and so on. You just multiply the power in kW by the time it is running in hours, to find the total energy consumed in kWh.</p><p>This means that a 2kW kettle, taking 2 minutes to boil, uses much less energy than a 2kW tumble drier running for 90 minutes to dry a load:</p><ul><li>Boil a kettle: 2kW x (2/60) = 0.067 kWh of energy</li><li>Dry a load: 2kW x (90/60) = 3.000 kWh of energy</li></ul><p>What if you had a kettle with a smaller heating element, say 1kW? It consumes energy at half the rate, but this also means it takes twice as long to heat the same amount of water — which would be 4 minutes in this case. So the total energy used is the same:</p><ul><li>Less powerful kettle: 1kW x (4/60) = 0.067 kWh of energy</li></ul><p>You also have to wait longer for your cup of tea. But if you put less water in either type of kettle, it will take less time to boil, and save you energy.</p><p>In short: energy (kWh) is what your electricity meter measures. Power (kW) is how quickly the meter is increasing.</p><h4>Peak power: kWp</h4><p>The power generated by solar panels varies depending on how much light is striking them. Obviously, there’s less light on cloudy days or in shade. Even on sunny days, it is affected by the angle at which the light hits the panels, which changes as the sun moves across the sky. When striking at an angle, the same amount of sunlight is spread over a larger area, so each square metre of panel receives less light. Furthermore, when the sun is low in the sky, more light is filtered out by the atmosphere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*dt_P1uPFR4A2eKO96D4Mlg.png" /><figcaption>Power output on 22nd June 2022, a totally cloudless day. System with 14 panels (5.18kWp), facing south-west. Times in UTC (local daylight savings time is UTC+1)</figcaption></figure><p>Therefore, the panels are rated by their <strong>peak</strong> output power, which is how much power they will give under optimal conditions²: the sun is shining brightly, completely perpendicular to the panels, and (perhaps surprisingly) when it is cool — solar panels work less efficiently when they get hot.</p><p>The instantaneous power generated is in kilowatts, so this maximum figure is <strong>kilowatts-peak</strong> (kWp). When completed, my system has 14 panels rated at 370Wp, so the total rating of the system is 5.18kWp. This means that in theory, my system could generate 5.18kW of power, when all the conditions are perfect. In practice, it will rarely reach that³.</p><h4>Putting it together</h4><p>Power (kW) measures, at a single instant in time:</p><ul><li>The rate at which you are using energy in your house</li><li>The rate at which your panels are generating energy</li><li>The rate at which you are importing energy from or exporting to the grid</li><li>How quickly your battery is charging or discharging</li></ul><p>Peak power (kWp) measures the instantaneous power which <em>could</em> be generated by your panels, in absolute best-case conditions.</p><p>Energy (kWh) measures, over a period of time:</p><ul><li>The total your panels have generated — also called the <strong>yield</strong>.</li><li>The total you have consumed from the grid (and paid for)</li><li>What you have exported to the grid (and been paid for)</li></ul><p>Energy also measures the storage capacity of your battery. A 7kWh battery could power 1kW for 7 hours — if it were able to discharge all the way from 100% to 0%.</p><h3>Terminology: system components</h3><p>These are some of the terms you may come across:</p><ul><li>The device which converts the Direct Current (DC) from the panels into the Alternating Current (AC) required for your house and the grid, is called an <strong>inverter</strong>.</li><li>If the inverter also has a battery connection, so that it can charge and discharge the battery, it is a <strong>hybrid inverter</strong>. Otherwise you will need a separate <strong>battery charger</strong>.</li><li>Instead of one large central inverter, you may be offered separate <strong>micro-inverters</strong> which fit behind each panel.</li><li>With a central inverter, the photovoltaic (<strong>PV</strong>) panels are connected together in series, forming <strong>strings</strong>, like daisy chains.</li><li>The current flowing through a string is limited by the least-well-performing panel; if one panel is in shade, it reduces what the other panels can generate. You can fix this problem by fitting <strong>optimizers</strong> to the panels, or by using micro-inverters. (These add to the cost, of course!)</li><li>The device which distributes electricity around your house, which you may informally know as the “fuse box”, is the <strong>consumer unit</strong>. You will have one of these already, and the PV system will connect to it. At worst, if you don’t have any spare circuit breakers, it may need to be replaced.</li></ul><p>In <a href="https://brian-candler.medium.com/living-with-solar-part-2-dcb2adc7612b">part 2</a>, I’ll describe my experiences having the system designed and installed.</p><p>¹One kilowatt is 1000 joules per second, and an hour has 3600 seconds, so 1kWh of energy is equal to 3,600,000 joules, or 3.6 megajoules (MJ).</p><p>²More precisely, it’s the output under “standard test conditions” (STC): incident radiation of 1kW/m² and a cell temperature of 25°C.</p><p>³However there are phenomena which mean that the peak can be briefly exceeded — for example, if the sun is very close to the edge of a cloud, it may illuminate that cloud and increase the total light received.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9037739cad6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Vault as an OpenID Connect Identity Provider]]></title>
            <link>https://brian-candler.medium.com/using-vault-as-an-openid-connect-identity-provider-ee0aaef2bba2?source=rss-85f9051accd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee0aaef2bba2</guid>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Brian Candler]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 14:08:50 GMT</pubDate>
            <atom:updated>2022-04-28T11:05:38.618Z</atom:updated>
            <content:encoded><![CDATA[<p>In a <a href="https://brian-candler.medium.com/using-hashicorp-vault-as-an-ssh-certificate-authority-14d713673c9a">previous article</a> I wrote about using Hashicorp Vault as an SSH certificate authority. As of version 1.9, Vault has <a href="https://learn.hashicorp.com/tutorials/vault/what-is-new?in=vault/new-release">gained</a> the ability to act as an OpenID Connect Identity Provider as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*8JpyLi_XWb9yj9wl6wq9Xg.png" /></figure><p>This is an exciting development which greatly increases the scope and utility of Vault. The feature is in “Technical Preview” so may be subject to change, but I can confirm that it works in its current state.</p><h3>What this means</h3><p>You can now configure your local web applications (and some other systems like Kubernetes) to perform single sign-on authentication against Vault — as long as they support OpenID Connect (OIDC).</p><p>The user experience is:</p><ul><li>The user connects to a web app.</li><li>The web app redirects them to Vault’s web interface, where they can choose from available upstream identity providers (IDPs), and login with that provider. If the user has previously authenticated to Vault (i.e. has a cookie to prove it) then this step completes automatically with no further interaction.</li><li>The user is redirected back to the web app, and Vault sends a token back to the application which proves that the user is who they say they are.</li><li>The web app accepts the user and continues as normal</li></ul><p>Compared to making those applications authenticate directly against Google or Office365 or whatever, there is a great amount of flexibility:</p><ul><li>You can add and remove client applications without having to making any changes at the upstream IDPs; and you can add and remove IDPs without touching the client applications.</li><li>You can choose which upstream IDP account(s) each user can authenticate with.</li><li>You have full control over group membership. You can create and manage groups manually, by adding individual users (entities); and/or you can honour group claims from the upstream identity platforms.</li><li>You have full control over authorization. You can add claims to individual users via entity metadata (regardless of which upstream account they authenticated from)</li><li>You can control the names and format of the OpenID claims which are sent to your applications. This is important, since some applications have fixed requirements.</li></ul><h3>Competing alternatives</h3><p>Apart from the commercial cloud services like Okta and Auth0, I think the software which comes closest is <a href="https://www.keycloak.org/">Keycloak</a>. This is a mature open source project which has the weight of Red Hat behind it, and has a wider range of SSO functionality (e.g. it can do SAML). I also find its web interface is much clearer for managing users, groups and clients than Vault’s rather technical web UI. Vault’s CLI is even lower level, only a thin wrapper around the API.</p><p>However, Vault has its own advantages:</p><ul><li>Vault has a small resource footprint, written in Go rather than Java</li><li>Vault has a wide range of <a href="https://www.vaultproject.io/docs/configuration/storage">storage backends</a>, from simple file storage and robust HA raft implementation, to SQL and noSQL databases</li><li>Vault has a very good story around data security and encryption. Regardless of which backend you use, all the secret data is encrypted with the master (“unseal”) key. Whenever you restart Vault, you have to provide a subset of the unseal key shards; the contents of the database by itself are not usable to an attacker.</li><li>Vault can provide other identity services, in particular issuing SSH certificates and X509 certificates</li><li>Vault also provides its original core functionality of API-based “secret store” for managing credentials used by applications to communicate with each other</li></ul><p>(If you are feeling more conservative, you could use Vault for SSH certificates whilst using Keycloak as its upstream IDP)</p><h3>Proof-of-concept</h3><p>Now I’ll go through the steps I did to demonstrate this in action.</p><h4>Install and configure Vault</h4><p>I already had an existing installation of Vault, running with HTTPS using a LetsEncrypt certificate (in my case using <a href="https://dehydrated.io/">dehydrated</a>). Having a real certificate is strongly recommended, since each of your users <em>will</em> need to interact directly with Vault’s web interface to login.</p><p>Here is my /etc/vault/vault-conf.hcl with the domain name changed:</p><pre># https://www.vaultproject.io/docs/configuration/storage/filesystem<br>storage &quot;file&quot; {<br>  path = &quot;/var/lib/vault&quot;<br>}</pre><pre>listener &quot;tcp&quot; {<br>  address = &quot;[::]:8200&quot;<br>  tls_cert_file = &quot;/etc/dehydrated/certs/vault1.example.net/fullchain.pem&quot;<br>  tls_key_file = &quot;/etc/dehydrated/certs/vault1.example.net/privkey.pem&quot;<br>}</pre><pre>cluster_addr = &quot;https://vault1.example.net:8201&quot;<br>api_addr = &quot;https://vault1.example.net:8200&quot;<br>ui = &quot;true&quot;</pre><pre># The following setting is not recommended, but you may need<br># it when running in an unprivileged lxd container<br>disable_mlock = &quot;true&quot;</pre><p>For convenience I also have /etc/profile.d/vault.sh:</p><pre>VAULT_ADDR=https://vault1.example.net:8200<br>export VAULT_ADDR</pre><p>To make the config changes below, you’ll need to be able to authenticate to Vault with sufficient privileges, e.g. with a root token.</p><blockquote>Aside: in a production environment, you would avoid using root tokens if possible. Instead you might define a vaultadmin group with rights to update policies, and authenticate as a member of that group.</blockquote><h4>Upgrade Vault to v1.9+</h4><p>If you’ve installed a fresh Vault v1.9, skip this section.</p><p>Otherwise, you need to upgrade Vault to v1.9+ before continuing. Choose the latest available v1.9.x <a href="https://www.vaultproject.io/downloads">release</a>. Restart and unseal.</p><p>You will also need to replace the “default” policy, inherited by all users unless you specify otherwise, to allow users to access the OIDC authorization endpoint. Upgrading Vault doesn’t automatically change the existing policy.</p><p>Get the new default policy by firing up a temporary dev server with 1.9:</p><pre>vault server -dev -dev-listen-address 127.0.0.1:8299 \<br>  -dev-root-token-id root</pre><pre># in another window:<br>VAULT_ADDR=http://127.0.0.1:8299 VAULT_TOKEN=root \<br>  vault policy read default &gt;policy-default-1.9</pre><p>Then apply this to your main running instance, after you’ve upgraded it to 1.9, unsealed, and have authenticated to it:</p><pre>vault policy read default &gt;policy-default-old<br>vault policy write default - &lt;policy-default-1.9</pre><h4>Configure user authentication</h4><p>I had already configured users to be able to login to Vault, using userpass and OIDC, as per the previous <a href="https://brian-candler.medium.com/using-hashicorp-vault-as-an-ssh-certificate-authority-14d713673c9a">SSH Certificate Authority article</a>.</p><p>To check this is working, users should be able to go to the Vault URL, select a login method, and login:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*GcPE0zwnLAbe71sF-2HWYg.png" /></figure><p>After logging in, they should see their ID alias by clicking the top-right corner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*v9JQReq0T-cLfUx8p2JUFg.png" /></figure><p>In essence, what we’re going to do next is to allow the Vault login process to extend to other web apps that you have.</p><p>You’ll need to know how to find the entity IDs of your users, and/or the ID of a group to which they all belong. Use the web interface, or the CLI, e.g:</p><pre>vault list identity/entity/id<br>vault list identity/group/id</pre><pre>vault read -format=json \<br>  identity/group/id/ae911de1-e52a-ab87-3dfe-5e7b1d88c643</pre><h4>Configure a sample web app</h4><p>The first client app I tested is the “example-app” supplied with the <a href="https://github.com/dexidp/dex">Dex IDP</a>: this performs an OIDC exchange and decodes and displays the identity token. Note that you need at least Vault v1.9.1 to work with this app, due to a <a href="https://github.com/hashicorp/vault/issues/13204">spec compliance issue</a> in v1.9.0.</p><p>You need to compile the Dex example-app from source. Then you run it like this:</p><pre>bin/example-app --debug \<br>  --client-id XXXXXXXX \<br>  --client-secret YYYYYYYY \<br>  --issuer https://vault1.example.net:8200/v1/identity/oidc/provider/my-provider \<br>  --listen http://0.0.0.0:5555 \<br>  --redirect-uri http://dex1.example.net:5555/callback</pre><p>Note that we won’t know the client-id and client-secret until later. You need to give the application a resolvable hostname — it could be on the same host as Vault itself, but in my case I chose to run it elsewhere to be more realistic, with DNS name dex1.example.net. You could refer to it by IP address, and if you’re running this app on the same PC where you’re running your web browser, then “localhost” is sufficient.</p><p>It would be better practice to use HTTPS of course, which is easy enough, but you need to provide a suitable key and certificate.</p><h4>Create OpenID Connect Provider</h4><blockquote><strong>Update</strong>: this process has been <a href="https://www.vaultproject.io/docs/upgrading/upgrade-to-1.10.x#oidc-provider-built-in-resources">much simplified in Vault 1.10</a>. You automatically get a key “default”, a provider “default”, and an assignment “allow_all”. The following steps are kept for reference only.</blockquote><p>Now I’m more or less following the steps from the <a href="https://www.vaultproject.io/docs/secrets/identity/oidc-provider">OIDC Identity Provider</a> Secrets Engine documentation.</p><p>Create a key called “my-key”:</p><pre>vault write identity/oidc/key/my-key \<br>  allowed_client_ids=&quot;*&quot; \<br>  verification_ttl=&quot;1h&quot; \<br>  rotation_period=&quot;1h&quot; \<br>  algorithm=&quot;RS256&quot;</pre><p>Create an assignment. This specifies which Vault entities and groups are authorized to use a specific OIDC client for authentication flows. Here you can provide a space or comma-separated list of entity IDs (e.g. the entity IDs for “alice” and “bob”), and/or one or more group_ids that alice and bob belong to.</p><pre>vault write identity/oidc/assignment/my-assignment \<br>  group_ids=&quot;ae911de1-e52a-ab87-3dfe-5e7b1d88c643&quot; \<br>  entity_ids=&quot;d2f5ddbb-d6d9-e951-7585-78dadd492da9&quot;</pre><p>Optionally create a custom scope, here called “user”, which can provide additional information in the identity token. The default scope “openid” is always available.</p><pre>vault auth list<br>export MOUNT_ACCESSOR=auth_userpass_bbcef7b5   # example</pre><pre>TOKEN_TEMPLATE=$(cat &lt;&lt; EOF<br>{<br>    &quot;username&quot;: {{identity.entity.aliases.$MOUNT_ACCESSOR.name}},<br>    &quot;contact&quot;: {<br>        &quot;email&quot;: {{identity.entity.metadata.email}},<br>        &quot;phone_number&quot;: {{identity.entity.metadata.phone_number}}<br>    },<br>    &quot;groups&quot;: {{identity.entity.groups.names}}<br>}<br>EOF<br>)</pre><pre>vault write identity/oidc/scope/user \<br>  description=&quot;Scope for user metadata&quot; \<br>  template=&quot;$(echo $TOKEN_TEMPLATE | base64 -)&quot;</pre><p>Create an OIDC client:</p><pre>vault write identity/oidc/client/my-webapp \<br>  redirect_uris=&quot;http://dex1.example.net:5555/callback&quot; \<br>  assignments=&quot;my-assignment&quot; \<br>  key=&quot;my-key&quot; \<br>  id_token_ttl=&quot;30m&quot; \<br>  access_token_ttl=&quot;1h&quot;</pre><pre>vault read identity/oidc/client/my-webapp<br>...<br>client_id           VwxGdHaLCa7gOfoauWSaK8cua8kfecEU<br>client_secret       hvo_secret_yh3hDNBocUZRxxxxxxxxx</pre><p>You can see that the callback URL of the example app is included here. Make a note of the client_id and client_secret returned.</p><p>Create an OIDC provider:</p><pre>vault write identity/oidc/provider/my-provider \<br>  allowed_client_ids=&quot;*&quot; \<br>  scopes_supported=&quot;user&quot;</pre><p>(It’s possible to restrict the provider to specific client-ids, should you need to, but &quot;*&quot; is simpler)</p><p>You can now check the OpenID Provider configuration:</p><pre>curl -Ss $VAULT_ADDR/v1/identity/oidc/provider/my-provider/.well-known/openid-configuration</pre><p>Pipe the output to jq . or python3 -m json.tool to get neater formatting.</p><h4>Test the application</h4><p>Now we’re ready to go! Return to the example-app and run it with the correct client_id and client_secret. Point a browser at the example-app, e.g. http://dex1.example.net:5555/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*ROMw91KyN7itV06r4gEGTA.png" /><figcaption>Login to example-app</figcaption></figure><p>Enter “user” as the extra scope, then Login. This will take you to the Vault UI, where you can login as alice. If all goes well then you’ll be returned to the app, where it will show the ID and Access tokens and the decoded claims:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*cLWTUPtIMoJdsWbBrVnDpA.png" /><figcaption>Response from example-app after logging in</figcaption></figure><p>The “aud” (audience) is the client_id, and “sub” (subscriber) is the Vault entity ID. In this case the “contact.email” claim has been picked up from entity metadata, “groups” from the entity group memberships, and the “username” claim from the entity alias.</p><p>For debugging, check the console output from the app. If it’s still not clear what the problem is, you may need to set log_level=&quot;trace&quot; in Vault’s config, and/or turn on audit logging in Vault.</p><h4>Apache</h4><p>The second web app that I tested, a more realistic example, was Apache with mod_auth_openidc. Installation under Ubuntu:</p><pre>apt-get install apache2 libapache2-mod-auth-openidc</pre><p>Create /etc/apache2/conf-available/openidc.conf:</p><pre>OIDCProviderMetadataURL https://vault1.example.net:8200/v1/identity/oidc/provider/my-provider/.well-known/openid-configuration<br>OIDCClientID XXXXXXXX<br>OIDCClientSecret YYYYYYYY</pre><pre>OIDCRedirectURI /protected/callback<br>OIDCCryptoPassphrase W1Qnf4qG2kVo36A1hvDhxDkj9319ewUNBbC7/uvUrj2r<br>OIDCScope &quot;openid user&quot;<br>OIDCSessionInactivityTimeout 43200</pre><pre># Required when using HTTP rather than HTTPS<br>OIDCCookieSameSite On</pre><pre>#OIDCRemoteUserClaim email</pre><pre>&lt;Location /protected&gt;<br>        AuthType openid-connect<br>        Require valid-user<br>        #Require claim groups:engineers<br>&lt;/Location&gt;</pre><p>(use any long, random string for OIDCCryptoPassphrase)</p><p>Enable the configuration:</p><pre>a2enconf openidc<br>systemctl reload apache2</pre><p>Again, making the server run HTTPS would be best, but for simplicity I allowed HTTP on port 80.</p><p>In order to obtain the OIDCClientID and OIDCClientSecret, you can either:</p><ol><li>Create a new client — this is the proper approach.</li><li>Use the same client_id and client_secret as you did for the Dex example-app.</li></ol><p>However if you do the latter, you’ll have to extend the list of allowed redirect_uris for this client, so that both clients can use it:</p><pre>vault write identity/oidc/client/my-webapp \<br>redirect_uris=&quot;http://dex1.example.net:5555/callback,http://dex1.example.net/protected/callback&quot; \<br>  assignments=&quot;my-assignment&quot; \<br>  key=&quot;my-key&quot; \<br>  id_token_ttl=&quot;30m&quot; \<br>  access_token_ttl=&quot;1h&quot;</pre><p>Connect to the web server’s protected area (http://dex1.example.net/protected/) and it should go through the OpenID authentication process. To logout, go to http://dex1.example.net/protected/callback?logout=/ (however, a future access to /protected/ will log you back in automatically, unless you logout of Vault itself)</p><p>For debugging, check the Apache error logs at /var/log/apache2/error.log</p><h4>kubelogin</h4><p>For kubernetes login via OIDC, you will need <a href="https://github.com/int128/kubelogin">kubelogin</a>. The OIDC client in Vault needs to be configured with:</p><pre>redirect_uris=&quot;http://localhost:8000&quot;</pre><p>The kube config will contain something like this:</p><pre>apiVersion: v1<br>clusters:<br>- cluster:<br>    certificate-authority-data: ...<br>    server: ...<br>  name: my-cluster<br>contexts:<br>- context:<br>    cluster: my-cluster<br>    user: oidc<br>  name: my-cluster<br>current-context: my-cluster<br>kind: Config<br>preferences: {}<br>users:<br>- name: oidc<br>  user:<br>    exec:<br>      apiVersion: client.authentication.k8s.io/v1beta1<br>      command: kubectl<br>      args:<br>      - oidc-login<br>      - get-token<br>      - --oidc-issuer-url=https://vault1.example.net:8200/v1/identity/oidc/provider/my-provider<br>      - --oidc-client-id=VwxGdHaLCa7gOfoauWSaK8cua8kfecEU<br>      - --oidc-client-secret=hvo_secret_yh3hDNBocUZRxxxxxxxxx</pre><p>Issuing a command like “kubectl get pod” will then perform the OIDC authentication dance to get the identity token, before contacting the Kubernetes API. The token is cached as a file under ~/.kube/cache/oidc-login/ and you can delete this if you wish to repeat the authentication.</p><p>Configuring the Kubernetes API to accept this token is outside the scope of this document, but is described <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/#configuring-the-api-server">here</a>.</p><h3>Conclusion</h3><p>Vault v1.9 now provides a working OpenID Connect Identity Provider!</p><h3>References and notes</h3><p>The Hashicorp documentation for OIDC Provider is somewhat spread around, but these are the bookmarks I’ve kept:</p><p>Tutorial: <a href="https://learn.hashicorp.com/tutorials/vault/oidc-identity-provider">Vault as an OIDC Identity Provider</a><br>Concepts: <a href="https://www.vaultproject.io/docs/concepts/oidc-provider">OIDC Provider</a><br>Secrets Engine: <a href="https://www.vaultproject.io/docs/secrets/identity/oidc-provider">OIDC Identity Provider</a><br>Secrets Engine: <a href="https://www.vaultproject.io/docs/secrets/identity/identity-token#token-contents-and-templates">Identity Token Templates</a><br>API (OIDC Provider): <a href="https://www.vaultproject.io/api-docs/secret/identity/oidc-provider#create-or-update-a-provider">Create or Update a Provider</a><br>API (Identity Tokens): <a href="https://www.vaultproject.io/api-docs/secret/identity/tokens#create-a-named-key">Create a Named Key</a></p><p>For my testing I followed the steps in the “<a href="https://www.vaultproject.io/docs/secrets/identity/oidc-provider">Secrets Engine</a>” section, as I hadn’t come across the “tutorial” section at that point. I found a few niggles which weren’t obvious at first:</p><ol><li>You should set MOUNT_ACCESSOR to an appropriate value, as shown by vault auth list. e.g. export MOUNT_ACCESSOR=auth_userpass_bbcef7b5<br>(It’s not a big problem if you don’t, but the ID tokens will contain an empty “username” claim)</li><li>After creating a client (say “my-webapp”), to find the client_id and client_secret you need to do vault read identity/oidc/client/my-webapp</li><li>issuer can only be set to <em>scheme://host:port</em> (no path). If you don’t set issuer, it defaults to api_addr. Note that api_addr can be a hostname, not just an IP address, and indeed really should be a hostname if you’re using proper certificates. The full issuer URL generated is <em>scheme</em>://<em>host:port</em>/v1/identity/oidc/provider/<em>provider-name</em>, to which you add /.well-known/openid-configuration to get the OpenID configuration URL.</li><li>Remember to change the redirect_uri to suit your application, and change assignment (i.e. which entities and/or groups are permitted to authenticate with this provider)</li><li>You need to set the correct allowed_client_ids in key and provider — or more simply, set them to * (Note that you can’t create a client until you have created a key, and you can’t choose your own client_id, so you can’t restrict a key to specific clients until after the clients have been created). I made a suggestion <a href="https://github.com/hashicorp/vault/issues/13224">here</a> about how the documentation could be improved. The “tutorial” document handles it better, by setting allowed_client_ids=&quot;*&quot;</li><li>If you are upgrading from an older version of Vault, you need to upgrade the default policy (which allows users to access the /authorize endpoint)</li><li>In Vault v1.9.0, the nonce parameter was mandatory, which prevented the Dex example-app from working. This was a <a href="https://github.com/hashicorp/vault/issues/13204">spec violation</a>, and has been fixed in vault v1.9.1 (showing a very rapid response from Hashicorp!)</li><li>If using mod_auth_openidc, but the web server is using HTTP rather than HTTPS, then you need to set OIDCCookieSamesite on. Thanks to:<br><a href="https://medium.com/swlh/7-keys-to-the-mystery-of-a-missing-cookie-fdf22b012f09">https://medium.com/swlh/7-keys-to-the-mystery-of-a-missing-cookie-fdf22b012f09</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee0aaef2bba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>