Hacker News new | comments | ask | show | jobs | submit login
Show HN: I wanted to measure CO2 in my office, so I build a C++ WebServer/App (github.com)
146 points by stackmad 22 days ago | hide | past | web | favorite | 120 comments



Shameless plug: I wanted to measure PM10 and PM2.5 pollution level in my neighbourhood, so I built the ESP8266-based sensor using instructions from Luftdaten [1] and since the original interface is pretty ugly, I created my own UI:

http://smog.rekawek.eu/ https://github.com/trekawek/air-quality-info

(I know, it's PHP, but can be hosted virtually anywhere!)

[1] https://luftdaten.info/feinstaubsensor-bauen/


I built a pretty similar rig around an RPi Zero W, same SDS011 AQ sensor and BME280 temp/pressure/humidity sensors as Luftdaten, just polled by a couple of python scripts on cronjobs.


I would have just had the CO2 level read via a $8 I2C device connected to an Esp8266/Esp32 running Arduino.

I would post the result to a web service in this fashion from the Esp8266:

https://techtutorialsx.com/2016/07/21/esp8266-post-requests/

Then just setup a nice Graphana+Prometheus as a service, graphana.com is nice and can expose a Prometheus end point over basic http auth - easy to post to. Then you can setup alerts, graphs, dashboards, etc.

In fact you could have a whole suite of IoT reports flowing in from various Arduinos really easily. Or at least a couple CO2 sensors spread around the house.

Total investment of coding would be about 30-50 lines of Arduino code for the Esp8266 and you may even get away with the free plan on Graphana.com.

I obviously like to outsource as much as possible these days. Less learning, but more efficient.


Would you be able to share where you might get such a cheap CO2 sensor/the name of it? I've had trouble finding them for less than £60 in the UK and would like to set one up.


MH-Z14 or Z19 are cheap, but not 8$ cheap, more like 25.


https://www.co2meter.com/collections/sensors has a bunch of different ones, I usually look on Mouser also. I don't have a name of one currently. I've been using the particle.io platform with a particle device/LTE for sending out data and programming them.


None of them are in the 8$ range. There also seem to some copies which are way overpriced.


Interesting to have an arbitrary $8 price point. You only live once, get the best!


Not my restriction.



Adafruit sell a 1-60,000 ppm equivalent-CO2 sensor for £15. https://www.adafruit.com/product/3709


This doesn't measure CO2 levels. It measures volatile organic compounds and calculates the amount of CO2 that would cause the same greenhouse effect.

>The SGP30 does have built in calibration capabilities, note that eCO2 is calculated based on H2 concentration, it is not a 'true' CO2 sensor for laboratory use.


Not even that. It is designed for hvac applications and measures VOCs on the assumption that they are from human breath and have a corresponding increase in CO2 levels due to breath.


Slight aside, anyone know why all the supposedly iot-oriented small arduino devices are IPv4-only? Is everyone deploying them in some kind of NATs + port forwards / upnp system or tunneled overlay IPv4 network using external gateway devices?


Seems that both "official" SDK for esp8266 and its Arduino port support ipv6 out of the box: https://github.com/esp8266/Arduino/pull/5136.

esp8266-nonos-sdk/esp8266-rtos-sdk/esp8266-arduino uses lwip as tcp/ip stack, which supports ipv6.


Awesome. The Arduino port "IPv6 support" issue was closed 9 days ago too. No other IPv6 related issues reported yet. Off to look for reports from elsewhere of people using it...

The Espressif 8266 SDK docs make no mention of IPv6, does it really work there? (https://www.espressif.com/sites/default/files/documentation/... linked from https://www.espressif.com/en/products/software/esp-sdk/resou...)

I only found one example for the Espressif-provided RTOS, at https://github.com/IPv6-ESP8266/IPv6-ESP8266 . The example says it only works in a IPv6-only network and it's using link-local addresses, which kind of defeats the point of IPv6. No idea if these reflect limitations of the stack. It's a start at least :)


Genuine question: are Arduino's really for IOT or for prototyping? Not an expert, just read a lot about startups starting with a RaspPI or Arduino prototype for the Kickstarter or something and then getting "real" dedicated hardware for production.


It is common to start with these before the Kickstarter, just to get a proof of concept, but those boards (and the ESP8266) absolutely aren't for production. Raspberry Pis are terrible since the only way to interface with them is over a single USB 2.0 port - and that's shared with the 100M ethernet and the SD slot.

You might see an ATMega328p chip isolated, and that's "good enough" for hobbyist projects where you just want to make HID easier on yourself. But I think most shops that need one of these three would be much better off with a STM32-series chip - they cost pennies compared to consumer boards, run on microamps, and have much better documentation.

It'd be a huge red flag for me if I was interviewing with a hardware startup and they said they wanted to put Arduinos into mass production.


Arduinos are not for production, but for prototyping, hobby projects.


Totally true, but my soldering iron is in the basement, so ... ;)


And where can you buy a 8$ Co2 sensor that doesn't suck?


Installed a CO2 monitor in my home two days ago. Already changed my life. It warns me when I need additional ventilation and even beeps if CO2 levels raise too high.

It sounds silly but it's scary how quickly levels rise when the windows are closed.


>It sounds silly but it's scary how quickly levels rise when the windows are closed.

It might be scary, but is it actually dangerous? It could just be that the levels shown, even if raised, are inconsequential.

Basically wondering about the "Already changed my life" line.

Are we all without one risk certain CO2 death every day, or is the parent overly worried over nothing (and opens windows without really a need for it).


Higher ppm decreases cognitive function even at pretty low levels, so being alerted to open your window might improve your work / study.

There's at least this study: https://ehp.niehs.nih.gov/doi/10.1289/ehp.1510037

And this video has the quote "At 1000ppm there is a 15% decrease in cognitive function". https://www.youtube.com/watch?v=1Nh_vxpycEA


"At 1000ppm there is a 15% decrease in cognitive function"

In a century or so we could be looking at similar CO2 levels in the atmosphere if we don’t significantly cut emissions.

Will our decencents be made stupider by higher CO2 levels? Or will they be able to adapt?


My wife is a respiratory therapist. When asked, she said higher-than-average CO2 is seen in COPD patients, and is compensated through an increase in metabolic bicarbonate production, countering the acidic properties of CO2. We are still entering unknown territories with such large populations getting exposed to higher CO2 levels, but she thinks we'll be fine.


I'm having trouble recounciling that with the study that shows cognitive decline, can you explain your wife's thinking?


The short answer is that we're great at compensating for CO2 variation, but only if it's constantly elevated for days or more.

The long answer:

I think the clarifying reference here is 'respiratory acidosis', which is the general name for what blood acidification that comes from CO2 exchange problems instead of internal sources. It's diagnosed as a disease when people exceed a threshold pH, but the body's behavior is the same before that. Acidosis is diagnosed in two forms, acute and chronic. Predictably, both represent the same problem of too-low blood pH, but acute is more extreme and shorter term. What's relevant here is the difference in subsequent outcomes.

Regardless of what's driving the acidification, the body responds first by making more bicarbonate, then by excreting more carbonic acid and reabsorbing more bicarbonate. The production response happens on the order of an hour, but heavily undercompensates for acidification. The reabsorption response happens over several days, and multiplies the effect of the first response for full compensation.

This makes the problem with acute acidosis obvious: you suffer symptoms much faster than you adjust. A weaker version of the same effect is what happens when you go into a high-CO2 space. Chronic acidosis, meanwhile, creates two different concerns:

First, can the body compensate for CO2 levels? If bicarbonate production is disrupted or acidification is very severe (e.g. late-stage emphysema), it's possible to exceed the bounds of compensation and end up with an extended form of the acute symptoms. For our purposes, though, this isn't a concern; at sub-disease levels, the only people who can't compensate probably can't produce bicarbonate at current levels either.

Second, does the compensation have health consequences? Chemically, we see slightly elevated serum levels of Ca and K, but even serious acidosis rarely requires any response. Experimentally, submarine atmospheres are substantially higher in CO2 than poorly-ventilated houses or global warming projections, but animal experiments show basically no effect and submariners don't show obvious problems.


Thanks for the high quality response!


Maybe it means that if you are _always_ exposed to high CO2 your body adjusts, but if you are sporadically exposed it does not? Kind of like living in the mountains vs going there occasionally


>> adjusts

Only true if adjustment isn’t giving up higher functioning of the body for a less efficient metabolism.


Fortunately, we're really good at compensating for blood acidification. It's offset with higher bicarbonate levels and more excretion, which means the reaction uses carbonic acid and hydrogen to offset carbonic acid - pretty low-consequence to produce. Having more bicarbonate raises calcium and potassium levels slightly, but even when it's way outside of any normal exposure it doesn't seem to cause further effects.


Exactly. Metabolic changes take time.


Assuming the results of that study hold up, it seems like a legitimate concern, although at those CO2 levels I dare say there would be bigger problems.


It was causing a narcolepsy-like condition which caused me to experience extreme drowsiness and lethargy and fall asleep at inappropriate hours in my apartment.

My doctors couldn't figure out what it was because every time I'd go get bloodwork done, I'd be out of the house and the symptoms would clear up. I thought it was due to age and that I was simply getting tired when I got home. It took me nearly two years to realize the fatigue didn't happen when I was spending the night somewhere else. I read an article on CO2 levels affecting quality of sleep a few days ago here on HN and it dawned on me that the symptoms weren't happening when I was out of my own apartment and I'd sealed and weather-stripped the apartment shortly before the symptoms began.


The "changed my life" is probably "I have one more thing to focus on for a while". As humans emit CO2 and your lungs are full of it, the danger exists if you run out of oxygen and get too much CO2, the kind of situation where you can get indoors only if you tape all your doors and windows creating an airproof seal.


It solved a chronic lethargy problem that resulted in me falling asleep randomly at inappropriate hours at home.

Literally -- not figuratively -- changed my life.


It could be dangerous if the room is completely sealed, as the oxygen would eventually run out.


Fun fact: humans do not have oxygen levels detection, but do have CO2 levels detection. Your body would ring all kinds of the alarm bells if CO2 levels rise above the norm, even if there is enough oxygen.


Its not that I'm afraid to die here :) Its more about improving the quality of the air. And the body is pretty bad at recognizing higher than norm CO2 level unless it gets to life threatening levels. ( https://youtu.be/1Nh_vxpycEA?t=45 )


On top of everything else, try putting a plant in your room too. Works wonders for air quality and is fun to take care of.


How much CO2 does a plant really turn into O2? I can't imagine that a few plants make much of a difference, or do they?


At night plants start to produce CO2 as well - when you're sleeping and most vulnerable! If the amount of CO2 they scrub is significant, the amount of CO2 they produce in the evening should be as well, no?


Plants produce a net deficit of CO2, so you're correct but over a 24 hour period with proper lighting they will produce more oxygen than CO2. The important thing, however, is that they produce this CO2 at night at such an unbelievably slow rate that you wont be choking to death in your sleep, that's silly. If you fill a room with plants and cut out the lights, most CO2 produced will be from your cat sleeping on the floor than from the plants.

Either way I was referring to other chemicals that plants remove from the air, not CO2.


Apparently plants put out half the CO2 again over the night that they took in. I'm just thinking that either way they aren't that big of deal as far as oxygen/carbon dioxide production/consumption. Air filtration, possibly.


Depends on the number of plants. Growing up, my mom was a florist and we had an abundance of plants throughout the house. Wouldn't necessarily suggest going to that level, but plants do make for a much less sterile environment. Big green leafy plants are better air scrubbers and much easier to care for than cute dainty flowers.

Examples: https://www.google.com/search?hl=en-CA&authuser=0&biw=1345&b...

Depending on choice of pot and soil, most only need to be watered once a week. Even still, there are decorations that hold water to slow release for even extended times between watering. Great for vacations, or the forgetful.


I didnt really mean CO2 specifically, I meant it improves air quality by removing other chemicals from the air. Either way the effect is not completely insignificant especially over long periods of time with correct conditions.


For those who are wondering about 'changed my life':

Tom Scott uploaded a video about CO2 and its influences a few days ago. it's a good palce to start research:

https://youtu.be/1Nh_vxpycEA


Also DHH presenting about this at Basecamp from a few months ago:

https://youtu.be/MRqh8oLY7Ik


This is what I was looking for!


Which one did you get? I'm interested in getting one as well.


This one on Amazon: https://www.amazon.com/gp/product/B001PDGFR8/ref=ppx_yo_dt_b...

Looks like they're out of stock now, but it has a big label on the front that says co2meter.com, so you might want to check there.

I am not affiliated with that company.


How do you know this isn't placebo?


I've had a CO2Meter monitor for about a year now, and I have mine connected to a Raspberry Pi. I use a node script to push readings to a database on my NAS, and to fire an IFTTT webhook to my Nest to turn on the fan when CO2 levels hit a certain threshold.


Why is it so scary? There is no danger for you to get sick or die.


I saw some study that suggests that higher CO2 levels decrease cognitive abilities. You wont die, but I do tend to get headaches when the air gets worse.


Which monitor did you install?


This device's manufacturer claims an accuracy of "± 100ppm or ± 7% of reading".

But there's a review on Amazon that describes someone getting three units and finding as much as 600ppm variation among them.

Maybe they need some kind of calibration or tuning? Or their manufacturing process is way out of control.


They have a calibration feature, of course most of the reviews fail to mention if the person understood how it worked and used it. (I personally find the mechanism a bit odd, but I guess it makes some sense if you assume some things about the environment)


It definitely shows that this is one of the cheapest meters on the market. But the values seem to be realistic, when having all windows open it shows 450-460 ppm which is at least close to the global 400ppm ( and I live next to a road in a bigger city ).


I'm looking around for an affordable household CO2 measurement tool but they're all wildly expensive. Is this technology complicated and cannot be obtained for $30? They're all like $120+

Edit: I realised that this is a perfect item for public libraries to loan out. Expensive, only needed occasionally, easy to use, potential for significant positive public impact on becoming more informed and healthier.

If you're looking for a cause that's affordable, practical, and local, consider buying and donating one to your local library.


MH-Z14 or Z19. But this is just the sensor, you'll need an Arduino/ESP/Rpi too.


What's particular about these sensors? I've been researching technologies to monitor plant growth and haven't yet looked into CO2 sensors, hence my asking. Do they come in an IC package?


They use optical measurement, are reasonable in pricing. Outputs are UART, PWM and analoge.

They have pins with 2.54mm spacing if that helps you.


Would you use something else if you meant to solder something on a PCB for medium scale production?


Don't know. There are chemical sensor with a heating element, but those usually suck.


No story behind the build, just a link to the git repo? yay


You can only put link + title on here. And the story is rather boring :) I wanted to measure it, I got a device from amazon, found a python script to read the data, the dependencies (pyhidapi) always sigfaulted, so I wrote my own :)


