Is this easier in C or C++?

Like most projects I started long ago, mltt was written in C. It’s my goto programming language for most things but most especially anything in any way low level. But at some point I always end up asking myself wouldn’t this be easier to write in C++? (I’m just waiting for someone to say Python). C++ had such a terrible reputation among embedded coders for so long that it’s ingrained in my subconscious to avoid it. But after I’ve written my own linked list for the 1000th time I’m starting to wonder why am I making life so hard for myself. Is it really so bad to declare vector<int> to implement a list instead of writing dozens of lines of C? This feels like deja-vu all over again as I went through the same a couple of years at my day job (thanks Elías !).

C is such simple language that it’s not hard to master. There really are not that many options for how to do most things. I’ve always managed to make it object oriented when I needed to with modules performing data hiding by return opaque handles, so why would I use C++? A for loop really can only be:

for (i = 0; i < 10; i++)     array[i] = foo(i);

With C++ it’s so different. If array is a container then should I use

for (i = 0; i < array.size(); i++) 
array[i] = foo(i);

or

for (auto it = array.begin(); it != array.end(); ++it)
*it = foo(*it);

or

for (auto it : array)
it = foo(it);

And why is it sometimes a pointer and sometimes not? And why is it ++it and not it++? (it turns out it’s more effecient if the ++ operator is overloaded). In fairness, that last option was only introduced in C++11. Which in itself is a problem – the language is still evolving. I’m not going near for_each and lambdas yet. When I looked for a replacement for printf ("%02x") I found std::format and I thought that’s cool, only to find out it’s a C++20 feature not yet supported by gcc12 on debian bookworm. So that leads to finding coding examples online may or may even work.

When I started refactoring the disk volume and file code in mltt it dawned on me that the natural object hierarachy of volumes to files to sectors would be ideal to implement as classes, so I bit the bullet and started translating what I had. Rather than wrestling with extern "C" declarations around all my legacy code I renamed all source files and began compiling as C++. In general, C will compile fine with g++ but there are a few cases where it is just a little bit stricter. char *s = "foo" is not allowed for example so lots of const keywords have to be added. Due to name mangling, any slight changes to function prototypes causes linker errors, which isn’t such a bad thing (did you forget to include your own header file again?). In general though, it isn’t too painful and is easier in the long run that trying to maintain mixed C and C++ code.

The much bigger problem is actually changing the code to be reasonable C++ and not just straight C compiled with g++. Once you start converting it, OCD starts to kick in and the inconsistency of seeing some files using cout << endl and some using printf ("\n"); starts to become almost physically painful. Resisting the temptation to rewrite everything is soooo hard. And I can see so many opportunities for rewrites too. My TI99 emulator has had separate modules to implement different types of memory (ROM, RAM, cartridge ROM) as well as all memory mapped devices (speech, VDP, GROM, etc) since I started the project 20 years ago. But seeing them now I can see they are just crying out for a little bit of polymorphism.

The real kicker here is after all this refactoring, there is zero new functionalty. The end user will see no difference whatsoever other than things run a little bit more slowly. This is what makes refactoring painful and a really hard sell to your manager (luckily I don’t have one of those so I just get to be hard on myself). That brings to my other major gripe with C++. Engineers just love to use any feature that’s available whether they need to or not. C++ has so many more options available to it than C that writing consistent code is a lot more effort and dev teams need very strict rules to stay efficient.

On balance though I’m happier with the code now that it is C++’ish. At least any new code will be more structured and maintainable and I’ll try to learn to live with the legacy code as is.

EV batteries

I seem to be attracting lots of EV cynics these days for some reason. I can’t count the number of times someone has told me that I shouldn’t be driving an EV and that don’t I know that when I have to replace the battery it will cost me €10K. Or that mining Lithium is destroying the planet and it takes a thousand tonnes of rock just to mine 1kg of Lithium. Not as bad as the guy who asked me why they don’t add a dynamo to the wheels so the car can charge itself while it’s driving I suppose.

