Hack my House: UL Certification and Turning the lights on with an ESP8266

It’s hard to imagine a smart house without smart lighting. Maybe it’s laziness, but the ability to turn a light on or off without walking over to the switch is a must-have, particularly once the lap is occupied by a sleeping infant. It’s tempting to just stuff a relay in the electrical boxes and control them with a Raspberry Pi or micro-controller GPIO. While tempting, get it wrong and you have a real fire hazard. A better option is one of the integrated WiFi switches. Sonoff is probably the most well known brand, producing a whole line of devices based on the ESP8266. These devices are powered from mains power and connect to your network via WiFi. One disadvantage of Sonoff devices is they only work when connected to Sonoff’s cloud.

Light switches locked in to a cloud provider are simply not acceptable. Enter Tasmota, which we’ve covered before. Tasmota is an open source firmware, designed specifically for Sonoff switches, but supporting a wide range of ESP8266 based devices. Tasmota doesn’t connect to any cloud providers unless you tell it to, and can be completely controlled from within a local network.

Certifications, Liability, and More

We’re well acquainted with some of the pitfalls of imported electronics, but one of the lesser known problems is the lack of certification. In the United States, there are several nationally recognized testing laboratories: Underwriters Laboratories (UL) and Intertek (ETL) are the most prominent. Many  imported electronic devices, including Sonoff devices, do not have either of these certifications. The problem with this is liability, should the worst ever happen and an electrical fire break out. The Internet abounds with various opinions on the importance of the certification — a missing certification mark is somewhere between meaningless and a total hazard. The most common claim is that a house fire combined with non-certified equipment installed would result in an insurance company refusing to pay.

Rather than just repeat this surely sage advice from the Internet, I asked my insurance agent about uncertified equipment in the case of a fire. I discovered that insurance agencies avoid giving definite answers about claim payments. The response that came back was “it depends”: homeowner’s insurance covers events that are accidental and sudden. If a homeowner was aware that they were using uncertified equipment, then it could be categorized as “not an accident”. So far, the myth seems plausible. The final answer from the insurance agency: it’s possible that a non UL-certified device could result in denial of payment on a claim, but it depends on the policy and other details– why take the risk? Certification marks make insurance companies happier.

I also talked to my city’s electrical inspector about the issue. He commented that non-certified equipment is a violation of electrical code when it is hard-wired into a house. He echoed the warning that an insurance company could refuse to pay, but added that in the case of injury, there could be even further liability issues. I’ve opted to use certified equipment in my house. You’ll have to make your own decision about what equipment you’re willing to use.

There are some devices on Amazon that claim to have certification, but searching the certification database leads me to believe that not all of those claims are valid. If in doubt, there is a searchable UL database, as well as a searchable Intertek database.

Selecting a Device

So let’s review our requirements: We need a WiFi connected switch, supported by Tasmota, and either UL or ETL listed. So far, I’ve found exactly one device that fits these criteria. The EtekCity ESWL01 is certified by Intertek, relatively easily flashed to Tasmota, and even mounts on Decora plates. I’ve also received confirmation that Shelly has applied for UL certification, and is expecting that certification to be approved soon. Once they are certified, they will also make a good choice.

Flashing the switch is fairly straightforward, using a TTL serial connection. First, do not connect the switch to mains power while working on the internals. It can shock you, which is bad, but there is the very real possibility of feeding mains voltage into your serial port, which is worse. Instead, we’ll power the device with the power pin on the serial adapter. Note, this isn’t an RS 232 serial port, but a 3.3 V TTL level serial connection. I use the MM232R module, but any TTL serial adapter would work, including a Raspberry Pi.

To put the device in flashing mode, short GPIO0 to ground while connecting the power. There are several flashing tools, but Esptool seems the easiest, with a single command to flash. The official recommendation is to backup the factory firmware, zero out the ESP8266, and then flash the firmware. I’ve not found it necessary to take the extra steps, but if you run into problems, keep it in mind.