Why do you need a script for this? Isn't the device good enough at telling you the bare necessary information?

Still a cool script nonetheless, no hate.


Sure, but I wanted to see the data over time. And I was bored :)


Sounds like you have a ventilation problem, buildings are required by code to get a certain amount of fresh air from outside so that CO2, VOCs, chloroform, etc don't get too high.

Incidentally, NHTSA projects in 2100 CO2 will be at 789ppm [0] in the atmosphere, up from 410 today and 350 pre-industrial. And there are higher projections. One would assume that this would make ventilation more urgent, I guess building codes will have to be updated and existing buildings retrofitted.

[0] https://www.washingtonpost.com/national/health-science/trump...


Whats wrong with this one? (it works with the same device) https://github.com/larsp/co2monitor


Maybe they didn’t know of it? Maybe they liked building their own regardless?


That looks good as well! I actually didn't know about that project. It wouldn't have worked on my specific case though since I wanted it connected to my Mac, that tool only works on Linux.


The Mac doesn't provide a device to read from? Because beyond that, it should be pretty similar (posix-ish and golang)?


Yeah, you have to use IOKit, which hidapi wraps.


Anyone know other, possibly cheaper, devices besides https://www.co2meter.com/products/co2mini-co2-indoor-air-qua... that can display current CO2?