So my car, like most EVs, has an 8 year battery warranty. I’m sure any sane manufacturer offering such a warranty is reasonably sure the battery is unlikely to fail during the warranty or else they would bankrupt themselves replacing batteries. So it’s safe to assume the mean time between failures (MTBF) is at least 10 years. Given the average lifetime of any car is only 11 or 12 years anyway, even then the battery will outlive the car for the vast majority of cases. It’s only logical.

But what is a failure? An outright total fail is possible but unlikely. If that does happen, it probably isn’t the individual cells that are at fault but some other component. Repairing EV batteries isn’t commonly done yet AFAIK, but as EVs age there will almost certainly be repair shops springing up that specalise in battery refurbs. It’s more likely to be a gradual degradation, eventually becoming severe enough that the car is unusable. I’ve read stories of older Nissan Leaf’s that can’t even do 100km on a full charge any more. Those older cars were missing a lot of the features in a modern battery management system (BMS) like thermal management so they certainly did degrade faster. But any research I’ve seen (like this one) on Tesla or newer EVs just aren’t showing anywhere near that level of degradation any more. I think I can live with 15% degradation after 200,000kms. That’s probably on par with the degradation of an ICE engine block.

The idea that I would spend €10K on new battery for a car over 8 years old is silly anyway. Why would I do that? I’d just scrap the car if it was that bad. 20 years ago I bought a brand new Honda Accord for €40K and kept it for 11 years. When I eventually traded it in, I got a whopping €2K for it against my next car. So that’s a 95% deprecation over 11 yrs, or a compounded annual deprecation of 6.5%, not unreasonable. If it was an EV and the battery had failed at 11 years, does anyone really think I would have put a €10K battery into a car worth €2K? Would anyone put a brand new ICE engine into a 10 year old car? Why do they think EVs are any different? If a post-warranty battery replacement is needed, it’s going to be a second hand battery from a scrapped car, or maybe some kind of refurb, or else scrap the car. Same as with an ICE. A friend of mine had an engine blow on a 5 year old landrover. The timing chain snapped and caused lots of internal damage. Apparently it’s a common fault with the model of engine (Ingenium?) in those cars. But out of warranty so tough luck. It made no sense to them to buy a brand new engine, which would have cost in excess of €10K so they went for a rebuild instead.

But what about the Lithium? You have to go and destroy the planet again to get more, right? Well the Lithium hasn’t gone anywhere. The 8kg of Lithium that was in the battery at the start of it’s life is all still in the battery. So why would you dump the battery in a landfill and go and mine another 8kg? That doesn’t make sense to me. I can’t see how it’s harder, in the worst case, to crush the battery and use solvent extraction to get the Lithium out? I just don’t get it. But Cobalt!!! That enslaves children in the Congo! Well, it’s true that 50% of the world’s Cobalt comes from the Congo, but most EV batteries aren’t using Cobalt any more. Lithium Ferro-phosphate (LFP) batteries are Cobalt free. And never mind that one of the biggest uses of Cobalt is to make catalysts for the de-sulpherisation of petroleum.

EVs go on fire all the time too – did you know that? I didn’t. I’ve never had any first hand experience of anyone having an EV fire. I’ve seen several fires caused by diesel runaways – one happened to a friend of mine’s neighbour. Why am I not hearing about all these EV fires? I don’t get that either.

A retired doctor recently told me my EV was destroying the roads because battery is so heavy. So my 2 tonne car is destroying the road but your 2.5 tonne range rover doesn’t cause any issues? Maybe it’s the 40 tonne trucks that damage roads? No that can’t be it – I must be wrong there. Or is it the tyres that are bad? Well I put regular tyres on my EV. My last set lasted 46,000km. I don’t see how that’s any different to my previous ICE cars?

Maybe I’m just not as smart as the people I meet who know all this stuff about EVs cos they read it on the internet. I just wish they’d talk to people who actually own one though.

The great crypto ponzi scheme

I’m still dismayed at the number of people I meet or hear about asking if cryptocurrency is a good investment. How can they even think it is an investment? Of course it isn’t an investment at all. Time for a rant. I know this has all been said before elsewhere but ….