esptool.py write_flash --flash_size 1MB --flash_mode dout 0x00000 sonoff.bin

I’ve used the released Tasmota binaries, but if you prefer to compile them yourself, instructions are provided. An advantage of compiling is that you can bake your WiFi information and other settings directly into the binary. If you don’t add WiFi information, the module will broadcast an open WiFi network you can connect to, in order to do your configuration. Set your WiFi information, and make sure to pick a useful hostname, as that’s what we’ll use to control the switch.

The unit will reboot, and should connect to your network. One last configuration step is to tell Tasmota about the device it’s running on. We’ll use the templates feature to define the important GPIOs.

{"NAME":"EtekCityESWL01",
"GPIO":[255,255,255,255,52,53,255,255,255,21,122,255,255],
"FLAG":1,"BASE":18}

Tasmota can be controlled via the web interface, with MQTT, or with a REST API, where commands are sent as HTTP GET and HTTP POST requests. We’ll use this REST interface. Once the switch is flashed and connected to your WiFi, re-assemble and install it using the manufacturer’s instructions.

A Touch Screen Interface

We’ll start by building a simple PHP control interface, lights_api.php. This extra layer is important when isolating the IoT network, and means that only an HTML connection is needed to control everything.

<?php
  $curl_handle = curl_init();
  if ($_POST["toggle"]) {
    $command = explode(".", $_POST["toggle"]);
    curl_setopt( $curl_handle, CURLOPT_URL, 'http://' . $command[0] .
     '/cm?cmnd=' . $command[1] . '%20Toggle' );
    curl_exec( $curl_handle ); // Execute the request
  }
  if ($_GET["device"]) {
    curl_setopt( $curl_handle, CURLOPT_URL, 'http://' . $_GET['device'] .
     '/cm?cmnd=state' );
    curl_exec( $curl_handle ); // Execute the request
  }
  curl_close( $curl_handle );

This lets us make a simple HTML request, like “lights_api.php?device=entry-light-1”, and receive a JSON object with the current status of the device. A POST message allows toggling the switch state.

You may remember that we’re using the Raspberry Pi touchscreen as one of our primary interfaces. This interface is only 800 x 480, which is quite a design challenge for a user interface. I’ve sketched a rough floorplan of my house using Libreoffice Draw, and exported it as an SVG. Over this image, we’ll draw icons to represent the controllable lights.

<div style="width:700px; margin:auto; margin-top: -4px;">
 <div style="float:right; float:top;">
  <button onclick="window.location.href = 'index.php'" style="padding:25px 15px; margin-right:25px;">Thermostat</button>
 </div>
  <div style="height:470px">
  <img style="position:absolute;" height=470px src="House-Blueprint.svg"/>
  <img class="light" style="position:absolute; margin-top:0px; margin-left:95px;" height=50px id="office-light-1.POWER3" onclick="button(this)" src="unlit.svg" />
  <img class="light" style="position:absolute; margin-top:15px; margin-left:30px;" height=50px id="office-light-1.POWER2" onclick="button(this)" src="unlit.svg" />
  <img class="light" style="position:absolute; margin-top:50px; margin-left:95px;" height=50px id="office-light-1.POWER1" onclick="button(this)" src="unlit.svg" />
  <img class="light" style="position:absolute; margin-top:225px; margin-left:155px;" height=50px id="entry-light-2.POWER" onclick="button(this)" src="unlit.svg" />
  <img class="light" style="position:absolute; margin-top:220px; margin-left:255px;" height=50px id="entry-light-1.POWER" onclick="button(this)" src="unlit.svg" />
 </div>
</div>
<script>
  updateAll();
  let updateTimer = setInterval(updateAll, 10000);

  function button(caller) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      update(caller);
    }
    xhttp.open("POST", "lights_api.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("toggle=" + caller.id);
  }

  function update(element) {
    var switchInfo = element.id.split(".");
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var state = JSON.parse(this.responseText);
        if (state[switchInfo[1]] == "ON") {
          element.src = "lit.svg";
        } else {
          element.src = "unlit.svg";
        }
      }
    };
    xhttp.open("GET", "lights_api.php?device=" + switchInfo[0], true);
    xhttp.send();
  }

  function updateAll() {
    document.querySelectorAll('.light').forEach(function(light_element) {
      update(light_element);
    });
  }
</script>

There is a bit of trickery going on here. The img elements contain the entire definition for each switch. The updateAll() function iterates through all of the elements of class “light”, fetching the status of each switch and updating the graphic. The ID of each img contains the hostname of the switch, as well as the indicator of which GPIO we’re interested in, allowing support for devices that control multiple lights. The update() function is run on each img element, using the information baked into the ID to request the switch state from our PHP interface.

We’ve also defined the onclick of each img, giving us our touchscreen functionality. After the toggle request has been sent, we also force an update on that light, in order to keep the interface synced. I’ll leave it as an exercise for the reader to write out the img elements with PHP and add a database back-end.

And with that, we have a simple touchscreen interface to control lighting. It works on a cell phone or desktop, so no more waking the baby to turn off the lights. It’s also a simple interface for further programming. Want the hallway lights to come on when the front door is opened? Just add an HTTP GET request to the handler script.

With a Raspberry Pi in every room, and the lights under control, I’ve got a good start toward a smart house. I have a few items left on my wish list, but I want to hear from you. What haven’t I covered that you think is an indispensable smart-house function?

46 thoughts on “Hack my House: UL Certification and Turning the lights on with an ESP8266

    1. It depends on the cert! Is it a UL fire or electrical safety cert? Probably not. Is it UL 2900 cybersecurity series; then definitely yes. My favorite way to think of this is “does wiring 6 UL certified batteries in Serial invalidate the cert?” the answer is yes, yes, absolutely yes, and yes. Each cert has conditions of certificate. You can look up the cert publically and see what is allowed and what is not.

    2. Ugh, clicked report again when I meant to click reply. Sorry.

      The certification is pretty much useless when software is not part of what’s being certified. Flash a firmware onto the device that, for example, “strobes” the relay on and off rapidly and you have a fire hazard by software, even though the device may be reasonably and certifiably safe otherwise.

  1. I’d like to see if anyone can point to a concrete example (in the U.S.) of someone using a non-UL certified device and having an insurance company refuse to pay if it caused a fire. Heck, years ago I bought some CFL bulbs from Wal-Mart (branded under their Great Value store label) that were made in China and lacked UL (or any other) certification.

    Now Australia is a completely different matter. Apparently there it is actually a CRIME to do any electrical work without a government license, including just changing a light switch or even replacing a cord on a device that can be plugged into mains. And if you suffer a loss while committing a “crime”, well the insurance doesn’t pay. Jonathan Oxer had an interesting video on DIY electrical work there: https://www.youtube.com/watch?v=3K9QjRDIwuw

    1. There are multiple examples of people being killed by non-UL certified power supplies.

      An example of fires were all of the fires caused by the hoverboards. Several of those ended up in complex litigation when people were killed/injured. I don’t know how the trials turned out or if they are still on-going.

      1. But did any applicable insurance pay is the question. I actually always look for things that are UL listed if they’re going to be plugged into the mains, especially if it’s something that stays plugged in all the time. And if it’s from China I even eye UL listed items skeptically (it could be fake, or assuming it’s not, there’s no guarantee that what you’re buying is what they sent to UL for testing). This is the main reason I’ve resisted using Sonoff devices, although I haven’t heard of any glaring problems with them.

  2. The safety and EMC certifications would no longer be valid for any modification done to an intentional radiators or to equipment connected to hazardous voltages . Please reference 29CFR1910 and 47CFR15.

      1. I’m not intimately familiar with EMC in the US, but I would imagine that the FCC certificate (for an intentional radiator) might be invalidated if one were to flash a 3rd party firmware on the device?

  3. Can offer three such instances – one of which was my neighbor’s insurance company refusing to cover fire damage to his garage due to his home-made AC power controller for a compressor.

    The other two were corporate; that is, mandatory requirement for all equipment connected to AC mains to bear the mark of an NRTL; and all NRTL accreditations require the test lab to “enforce” their markings. OSHA regulations do not cover stuff in your home, so any requirement for NRTL-certified stuff would be under the scope of the individual residential insurance policy.

  4. “Not sure OSHA regulations apply to home wiring. I’d be more interested in what the International Residential code has to say.”

    The question was not if OSHA regulations are scoped for residential, but if any modifications effect the NRTL’s mark. The electrical part for IRC is essentially NFPA70, which has been soundly rejected elsewhere and will never be adopted outside of North America and U.S. protectorates.

    CSA, ETL, TUVR, UL, etc all have very clear and legally precise representations for the scope and effectivity of certifications where equipment has been modified in any way, to include exterior markings.

  5. “I’m pretty sure NEC requires certification for residential. That said, most houses aren’t totally up to code in some way. It matters if you pull a permit.”

    NEC (typically NFPA70) is building code. It has no practical use for equipment certification because there are no material requirements and no performance requirements, nor are there any Type Test requirements in NFPA standards. The various NFPA standards point the numerous ANSI, ASME, etc standards that would be scoped for a particular component or device where used in building construction.

    The NEC does not tell the current American home-owner what to do. The AHJ or your insurer may have something to say about this, but once the structure is built, the NEC is no longer directly scope.

      1. Please read my last comment “AHJ or your insurer may have something to say about this, but once the structure is built, the NEC is no longer directly scope”, which addresses this issue.

        For North America, yours and your AHJ’s only direction is per local and state/province administrative law. And the laws of Physics…

        And for those not in the Canada, Mexico, or USA; note that NEC is inconsistently and arbitrarily adopted by the various state and local governments. For example, Ms. List lives in a state with national-level control of this stuff (BS7671), where all facets of installation, audits, inspections, design, and competence are specified. In North America, especially in Mexico and the US, we are left to the capricious and indeterminate whim of the AHJ.

  6. BIG shelly fan here. The stock firmware includes a rest interface, so no need to faff about with tasmota. All my sonoff tasmota devices seem to watchdog periodically – noticeable as a brief led flash from the corner of the room. The lack of a proper recall re. defective Sonoff 16A switches also left a bad taste (and small as it melted down…).

  7. A few things (speaking to matters relevant for USA):

    Its NRTL Listing, not certification. Here’s a brief rundown of the process:
    -UL publishes standards covering pretty much everything.
    -A manufacturer of a product that wishes to obtain a listing obtains copies of the applicable standards.
    -The manufacturer designs their product to meet or exceed these standards.
    -The product is then sent to the NRTL of choice for testing.
    -If the product passes testing, a listing is issued. If the product fails testing it is returned to the manufacturer for revision and retesting.

    There are several NRTLs (nationally recognized testing laboratories) that perform safety testing and listing. UL and Intertek are the most common, there is also CSA, TUV, and others. Some labs can not test to every standard.

    The NEC (national electrical code) is a code published by the National Fire Protection Association and is adopted by individual states, either in its original form, with addendums, or is incorporated into that state’s own code. For example California has the California Electrical Code which is mostly the NEC with a few additions and changes. In whatever form, a state’s electrical code becomes part of that state’s laws. Not obtaining a permit (required or not) does not eliminate the code requirements. There are numerous instances of criminal charges being brought against individuals who performed illegal (non code compliant) work which failed resulting in injury or death. And rightly so.

    The NEC dictates what must be (NRTL) listed. For example light fixtures (which are a particular plague right now with the rise of etsy and everyone making industrial style lamps out of metal things) must be listed.

    Here is a hypothetical scenario based on things that actually happen which demonstrates why listings are required:
    A restaurant comissions an artist or sculptor to fabricate some custom industrial style light fixtures from black iron pipe. The fabricator, having wired things up before, knows he can purchase the pipes, fittings, wire, lampholders, and other parts to make the light fixtures and proceeds to do so.
    These fixtures are not listed and the restaurant’s electrical contractor refuses to install them as they are not code compliant and will not pass inspection. The restaurant owner instructs to the contractor to install some other cheap listed fixtures he bought in order to pass inspection.
    After inspections are passed and contractors are off site, the owner has his maintenance person swap out the light fixtures for the custom pieces.
    Unknown to the restaurant owner, the fabricator did not really know what he was doing when he built the fixtures and did not bond (ground) the metal parts. No one noticed anything wrong because the lights work. Inside one of the iron pipes, there is a wire laying against a sharp metal edge inside the pipe assembly. The fixture happens to be mounted to a wall that experiences vibration from a refrigeration unit mounted to the ceiling above. Over time the sharp metal edge abrades through the wire’s insulation and the entire fixture becomes energized. The circuit breaker does not trip as there is no return path for the current energizing the fixture due to lack of an equipment ground and the light fixture remains energized. The problem goes unnoticed because with LED bulbs lasting as long as they do no one has ever touched the fixture until one day a child stands on the table below the fixture, reaches up to grab it, and is electrocuted.

    1. A ‘listing’ is not an OSHA (controller of the NRTL accreditation program) term. It is a term invented by a particular NRTL, some parts of industry and other NRTLs may or may not have adopted this term. And much stuff is NOT listed – it is ‘recognized’ or it is ‘classified’.

      UL does not officially publish standards. UL originates standards and convenes STPs. But ANSI is the body that does the official national version of a standard.

      NFPA versions of its various standards can be adopted by state, county, or municipal governments. Outside of public venues or the the workplace, there is no national requirement for adoption of building code or any particular ANSI safety standard for components or equipment that would be in construction materials.

      Pedantic? Perhaps, but terminology and formal definitions are important for this stuff.

      1. I am not sure about OSHA using the term ‘listed’ I was speaking to how it is used in the NEC which exclusively refers to listed. For instance the applicable section for my light fixture example is “410.6 Listing Required. All luminaires, lampholders, and retrofit kits shall be listed.”

        There are three categories of NRTL ‘approval’ (as applies to this discussion, and my definitions of these categories paint a broad stroke and are by no means comprehensive)

        -Listed means the product has been tested to the applicable standards, meets those standards, and is acceptable for general use.

        -Recognized means a component that is intended for use in a listed assembly. Using recognized components in a listed assembly makes the testing process easier because those components don’t have to undergo individual testing.

        -Classified (and I don’t know as much about this one) is for products that have been tested to a particular use or circumstance. The one example I am familiar with is circuit breakers. Typically circuit breakers are only listed to be installed in the same manufacturer’s panel for those breakers. Some breakers are UL Classified for use in another manufacturer’s panel. The classified use is limited to that designated panel, even though the breakers may fit others.

        Are you sure about UL not publishing standards? They are accredited by ANSI to do so, and the standards in discussion are titled ULxxxx where xxxx is the standard number. EX: UL943 is the UL standard for GFCI devices https://standardscatalog.ul.com/standards/en/standard_943_5

        Hopefully I am not coming off as being argumentative, that is not my intent. I just want to make sure I have my facts and understandings correct and perhaps learn something along the way.

    2. So, it’s all about the safety of the children, where have we all heard that before. Besides if the child is standing on the table in a restaurant, his/her parents/guardians should be taking care of the situation. Also, the little one would need to be grounded, same way birds and squirrels don’t get electrocuted. I would be more worried about an over head light fixture that was installed using a standard ceiling mount and then somebody comes behind them and installs a heavy beast made out of black iron or similar.

  8. Oh seriously it’s called a hook. You make the first paragraph draw people in, add in a “continue reading” at that point, and finish the article after the jump. How hard is this to grasp? News sites and blogs have been doing this for decades yet HaD is littered with five page articled blocking up the blog. The main blog page is a LISTING of articlea, not the place for your entire article! Use the [continue reading] feature.

  9. As an Aussie, I just started looking at WIFI touch switches for our Downlights. Certified Switches start from $150AUD (US$106), and that’s only *one* switch on a wallplate, It’s even more for multi switches, meanwhile Sonoff switches are ~$20 AUD.

    in Australia, light-switches can only be installed by a licenced electrician, who aren’t allowed to fit anything that’s not certified.

    The end result is that anything certified has a huge price gouge for the part, then install.

    (NB: know there are certification costs, and with 240VAC, you don’t want to cheap out, but a 10x markup is a bit rich)

    1. Exactly… The cost can sterilize a solution from ever being implemented. Someone out to prove Darwinian evolution theory figures out a way around safeguards and removes themselves from the mortal coil. Said safety agencies and code committee’s then look to eliminate that newfound risk that person demonstrated… how to prevent that 1 in a Million from ever happening again is the goal. The result is that 999,999 others have to pay for a more expensive product because of that one idiot, who had a direct hand in their own demise. Of course, the company that produces that product stands to benefit, and also sits on the code committee, but that is sublime when safety is at stake.

  10. For an off grid house, multiple RPi boards and lots of discrete controllers, one per fixture, are a non starter. Smart wall switches, like Clipsal C-Bus controller plates, are also a non starter, since the always on power load, at perhaps 0.5W per controller/wallplate/RPi quickly adds up to more than the power used by a domestic refrigerator, i.e. 400WHrs/day.

    Do this in a lot of houses, and the baseload power consumption implications are significant.

    We need solutions that perform much better with respect to standby/phantom power consumption.

  11. The bot seems to have eaten my more considered and researched comment…

    The elephant in the room here is standby power consumption and the phantom load caused by all the RPi boards and controllers +/- smart wall switches… It can easily add up to 20W always on, which is a non starter for off grid situations, and has broader societal implications.

  12. “non-certified equipment is a violation of electrical code when it is hard-wired into a house” .

    I would be wary of installing any hipster-tech into your home electrical system. It’s just not worth it, even if it was certified. Your home value will not increase at all, only the opposite.

    Still you can mix old with new and mostly get what you want.

    1) X10 devices. They’re already certified. Simply tap the ESP8266 into a serial X10 controller. Ie a CM17A/TM751 combo or even an old TRS80 appliance and light controller. Safe and isolated.

    2) It’s easier (and safer) to work with low voltage devices behind isolation than those that work directly on the mains. These days do you really need to switch 120v or 240v AC? If you’re wanting to switch lamps that are already LED, think about low voltage solutions. A nice shielded power supply or even USB chargers can power ESP8266’s and LED’s quite well.

    It’s not worth it to mess about with mains wiring, especially older homes with Knob-and-tube wiring or a mobile home with aluminum wiring behind walls made with kindling. They go up fast.

  13. FYI As was mentioned in the article UL is only one of several NRTLs. I have heard that others offer similar service for far less cost. Though they won’t be as easily recognized by the public, they (I would assume) are still valid marks for insurance purposes. It pays to shop around. (YMMV and IANAL.)

  14. For anyone interested you can also use MicroPython with these. I was able to flash with:
    esptool.py –baud 460800 write_flash –flash_size=detect 0 esp8266-20180511-v1.9.4.bin

    The pins are:
    4 – wifi signal led
    5 – power button led
    13 – relay
    14 – touch input

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.