I hoped there would be cheaper versions on Aliexpress, but no luck :(


MH-Z19 is a sensor on sale on Aliexpress for ~20 USD. It works with Arduino and ESP32


It looks like the same thing is cheaper on Amazon.


Why are there steps in the CO2 levels?


Since this is based on a reverse-engineered binary protocol and since the step sizes are reasonably close to 64 and 128, I'd guess it's a bug.


It looks like there's no need to reverse-engineer the protocol:

https://www.co2meter.com/products/co2mini-co2-indoor-air-qua...


The device on its onscreen display shows the same steps, so I think its due to how the sensor works.


Unrelated to the project, but your CO2 levels are far to high. The maximum should be around 600ppm.


Your comment doesn't seem to match up with https://www.kane.co.uk/knowledge-centre/what-are-safe-levels... unless you mixed up CO and CO2? Am I missing something?

EDIT: ah, looking at a CO2 monitor, it says "Indoor air quality: Good (0 to 800ppm), Normal(800 to 1200ppm), Poor (>1200ppm) indication"


Yes, I agree. I've already ordered a bunch of plants :) Sadly my building is quite old and ventilation is poor.


In most places ventilation standards are set by building code. Point this out to your landlord, if they are not responsive notify the relevant local authority.


I heard that you would need about 40(?) plants per person. Best advice was to be well ventilated unless the outdoor CO2 is worse than indoors.


You literally can't have enough plants in the house to compensate for the CO2 production of its inhabitants.

You would have to place water immersed algae farms on every open space in the house and keep them illuminated with artificial light 24/7, because plants will produce CO2 at night otherwise.

Like you said, good ventilation is far more effective than any plant.


I wanted to do this in my office and was told, "if we find out something is wrong then we'd have to fix it." facepalm


I think it's safe to say CO2 levels in your office are already over the limit with coworkers making arguments like that lol

The company saved $25 though!


LOL


I am new to this one. I always wonder about accuracy. I think it depends on where you place your sensor in the room matters. If it is in place where lot of window air is hitting, it might alter the values. Or am I completely wrong? Or are you using multiple devices to get the average of those devices?


Yes, absolutely. I only have one device at the moment, but it sure would be interesting to see how fast the levels equalize between rooms


Friend of stackmad here. Just wanted to let you know that he got himself a plant as a result of the CO2 measurements :)


