<?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 Chrispine Tinega on Medium]]></title>
        <description><![CDATA[Stories by Chrispine Tinega on Medium]]></description>
        <link>https://medium.com/@tinegachris?source=rss-699d704a2365------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v_E72mNFsbs7jUbaIhZN5g.jpeg</url>
            <title>Stories by Chrispine Tinega on Medium</title>
            <link>https://medium.com/@tinegachris?source=rss-699d704a2365------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:14:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tinegachris/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[Ethics at the Edge of the Grid]]></title>
            <link>https://medium.com/random-post-mortems/ethics-at-the-edge-of-the-grid-8598573e8a68?source=rss-699d704a2365------2</link>
            <guid isPermaLink="false">https://medium.com/p/8598573e8a68</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[renewable-energy]]></category>
            <dc:creator><![CDATA[Chrispine Tinega]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 21:28:21 GMT</pubDate>
            <atom:updated>2025-12-26T21:34:05.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>Where Energy Infrastructure Meets Moral Infrastructure</h4><p>In 1980, philosopher Langdon Winner posed a question that still resonates in engineering departments today: “<a href="https://www.jstor.org/stable/20024652">Do artifacts have politics?</a>” His answer was unsettling. The bridges Robert Moses built on Long Island parkways were deliberately designed too low for buses to pass underneath. Only people who could afford cars could easily reach certain public beaches. The infrastructure encoded exclusion into concrete and steel, lasting decades beyond Moses himself.</p><p>Winner’s insight cuts deep: technologies are never neutral. They carry values. They distribute power, access, and risk in specific ways. Once built, these choices become durable, shaping human action far into the future.</p><p>For most engineers, this sounds like a philosophical concept. Abstract. Disconnected from the real work of calculating load capacities, debugging firmware, or commissioning inverters. But working on energy systems across Africa for the past five years has taught me something uncomfortable: Winner’s bridges look a lot like the systems we build every day. The difference is that instead of encoding access to beaches, we’re encoding access to hospitals, schools, economic opportunity, and basic human dignity.</p><p>This is a reflection on where those encoded values live in energy infrastructure, why they matter more than we typically acknowledge, and what it means to build responsibly at the intersection of technical and moral choices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QQQ_Tg-Fo9G_jx2Ix9eHw.jpeg" /><figcaption>Reflecting ethics at the edge of the grid</figcaption></figure><h3>The Invisibility Problem</h3><p>Energy systems have a peculiar characteristic: when they work well, they disappear. You flip a switch. Light appears. You plug in a device. It charges. The vast technical infrastructure that makes this possible, the batteries and inverters and controllers and communication protocols, becomes an invisible background to daily life.</p><p>This invisibility creates a moral hazard. Because when systems work, we stop questioning the choices embedded in them. We forget that someone decided which parameters operators can adjust and which require engineering credentials. Someone determined acceptable downtime, tolerable voltage fluctuations, and sufficient redundancy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcQzZPsAyxwfZS7u8tukyA.jpeg" /><figcaption>One technical decision I ended up questioning</figcaption></figure><p>These are not purely technical decisions. They are value decisions dressed in technical language.</p><h3>Edges Where Ethics and Engineering Intersect</h3><p>Working on smart renewable energy installations and embedded energy management systems has revealed four distinct places where technical choices become ethical choices. I call them “edges” because they’re boundary zones: places where engineering discipline meets social reality, where optimisation runs into human need, where theory confronts practice.</p><h4><strong>Edge One: Quality Assurance as Risk Distribution</strong></h4><p>Quality assurance is usually framed as a technical discipline. We talk about coverage, test plans, pass rates, regression suites, and performance envelopes. The language is neutral and mathematical. It sounds like optimisation.</p><blockquote>In energy systems, that picture is incomplete. QA is also about <strong>who carries the risk when things go wrong.</strong></blockquote><p>Every test you do not run, every scenario you choose to deprioritise, every “known issue” you accept as acceptable is effectively a decision about <strong>where to park the uncertainty</strong>. In an energy system, that uncertainty does not stay in the lab. It travels downstream to:</p><ul><li>The nurse relying on stable power for a vaccine refrigerator</li><li>The small business with a single welding machine and tight delivery deadlines</li><li>The student whose only study time is at night under electric light</li></ul><p>Classic engineering ethics codes are explicit here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hI_w_Mna7SLRsTWSTEdJlQ.jpeg" /><figcaption>The Responsibilities of Engineers</figcaption></figure><p>Read through that lens, QA is not just a quality function. It is one of the main ways engineers either honour or quietly erode that obligation.</p><p>QA has three ethical dimensions:</p><ul><li><strong>Duty</strong>: There is a baseline obligation not to release systems that are foreseeably unsafe or grossly unreliable, regardless of schedule pressure.</li><li><strong>Virtue</strong>: Good engineers develop habits of thoroughness, honesty about unknowns, and discomfort with unexamined edge cases. QA is where those habits are tested.</li><li><strong>Justice</strong>: The harshest consequences often fall on people far from the design table, with the least power to complain or demand remediation. QA decisions either mitigate or amplify that imbalance.</li></ul><p>A practical way to internalise this is to treat every QA decision as a risk distribution question:</p><ul><li>If we skip this test, who pays if we are wrong?</li><li>If this bug escapes into the field, who will notice first: our monitoring system, a trained operator, or an end user?</li><li>If this failure happens at the worst possible time, is that acceptable?</li></ul><p>These are not comfortable questions. They are necessary if QA is to be more than a compliance exercise.</p><p>At the edge of the grid, QA is not just about proving that a design works. It is about deciding, with open eyes, who will bear the cost when it does not.</p><h4>Edge Two: <strong>Commissioning as Delegated Responsibility</strong></h4><p>Commissioning is where design meets reality. It is the moment when a system transitions from theoretical design to operational infrastructure. And it is the moment when engineers hold maximum authority with minimum external oversight.</p><p>On site during commissioning, the engineer makes dozens of judgment calls: Is this communication delay acceptable? Is this voltage fluctuation within tolerance? Can we proceed despite this intermittent behaviour, or do we need to investigate further?</p><p>These judgments are made under pressure. Contractors are waiting. Clients are watching timelines. Equipment is expensive to keep on standby. There is momentum toward proceeding, always toward proceeding, because delay costs money and patience.</p><p>This creates an ethical structure that engineers often do not explicitly acknowledge:</p><ul><li><strong>Authority</strong>: You have the power to proceed or pause. This power is real and consequential.</li><li><strong>Knowledge asymmetry</strong>: You understand technical risks that clients and contractors cannot. They depend on your judgment.</li><li><strong>Accountability gap</strong>: Once systems are deployed, you are often not present if problems emerge. Others will bear the consequences of your decisions.</li></ul><p>These three elements together create something philosophers call a “<em>delegated responsibility.</em>” The decision is yours, but the consequences belong to others. This is where engineering virtue matters most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0do411RaFhLPnL4bld-AnQ.jpeg" /><figcaption>The wisdom of action is the engineer’s responsibility</figcaption></figure><p>Aristotle called it <a href="https://doi.org/10.1093/med/9780197524480.003.0009"><em>phronesis: practical wisdom</em></a>. The capacity to recognise when technical margins matter, when “probably fine” is not good enough, when the pressure to proceed should be resisted.</p><p>The ethical decision while commissioning is not technical. It is personal: am I willing to sign off on this system as it stands? Would I accept this level of uncertainty if it were my hospital, my school, my business, depending on reliable power?</p><p>That reversal test, simple as it sounds, is powerful. It forces engineers to confront the asymmetry between their authority to proceed and their liability for consequences. Management cannot see what you see. Clients do not know what you know. The judgment call is yours.</p><p>The virtue here is courage: not dramatic courage, but the quiet kind. The courage to say “I am not confident yet” when everyone wants you to be. The courage to delay when delay costs money. The courage to escalate concerns despite social and financial pressure to proceed.</p><h4>Edge Three: Design as Encoded Values</h4><p>Every choice about what to automate and what to leave manual, every default parameter, every interface design is a choice about human-machine relationships. Engineers do not just build systems. We design interactions, distribute control, and encode assumptions about competence, authority, and trust.</p><p>Consider the interface for energy management systems. When designing the interface, several tensions emerge:</p><ul><li><strong>Simplicity vs. Visibility</strong>: Simple dashboards are intuitive but can hide system details. Complex dashboards reveal problems but overwhelm non-technical users.</li><li><strong>Access vs. Safety</strong>: Allowing operators to adjust battery charge rates gives them flexibility to respond to local conditions. But without a deep understanding of battery chemistry, thermal limits, and cycle life impacts, that flexibility can accelerate degradation or create safety risks.</li><li><strong>Autonomy vs. Dependence</strong>: Systems that automatically handle edge cases reduce operator workload but create dependence on the manufacturer. When problems arise that automation cannot handle, operators lack the visibility or access to intervene.</li></ul><p>These trade-offs do not have universal right answers. They depend on context: operator training levels, availability of technical support, consequences of failure, and importance of system lifetime versus upfront cost.</p><p>The ethical frame here is about <strong>distribution</strong>: who gets agency, who must wait for expertise, who can act, who must watch? These distributions are encoded into the interface. They persist as long as the system operates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-JZ1eB-G0ZWzEWZ2bmpow.jpeg" /><figcaption>It is the engineer’s responsibility to distibute understanding</figcaption></figure><p>Winner’s insight applies directly: the interface is political. It distributes capacity and constraint. And those distributions shape the possibilities available to operators for years.</p><p>The same pattern appears in reporting and dashboards. Performance metrics for solar installations can emphasise simple numbers (kilowatt-hours produced today) or complex ratios (performance ratio accounting for irradiance, temperature, and losses). The first is accessible but incomplete. The second is informative but requires expertise to interpret.</p><p>The choice encodes an assumption: are we building for informed understanding or for simple oversight? Are we designing systems that empower users to make better decisions, or systems that reduce decision-making to simple thresholds?</p><p>Design choices that distribute understanding, that make systems legible to operators, that provide the information needed for smart local decisions, those are choices aligned with what some call “<strong><em>care ethics</em></strong>.” They say: I respect your capacity to understand and act on this system. I am designing so that you can.</p><p>The opposite design, which makes systems opaque and forces dependence, says something different. It is not necessarily malicious. But it is a distribution of power, and ethical engineers need to be conscious of what they are distributing and why.</p><h4>Edge Four: Documentation as Covenant Across Time</h4><p>Documentation is often treated as bureaucratic overhead: a box to check, a document to produce, something to do “if there is time at the end.” This attitude reveals a fundamental misunderstanding of what documentation is and who it serves.</p><p>Documentation is how engineers communicate across time. It is how we speak to future operators who will run the systems we built, future maintenance technicians who will troubleshoot problems we never anticipated, and future engineers who will modify or extend what we designed.</p><p>The quality of that communication is an ethical matter, sharing a common ethical dimension: honesty about limitations, workarounds, and known issues.</p><p>Across projects, a recurring problem appears: documentation that does not match implementation. Code evolves. Fixes get applied. Parameters get adjusted during commissioning based on site-specific conditions. But documentation does not get updated. It continues to describe the system as originally designed, not the system as actually built.</p><p>This creates a dangerous situation: operators follow procedures that no longer match reality. Maintenance technicians troubleshoot based on outdated assumptions. Future engineers make changes that conflict with undocumented modifications.</p><p>The problem is not always neglect. Often, it is pressure: commissioning timelines do not include time for documentation updates. Fixes made on-site under deadline pressure do not get properly recorded. “We will update the docs later” becomes “we never got around to updating the docs.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzGdfCOgE2WD9qUgngaulw.jpeg" /><figcaption>Commit messages are documentation too!</figcaption></figure><p>The ethical failure here is about what you might call fidelity: keeping faith with future people. By leaving documentation incomplete or incorrect, we transfer the cost of understanding the system to everyone who comes after us. We save ourselves a few hours of work by imposing many more hours of confusion, debugging, and potentially dangerous misunderstandings on others.</p><p>We also make a statement about how much we trust future people to understand complex systems, and how much we respect their time and intelligence.</p><p>The alternative requires discipline: treat documentation updates as part of the work, not something to do afterwards. If code changes, documentation changes in the same commit. If commissioning requires workarounds, the manual gets updated before leaving the site. If choices were made due to constraints rather than preference, that context gets recorded.</p><p>This is not perfectionism. It is respect for future people: the operators, maintainers, and engineers who will inherit what we built and need to understand not just what it does but why it does it that way.</p><p>It is also a practical self-interest. Systems you documented well are systems you can return to confidently. Systems left undocumented are liabilities that plague you when you need to troubleshoot or modify them later.</p><p><strong>Documentation is a covenant</strong>: a commitment that what we leave behind is not just code or hardware, but knowledge, context, and honest accounting of choices made.</p><h3>Toward a Practice of Responsible Engineering</h3><p>So what does responsible engineering look like at these edges? Not rules, because rules do not adapt to context. Not checklists, because checklists do not build judgment. Instead, a practice: a set of habits, questions, and commitments that engineers carry into uncertain situations.</p><p><strong>First, cultivate awareness that technical choices have moral dimensions. </strong>This sounds obvious, but it runs counter to engineering education, which typically treats ethics as a separate topic, disconnected from the core work of calculation and design. The shift required is to recognise that choosing which test cases to run, which parameters to expose in an interface, and which level of detail to document, are ethical choices from the start, not technical choices that ethics gets applied to later.</p><p><strong>Second, develop the habit of consequence mapping.</strong> Before making decisions, ask: who is affected? Not just immediate clients, but operators, communities, maintenance technicians, and future engineers. What happens if this choice is wrong? Who bears the cost? This does not require perfect prediction, but it does require thinking beyond the immediate task.</p><p><strong>Third, practice the reversal test.</strong> Would you accept this system in your own home, clinic, or business? If not, why are you comfortable deploying it elsewhere? This question cuts through rationalisation. It forces you to confront asymmetries between your authority to proceed and your willingness to experience consequences.</p><p><strong>Fourth, build in margins for uncertainty.</strong> Engineering is full of unknowns: field conditions that differ from lab tests, use patterns that diverge from assumptions, and environmental factors that exceed specifications. Responsible practice means designing systems that degrade gracefully under unexpected conditions rather than failing catastrophically.</p><p><strong>Fifth, prioritise documentation as integral to the work.</strong> If something is worth building, it is worth explaining. If a choice has reasoning behind it, that reasoning should be recorded. If a workaround was necessary, future people need to know it is a workaround, not a feature. This takes time. It is time well spent.</p><p><strong>Sixth, create space for the decision to pause.</strong> In environments where timelines and budgets create pressure to proceed, the ability to say “I am not confident yet” requires structural support. Organisations should reward engineers who raise concerns, not punish delays. Cultures should respect thoroughness, not just speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ectOtzDhmj_HSv2MoWihfg.jpeg" /><figcaption>Infrastructure outlasts intentions. What politics will we encode into the systems we build?</figcaption></figure><p>These are not heroic acts. They are professional habits. They are the difference between engineering as mere technical problem-solving and engineering as the responsible creation of infrastructure that shapes human possibilities.</p><h3>P.S. Post-Mortem</h3><p>Writing this piece forced me to confront something uncomfortable: the gap between knowing that technical choices are ethical choices and actually acting on that knowledge when it matters most.</p><p>I spent four years reading about Winner, studying virtue ethics, and understanding how design distributes power and opportunity. But knowing these ideas and living them are different things. When you are on-site commissioning with contractors standing idle and a client watching the clock, your philosophical commitment to “<em>practical wisdom</em>” gets very practical very quickly.</p><p>The post-mortem is this: I have failed the reversal test more times than I would like to admit. I have rationalised “probably fine” when I had nagging doubts. I have shipped systems, telling myself that monitoring would catch problems, that we could patch them later, and that the redundancy would hold. Sometimes it did. Sometimes I was lucky. Sometimes I was just wrong.</p><p>What changed was recognising that luck is not strategy. After several projects where luck ran out and problems emerged months later, I started treating commissioning decisions like irreversible commitments, because they are. Once you leave the site, you are not coming back until something breaks or quarterly maintenance happens. That changes how you think about “good enough.”</p><p>The second uncomfortable realisation: documentation is not a chore I do after the real work is done. It is the real work. The code is just an artefact. The documentation explains why the artefact exists and how to work with it. Poor documentation is not incomplete work. It is a broken promise to everyone who comes after.</p><p>So here is what the four years taught me: ethics in engineering is not something you learn in university and then implement. It is something you practice, fail at, learn from, and practice again. Each project teaches you something about the gaps between what you believe and what you do.</p><p>The goal is not perfection. The goal is direction: Are you getting better at recognising when choices matter? Are you getting braver about pausing when you should? Are you getting more disciplined about documenting thoroughly? Are you building systems that respect the intelligence and agency of the people who will use them?</p><p>Some days, yes. Some days, not yet. But the edges keep teaching, if you pay attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8598573e8a68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/random-post-mortems/ethics-at-the-edge-of-the-grid-8598573e8a68">Ethics at the Edge of the Grid</a> was originally published in <a href="https://medium.com/random-post-mortems">Random Post-Mortems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A PID Controller for Zero Grid Export: When Theory Meets Reality in Energy Management]]></title>
            <link>https://medium.com/random-post-mortems/a-pid-controller-for-zero-grid-export-when-theory-meets-reality-in-energy-management-87c85562413b?source=rss-699d704a2365------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c85562413b</guid>
            <category><![CDATA[energy-management-system]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[pid-control]]></category>
            <category><![CDATA[control-system]]></category>
            <category><![CDATA[renewable-energy]]></category>
            <dc:creator><![CDATA[Chrispine Tinega]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 19:37:43 GMT</pubDate>
            <atom:updated>2025-11-22T19:37:43.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkethNJNqssfX3tsa7Hfvw.jpeg" /></figure><p>Zero-export control doesn’t care about elegance, textbook stability, or the beauty of control theory. It cares about one thing: <strong>never letting energy flow back to the grid</strong>. Any overshoot is a failure, and every correction comes with real consequences.</p><p>That’s the environment I stepped into when I set out to design a controller for solar-battery systems. After days of tuning PID gains, staring at oscillating graphs, and hunting down a critical sign error that had my battery doing exactly the opposite of what it should, I finally achieved what I set out to do: a rock-solid zero-export controller that keeps grid power exactly where it should be. But getting there taught me that the gap between the control theory I learned in Ogata’s “<em>Modern Control Engineering</em>” and real-world energy systems is wider than I ever imagined.</p><p>Here’s the story of how I built a sophisticated control system for solar battery systems, discovered a fundamental sign error that made everything worse, and learned why simulation fidelity matters more than perfect control theory.</p><blockquote>I write random post-mortem stories like this <a href="https://medium.com/random-post-mortems">here</a>. Not a Medium member? Use <a href="https://tinegachris.medium.com/87c85562413b?source=friends_link&amp;sk=68e95060296111544feb08d2d70b8f64">this friend link</a> to read for free.</blockquote><h3>The Challenge: Quality Assurance in Energy Management Systems</h3><p>As an Embedded Systems QA Engineer at a renewable energy company, I spend my days ensuring that Energy Management Systems (EMS) work exactly as they should. My work involves building test simulators that emulate PV inverters, battery systems, and energy meters, then putting our EMS software through its paces to catch bugs before they reach the field.</p><p>One control function I test repeatedly is zero grid export. In many African markets, including Kenya, regulatory frameworks are evolving rapidly around distributed generation. The Energy and Petroleum Regulatory Authority (EPRA) oversees grid-tied solar installations, and increasingly, utilities are imposing strict limits on how much power can be exported back to the grid.</p><p>For some installations, the requirement is absolute: zero export. <strong>Not “minimal export” or “export within limits.” Zero</strong>.</p><p>This creates a fascinating control problem.</p><h4>Why Zero Export Matters</h4><p>The technical and regulatory reasons for zero export are compelling:</p><ul><li><strong>Grid Stability:</strong> In areas with weak distribution infrastructure (common across rural Africa), unexpected power injection can cause voltage rise issues, potentially damaging equipment or triggering protective relays.</li><li><strong>Regulatory Compliance:</strong> Many utilities in Kenya prohibit export entirely for smaller installations. As someone who holds an Electrical Worker license from EPRA, I’ve seen firsthand how seriously these regulations are enforced.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fcmc2gThmdejGoDZVghomA.jpeg" /></figure><ul><li><strong>Economic Optimisation:</strong> In markets without favourable feed-in tariffs, exported energy represents wasted generation. Every watt sent to the grid is a watt not used to offset expensive grid imports.</li></ul><h3>From Testing to Building: The Decision</h3><p>After testing dozens of zero-export implementations in our EMS software, I started asking deeper questions. How would I implement this myself? What are the real challenges beyond the control algorithm? Can I build a simulation accurate enough to trust before deploying to hardware?</p><p>Having studied control systems theory extensively during <a href="https://medium.com/random-post-mortems/the-university-experience-a-journey-of-growth-discovery-and-transformation-579b3d3077a1">my electrical engineering degree at JKUAT</a>, and with hands-on experience from commissioning over 10 MVA energy systems, I decided to give it a shot.</p><p>The goal was simple: build a PID-based zero export controller with a simulation environment so realistic that I could confidently deploy the tuned parameters to actual hardware. Yes, it seemed simple at first.</p><p>This wasn’t just an academic exercise. In my work and hobby projects, I interact with <a href="https://github.com/tinegachris/hybrid_renewable_pypsa">energy models</a> and <a href="https://medium.com/random-post-mortems/a-simple-bug-with-lessons-modbus-python-rust-and-buffer-overflows-5e5036cd5066">simulators </a>constantly. My priority is always ensuring that models and simulations accurately depict real-world behaviour.</p><blockquote>A simulation that lies to you is worse than no simulation at all.</blockquote><h3>Understanding the Control Problem</h3><p>Before writing a single line of code, I needed to understand the unique characteristics of the zero-export control problem.</p><h4>The Power Balance Equation</h4><p>The fundamental equation that governs the system:</p><pre>Grid Power = PV Generation - Load Consumption - Battery Power</pre><p>This seemingly simple equation became the source of a critical bug I later discovered. When grid power is positive (export), the battery should discharge to absorb that excess. When grid power is negative (import), the battery can charge from the excess PV.</p><h4>The Asymmetric Constraint</h4><p>Traditional PID control aims to drive a process variable to a setpoint and maintain it there. Deviations in either direction are equally bad. But zero export is fundamentally asymmetric:</p><p>Here’s what this means in practice:</p><pre>*Scenario*     | *Grid Power* | *Interpretation*     | *Consequence*<br>|--------------|--------------|----------------------|-------------------------------<br>Perfect        |  -250 W      | small import buffer  | Ideal<br>Negative error | -2000 W      | Importing from grid  | Missed opportunity, but legal<br>Positive error |  +500 W      | Exporting to grid    | Regulatory violation</pre><p><strong>Any export is a compliance failure.</strong> But importing more than necessary just means you’re not maximising solar self-consumption. This asymmetry completely changes how you must tune the controller.</p><p>A standard PID tuning approach optimises for fast setpoint tracking with acceptable overshoot (typically 10–25%). But in zero-export control, overshoot means export, and export means you’ve failed.</p><h4>The Physical System</h4><p>The system consists of three main power flows:</p><ul><li><strong>PV Generation:</strong> Completely uncontrolled, varies with weather (clouds, time of day). My 5 kW array generates a smooth bell curve, interrupted by random cloud events.</li><li><strong>Load Consumption:</strong> Uncontrolled, varies with user behaviour. Random appliance switching, motors starting, averaging around 2 kW baseline.</li><li><strong>Battery Power:</strong> The only controlled variable. This is our “actuator” in control theory terms. My 10 kWh battery can charge/discharge at up to 5 kW.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hh6BP9fG_RCBNGH9ateGQw.jpeg" /></figure><p>The controller measures grid power (through a Modbus-connected energy meter) and commands the battery inverter to charge or discharge to drive grid power to the target (typically -250W, allowing a small import buffer).</p><h3>Implementation: Building the Simulation Environment</h3><p>The first major decision was to build this entirely in simulation before touching hardware. In my QA work, I’ve learned that good simulations save time and prevent expensive mistakes.</p><h4>Realistic Component Models</h4><p>I started with a battery model that captures real-world behaviour:</p><pre>class Battery:<br>    def __init__(<br>        self,<br>        capacity_kwh=10.0,<br>        soc_init=0.5,<br>        max_charge_kw=3.0,<br>        max_discharge_kw=3.0,<br>        eff_charge=0.97,<br>        eff_discharge=0.97,<br>        min_soc=0.1,<br>        max_soc=0.95<br>    ):<br>        self.capacity_kwh = capacity_kwh<br>        self.max_charge_kw = max_charge_kw<br>        self.max_discharge_kw = max_discharge_kw<br>        self.eff_charge = eff_charge<br>        self.eff_discharge = eff_discharge<br>        self.min_soc = min_soc<br>        self.max_soc = max_soc<br>        self.soc_kwh = soc_init * capacity_kwh</pre><p>This isn’t just a simple integrator. The model includes:</p><ul><li><strong>Round-trip efficiency:</strong> Charging at 97% efficiency, discharging at 97% efficiency gives you 94% round-trip.</li><li><strong>Power limits:</strong> Real batteries have C-rate limitations (5 kW for 10 kWh = 0.5C).</li><li><strong>SOC limits:</strong> Operating between 10–95% protects battery life</li><li><strong>Energy balance with losses</strong> properly modelled.</li></ul><h4><strong>Energy balance with efficiency:</strong></h4><pre>def step(self, commanded_power_kw, dt_s):<br>    dt_h = dt_s / 3600.0<br>    <br>    if commanded_power_kw &lt; 0:  # Charging<br>        energy_in = abs(commanded_power_kw) * dt_h<br>        energy_stored = energy_in * self.eff_charge<br>        self.soc_kwh += energy_stored<br>    else:  # Discharging<br>        energy_out = commanded_power_kw * dt_h<br>        energy_removed = energy_out / self.eff_discharge<br>        self.soc_kwh -= energy_removed<br>    <br>    # Clamp to physical limits<br>    self.soc_kwh = np.clip(<br>        self.soc_kwh,<br>        self.min_soc * self.capacity_kwh,<br>        self.max_soc * self.capacity_kwh<br>    )</pre><h4>Realistic Disturbance Profiles</h4><p>The PV and load profiles had to capture real-world variability. I generated synthetic profiles with:</p><p><strong>PV Profile (5 kW peak):</strong></p><ul><li>Solar irradiance curve following the sun&#39;s position</li><li>3 random cloud events (Gaussian drops lasting 2–10 minutes)</li><li>High-frequency measurement noise</li><li>Total generation: <strong>2.304 kWh</strong> over 1 hour</li></ul><p><strong>Load Profile (~2 kW average):</strong></p><ul><li>Base load around 2 kW</li><li>Random walk with Gaussian noise</li><li>8 discrete step events (appliances switching)</li><li>Total consumption: <strong>1.930 kWh</strong> over 1 hour</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6r05FCbVq8-giK4mcDYoQg.png" /><figcaption>PV and load profiles</figcaption></figure><p>This matters because PID tuning depends heavily on the disturbance characteristics.</p><h3>The PID Controller: The First Attempt</h3><p>Now came the interesting part: implementing the PID algorithm and discovering why textbook formulas are just the starting point.</p><h4>The Basic Algorithm</h4><p>The PID controller calculates a control output based on three terms:</p><pre># 1. Compute error (target - actual)<br>error = target_export - smoothed_pgrid<br><br># 2. Integral term with time step<br>integral += error * dt<br><br># 3. Derivative term<br>derivative = (error - prev_error) / dt<br><br># 4. PID output (commanded battery power in watts)<br>raw_output_w = Kp * error + Ki * integral + Kd * derivative</pre><h4>The Ziegler-Nichols Trap: Initial Tuning</h4><p>The Ziegler-Nichols method is the classical approach to PID tuning:</p><ol><li>Set Ki = 0 and Kd = 0</li><li>Increase Kp until the system oscillates with constant amplitude</li><li>Record the critical gain (Ku) and oscillation period (Tu)</li><li>Calculate gains from lookup tables</li></ol><p>I started with ultra-conservative gains based on Ziegler-Nichols guidelines:</p><ul><li>Kp = 0.005</li><li>Ki = 0.001</li><li>Kd = 0.0</li></ul><p><strong>Result: Complete Failure</strong></p><ul><li>Grid export: <strong>0.330 kWh (30% of PV generation)</strong></li><li>Battery barely activated (max discharge only 1.3 kW)</li><li>System essentially uncontrolled</li></ul><p>The problem was obvious: the gains were far too conservative and made the system oscillate beautifully with about 25% overshoot, which is exactly what Ziegler-Nichols optimises for.</p><p><strong>But a 25% overshoot means export.</strong> And export means failure.</p><p>The classical tuning rules are designed for systems where overshoot is acceptable. Process control, temperature regulation, and motor speed control all tolerate overshoot. Zero-export control does not. This is where I learned that control theory provides guidelines, not answers.</p><h3>The Debugging Journey: When Everything Goes Wrong</h3><h4><strong>Attempt 1: Increase Proportional Gain</strong></h4><p>I increased Kp to 0.8 and Ki to 0.15, expecting better performance.</p><p><strong>Result: Catastrophic Failure</strong></p><ul><li>Grid export: <strong>1.159 kWh (138% of PV generation!)</strong></li><li>The system went from 30% export to 138% export</li><li>Battery saturating at -5 kW (maximum charge rate)</li></ul><p>Wait… <strong>the export got WORSE?</strong> This made no sense. More aggressive control should improve performance, not destroy it.</p><h4>Attempt 2: Even More Aggressive</h4><p>Thinking maybe I needed even more gain, I tried Kp=1.2, Ki=0.08.</p><p><strong>Result: Complete Disaster</strong></p><ul><li>Grid export: <strong>1.254 kWh (149% of PV generation)</strong></li><li>Peak export: 4800W</li><li>Battery behaviour is completely inverted</li></ul><p>At this point, I had to stop and think. The pattern was clear: <strong>higher gains = worse performance</strong>. This is backwards from every control theory textbook.</p><h4>The Critical Discovery: A Sign Error</h4><p>I started analysing the CSV data from the simulation. During export events, I noticed something shocking:</p><pre>Grid Power: +2000W (exporting - BAD!)<br>PID Error: -2250W (target -250W, actual +2000W)<br>PID Output: -4750W (commanding battery to CHARGE)<br>Battery Power: -4750W (charging at max rate)</pre><p><strong>The battery was charging during export events!</strong></p><p>When we’re exporting to the grid, the battery should discharge to absorb that excess power. But my controller was doing the exact opposite: charging the battery, which made the export even worse.</p><h4>Understanding the Root Cause</h4><p>The bug was in my power balance equation:</p><pre>Grid = PV - Load - Battery</pre><p>When Grid &gt; 0 (export), we need Battery &gt; 0 (discharge) to reduce grid export.</p><p>But my PID output was: raw_output_w = Kp * error + ...</p><p>With export:</p><ul><li>error = target - Grid = - 250 - (+2000) = -2250W</li><li>raw_output = Kp * (-2250) = negative value</li><li>Battery receives negative command = CHARGE</li></ul><p><strong>The sign was inverted!</strong> The PID output needed to be negated.</p><h4>The Fix</h4><p>The fix was simple but profound:</p><pre># BEFORE (WRONG):<br>raw_output_w = Kp * error + Ki * integral + Kd * derivative<br><br># AFTER (CORRECT):<br>raw_output_w = -(Kp * error + Ki * integral + Kd * derivative)</pre><p>One minus sign. That’s it. But it transformed everything.</p><p><strong>Result After Sign Fix (Kp=0.8, Ki=0.05):</strong></p><ul><li>Grid export dropped from 149% to <strong>17.6%</strong></li><li>Battery behaviour normalised</li><li>Symmetric charging/discharging restored</li></ul><h3>Systematic Tuning: Getting to Production Quality</h3><p>With the sign bug fixed, I could finally tune the controller properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibiMPxbp7OSGu2FQR1MUhA.jpeg" /><figcaption>Optimization Strategy</figcaption></figure><p>I systematically increased proportional gain while monitoring:</p><ol><li>Grid export percentage</li><li>Mean Absolute Error (MAE) from target</li><li>Time in range (within ±500W of target)</li><li>Battery utilization</li></ol><p><strong>Results:</strong></p><pre>| Kp  | Ki   | Export % | MAE (W) | Time in Range | Notes                     |<br>|-----|------|---------:|--------:|--------------:|---------------------------|<br>| 0.8 | 0.05 | 17.6%    | 864     | 51.2%         | Post sign-fix baseline    |<br>| 1.5 | 0.12 | 14.3%    | 802     | 52.1%         | Significant improvement   |<br>| 2.5 | 0.20 | 12.9%    | 778     | 52.3%         | Diminishing returns       |<br>| 4.0 | 0.35 | 12.2%    | 782     | 51.2%         | Optimal aggressive tuning |</pre><h4>Buffer Optimization</h4><p>The target buffer (setpoint of -250W vs 0W) also needed tuning:</p><ul><li><strong>500W buffer:</strong> Export 12.2%, but MAE of 782W (more conservative)</li><li><strong>250W buffer:</strong> Export 14.3%, MAE of 771W (best overall balance)</li><li><strong>100W buffer:</strong> Export 16.7% (paradox — too tight allows transients!)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsntOE4VUD0rZ1FDE6Lu5w.png" /></figure><h4>Final Results: Production-Ready Performance</h4><p>After all the debugging and optimisation, here are the final numbers with the optimal configuration (Kp=4.0, Ki=0.75, Buffer=-250W):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dc39X8h9eHtj-exCwGU_rw.png" /></figure><p><strong>Energy Performance</strong></p><ul><li><strong>PV Generation:</strong> 2.304 kWh</li><li><strong>Grid Export:</strong> 0.340 kWh (14.7% of PV)</li><li><strong>Grid Import:</strong> 0.471 kWh</li><li><strong>Net Grid:</strong> -0.130 kWh (net importer, compliant!)</li></ul><p><strong>Control Quality</strong></p><ul><li><strong>Mean Absolute Error:</strong> 787W from -250W target</li><li><strong>Time in Range:</strong> 51.2% within ±500W tolerance</li><li><strong>Maximum Error:</strong> 3516W during worst cloud transient</li><li><strong>Settling Time:</strong> 110 seconds after disturbances</li></ul><p><strong>Battery Utilization</strong></p><ul><li><strong>Discharge:</strong> 0.559 kWh (providing grid support)</li><li><strong>Charge:</strong> 0.054 kWh (absorbing excess)</li><li><strong>SOC Change:</strong> 50.0% → 44.8% (healthy range)</li><li><strong>Max Discharge:</strong> 1.52 kW (well within 5 kW limit)</li><li><strong>Max Charge:</strong> 0.65 kW (controlled, not saturating)</li></ul><p><strong>Anti-Windup Performance</strong></p><ul><li><strong>Saturation Events:</strong> 0% (controller stays within limits)</li><li><strong>Integral Range:</strong> -205 to +54 (well-bounded)</li><li><strong>No windup</strong> despite aggressive gains</li></ul><p>The anti-windup mechanism works <strong>preventively — </strong>by implementing conditional integration and proper integral limits, the controller never needs to recover from windup because it never winds up in the first place.</p><h3>Key Challenges and Solutions</h3><h4>Challenge 1: Rate Limiting</h4><p>Just when I thought I had it figured out, I remembered something from my field commissioning experience: real inverters have slew rate limits. You can’t command an inverter to jump from -3000W (charging) to +5000W (discharging) instantaneously.</p><p>The power electronics have thermal constraints, DC-link capacitors need time to charge/discharge, and most importantly, grid codes often mandate maximum ramp rates to prevent voltage transients.</p><p>I implemented a 2500 W/s slew rate limit:</p><pre># Rate limiting<br>max_change = self.max_slew_rate_w_per_sec * dt<br>if abs(cmd_w - self.last_cmd_w) &gt; max_change:<br>    direction = 1 if cmd_w &gt; self.last_cmd_w else -1<br>    cmd_w = self.last_cmd_w + direction * max_change</pre><p>This prevents:</p><ul><li>Mechanical stress on battery contactors</li><li>Grid disturbances from rapid power swings</li><li>Destabilising the control loop with impossible commands</li></ul><h4>Challenge 2: Measurement Noise</h4><p>Raw grid power measurements are noisy. Very noisy. Energy meters report values that can fluctuate by ±50W between samples, even when nothing has changed. This creates two problems:</p><ul><li><strong>The derivative term amplifies noise.</strong> When you differentiate a noisy signal, you get noise multiplied by the sampling frequency. In my initial tests with Kd &gt; 0, the battery was thrashing wildly between charge and discharge.</li><li><strong>The proportional term fights noise instead of real disturbances.</strong> With high Kp, the controller would react to measurement noise rather than actual grid power changes.</li></ul><p><strong>Solution:</strong> I used an exponential moving average (EMA) filter before the PID calculation:</p><pre>smoothed_pgrid = alpha * raw_pgrid + (1 - alpha) * prev_smoothed</pre><p>With ALPHA = 0.15I&#39;m giving 15% weight to new measurements and 80% to the smoothed history. This eliminated the noise-induced oscillations, but introduced a new problem: lag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvfCFtDhlp3qUw_j9TO9YQ.png" /></figure><p>More filtering means slower response. Less filtering means more noise. This trade-off defined my entire tuning process.</p><h4>Challenge 3: Integral Windup</h4><p>The integral term is essential for zero-export control because it eliminates steady-state error. Without it, you’ll have a persistent small export or import because the proportional term needs an error to generate output.</p><p>But the integral term has a dark side: <strong>windup</strong>.</p><p>Imagine this scenario:</p><ol><li>PV generation is high, load is low</li><li>Battery is at 95% SOC (maximum)</li><li>The controller wants to charge more to prevent export</li><li>A battery physically cannot accept more charge</li><li>Integral keeps accumulating error</li><li>When conditions change, the integral is huge</li><li>System overshoots wildly</li></ol><p><strong>Solution:</strong> When the battery hits power or SOC limits, the integral term must stop accumulating:</p><pre># Check if we&#39;re saturating<br>would_saturate = (cmd_w &gt; max_limit) or (cmd_w &lt; min_limit)<br><br># Conditional integration<br>if not would_saturate:<br>    integral += error * dt<br>else:<br>    # Recalculate integral from P and D to prevent windup<br>    integral = (raw_output_w - Kp * error - Kd * derivative) / Ki</pre><p>This prevents the integral from growing when we’re already at the control limits. The controller “knows” it can’t do anything more, so it stops accumulating errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f77gzpFhmnJukkjYXh-Amw.png" /></figure><h3>Why This Simulation is Trustworthy</h3><p>The question I kept asking myself throughout this project: can I trust these results enough to deploy this controller to real hardware?</p><p>In my QA work, I’ve seen too many simulations that worked perfectly in the lab but failed in the field. The difference comes down to modelling fidelity.</p><h4>What Makes This Simulation Realistic</h4><ul><li><strong>Realistic component models:</strong> Battery efficiency losses, power limits, SOC constraints. These aren’t ideal integrators; they’re models of real electrochemical systems.</li><li><strong>Real-world disturbances:</strong> The PV and load profiles include noise, rapid transients, and discrete events that mirror actual system behaviour.</li><li><strong>Communication latency:</strong> My simulation runs at 0.1-second timesteps, matching typical Modbus polling intervals in real systems.</li><li><strong>Physical constraints:</strong> Rate limiting, saturation, anti-windup. These aren’t optional features; they’re mandatory in real hardware.</li><li><strong>Efficiency modelling:</strong> Round-trip losses match real battery systems (94% measured vs 94.1% theoretical).</li></ul><h4>What’s Still Missing</h4><p>I’m honest about the limitations:</p><ul><li><strong>No communication failures:</strong> Real Modbus networks have packet loss, timeouts, and occasional CRC errors.</li><li><strong>No hardware faults:</strong> Real systems have sensor drift, inverter faults, and unexpected shutdowns.</li><li><strong>No grid disturbances:</strong> Real grids have voltage sags, frequency variations, and harmonics.</li><li><strong>No thermal effects:</strong> Real batteries have temperature-dependent efficiency and power limits.</li></ul><p>For a first deployment, I would start with a very conservative operation (lower gains, wider safety margins) and gradually tune based on real-world data. But I’m confident the fundamental control strategy is sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmiLKuM_ciqG4dNfTL_Qow.jpeg" /></figure><h3>Post-mortem: Every Watt Matters</h3><p>What started as a personal challenge to understand zero-export control became a deep dive into the gap between theory and practice. Building a PID controller isn’t hard. Building a PID controller that works reliably in a real, noisy, constrained, asymmetrically-limited system is hard.</p><p>The experience reinforced what I already knew from my QA work: realistic simulation is the foundation of reliable control. When your simulation accurately captures the physics, the noise, and the constraints of the real world, you can tune with confidence.</p><p>For anyone working on energy management systems, remember that in grid-tied solar control, every watt matters. A momentary export might seem trivial in simulation, but it represents a compliance failure in the real world. The asymmetry of the constraint (import acceptable, export forbidden) requires tuning approaches that prioritise stability over speed.</p><p>As Africa’s energy infrastructure continues to evolve, with more distributed generation coming online every day, control systems like this will become increasingly critical. Whether it’s a 5 kW residential system in Nairobi or a 2 MW commercial installation in Mombasa, the fundamental challenge remains: balancing generation, storage, and load in real-time while respecting hard regulatory constraints.</p><p>The good news is that with careful modelling, patient tuning, and respect for real-world constraints, it’s entirely achievable. My simulation proved it works. Now it’s time to prove it in the field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c85562413b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/random-post-mortems/a-pid-controller-for-zero-grid-export-when-theory-meets-reality-in-energy-management-87c85562413b">A PID Controller for Zero Grid Export: When Theory Meets Reality in Energy Management</a> was originally published in <a href="https://medium.com/random-post-mortems">Random Post-Mortems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Bug With Lessons: Modbus, Python, Rust and Buffer Overflows]]></title>
            <link>https://medium.com/random-post-mortems/a-simple-bug-with-lessons-modbus-python-rust-and-buffer-overflows-5e5036cd5066?source=rss-699d704a2365------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5036cd5066</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[modbus]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chrispine Tinega]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 17:44:50 GMT</pubDate>
            <atom:updated>2025-10-14T22:20:34.376Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How a subtle 16-bit overflow in our Modbus simulator led to days of debugging and taught me why type safety matters in industrial systems</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*ahktpmV-Ik6b0pb65HEeFQ.jpeg" /></figure><p>Not a Medium member? <a href="https://medium.com/random-post-mortems/5e5036cd5066?source=friends_link&amp;sk=485188a2da3046535633202bd6461ddb">Use this link</a>.</p><p>After three days of head-scratching debugging, the culprit turned out to be something I never expected: a buffer overflow in our Modbus device simulator that was silently corrupting register values.</p><p>Here’s the story of how we built a sophisticated Modbus device simulator, discovered a critical vulnerability, and learned why every bit matters in industrial automation.</p><h3>The Challenge: Testing Without Hardware</h3><p>In my latest project, I’ve been building Modbus servers to simulate real-world energy system devices, such as photovoltaic inverters, battery management systems (BMS), energy meters, power conversion systems (PCS), and various auxiliary controllers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*7Gebq_QuDE-60gRu6r4CMg.jpeg" /></figure><p>Testing this EMS software with real hardware would be prohibitively expensive. A single commercial PV inverter can cost $10,000 or more, and we needed to test scenarios with dozens of devices. Plus, triggering specific fault conditions or edge cases with real hardware is either impossible or dangerous.</p><p>Each simulated device exposes a Modbus TCP server. A web API lets engineers tweak register values in real time to exercise EMS logic (state transitions, fault paths, recovery, optimisation strategies).</p><h4>Building the Simulator: More Complex Than Expected</h4><p>Our simulator needed to be sophisticated. We weren’t just mocking simple sensor readings; we were emulating complex industrial devices with hundreds of registers each, covering everything from real-time power measurements to configuration parameters and alarm states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*UYM4QQuzgzdCAdnaKa0Ifw.jpeg" /></figure><p>The architecture we built included:</p><ul><li><strong>Multiple concurrent Modbus TCP servers</strong>, each emulating a different device</li><li><strong>Database persistence</strong> for register values across simulator restarts</li><li><strong>Web API interface</strong> for real-time register manipulation during testing</li><li><strong>Device-specific emulation logic</strong> for realistic behaviour patterns</li><li><strong>Support for various data type</strong>s: 16-bit integers, 32-bit floats, boolean flags, and string values</li></ul><p>At its core was our Python Modbus server implementation consisting of routines for creating Modbus servers, encoding payloads and updating Modbus registers.</p><p>Here’s an example of a Modbus server setup:</p><pre>from pymodbus.server import StartTcpServer<br>from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext<br>from pymodbus.datastore.store import ModbusSequentialDataBlock<br><br># Create a datastore with 10 holding registers<br>store = ModbusSlaveContext(<br>    hr=ModbusSequentialDataBlock(0, [0]*10)<br>)<br>context = ModbusServerContext(slaves=store, single=True)<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Starting Modbus server on localhost:5020&quot;)<br>    StartTcpServer(context, address=(&quot;localhost&quot;, 5020))</pre><h4>The Bug That Wasted Hours</h4><p>The first sign of trouble was subtle. During a routine test, our EMS was making decisions that didn’t match the expected logic. A battery system was reporting a state of charge of 100%, but the EMS was treating it as if it were nearly empty.</p><p>I checked the test data we had entered through our web interface: 100% state of charge should map to a register value of 10000 (representing 100.00%). But when I queried the Modbus register directly, it showed 34464.</p><p>Wait, what?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zz1fHf0hoktclhXPUySuvg.jpeg" /></figure><p>More testing revealed the pattern. Large values were being mysteriously truncated:</p><ul><li>Input: 100000 → Stored: 34464</li><li>Input: 75000 → Stored: 9464</li><li>Input: 50000 → Stored: 49999 (this one worked?)</li></ul><p>The pattern seemed random at first, but there was definitely something systematic happening.</p><h4>The Discovery: Understanding 16-Bit Overflow</h4><p>After some investigation, I realised what was happening. Modbus registers are 16-bit unsigned integers, which means they can only hold values from 0 to 65535. When we tried to store larger values, Python’s pymodbus library was silently truncating them using modulo arithmetic:</p><pre>100000 % 65536 = 34464<br>75000 % 65536 = 9464  <br>50000 % 65536 = 50000 (fits within range)</pre><p>This is classic integer overflow behaviour, but it was happening silently. No errors, no warnings, no indication that our carefully crafted test data was being corrupted.</p><pre># Original problematic code (simplified)<br>def encodeRegisterPayload(self, value: Any, data_type: str):<br>    encoder = BinaryPayloadBuilder(byteorder=Endian.Big, wordorder=Endian.Big)<br>    <br>    if data_type == &quot;uint16&quot;:<br>        # pymodbus silently truncates values &gt; 65535<br>        encoder.add_16bit_uint(value)  # DANGEROUS!<br>    <br>    return encoder.to_registers()</pre><p>The problem was not obvious because:</p><ul><li><strong>No immediate failure</strong>: the Modbus server kept running normally</li><li><strong>Valid Modbus traffic: </strong>the truncated values were still valid 16-bit integers</li><li><strong>Intermittent issues: </strong>only values &gt; 65535 were affected</li><li><strong>Complex system: </strong>the EMS logic made it hard to trace the root cause</li></ul><h4>The Fix: Defensive Programming</h4><p>Once I understood the problem, the fix was straightforward. We needed to validate and clamp values before encoding them:</p><pre>def addDataToEncoder(self, encoder, data_type, data_value):<br>    &quot;&quot;&quot;Add data to encoder with proper type validation.&quot;&quot;&quot;<br>    if data_type == &quot;uint16&quot;:<br>        safe_value = self.safe_int_conversion(data_value, 0, 65535)<br>        encoder.add_16bit_uint(safe_value)<br>    elif data_type == &quot;int16&quot;:<br>        safe_value = self.safe_int_conversion(data_value, -32768, 32767)<br>        encoder.add_16bit_int(safe_value)<br>    # ... handle other types with appropriate bounds</pre><p>The improved version:</p><ul><li><strong>Validates all inputs</strong> before encoding</li><li><strong>Logs overflow attempts</strong> for debugging visibility</li><li><strong>Clamps values</strong> to valid ranges instead of truncating</li><li><strong>Handles type conversion errors</strong> gracefully</li><li><strong>Provides clear error messages</strong> when problems occur</li></ul><h4>The Real-World Impact: More Than a Functional Bug</h4><p>This wasn’t just a testing inconvenience. In our simulated scenarios:</p><ul><li><strong>Battery systems</strong> appeared to have incorrect charge levels</li><li><strong>Power readings</strong> from inverters were wrong by orders of magnitude</li><li><strong>Energy meters</strong> showed impossible negative consumption values</li><li><strong>Alarm thresholds</strong> were set to meaningless, truncated values</li></ul><p>The implications of the above scenarios in real industrial systems are serious. Modbus is one of the most widely deployed protocols in industrial automation, powering everything from factory automation to power grid infrastructure.</p><ul><li><strong>Energy Management</strong>: A battery management system with corrupted state-of-charge readings could lead to dangerous overcharging or premature shutdown during critical grid support operations.</li><li><strong>Industrial Safety</strong>: Temperature sensors with truncated readings might not trigger safety shutdowns when equipment overheats.</li><li><strong>Process Control</strong>: Flow meters with overflow errors could cause improper chemical mixing in manufacturing processes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2GQrgFCq5_P59vjramcbg.jpeg" /></figure><p>The same silent overflow behaviour that corrupted our test data could:</p><ul><li><strong>Bypass safety systems</strong> by corrupting alarm thresholds</li><li><strong>Cause equipment damage</strong> through improper control decisions</li><li><strong>Create security vulnerabilities</strong> if attackers can trigger specific overflow conditions</li><li><strong>Lead to regulatory compliance issues</strong> in safety-critical industries</li></ul><h4><strong>The Security Angle: From Bug to Weakness</strong></h4><p>In a real-world industrial control system (ICS), this type of flaw is more than just a bug.</p><p>It can become a security vulnerability.</p><p>The same overflow issue that frustrated our testing could be exploited by attackers targeting real infrastructure.</p><p>Attack Scenarios:</p><ul><li><strong>Malicious Register Writes</strong>: An attacker with network access could send oversized values to corrupt critical control registers</li><li><strong>State Confusion</strong>: Overflowing safety thresholds could disable protective mechanisms</li><li><strong>Denial of Service</strong>: Carefully crafted overflow conditions might crash or destabilise Modbus servers</li><li><strong>Data Integrity</strong>: Silent corruption could hide the evidence of other attacks</li></ul><p>Real-World Context:</p><p>Industrial control systems have been targeted by nation-state actors in attacks like <a href="https://en.wikipedia.org/wiki/Stuxnet">Stuxnet</a>, <a href="https://en.wikipedia.org/wiki/Triton_(malware)">TRITON</a>, and others. These attacks often exploit subtle vulnerabilities in industrial protocols and their implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6-vuMVTdkv7qJ2YMpMX0Q.png" /></figure><p>A buffer overflow vulnerability in a Modbus implementation might seem minor compared to these sophisticated attacks, but it could be:</p><ul><li><strong>A stepping stone</strong> for lateral movement in industrial networks</li><li><strong>A persistence mechanism</strong> by corrupting configuration values</li><li><strong>A cover</strong> for other malicious activities by creating apparent “random” failures</li></ul><h4>The Rust Alternative: Compile-Time Safety</h4><p>This experience made me appreciate languages with stronger type systems. Now let’s rewrite the server in Rust using tokio-modbus:</p><pre>use tokio_modbus::prelude::*;<br>use tokio::net::TcpListener;<br><br>#[tokio::main]<br>async fn main() -&gt; anyhow::Result&lt;()&gt; {<br>    // Create a TCP listener for Modbus server<br>    let listener = TcpListener::bind(&quot;127.0.0.1:5020&quot;).await?;<br>    println!(&quot;Starting Modbus server on localhost:5020&quot;);<br><br>    loop {<br>        let (stream, _) = listener.accept().await?;<br>        let svc = service::tcp::Server::new(stream);<br><br>        // Example: handle holding register writes<br>        let context = svc.serve(|| async {<br>            Ok(service::FunctionService::new(move |req| {<br>                match req {<br>                    // Accept only valid u16 register writes<br>                    service::Request::WriteSingleRegister(addr, value) =&gt; {<br>                        println!(&quot;Register {} set to {}&quot;, addr, value);<br>                        Ok(service::Response::WriteSingleRegister(addr, value))<br>                    }<br>                    _ =&gt; Err(service::Exception::IllegalFunction),<br>                }<br>            }))<br>        });<br><br>        tokio::spawn(context);<br>    }<br>}</pre><p>Let’s look at how Rust would handle the same scenario:</p><pre>use tokio_modbus::prelude::*;<br><br>fn write_register_value(value: u32) -&gt; Result&lt;u16, String&gt; {<br>    // Rust won&#39;t compile if you try to pass u32 directly to a u16 function<br>    match value.try_into() {<br>        Ok(safe_value) =&gt; Ok(safe_value),<br>        Err(_) =&gt; {<br>            println!(&quot;Error: Value {} exceeds u16 range (0-65535)&quot;, value);<br>            Err(format!(&quot;Value {} too large for 16-bit register&quot;, value))<br>        }<br>    }<br>}<br><br>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    let socket_addr = &quot;127.0.0.1:5020&quot;.parse()?;<br>    let mut client = tcp::connect(socket_addr).await?;<br>    <br>    let user_input: u32 = 100000;<br>    <br>    // This forces explicit handling of overflow<br>    match write_register_value(user_input) {<br>        Ok(safe_value) =&gt; {<br>            client.write_single_register(0, safe_value).await?;<br>            println!(&quot;Successfully wrote: {}&quot;, safe_value);<br>        }<br>        Err(error) =&gt; {<br>            println!(&quot;Failed to write register: {}&quot;, error);<br>            // Handle error appropriately - maybe clamp, maybe reject<br>        }<br>    }<br>    <br>    Ok(())<br>}</pre><p>Rust’s approach provides several advantages:</p><ul><li><strong>Compile-time enforcement</strong>: You cannot accidentally pass incompatible types</li><li><strong>Explicit error handling</strong>: Overflow conditions must be handled deliberately</li><li><strong>Memory safety</strong>: No risk of buffer overflows in safe Rust code</li><li><strong>Performance</strong>: Zero-cost abstractions mean safety doesn’t hurt runtime performance</li></ul><p>The trade-off is development speed. Python’s flexibility lets you prototype quickly, but that same flexibility can hide serious bugs until runtime (or, in our case, until days of debugging).</p><h4>Lessons Learned: Building Resilient Industrial Software</h4><p>This experience taught me several important lessons about developing software for industrial and energy systems:</p><p><strong>1. Validate Everything at Boundaries</strong><br>Never trust that external input fits your data model, even in testing environments:</p><pre>def validate_register_value(value: Any, data_type: str) -&gt; Tuple[bool, Any, str]:<br>    &quot;&quot;&quot;Validate a register value before encoding.&quot;&quot;&quot;<br>    if data_type == &quot;uint16&quot;:<br>        if not isinstance(value, (int, float)) or value &lt; 0 or value &gt; 65535:<br>            return False, None, f&quot;uint16 must be 0-65535, got {value}&quot;<br>    elif data_type == &quot;int16&quot;:<br>        if not isinstance(value, (int, float)) or value &lt; -32768 or value &gt; 32767:<br>            return False, None, f&quot;int16 must be -32768 to 32767, got {value}&quot;<br>    # ... additional validations<br>    <br>    return True, value, &quot;OK&quot;</pre><p><strong>2. Make Failures Visible</strong><br>Silent failures are the enemy of reliable systems. Log everything:</p><pre>def update_register_with_logging(self, address: int, value: Any, data_type: str):<br>    &quot;&quot;&quot;Update register with comprehensive logging.&quot;&quot;&quot;<br>    is_valid, clean_value, error_msg = self.validate_register_value(value, data_type)<br>    <br>    if not is_valid:<br>        sys_log.error(f&quot;Register update failed: addr={address}, &quot;<br>                     f&quot;value={value}, type={data_type}, error={error_msg}&quot;)<br>        return False<br>    <br>    if clean_value != value:<br>        sys_log.warning(f&quot;Value clamped: addr={address}, &quot;<br>                       f&quot;original={value}, clamped={clean_value}&quot;)<br>    <br>    return self.update_register(address, clean_value, data_type)</pre><p><strong>3. Choose Tools That Match Your Risk Profile</strong><br>For safety-critical or security-sensitive applications, consider languages and frameworks that provide stronger guarantees:</p><ul><li><strong>High-risk systems</strong>: Rust, Ada, or other memory-safe languages</li><li><strong>Moderate-risk systems</strong>: Python/Java with extensive validation and testing</li><li><strong>Prototype/testing systems</strong>: Python with defensive programming practices</li></ul><p><strong>4. Test Edge Cases Deliberately</strong><br>Don’t just test the happy path. Deliberately try to break your system:</p><pre># Edge case test scenarios<br>test_cases = [<br>    (65535, &quot;uint16&quot;),    # Maximum valid value<br>    (65536, &quot;uint16&quot;),    # Just over limit  <br>    (100000, &quot;uint16&quot;),   # Way over limit<br>    (-1, &quot;uint16&quot;),       # Negative for unsigned<br>    (&quot;not_a_number&quot;, &quot;uint16&quot;),  # Type conversion error<br>    (None, &quot;uint16&quot;),     # Null value<br>]<br><br>for value, data_type in test_cases:<br>    result = update_register_safely(0, value, data_type)<br>    print(f&quot;Input: {value} ({data_type}) → Result: {result}&quot;)</pre><p><strong>5. Monitor for Anomalies</strong><br>In production systems, implement monitoring that can detect signs of data corruption:</p><pre>def detect_register_anomalies(self, device_name: str, address: int, <br>                             old_value: int, new_value: int):<br>    &quot;&quot;&quot;Detect potentially suspicious register changes.&quot;&quot;&quot;<br>    if abs(new_value - old_value) &gt; 32767:  # Suspiciously large change<br>        sys_log.warning(f&quot;Large register change detected: {device_name} &quot;<br>                       f&quot;addr={address} {old_value}→{new_value}&quot;)<br>    <br>    if new_value in [34464, 9464]:  # Known overflow signatures<br>        sys_log.error(f&quot;Possible overflow detected: {device_name} &quot;<br>                     f&quot;addr={address} value={new_value}&quot;)</pre><h4><strong>Conclusion: Every Bit Matters</strong></h4><p>What started as a convenient testing tool taught me that in industrial systems, every bit matters. A simple 16-bit overflow in our Modbus simulator cascaded into days of debugging EMS logic that was actually working correctly.</p><p>The experience reinforced several key principles:</p><ul><li><strong>Fail fast and loud</strong> rather than silently corrupting data</li><li><strong>Validate inputs</strong> at every system boundary</li><li><strong>Choose appropriate tools</strong> for your risk tolerance</li><li><strong>Test edge cases</strong> deliberately and systematically</li><li><strong>Monitor for anomalies</strong> in production systems</li></ul><p>For developers working on industrial automation, energy management, or other safety-critical systems, remember that our code doesn’t exist in isolation. A subtle bug in a testing tool can hide serious logic errors. A minor overflow in a sensor reading can trigger inappropriate safety responses. A silent truncation in a configuration value can disable protective mechanisms.</p><p>The good news is that these issues are preventable. With defensive programming practices, appropriate tooling choices, and systematic testing approaches, we can build industrial software that is both robust and secure.</p><p>As our energy infrastructure becomes more complex and interconnected, the stakes for getting this right continue to grow. Whether you’re building testing tools or production systems, take the time to understand your data boundaries, validate your inputs, and make your failures visible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5036cd5066" width="1" height="1" alt=""><hr><p><a href="https://medium.com/random-post-mortems/a-simple-bug-with-lessons-modbus-python-rust-and-buffer-overflows-5e5036cd5066">A Simple Bug With Lessons: Modbus, Python, Rust and Buffer Overflows</a> was originally published in <a href="https://medium.com/random-post-mortems">Random Post-Mortems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started in Hardware Hacking: One-Year Roadmap]]></title>
            <link>https://medium.com/random-post-mortems/getting-started-in-hardware-hacking-one-year-roadmap-3a051f07d784?source=rss-699d704a2365------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a051f07d784</guid>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[hardware-hacking]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[pcb-design]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Chrispine Tinega]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 19:04:41 GMT</pubDate>
            <atom:updated>2025-09-05T18:26:50.252Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>From curiosity to capability. A retrospect of my one year journey into hardware hacking.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*lx-TJRXlq_OcLuBU.jpeg" /><figcaption>Glitching the Olimex LPC-P1343 | Grazfather</figcaption></figure><p>The first time I held a soldering iron, I was nineteen. My hands shook as I approached the tiny surface-mount resistor, convinced that one wrong move would send smoke signals announcing my incompetence to the entire electronics lab. That moment of fear mixed with fascination perfectly captures the essence of hardware hacking: the thrilling intersection of curiosity, technical challenge, and the very real possibility of spectacular failure.</p><p>Exactly one year ago, I dived right in.</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;I am diving deep into hardware hacking.See you on the other side.#avrdude #firmware #GoodFET / X&quot;</h3><p>I am diving deep into hardware hacking.See you on the other side.#avrdude #firmware #GoodFET</p><h3>What is Hardware Hacking, Really?</h3><p>Hardware hacking encompasses a broad spectrum of activities centred around understanding, modifying, and creating electronic systems. At its core, it’s about developing the skills and mindset to:</p><ul><li><strong>Reverse engineer existing devices</strong> to understand their operation and capabilities</li><li><strong>Modify hardware</strong> to add new functionality or improve performance</li><li><strong>Create custom solutions</strong> by combining existing components in novel ways</li><li><strong>Debug and repair</strong> electronic systems using systematic troubleshooting approaches</li><li><strong>Bridge the gap</strong> between software and hardware through embedded systems development</li></ul><p>The subject of hardware hacking doesn’t receive as much attention as software hacking. The likely reason for this is the <a href="https://www.educba.com/hardware-hacking/">steep learning curve and financial investment that comes with it</a>. However, that does not mean that hardware is of less significance.</p><p>It won’t help if you fix your software, yet you have loopholes in your hardware. You are still vulnerable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*rI7QdlvSZcY5SWXlVI6LYg.jpeg" /><figcaption>The Cyber Security Hub™ posted on LinkedIn</figcaption></figure><p>IHS estimated that over <a href="https://www.statista.com/statistics/471264/iot-number-of-connected-devices-worldwide/#statisticContainer">75.44 billion IoT devices will be manufactured by the year 2025</a>. These devices will generate 79.4 zettabytes of data, according to IDC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*233-Bhfu-t8uA3FGT4WGhQ.jpeg" /><figcaption>IHS IoT market estimates 2015–2025, Forbes</figcaption></figure><p>The expansive application of IoT technologies calls for appropriate security measures, not limited to hardware security.</p><h4>The Philosophy Behind Hardware Hacking</h4><p>Hardware hacking embodies a philosophy of curiosity and empowerment. In a world where most technology is designed to be consumed rather than understood, hardware hackers choose to peek behind the curtain. We ask questions like:</p><ul><li>How does this device actually work? What components make it function, and how do they interact?</li><li>Can this be improved? Are there ways to enhance performance, add features, or fix limitations?</li><li>What can I learn from this? How can understanding this device teach me principles applicable to other systems?</li><li>How can I build something similar? What would it take to create my own version with different capabilities?</li></ul><p>This mindset proves invaluable in professional engineering contexts. When you understand how hardware works at a fundamental level, you make better decisions about system architecture, debugging approaches, and performance optimisation. You become a more effective engineer because you understand the complete technology stack from silicon to software.</p><h4>Hardware Security Space</h4><blockquote><em>“We’ve entered a new era, where hardware is finally recognized as an important part of the security landscape.” — Kingpin </em>, The Hardware Hacking Handbook</blockquote><p>The hardware security space has continually been getting attention with notable efforts from Stephen A. Ridley, Joe Grand, Brett Giller, Dave Kennedy, Jasper van Woudenberg, Joe FitzPatrick, Colin O’Flynn, Marc Witteman, among others.</p><p><a href="https://youtu.be/Iv62xszXSj4">Joe Grand’s story</a> was my inspiration for hardware hacking.</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;Not all engineers think like hackers, and not all hackers think like engineers. - @joegrand Design with the hacker in mind. pic.twitter.com/250m8PfbbN / X&quot;</h3><p>Not all engineers think like hackers, and not all hackers think like engineers. - @joegrand Design with the hacker in mind. pic.twitter.com/250m8PfbbN</p><p>The past year had me in the learning, unlearning and relearning cycle. It was a steep learning curve, but the steeper it got, the deeper I dived.</p><h3>The Progressive Learning Framework</h3><p>Successful hardware hacking requires systematic skill development across multiple domains. Rather than jumping immediately into complex projects, effective learning follows a <em>progressive framework </em>that builds competency layer by layer.</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;PoA is the acronym for Power of Attorney.&#39;Practical IoT Hacking&#39; has been my read lately. Check it out. pic.twitter.com/qdMz8LKMBg / X&quot;</h3><p>PoA is the acronym for Power of Attorney.&#39;Practical IoT Hacking&#39; has been my read lately. Check it out. pic.twitter.com/qdMz8LKMBg</p><p>The books that helped me get started were:</p><ol><li><a href="https://doi.org/10.1016/C2016-0-03251-5">Hardware Security</a>: A Hands-On Learning Approach.</li><li><a href="https://www.amazon.com/Hardware-Hacking-Handbook-Breaking-Embedded-ebook/dp/B077WZBFYL">The Hardware Hacking Handbook</a>: Breaking Embedded Security with Hardware Attacks.</li><li><a href="https://www.amazon.com/Practical-IoT-Hacking-Fotios-Chantzis-ebook/dp/B085BVVSN6">Practical IoT Hacking</a>: The Definitive Guide to Attacking the Internet of Things.</li></ol><h3>Core Concepts Every Hardware Hacker Must Master</h3><p>While securing hardware may be assumed to be only against physical attacks in the field, it involves countermeasures throughout the device’s lifecycle — from design to end-of-life.</p><p>Reverse engineering, hardware Trojan attacks, side-channel attacks, IP piracy and fault injection are the most common attacks that exploit hardware vulnerabilities. I will discuss them below.</p><h4>Reverse Engineering Attacks</h4><p>Technology upgrade through efficient signal processing has made reverse engineering even easier. ABI’s <a href="https://youtu.be/0AZOTsuxvbM?list=PLvn9LlA-_znK1eQYi-SHSbnnYHgDhorgN">RevEng Schematic Learner System</a> recreates schematics from an existing printed circuit board!</p><p>Hardware obfuscation is a countermeasure used to prevent reverse engineering attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*0T8LztfQUYPnfAK3.png" /><figcaption>Hardware obfuscation illustration | Source: ISBN: 978–3–319–49019–9</figcaption></figure><p>Vijayakumar et al.’s <a href="http://dx.doi.org/10.1109/TIFS.2016.2601067">paper on Physical Design Obfuscation of Hardware</a> presents camouflaging techniques that defend hardware against reverse engineering. An attacker using reverse engineering tools to attack a physically obfuscated hardware will likely generate a netlist not corresponding to it.</p><h4>Hardware Trojan Attacks</h4><p>Hardware Trojan attacks, on the other hand, involve malicious design modifications either on a chip or a PCB. The attacker may create hardware Trojans during design or fabrication to introduce malfunction, alter reliability or steal sensitive information.</p><p>In this age where someone can <a href="http://sam.zeloof.xyz/">fabricate an IC in a garage</a>, I won’t be surprised when one ‘cooks’ a Hardware Trojan in their kitchen!</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;I am studying microcomputer design and I just remembered @szeloof who in 2018, fabricated the first DIY integrated circuits in his garage. Yoh!Check his work out:https://t.co/cE5L8f6bsLhttps://t.co/v1V3uzdsXt / X&quot;</h3><p>I am studying microcomputer design and I just remembered @szeloof who in 2018, fabricated the first DIY integrated circuits in his garage. Yoh!Check his work out:https://t.co/cE5L8f6bsLhttps://t.co/v1V3uzdsXt</p><h4>Side-Channel Attacks</h4><p>An attacker can monitor the parametric behaviour of the system (power consumption, electromagnetic leaks, heat dissipation, sound emission, timing information, etc.) during operation to gather information and exploit vulnerabilities. This attack technique is called the side-channel attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*H_2P7SKlJTxTK8w6.png" /><figcaption>Side-channel emissions | Source: DOI: 10.1007/978–1–4419–8080–9_8</figcaption></figure><p>Masking through adding noise and reducing information leakage through side-channel parameters is a counter-option to side-channel attacks.</p><h4>Fault Injection Attacks — Glitching</h4><p>Grazfather did an excellent job on <a href="https://grazfather.github.io/posts/2019-12-08-glitcher/">glitching the Olimex LPC-P1343</a>.</p><p>Glitching is a fault injection technique that undermines a device’s security by introducing intentional faults. These faults can cause instruction skipping, malformed data readbacks/writebacks and instruction decoding errors.</p><p>Learn more about glitching from Brett Giller’s presentation on <a href="https://www.blackhat.com/docs/eu-15/materials/eu-15-Giller-Implementing-Electrical-Glitching-Attacks.pdf">Implementing Practical Electrical Glitching Attacks</a> during the <a href="https://www.blackhat.com/eu-15/">Black Hat 2015 conference</a>.</p><h4>IP Piracy Attacks</h4><p>IP piracy attacks, also known as counterfeiting attacks, are where the attacker clones the device or part of it, intending to promote their malicious goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*49AQ9f4kGwSaOncY.jpeg" /><figcaption>IP piracy</figcaption></figure><p>Hardware-based security primitives such as Physical Unclonable Function (PUF) and True Random Number Generator (TRNG) are used to defend against counterfeiting attacks. PUF and TRNG offer protection in cryptographic applications and against hardware attacks.</p><h3>P.S. Post-Mortem</h3><p>Above, I have compressed the knowledge I acquired within the past year, venturing through hardware hacking.</p><p>The journey has been worthwhile as I learnt a lot regarding hardware security that I would less likely get in class.</p><p>Writing this issue, I aimed to focus the lens on hardware hacking and encourage those interested in the field to jump right in. <a href="http://grandideastudio.com/wp-content/uploads/hardware_is_the_new_software_slides.pdf">Hardware is the new software</a>.</p><p>As Groq’s CEO, Jonathan Ross, tells hardware engineers on the <a href="https://www.allaboutcircuits.com/podcast/ep-42-groq-ceo-ex-googler-jonathan-ross-petaflop-ai-chip-first-ever-tpu/">most recent episode of Moore’s Lobby</a>:</p><blockquote>keep your hopes active-low and stay grounded!</blockquote><p>This comprehensive guide represents the beginning of your hardware hacking journey. Future articles will explore specific project tutorials, advanced circuit design techniques, and professional development strategies for hardware engineers.</p><blockquote>“Hardware hacking is not about breaking things but about understanding things so deeply that you can make them better, different, or entirely new. Every circuit you build, every component you understand, and every problem you solve adds to your capability to create technology that serves human needs.”</blockquote><p><em>Originally published at </em><a href="https://chrispinetinega.substack.com/p/one-year-hacking-hardware-22-04-01"><em>https://chrispinetinega.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a051f07d784" width="1" height="1" alt=""><hr><p><a href="https://medium.com/random-post-mortems/getting-started-in-hardware-hacking-one-year-roadmap-3a051f07d784">Getting Started in Hardware Hacking: One-Year Roadmap</a> was originally published in <a href="https://medium.com/random-post-mortems">Random Post-Mortems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The University Experience: A Journey of Growth, Discovery, and Transformation]]></title>
            <link>https://medium.com/random-post-mortems/the-university-experience-a-journey-of-growth-discovery-and-transformation-579b3d3077a1?source=rss-699d704a2365------2</link>
            <guid isPermaLink="false">https://medium.com/p/579b3d3077a1</guid>
            <category><![CDATA[engineering-education]]></category>
            <category><![CDATA[personal-growth-journey]]></category>
            <category><![CDATA[student-life]]></category>
            <category><![CDATA[university-experience]]></category>
            <category><![CDATA[jkuat]]></category>
            <dc:creator><![CDATA[Chrispine Tinega]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 17:33:05 GMT</pubDate>
            <atom:updated>2025-09-02T17:31:00.215Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Five transformative years at JKUAT that shaped not just technical skills, but leadership capabilities and life perspective</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kPc5u9UNOqm61pulmXk_w.jpeg" /><figcaption>Jomo Kenyatta University of Agriculture and Technology</figcaption></figure><p>On March 15, 2020, the government abruptly closed all learning institutions in response to the COVID-19 pandemic. After switching to Zoom classes, it became evident that something the antique brick-and-mortar campus offered was lacking: <strong>the university experience</strong>.</p><p>Now that I’ve officially graduated and spent time reflecting on my journey, I recognise that my five (almost six) years at Jomo Kenyatta University of Agriculture and Technology (JKUAT) represented far more than academic preparation. They constituted a complete metamorphosis from a academically focused individual with limited leadership experience to someone comfortable speaking publicly, mentoring others, and tackling complex challenges with confidence and systemic thinking.</p><p>Even <a href="http://sam.zeloof.xyz/">Sam Zeloof</a>, the remarkable individual who fabricated integrated circuits in his garage, someone I’ve referenced in my hardware hacking explorations, acknowledges the irreplaceable value of the college experience.</p><h3>Sam Zeloof on X (formerly Twitter): &quot;Graduating collegeMany ppl said to skip it or drop out. Obv you can do great w/o it, very glad I went tho. Learned a lot, friends, fun, experience, growth. Higher edu &amp; academia are broken on some levels but you can make a lot out of itOn to the next thing😜🛹 / X&quot;</h3><p>Graduating collegeMany ppl said to skip it or drop out. Obv you can do great w/o it, very glad I went tho. Learned a lot, friends, fun, experience, growth.</p><p>This reflection isn’t just nostalgia but a framework for understanding how transformative experiences shape us and how we can maximise similar opportunities, whether in formal education or professional development contexts.</p><h3>The Academic Foundation: More Than Knowledge Transfer</h3><p>University education, at its best, teaches you <em>how to learn</em> rather than simply <em>what to learn</em>. This distinction became increasingly clear as I progressed through my electrical engineering program and continues to serve me in my professional work in energy systems and IoT development.</p><p>The first year felt like an intellectual homecoming. Mathematics, physics, and chemistry, subjects that had always been my academic fortresses, provided a confidence foundation that proved crucial for the challenges ahead. But more importantly, this early success taught me to trust in my ability to master complex concepts through systematic effort.</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;Mathematics, rightly viewed, possesses not only truth but supreme beauty, a beauty cold and austere like that of sculpture. &quot; ~ Bertrand Russell pic.twitter.com/QBxAgZppo8 / X&quot;</h3><p>Mathematics, rightly viewed, possesses not only truth but supreme beauty, a beauty cold and austere like that of sculpture. &quot; ~ Bertrand Russell pic.twitter.com/QBxAgZppo8</p><p>As coursework progressed into core engineering disciplines, the intellectual demands shifted dramatically. Success required not just conceptual understanding but practical application, systems thinking, and the ability to solve open-ended problems with multiple valid approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*6KlSEGQXXPT93bVMUo4ceA.jpeg" /></figure><h3>Leadership Laboratory: The Extracurricular Crucible</h3><p>The most profound transformation occurred outside formal coursework, in the <em>leadership laboratory</em> of student organisations. This is where theory met practice, where personal growth accelerated, and where I discovered capabilities I didn’t know I possessed.</p><p>Initially, I was always among those watching from the sidelines. However, toward the end of my second year, I discovered organisations that aligned with my values and offered growth opportunities.</p><p>In the Society of Engineering Students, I engaged with engineering minds while contributing to technical projects. This space became the catalyst for my most significant academic development.</p><h3>JKUAT_SES on X (formerly Twitter): &quot;#TestimonialsTuesday this week focuses on @tinegachris who is a Fourth Year Student, Electrical and Electronics Engineering at @DiscoverJKUAT. 🥳🙌🏾🙌🏾Follow this link to the Instagram post where Tinega shares his #SESExperience 😁😁: https://t.co/80t8PdfQii pic.twitter.com/P2L3r6eBOF / X&quot;</h3><p>TestimonialsTuesday this week focuses on @tinegachris who is a Fourth Year Student, Electrical and Electronics Engineering at @DiscoverJKUAT. 🥳🙌🏾🙌🏾Follow this link to the Instagram post where Tinega shares his #SESExperience 😁😁: https://t.co/80t8PdfQii pic.twitter.com/P2L3r6eBOF</p><p><a href="https://twitter.com/jkuatgavel">JKUAT Gavel Club</a> was the kiln where I honed my communication and leadership skills. I never missed a meeting during my active years; the energy and learning environment were irresistible.</p><h3>Not Todaymond on X (formerly Twitter): &quot;There&#39;s not a Toastmasters&#39; meeting on earth that has the same energy as a @jkuatgavel Toastmasters meeting. I miss my people! / X&quot;</h3><p>There&#39;s not a Toastmasters&#39; meeting on earth that has the same energy as a @jkuatgavel Toastmasters meeting. I miss my people!</p><p>Through this platform, I systematically developed skills that now define my professional capabilities:</p><ul><li>Public Speaking = Conference presentations, client meetings</li><li>Leadership = Project management, team leadership</li><li>Critical Thinking = Technical problem-solving, strategic planning</li><li>Mentoring = Team development, knowledge sharing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*l1UoKQeOu1e8-ImYGCgIkg.jpeg" /><figcaption>Speaking in JKUAT Gavel Club</figcaption></figure><p>The leadership skills extended far beyond communication. I learned to organise events, coordinate teams, manage budgets, and inspire others toward common goals. Most importantly, I discovered that <strong><em>leadership is not about title or authority — it’s about influence, service, and empowering others to achieve their potential</em></strong>.</p><h3>Technical Projects and Hands-On Learning</h3><p>The university provided the perfect environment for technical experimentation and creative projects. The combination of access to equipment, knowledgeable faculty, and peer collaboration enabled learning that would be difficult to replicate independently.</p><ul><li><strong>Hackathons and coding competitions</strong>: Intensive problem-solving under pressure.</li><li><strong>Electronic projects and prototypes</strong>: Hardware-software integration experience</li><li><strong>Industry visits and conferences</strong>: Exposure to real-world applications</li><li><strong>Research projects</strong>: Faculty mentorship in systematic investigation</li><li><strong>Final year project</strong>: Comprehensive system design and implementation</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/tinegachris/status/1438804378853457920&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a5b55b1cdfe668bdf4e85b39c707a04/href">https://medium.com/media/3a5b55b1cdfe668bdf4e85b39c707a04/href</a></iframe><p>Each project, successful or not, contributed to my technical skills and problem-solving methodology. The university environment provided the safety to experiment, fail, learn, and iterate, luxuries that are harder to find in professional settings where mistakes have immediate consequences.</p><h4>The Network Effect: Relationships That Define Careers</h4><p>University is fundamentally about <strong>people. </strong>Meeting individuals who challenge your thinking, support your growth, and become part of your extended professional and personal network. The relationships built during these formative years remain among the most valuable assets from my university experience.</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;There is no price for true friendship ❤️ / X&quot;</h3><p>There is no price for true friendship ❤️</p><p>I made true friends while in college. Friends I can reach out to during tough times. People I consider my family, even when away from home. I met my mentor and mentees while in college. I have a clique that creates time to catch up even after school. I have people who will challenge me or even say the truth, even when it is bitter.</p><p>While you find people with different characteristics and personalities in college, the years spent there are enough to swipe right until you find your match!</p><h3>The Success Framework: Four Essential Strategies</h3><p>Based on my university experience and subsequent professional development, here are <strong>four strategic approaches</strong> that maximise the transformative potential of any learning environment:</p><h4><strong>Consistency Over Intensity: The Power of Showing Up</strong></h4><p>One of the most popular misconceptions in university is believing you can <em>”save the semester in two weeks”</em> through intensive cramming. While this might work occasionally for specific assessments, it fails to build the deep understanding and systematic thinking skills that define professional competence.</p><blockquote>Showing up is 80% of success. The other 20% is being prepared when you show up.</blockquote><p>I progressed from the first semester to graduation without failing any course, primarily because I consistently attended classes and engaged with the material regularly.</p><h4><strong>Proactive Skill Development: Beyond the Curriculum</strong></h4><p>University professors cannot teach you everything, and academic content often lags behind industry trends and market demands. <strong>Don’t wait for formal instruction</strong>; take ownership of your professional development by identifying and pursuing relevant skills independently.</p><h3>Chrispine Tinega on X (formerly Twitter): &quot;There&#39;s this engineer at the place I was interning who said that given the option to retake his undergraduate degree he would focus more on developing his skills.I still think about that. / X&quot;</h3><p>There&#39;s this engineer at the place I was interning who said that given the option to retake his undergraduate degree he would focus more on developing his skills.I still think about that.</p><h4>Strategic Exploration: Embracing Calculated Risks</h4><p>University represents the <em>ultimate sandbox for experimentation</em>. Beyond classes, labs, and dormitories lies a world of opportunities that can shape your entire professional trajectory.</p><p>Rather than pursuing random opportunities, use a systematic approach to exploration.</p><ul><li><strong>Values alignment</strong>: Choose activities that align with your core values and long-term goals</li><li><strong>Skill development</strong>: Prioritise opportunities that develop transferable skills</li><li><strong>Network building</strong>: Consider the relationship-building potential of different activities</li><li><strong>Growth stretch</strong>: Select challenges that push you beyond current comfort zones</li><li><strong>Time investment</strong>: Balance exploration with academic and personal commitments</li></ul><h4>Dynamic Balance: Integration Over Fragmentation</h4><p>Scott Galloway famously argued that “<a href="https://www.profgalloway.com/advice-to-grads/"><em>balance is a myth</em></a><em> — there are only trade-offs.”</em> While this might be true for established professionals managing complex careers, I believe university students have a unique opportunity to achieve genuine integration across multiple dimensions of growth.</p><p>As students, we don’t face the same zero-sum trade-offs that characterise professional life. You can excel academically while developing leadership skills, building relationships, and exploring personal interests. The key is <strong>intentional integration</strong> rather than compartmentalisation.</p><p>A friend from Makerere Gavel Club offered wisdom that kept me grounded:</p><h3>Elizabeth Kisaaka on X (formerly Twitter): &quot;You&#39;re a student leaderNever forget that!You&#39;re a student first then a leader Don&#39;t compromise your education / X&quot;</h3><p>You&#39;re a student leaderNever forget that!You&#39;re a student first then a leader Don&#39;t compromise your education</p><h3>TLDR: The Irreplaceable Value of Transformation</h3><p>The university experience is irreplaceable, not because of the classes, the degree, or even the knowledge, but because of the holistic development that emerges when academic challenge, social connection, and personal exploration converge in a structured yet flexible environment designed for growth.</p><p>My five years at JKUAT proved that a university at its best is a <strong>transformation engine </strong>where you discover capabilities you didn’t know you possessed, develop skills that will serve you for decades, and form relationships that enrich both professional and personal life. The academic credentials are important, but they’re ultimately just documentation of a much more profound change: becoming the person capable of making meaningful contributions to your field and community.</p><blockquote>University taught me that growth happens not in the classroom alone, but in the intersection of academic challenge, social connection, and personal exploration. The degree was just the beginning The real education was learning how to learn, lead, and contribute meaningfully to the world.</blockquote><p><em>This is the first article in a series exploring the intersection of technical expertise and personal development. Future articles will examine the specialisation dilemma in engineering education, the role of failure in professional growth, and the importance of a research mindset in continuous learning.</em></p><p><em>Originally published at </em><a href="https://chrispinetinega.substack.com/p/the-university-experience-22-06-01"><em>https://chrispinetinega.substack.com.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=579b3d3077a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/random-post-mortems/the-university-experience-a-journey-of-growth-discovery-and-transformation-579b3d3077a1">The University Experience: A Journey of Growth, Discovery, and Transformation</a> was originally published in <a href="https://medium.com/random-post-mortems">Random Post-Mortems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>