It’s really very simple. Before you invest in any asset class you must ask how will you get a return on your investment. If you “invest” in crypto, then how will you get your money back? Where will the profits come from? With crypto, the only answer is by selling it on to someone else. The only possible return will be from new entrants buying in to the currency, which by definition makes it a Ponzi scheme.

I’m obviously a “no coiner”. I have never owned and never will own any crypto. To me, the concept of cryptocurrency has flaws but more importantly, the way people are trading them shows they don’t understood what it is. The transaction mechanism, blockchain, is also flawed and has some really fundamental problems. Rather than dispelling the myths over and over, I’m going to write them down why so I can just post a link to this text instead.

Crypto is an investment

I think fundamentally people just don’t understand cryptocurrency. Which is a shame. The technology isn’t that complicated. Using the term “investing” in crypto underscores that they don’t understand what crypto actually is. If crypto is meant to be a currency then how can it also be an asset that you invest in? If you want to invest in dollars you don’t go to an ATM machine, withdraw lots of cash, and stuff it in your mattress. You may invest in assets that are denominated in a currency, like government bonds, or property in the country that issued the currency, but you don’t “invest” in the currency itself. You may speculate against movements in currencies, but this is really speculation against the underlying assets or the stability of the central bank or economy of the country that has issued the currency. The currency itself is not an asset and not even currency speculators will hold it for long.


The term investment implies buying an asset that will yield a return. It seems that crypto traders see investing in crypto the same as investing in property or a company and that it is a way to speculate that cryptocurrencies will become a standard way to buy goods in the future. But crypto isn’t a share in a company. It doesn’t entitle you to ownership of anything (other than the coin itself) and doesn’t yield any return. Buying shares in a company, say Apple, is fundamentally different. If I buy shares in Apple then I am buying an actual share of the company and I become a part-owner of Apple. I own part of their brands, intellectual property, sales pipelines and of their good chunk of cash in the bank as well. I get a return on my investment in a number of different ways. I get paid a dividend, I benefit from future profits on sales of Apple products and I get growth in value as the company increases its sales and product lines. Cashflows generated by sales of products can be used by Apple to invest in further product development or to buy back shares on the market, increasing the size of my share by reducing the float. My investment has the potential to grow in value as the company’s revenues grow. The value of my share is based on earnings, which I expect to increase. I can sell my share in the future to another investor who has calculated the value of the share from earnings, earnings growth, future cash flows, company balance sheet and other tangible values. If I buy crypto I get none of those. I get no dividend, no share in any future use of crypto or crypto-currencies, no growth in value, nothing. The value of crypto is completely arbitrary, apart from an expectation of recovering the cost of the ridiculous amount of energy that was used to “mine” the coin in the first place. The only way I have to get my investment back is to find another “investor” to sell my coin to. Eventually, the final investor loses everything – it’s a a zero-sum game. For every winner, there is a loser (and like with any investment, the winners are loud and the losers keep quiet). There is no way to win except for someone else to lose. It’s a classic “bigger fool” investment. I’m a fool to buy and can only get my money back by finding a bigger fool to sell to.

It doesn’t help when blog posts like this make claims such as “you own a portion of this technology that allows you to access the benefits”. This is such an outright lie. Nobody owns the technology. Anyone, even a central bank, can clone the code and create their own coins. Owning crypto currency does not convey any intellectual property rights whatsoever.

Cryptocurrencies will become the defacto payment method in the future

They won’t. But even if cryptocurrencies did become a defacto payment system this will have no bearing on the value of any specific coin. The technology may get reused, the coins will not. Owing coins does not entitle you to a share of anything. People think they are investing in a new technology that has the potential to revolutionise banking, but they’re not. Given the very serious drawbacks in using cryptocurrency for payment (lack of protection against loss or fraud, inefficient transaction ledger, lack of scalability…) it is almost guaranteed it will never become a mainstream currency (certainly not as the tech exists today anyway). But ironically, if it did, the whole reason people currently buy crypto would actually disappear. If many goods and services were priced in crypto the currency would stabilise and we wouldn’t see the huge swings in value that we see today. The huge potential gains that crypto traders are chasing would disappear. And the whole notion of “HODL”ing crypto would disappear as traders move to assets with an actual return.


Blockchain will revolutionise payments

The underlying payment technology, blockchain, is a decentralised and anonymous way to transfer cryptocurrency from one party to another. It is in fact an extremely inefficient and slow mechanism for conducting transactions. Bruce Schneier, who literally wrote the books we use as crypto texts, sum it up well here.

Blockchain can accomplish a maximum of 4.6 transactions per second, it uses huge amounts of energy to record transactions and the transaction ledger is only updated every 10 minutes. It just doesn’t scale. If every transaction in the world that is currently done with a credit card was instead done on blockchain, the population of the world could only perform one transaction per year.
The advantages of blockchain are often claimed to be that transactions are anonymous, decentralised and immutable. These are actually serious shortcomings that will prevent it from ever becoming a mainstream transaction record. Being anonymous means blockchain is attractive to criminal activities including money laundering, illegal drug trades, ransomware, etc. Most people do not need to hide their transactions from their government. There is no reason for people who don’t need to hide the source of their money not to use Euros or Dollars to make the same transaction. The idea that governments are prying and you should hide your dealings from them is flawed. Democracies around the world have elected governments who have implemented anti-money laundering legislation with the full support of their voters, who know it reduces criminality. Circumventing those restrictions enables and even encourages those criminal activities.

Being decentralised means there is no one entity that controls blockchain. This means there is no dispute mechanism, no anti-fraud protection and no way to recover lost coins. It is estimated that at least 4 million bitcoin have already been lost forever but this figure is probably underestimated. If someone who held BTC dies then there is no way to pass it on or even to tell if they ever owned it. If someone loses the password for their wallet, the coins are gone. If they are defrauded, scammed or transfer to the wrong person or just lose their password, their bitcoin is gone forever. If they die and haven’t shared their password, the bitcoin is lost forever. Many of the bitcoins that exist have been irrevocably lost already and as time goes on, more will be. If someone steals coin or commits a fraudulent transaction then there is no way to recover the coin. Most of us like the reassurance of using a bank to provide all those facilities and the lack of them will prevent cryptocurrency from ever becoming the default payment method.


Bitcoin is a store of value

The value of crypto has no basis in the real world, except maybe the cost of the electricity required to mine a coin. The theory goes that one coin will never be with less than the cost of the energy needed to find it, but that theory doesn’t stack up. The value of one coin can certainly go below the cost of mining and when this happens mining will just stop. It is estimated that the last coin will be mined before 2040 but the value of crypto most likely have collapsed long before then. The only real feature underpinning the value of crypto is belief. It is the belief that the value of a crypto-coin, essentially a random number, has value because you can buy or sell with others who also think these random numbers have value. Imagine I set up a ledger tomorrow recording ownership of prime numbers. The first prime numbers would be quickly taken but soon it would become more and more difficult to find unique prime numbers. When eventually prime numbers take substantial effort to find would you pay me a premium for the number 2 or 3 which I found first?

What is the long term outlook for bitcoin or any other cryptocurrency? No sane central bank would ever adopt them when they can just clone the code and create their own. They will invariably become worthless at some point. SHA-256 is still considered secure for now, but then so were SHA-1 and MD5 once. At some point SHA-256 will be broken. When that happens, or probably well before it, banks and other institutions will have upgraded to a stronger hash. But bitcoin holders will be left no way to upgrade, no way to exchange for a new type of coing, just nothing.


The basic concept of a cryptocurrency is in itself not a completely terrible idea. There are advantages in being able to seamlessly conduct transactions from anywhere simply by exchanging digital tokens certainly does have some merits. But buying and selling coins that are not backed by anything is certain to come to an unhappy ending. The purely illusionary value of the current crypto coins will collapse when the world eventually runs out of greater fools. There is no other possible endgame.

Solar PV Installation

Solar PV microgeneration has become a popular option for homeowners in Ireland in recent times, certainly helped by the introduction of an SEAI grant in July of 2018. Given my own personal interest in solar and IoT I checked if I was eligible for the grant and happily I was. A back of an envelope calculation showed a 6 year payback in terms of electrical energy saved based on a 75% reduction in imported energy from the grid which is reasonable. It also improves the BER rating for my house which makes it more salable so should pay for itself one way or another. And yeah its green too – saving maybe 4 tonnes of carbon per year.

I engaged next gen power to commission a system for me and this was finally installed last week. I went for the larger install of 18 panels (325W each, 6kWp total), a 5.8kW inverter and a 5.8kW battery. When I saw the effort they had to put in I was glad I didn’t consider going the self install route (which wouldn’t be grant eligible anyway).

There were some minor setbacks along the way, but nothing insurmountable. The first issue was that while I do have a large south-facing garage roof which I presumed would be ideal for mounting panels, it turns out that the dormer windows would make this awkward so the installers recommended a ground mount system instead. This was fine with me since I had the space for it. There is an area behind (west) the garage which is out of sight and a pain to keep anyway so losing a few metres of grass suited me just fine.

The panels are out of sight as you can see here. Only the cattle in the field behind us can see them and they probably won’t complain.

Most of the gear is in the garage which suits me fine too. And avoids complaints from herself about filling the utility room with equipment. The inverter and battery are rated for outdoor installation but I do prefer them indoors. The LiFePO4 battery tech is less prone to exploding (!) than regular Li-ion batteries but still better to not have it in the house as far as I am concerned.

There is a small consumer unit at the house (east) end of the garage where a new panel was installed with another meter. The wiring for the garage is a little messy (always was) so I plan to put in a new switch panel here at some stage with individual circuits for lighting and sockets (an item for the TODO list). The plan is to have lights controlled by PIR and to have some sockets driven from the essential loads circuit. The electric gates and a few other items are already distributed from here.

The wiring between the garage and the house needed a bit of work. The existing feed from the main consumer board to the garage was a 25A circuit using 2.5mm^2 cabling which wasn’t heavy enough to allow the 5.8kW inverter to drive the house. So we had to run a new cable. I had buried a 1.5″ hydrodair pipe before the tarmac went down so we were able to pull a shielded cable through this to feed the house. I prefer this anyway since now I can isolate the garage individually without losing the PV supply. I ran 2 x CAT5 cables while I was pulling through the power cable. One is for the PV metering, the other for internet. I just need to put some trunking around these cables at some stage to tidy up the entry point into the garage.

Inside the house, there are some additions to the utility room. The import/export meter has been added to main consumer unit which luckily fit into an empty slot. The garage MCB is now marked “solar”, which I may put on a separate one in time.

Finally there is “eddi” which is an energy diverter. This is connected to the immersion heater on the hot water tank to use up any excess power. More on this later.

Taking a few pics of the underside of the inverter shows some interesting ports. The two channels from the panels (9 panels per channel, 18 in total) have 4 cables coming into the inverter and there are two heavy cables to link to the battery (DC coupling).

The comms ports are more interesting. There is a USB port which has the WiFi dongle installed. This is configured to associate with the access point in the garage to give me telemetry from the inverter.

Temporarily removing the dongle and the cover over the comms ports shows that there are two RS485 ports. One for the import/export meter installed in the main house consumer board and one it seems for the battery which also has an RS485 port. There is an ethernet port too which I hope is a MODBUS/TCP port so I can query the inverter myself.

Having a peek under the mains output cover reveals the essential supply terminals. In time I plan to use these to power my server, the freezer, the boiler, the septic tank pump (it’s not pretty if that loses power) and maybe a few lighting circuits and sockets for phone chargers and so on. We do have fairly frequent power cuts out here and while the inverter can’t work in island mode (or can it?) at least the essential supply can be used for emergency power backup.

The givenergy portal is very good, but the updates are only every 5 minutes. Presumably the reports are an average over the 5 minutes and not a discrete sample but I won’t know for sure until I add my own telemetry. This snapshot shows a reasonably sunny day and the inherent problem of mismatched production and consumption. The battery is full at lunchtime but is empty again by 10pm. We will have to see in time if another battery is justified.

I have some initial observations after one week. It is definitely going to take some getting use to matching the production and supply. Most days even in the cloudy weather we had in the last week, there is more than enough energy supplied by the PV array (about 20kWhr) to cover the daily demand (about 18kWhr). But I am still exporting 2 or 3 kWhr per day. A bigger battery would help, but the payback may be too long if it only saves 2 kWhr per day.

Eddi helps BUT I am concerned the reaction time may be too slow. If sunshine is erratic, as it has been over the last few days, the switch from export to import occurs quickly and often. I wonder how often the inverter and the eddi read the import/export meter and react. Averaging out import and export doesn’t work – we don’t have net metering so exporting has to be minimised.

(UPDATE: The CT for the eddi was initially installed backwards which meant eddi was heating water while importing instead of when exporting. This explains the periodic bursts of battery power usage during the day. This is fixed now.)

Educating the family on how to optimise PV energy is challenging. When I suggested we run appliances during the day, the tumble dryer, washing machine, vacuum cleaner and dishwasher all went on at the same time resulting in an 8kW demand which is more than the inverter can supply so we imported anyway. I had to explain to add load during the day, but not all at the same time.

The PV array is (occasionally anyway) supplying the full 6kW but the battery can only charge at a rate of 2.4kW. This excess can be used to heat water using eddi, but once the water is hot, it gets exported regardless. To maximise the eddi excess diversion, I’ve turned off the gas boiler. But this runs the risk of not having enough hot water on a cloudy day. My teenagers seem to want to stay in the shower until the hot water tank is empty so managing expectations of hot water availability is a challenge.

Automation will help a lot here. Load scheduling by a smart gateway that knows the battery SoC, the scheduled demand, maybe even the weather forecast and coupled with an AI to learn the family demands will be an interesting area to explore.

And this is all happening mid summer. Really I will have to see what a full year looks like before I can accurately predict my payback. But given energy prices are only going up not down the payback should get shorter the longer it is is use so long as I can manage the load scheduling aspect.

GPL and why you need a COO

Early on in the development of ubiworx, we created a Certificate of Origin (COO) spreadsheet and kept it in our repo along with the code. It was a simple spreadsheet with one row per file in the repo, a data created column, author column and a column to describe any 3rd party code used. It was sometimes a bit of a pain to maintain and sometimes fell behind reality, but it got enough updates to be a reasonable reflection of the code base. It also was a good forcing function for engineers to think about where the code came from. As soon as John or I spotted anything in that column we immediately dug into why it was there.

Years later when we went to sell the company, that COO turned out to be an invaluable document. It would have been difficult to impossible to reconstruct the COO years after we started since dozens of developers had contributed to the 200KLOC or so of code. Having an up-to-date COO meant we knew the origin of every file and the license of every one as well. The git history helped a lot and we were able to cross-reference it to fill in any gaps, but it would be quite challenging if all we had was the git history.

Why not use GPL code?

From the outset of the project we had been very clear to all our team that any use of GNU General Public Licensed (GPL) code was forbidden. Copying and pasting code from slashdot or other sites was also forbidden. Lesser or Library GPL (LGPL) code was allowed with PM approval and there were strict conditions as to its use. MIT and other permissive licenses were allowed if absolutely necessary.

The GPL is a strict license that imposes several conditions on its use. These conditions are very clearly called out and integrators can make an informed decision to use GPL code or not. One of the best-known features of the GPL code is that using any GPL code in your system means the GPL must apply to your entire system. This is sometimes unfairly called the “viral” nature of the GPL. The virus analogy is unfair because you cannot choose to get a virus whereas the conditions attached to GPL-protected source code are as I said clearly called out and a clear choice must be made to include GPL code.

I have been asked before by engineers how can “they” force you to release your source code if they find you have used some GPL source code in your product. The answer is “they” (the original author or an organisation acting on their behalf) can’t force you to do anything! What the author can do is grant a license to use their source code and to specify conditions that must be met before the license can be used. If you choose not to comply with these conditions then you have not complied with the license and you are using unlicensed source code in your product. In this case, the original author can prevent you from shipping your product until you comply with the license conditions. What if you don’t want to comply? Your only choices then are recall your product or re-engineer it so it doesn’t contain any GPL code. Neither are pleasant options for a commercial product ready for launch. Some people naively think the GPL is new and untested (even now) and that it wouldn’t stand up in court, but copyright law goes back centuries. There is a mountain of legal precedent and fighting that is not going to be easy.

For our use case, we deemed the condition to release source code for our product to be too high a price to pay for the convenience of availing of some GPL source code so we opted to completely avoid GPL source code. I am sure many other software companies find themselves in similar situations and I do sometimes wonder if the GPL is in fact doing more to prevent the spread of open source than to enable it in some sectors? For us, we had decided that our closed source code was proprietary and was where our value was. The ability to charge a license fee for the use of our product was what was going to keep the lights on and the rent paid. Giving up this revenue stream simply wasn’t an option. Advocates of the GPL will of course say it does not prohibit charging for software but in reality nobody is going to pay a license fee for code they can get elsewhere and use for free.

Lesser GPL and permissive licences

LGPL often makes sense and is sometimes pretty much unavoidable. The glibc library is licensed under LGPL and not much would work without it. But engineers still need to be aware that while this license doesn’t mean you have to open source your entire product, it does mean any distribution must allow a user to rebuild and replace LGPL components if they choose. When using shared object libraries this is straightforward but linking static LGPL libraries may require you to release your Makefiles and any other tools needed to rebuild your system.

MIT, BSD, Apache and other permissive licenses don’t carry the requirement that all source code must be released. They do generally though look for an acknowledgement of their contribution so an about box or similar should acknowledge the original authors.

COO and due diligence

During the due diligence phase of the ubiworx acquisition, having a COO and knowing the origin of every file meant things ran very smoothly. There were a few queries from the consultant who had brought in to assess the code, but no red flags and nothing we couldn’t explain to their satisfaction. The very existence of the COO was a reassurance in itself to the due diligence team as it meant we had paid close attention to the origin of all of our source code.

Power your home and commute to work with a Zero carbon footprint

This article was submitted to the energy symposium in 2017.  Unfortunately I wasn’t able to attend.

Introduction

Today there are viable alternatives to consuming electrical energy from the national grid. Solar photovoltaic (PV) cells can generate electricity that domestic consumers can use to become more self sufficient. A key challenge has always been however matching the timing of supply and demand of energy sources like sunlight, which is not always available. Thanksfully, battery technology has now improved to the point that generation and consumption needs can be more closely matched for domestic use. Add to the mix the increasing use of the electric vehicle (EV) and we have an opportunity to solve two problems with one solution.

Batteries Requirements and Sizes

Batteries these days are usually lithium polymer or lithium iron phosphates. Flow batteries also exist that do not have anodes or cathodes. Even flywheel energy storage (FES) with rotors spinning at up to 50,000 RPM is being used to store excess energy to balance supply with demand.

Any storage method needs to be managed carefully to maximise efficiency and longevity and these requirements are not always in sync with each other. Take for example an electric vehicle (EV) battery. For maximum range and utility the battery management system (BMS) should allow state of charge (SoC) in the range of 20% to 100%. However for longer battery life this range should be limited to 30% to 70%. Using an intelligent IoT gateway running ubiworx™ we can achieve a balance between maximum utility and extending battery life.

Choosing a battery size is an important consideration. In the paper “Energy self-sufficiency, grid demand variability and consumer costs: Integrating solar PV, Stirling engine CHP and battery storage” (Balcombe et al, 2015) the authors found that for a typical household that consumes 3300kWh/yr and which utilises a 6kWp solar PV installation without a battery, only 28% of the energy produced would be consumed.

The report also found that “battery capacity has a significant impact on the amount of electricity imported from the grid” with import decreasing from 55% to 20% with a 5kWh battery down to 12% when a battery with a capacity of 20kWh was installed. Battery sizes in excess of 5kWh therefore produce diminishing returns for a typical household. In the paper “Storage Solutions for Renewable Production in Household Sector” (Bianchi et al, 2014) the authors found that the optimal battery size is 4 to 5 kWh for a 3200kWh/yr household so it is clear that a size of around 5kWh is optimal for a typical domestic installation.

Electric Vehicle Battery Sizes and Charge Requirements

The Nissan Leaf is an example of a popular electric vehicle that has a battery capacity of 30kWh. According to the US EPA the Nissan Leaf can travel 172km on a full charge of its 30kWh battery, which works out at 17.4kWh per 100km. At a grid import cost of about 20c per kWh that’s €3.49 per 100km. A diesel Nissan Note uses 4.2L/100km1 which at today’s price of about €1.20 per litre would cost €5.04 per 100km. So there is definitely some saving in running costs but it is not as much as it could be (although it should be noted that EVs have other advantages such as using far less power when in slow moving traffic). The need for further savings are particularly relevant if you are using Irish grid electricity which is generated created using fossil fuels in the first place.

One way to further reduce your carbon footprint is to use a solar charging station to charge your EV. A 3kWp solar installation will generate about 3,000kWh per year in Ireland2. At 17.4kWh per 100km this would power your EV to cover which would power an average of 17,000 km per year which is certainly adequate for most commuters. A disadvantage here though is that the rate of charge from a solar PV array is going to be quite slow and also limited to hours of daylight. Even at its peak output of 3kW it is going to take 10 hours to fully charge the EV, so a battery is clearly needed here to match the demand with the supply. The maximum charge the EV could use would be the size of its own battery (30kWh in the case of the Leaf) but the battery could be smaller if is only to be used as a top-up. If we aim to keep the EV in the 30% to 70% range then in theory we would need a battery with a capacity of 12kWh (this is assuming 100% efficiency of charge and discharge, which isn’t the case of course but it gives a reasonable indication for our purposes).

Now if we then put both of these concepts together we can have a single solar PV array with one battery that both powers the home and charges the EV. We will need to double the PV size to 6kWp to create enough power for both the EV and the home but a single battery of about 15kWh should under almost all circumstances be able to power both. The problem of wasted excess capacity from the home is reduced by using the stored energy to top up the EV instead and the carbon footprint of the EV is reduced even further by availing of stored energy generated from solar. In this way the two can work together to make best use of each other’s peaks and troughs in supply and demand.

Artificially Intelligent Optimisation

If we use an intelligent IoT gateway running ubiworx™ acting as an intelligent control and battery management system (BMS) to manage the state of charge (SoC) of the EV and the electrical loads in the home will create even further opportunities for optimisation. By performing this function we can also analyse individual cells within the battery. Different cells may have different SoC values or may have different lifetimes. We can optimise charge rates and levels for each cell as well as alerting users of any potential problems down the road.

We could collect and analyse usage data per site as well as using the ubiworx IoT cloud to aggregate big data for mining for trends and patterns to identify other opportunities for optimisiation. We can use machine learning to predict failures, to learn how battery lifetime is affected by charging patterns and to also learn about usage patterns to predict upcoming energy needs. For example, it may be that a user has a short commute during the week but travels longer distances at the weekend. Or that the home energy use is lower at weekends than during the week. These patterns can be used to predict what SoC should be the target for the battery and for the EV. The SoC charge target for the EV could be increased from 70% to 80% at the weekend for example. Being able to anticipate the SoC the EV will have when the home owner returns from work or what the expected domestic electrical load will be allows the BMS

Another option is that we could even treat the EV battery as an extension to the household battery. If a large power demand is made by the house and the EV battery is at full capacity then the BMS could decide to draw some power from the EV instead of from the grid.

Conclusion and Next Steps

As we have seen combining a domestic PV installation with a battery and an inverter along with an EV battery management system using an intelligent IoT gateway can potentially yield significant reductions in the percentage of electricity imported from the grid. Optimal usage of power sources, intelligent analytics and predicted estimates of power requirements can reduce the grid import even further. Participation in peak demand shaving networks and becoming part of a smart grid are also very viable options.

A primary obstacle that needs to be removed is the high capital cost of installing solar PV. In their paper, Balcombe et al recommend a government subsidy of 24% to reduce the 4300kWh/yr break even threshold to the 3300kWh/yr level of a typical household. Ironically also a decrease in the feed in tariff would create a wider gap in the cost between imported and self generated energy which would make the capital cost easier to justify and absorb.