Actually its 9 plants ;)


Architecturally speaking this should be a super simple script that pulls the sensor data into a database for any use instead of a custom written http server that manages the sensor.


Yes, I agree. But this was way more fun :)


Isn't C++ a bit overkill for a web app?


You are right, C++ is overkill. It would be much better if it was a javascript application with thousands of dependencies.


There are memory-safe languages that aren't Javascript, you know


ahh so you're in the camp of wanting to re-create a graphing library for every project..


ahh so you're in the camp of outsourcing your development cost to the user's hardware.


Depends, this was a question I tried to answer for myself with this project. I did not easily find a good library for Python that would work on my Mac for reading the HID messages, so writing the device part in C++ was easier for me ( and an interesting excercise in c++17'ifying C code ). I thought about just having the c++ app be called from python, but wanted to try and see how hard it would be in c++ and found it extremely easy with the cpprestsdk.


Did you search for... "co2 meter python"? The pypi package called "CO2meter" (https://github.com/vfilimonov/co2meter) not only works well as a library on Mac OS, but also comes with a web-based dashboard:

  $ pip install CO2meter flask pandas
  ...
  $ co2meter_server
Edit: link


Though with your steps it at least starts, but the webserver fails, and CTRL+C doesn't work ^^

   * Serving Flask app "co2meter.server" (lazy loading)
   * Environment: production
     WARNING: Do not use the development server in a production environment.
     Use a production WSGI server instead.
   * Debug mode: off
  INFO:werkzeug: * Running on http://127.0.0.1:1201/ (Press CTRL+C to quit)
  ERROR:flask.app:Exception on / [GET]
  Traceback (most recent call last):
    File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
      response = self.full_dispatch_request()
    File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
      rv = self.handle_user_exception(e)
    File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
      reraise(exc_type, exc_value, tb)
    File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
      rv = self.dispatch_request()
    File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
      return self.view_functions[rule.endpoint](**req.view_args)
    File "/usr/local/lib/python2.7/site-packages/co2meter/server.py", line 64, in home
      data = read_logs()
    File "/usr/local/lib/python2.7/site-packages/co2meter/server.py", line 236, in read_logs
      with open(os.path.join('logs', name + '.csv'), 'r') as f:
  IOError: [Errno 2] No such file or directory: 'logs/co2.csv'
  INFO:werkzeug:127.0.0.1 - - [25/Jan/2019 14:18:23] "GET / HTTP/1.1" 500 -
  INFO:werkzeug:127.0.0.1 - - [25/Jan/2019 14:18:23] "GET /favicon.ico HTTP/1.1" 404 -
  ^C^C^C^C
  ^C^C


co2meter_server writes measurements to "logs/co2.csv" in the current working directory every 30 seconds or so. As long as there is no measurement, you'll get this error from the web app trying to access the file. Just wait a minute and refresh the page.


That looks great as well! But for some reason the library they use (pyhidapi) would always crash on my Mac.


Not necessarily. You see web servers running on microcontrollers all the time and they are mostly written in C.


I've been using the Microsoft cpprestsdk, too, but for client stuff. I've been enjoying using it.


Yeah, its quite ok.


that thermostat is working pretty well, keeping the temperature stable like that


Yeah, I've finally managed to tweak the thermostat on the radiators and the main thermostat for the heater to where I like it :)


I'd improve the ticks on the x-Axis a bit. Otherwise looks fine to me.


Yeah, that was pretty quickly hacked together :)


@dhh highly recommends Awair for air quality monitoring. He gave some talk on it after be bought one for his whole staff (can't find the talk for some reason)

I got one and it's pretty cool. A bit of a game to get a high score.


what is the baseline for CO2 on certain Sq.ft?


I guess it should match the outside air as close as possible. So around 400ppm


I believe the title should be "I wanted to build a C++ WebServer/App, so I built a C++ WebServer/App".

Not that there anything wrong with that :)


:) But the CO2 measurement part honestly came first.




Applications are open for YC Summer 2019

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: