[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub:TakeyukiUEDA # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\npatreon: # Replace with a single Patreon username\nopen_collective:takeyuki-ueda # Replace with a single Open Collective username\nko_fi:atelierueda # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay:ueda # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie:TakeyukiUEDA # Replace with a single Otechie username\nlfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve! Thank you!\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\nPLEASE DON'T FORGET TO \"STAR\" THIS REPOSITORY :)\n\nIf you rather keep your project secret, feel free\nto email the author at `<ueda@latelierdueda.com>`; any\nprivate correspondence is treated as confidential.\n\nWhen reporting a bug please include the following:\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Feel free to ask me anything!\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\nPLEASE DON'T FORGET TO \"STAR\" THIS REPOSITORY :)\n\nIf you rather keep your project secret, feel free\nto email the author at `<ueda@latelierdueda.com>`; any\nprivate correspondence is treated as confidential.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/help-wanted.md",
    "content": "---\nname: Help wanted\nabout: Feel free to ask me anything!\ntitle: ''\nlabels: help wanted\nassignees: ''\n\n---\n\nPLEASE DON'T FORGET TO \"STAR\" THIS REPOSITORY :)\n\nIf you rather keep your project secret, feel free\nto email the author at `<ueda@latelierdueda.com>`; any\nprivate correspondence is treated as confidential.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question.md",
    "content": "---\nname: Question\nabout: Feel free to ask me anything!\ntitle: ''\nlabels: question\nassignees: ''\n\n---\n\nPLEASE DON'T FORGET TO \"STAR\" THIS REPOSITORY :)\n\nIf you rather keep your project secret, feel free\nto email the author at `<ueda@latelierdueda.com>`; any\nprivate correspondence is treated as confidential.\n"
  },
  {
    "path": ".gitignore",
    "content": "*.pyc\n*.bak\nsend2monitor.py\nhandlers\npypi/dist\npypi/mh_z19.egg-info\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Dr. Takeyuki Ueda\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# mh-z19\nRead CO<sub>2</sub> concentration from mh-z19 sensor and handle it.\n\n![MH-Z19](https://camo.qiitausercontent.com/a270df1162ed5c3bf9968b24064b91eed0dfcc11/68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f34363534342f31353739663964622d306634302d373665382d303566332d3939336132346334376431382e706e67)\n\n## cabling\nConnect RPi & mh-z19 as:\n\n- 5V on RPi and Vin on mh-z19\n- GND(0v) on RPi and GND on mh-z19\n- TxD and RxD are connected to cross between RPi and mh-z18 \n\nFollowings are example of cabling, but you can free to use other 5v and 0v Pin on the RPi. \n\n![Cabling](https://camo.qiitausercontent.com/112ad5fe41c82a16671d2882070384109c8860cc/68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f34363534342f30383238333031342d363864322d633364652d313634342d3763386439623762363266642e6a706567)\n\n```\npi@raspberrypi:~/mh-z19 $ gpio readall\n +-----+-----+---------+------+---+---Pi B+--+---+------+---------+-----+-----+\n | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |\n +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+\n |     |     |    3.3v |      |   |  1 || 2  |   |      | 5v      |     |     |\n |   2 |   8 |   SDA.1 |   IN | 1 |  3 || 4  |   |      | 5v      |     |     |  <---- Vin\n |   3 |   9 |   SCL.1 |   IN | 1 |  5 || 6  |   |      | 0v      |     |     |  <---- Gnd\n |   4 |   7 | GPIO. 7 |   IN | 1 |  7 || 8  | 1 | ALT0 | TxD     | 15  | 14  |  <---- RxD\n |     |     |      0v |      |   |  9 || 10 | 1 | ALT0 | RxD     | 16  | 15  |  <---- TxD\n |  17 |   0 | GPIO. 0 |   IN | 0 | 11 || 12 | 0 | IN   | GPIO. 1 | 1   | 18  |\n |  27 |   2 | GPIO. 2 |   IN | 0 | 13 || 14 |   |      | 0v      |     |     |\n |  22 |   3 | GPIO. 3 |   IN | 0 | 15 || 16 | 0 | IN   | GPIO. 4 | 4   | 23  |\n |     |     |    3.3v |      |   | 17 || 18 | 0 | IN   | GPIO. 5 | 5   | 24  |\n |  10 |  12 |    MOSI |   IN | 0 | 19 || 20 |   |      | 0v      |     |     |\n |   9 |  13 |    MISO |   IN | 0 | 21 || 22 | 0 | IN   | GPIO. 6 | 6   | 25  |\n |  11 |  14 |    SCLK |   IN | 0 | 23 || 24 | 1 | IN   | CE0     | 10  | 8   |\n |     |     |      0v |      |   | 25 || 26 | 1 | IN   | CE1     | 11  | 7   |\n |   0 |  30 |   SDA.0 |   IN | 1 | 27 || 28 | 1 | IN   | SCL.0   | 31  | 1   |\n |   5 |  21 | GPIO.21 |   IN | 1 | 29 || 30 |   |      | 0v      |     |     |\n |   6 |  22 | GPIO.22 |   IN | 1 | 31 || 32 | 0 | IN   | GPIO.26 | 26  | 12  |\n |  13 |  23 | GPIO.23 |   IN | 0 | 33 || 34 |   |      | 0v      |     |     |\n |  19 |  24 | GPIO.24 |   IN | 0 | 35 || 36 | 0 | IN   | GPIO.27 | 27  | 16  |\n |  26 |  25 | GPIO.25 |   IN | 0 | 37 || 38 | 0 | IN   | GPIO.28 | 28  | 20  |\n |     |     |      0v |      |   | 39 || 40 | 0 | IN   | GPIO.29 | 29  | 21  |\n +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+\n | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |\n +-----+-----+---------+------+---+---Pi B+--+---+------+---------+-----+-----+\n```\n\n## Install & Setup\n\n### Full Set Install\nFull Set include followings:\n\n- Setup script: Install & Setup following useful stuffs as:\n  - mh-z19:       A python module to read mh-z19 sensor.\n  - PondSlider:   A multipurpose versatile sensor handler for python, which read mh-z19 value and handle it.\n  - autostart.sh: Utility making mh-z19 as system service to act periodically.\n\nInstall Full Set, download from [release](https://github.com/UedaTakeyuki/mh-z19/releases)\n\n```\ngit clone https://github.com/UedaTakeyuki/mh-z19.git\n```\n\nThen, got to the folder and issue ***setup.sh****\n\n```\n./setup.sh \n```\nNecessary settings including serial port enabling are taken place in this script.\n\n### Install only sensor module\n\nFor python 2.x\n```bash:\nsudo pip install mh_z19\n```\n\nFor python 3.x\n```bash:\nsudo pip3 install mh_z19\n```\n\nIn case you would use it [witout root permission](#how-to-use-without-root-permission), call pip without sudo as follows:\n\nFor python 2.x\n```bash:\npip install mh_z19\n```\n\nFor python 3.x\n```bash:\npip3 install mh_z19\n``` \n\nThe differences of the interface between each Raspberry Pi model are resolved inside this module. For example, serial device name is difference between Raspberry Pi 3 and older model, but mh-z19 module automatically detect the model and read from appropriate serial device.\n\nTo use mh-z19, once you need to set up enabling serial port device on the Raspberry Pi.\nFollowing [Wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-Enable-Serial-Port-hardware-on-the-Raspberry-Pi) page might be informative.\nAlso, please refer [PyPi top page](https://pypi.org/project/mh-z19/) for detail.\n\n## read CO2 Sensor value\n```\npi@raspberrypi:~ $ sudo python3 -m mh_z19 \n{'co2': 668}\n```\n\nAs above, ***sudo*** might be necessary because mh-z19 sensor value is read through serial connection and it request root permission in general.\n\n## Handle sensor value by [PondSlider](https://github.com/UedaTakeyuki/pondslider) multipurpose sensor handler.\n\nThe installed ***mh-z19*** module is correspond the [pondslider](https://github.com/UedaTakeyuki/pondslider) which is multiple & versatile sensor handler to save, send and to do other necessary ***something*** with the sensor value.\n\nAs an example, we introduce following use case:\n\n- How to save sensor value to SD card as .CSV file.\n- How to send sensor value to free Remote Monitoring Service.\n\n### A brief explanation of pondslider\nThe pondslider read sensorvalue by ***sensor-handler*** specified, and pass the values to ***value-handlers**** which do something with it.\n\n![PondSlider](https://warehouse-camo.cmh1.psfhosted.org/4a74a04ed15e93c05a7c126b59459d98738a62d9/68747470733a2f2f7261772e67697468756275736572636f6e74656e742e636f6d2f5565646154616b6579756b692f706f6e64736c696465722f6d61737465722f706963732f73732e323031382d31312d30332e31332e35362e31312e706e67)\n\nBoth sensor and value handlers are python module. For more detail of handlers, please refer [this](https://github.com/UedaTakeyuki/pondslider).\n\n### How to use sensor value to send to server, save to strage, and so on.\nThis module correspond the [pondslider](https://github.com/UedaTakeyuki/pondslider) which is multiple & versatile sensor handler to save, send and to do other necessary ***something*** with the sensor value.\n\nIn case you choiced ***Full Install*** mentioned above, in other words, you've done ***setup.sh***,\nthe pondslider and there example handler's are already installed & setup.\n\n\n### How to save CO2 value on a SD card as a .CSV file.\nYou can do it with ***save2strage*** value handler which is in ***handlers/value/saver/save2strage***, and configuration file to read from mh-z19 sensor and save by save2strage is prepared as ***config.save.toml*** on the mh-z19 installed folder.\n\nOn the mh-z19 folder By calling pondslider as follows;\n\n```\nsudo python -m pondslider --config config.save.toml\n```\n\nThen, ***/home/pi/DATA/co2.csv*** should be created and new line will be added for each call.\n\n### How to send CO2 Value to the MONITOR™ Service\n\nThe MONITOR™ is a free Remote Monitoring Service to show latest data on the web.\n\n<p>\n<img src=\"pic/2018-11-20.11.23.19.png\" width=\"24%\">\n<img src=\"pic/ss.2018-11-20.11.25.43.png\" width=\"73%\">\n</p>\n\nPlease refer an [introduction](https://monitor.uedasoft.com/docs/UserGuide/) to grasp birds-eye understanding about MONIOR™.\n\nA free account is available as [follow](https://monitor.uedasoft.com/docs/UserGuide/Signup.html).\nThen, login and get a **view_id**, which is unique id to point a data area on the MONITOR™ to show latest value and chart, as [follow](https://monitor.uedasoft.com/docs/UserGuide/Value.html).\n\nAfter get a value_id at your browser, return back to terminal of your Raspberry Pi, then you should set your this software to send measured value to the value_id. To do this, call **setid.sh** command in the mh_z19 installed directory. Let's say your value_id is ***vpgpargj***, issue ***setid.sh*** command as follows:\n\n```\n./setid.sh vpgpargj\n```\n\nThen, call \"pondslider\" python script as follows:\n\n```\npi@raspberrypi:~/mh-z19 $ sudo python -m pondslider\n{'co2': 742}\nco2\n{\"ok\":false,\"reason\":\"ViewID not valid\"}\n```\n\nYour time-series chart on the MONITOR™ display on the browser must be updated by the latest CO2 concentration value.\n\n### How to set your Raspberry Pi to send CO2 data to MONITOR™ at 5 minute interval.\nYou can set it by autostart.sh command in the mh_z19 installed directory as follows:\n\n```\n./autostart.sh --on\n```\n\nYou can turn off this as follows:\n\n```\n./autostart.sh --off\n```\n\nAlso, You can check current status as follows:\n\n\n```\n./autostart.sh --status\n```\n\nFor more detail, please refer this [blog](https://monitorserviceatelierueda.blogspot.com/2018/11/how-to-measure-room-co2-concentration.html). \n\n### How to send CO2 Value to the ATT M2X.\n\nThe Pondslider also support ATT M2X. For detail, please refer [this](https://github.com/UedaTakeyuki/handlers/blob/master/value/sender/send2m2x/README.md) document.\n\n### Calibration, Detection range settings, and ABC(Automatic Baseline Correction) logic on/off.\nFeatures about calibration (both MH-Z19 & MH-Z19B), detection range change (MH-Z19B) and ABC logic on/off(MH-Z19B) are implemented at version 0.2.1 or later.\n\nI'm afraid I've just only implemented these without test due to lack necessary devices and apparatus for the test, fx: standard concentration CO2 GAS, also MH-Z19B module.\nIf you have these devices or apparatus and try to use these functions generously, I really appreciate your [issue report](https://github.com/UedaTakeyuki/mh-z19/issues) regardless result were positive or negative.\n\n- positive report [with mh_z19b on a Raspberry Pi Zero W](https://github.com/UedaTakeyuki/mh-z19/issues/27), Thank you [richteas75](https://github.com/richteas75)!\n\nFor detail please refer this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/CALIBRATION-&-detection-range).\n\n## Undocumented response values of 0x86 command.\nThe [Revspace/MHZ19](https://revspace.nl/MHZ19#Command_0x86_.28read_concentration.29) shows values undocumented on the official datasheets ([MH-Z19](https://www.winsen-sensor.com/d/files/PDF/Infrared%20Gas%20Sensor/NDIR%20CO2%20SENSOR/MH-Z19%20CO2%20Ver1.0.pdf), [MH-Z19B](https://www.winsen-sensor.com/d/files/MH-Z19B.pdf)). In accordance with this, **--all** option add these values in the return json value as follows:\n\n```bash:\nsudo python -m mh_z19 --all\n{\"SS\": 232, \"UhUl\": 10752, \"TT\": 61, \"co2\": 818, \"temperature\": 21}\n\nsudo python3 -m mh_z19 --all\n{\"TT\": 61, \"co2\": 807, \"SS\": 232, \"temperature\": 21, \"UhUl\": 10752}\n```\n\nor call **read_all()** function as follows:\n\n```\n>>> import mh_z19\n>>> mh_z19.read_all()\n{'SS': 232, 'UhUl': 10738, 'TT': 61, 'co2': 734, 'temperature': 21}\n>>> \n```\n\n## Use specific serial device.\nIn case you should use specific serial device instead of Raspberry Pi default serial device which this library automatically select, for example in case to need to use /dev/ttyUSB0 for **FT232 usb-serial converter** as [issue#12](https://github.com/UedaTakeyuki/mh-z19/issues/12), you can specify serial device by **--serial_device** option as follows:\n\n```\nsudo python -m mh_z19 --serial_device /dev/ttyUSB0\n```\n\n## How to use without root permission.\nSee this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-use-without-root-permission.).\n\n## How to use in your program.\nSee this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-use-in-your-program.).\n\n## PWM support.\nSee this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/PWM-support.).\n\n## In case you can't get the value.\nEven if cabling seems no problem and uart seems to be prepateted well but you can't get sensor value. As [nincube8](https://github.com/nincube8) suggested that the [pull up](https://github.com/UedaTakeyuki/mh-z19/issues/22#issuecomment-683393350) by [1-5kΩ register](https://github.com/UedaTakeyuki/mh-z19/issues/26#issuecomment-744039360) can be working solution. Thank you [nincube8](https://github.com/nincube8)!\n\n## Q&A\nThe forum is avai at [here](https://groups.google.com/g/mh_z19-users). Any questions, suggestions, reports are welcome!\n\n## Blog\n- [How to Measure ROOM CO2 concentration with 20$ sensor \"MH-Z19\" and Raspberry Pi.](https://monitorserviceatelierueda.blogspot.com/2018/11/how-to-measure-room-co2-concentration.html)\n- [Monitoring all over the world with 3G Network for not more than 10$ monthly payment.](https://monitorserviceatelierueda.blogspot.com/2018/10/continuous-monitoring-all-over-world.html)\n- [How to make shareable SD card by Raspberry Pi & PC.](https://monitorserviceatelierueda.blogspot.com/2018/09/how-to-make-shareable-sd-card-by.html)\n\n## References\n\n- [MH-H19B DataSheet version 1.5](https://www.winsen-sensor.com/d/files/MH-Z19B.pdf)\n- [MH-H19 DataSheet version 1.0](https://www.winsen-sensor.com/d/files/PDF/Infrared%20Gas%20Sensor/NDIR%20CO2%20SENSOR/MH-Z19%20CO2%20Ver1.0.pdf)\n- [MH-H19B DataSheet version 1.0](https://www.winsen-sensor.com/d/files/infrared-gas-sensor/mh-z19b-co2-ver1_0.pdf)\n- [RevSpace](https://revspace.nl/MHZ19#Setting_the_measurement_range)\n\n\n## history\n- 0.1.0  2018.09.13  first version self-forked from [slider](https://github.com/UedaTakeyuki/slider).\n- 0.2.2  2018.11.19  introduce [pondslider](https://pypi.org/project/pondslider/) and separate this [PyPi](https://pypi.org/project/mh-z19/) package.\n- 2.0.0  2019.01.18  Add Calibration, ABC on/off requested by [this issue](https://github.com/UedaTakeyuki/mh-z19/issues/1). Please refer this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/module).\n- 0.3.5  2019.01.22  Both Python2 & Python3 support\n- 2.3.6  2019.01.22  Merge [Pull Request #3](https://github.com/UedaTakeyuki/mh-z19/pull/3) & [Pull Request #4](https://github.com/UedaTakeyuki/mh-z19/pull/4). Thanks [David](https://github.com/kostaldavid8)!\n- 2.3.7  2019.02.25  Add **--all** option which requested as [issue#5](https://github.com/UedaTakeyuki/mh-z19/issues/5), thanks [Rafał](https://github.com/rzarajczyk)!\n- 2.3.8  2019.04.16  Merge [Pull Request #7](https://github.com/UedaTakeyuki/mh-z19/pull/7). Thanks [Alexander](https://github.com/belibak)!\n- 2.3.8.1  2019.04.20  Merge [Pull Request #8](https://github.com/UedaTakeyuki/mh-z19/pull/8). Thanks [WO15](https://github.com/WO15)!\n- 2.3.8.5  2019.04.21  Merge [Pull Request #9](https://github.com/UedaTakeyuki/mh-z19/pull/9). Thanks [WO15](https://github.com/WO15)!\n- 2.3.8.6  2019.04.22  Merge [Pull Request #10](https://github.com/UedaTakeyuki/mh-z19/pull/10). Thanks [WO15](https://github.com/WO15)!\n- 2.3.9  2019.05.06  Revise the serial port selection logic. Support using **PL011** uart on Raspberry Pi **Model 3 and Zero W** which is selected by setting dtoverlay=**pi3-miniuart-bt** or dtoverlay=**pi3-disable-bt**. Thanks **片岡さん** for your kindly [report](https://qiita.com/yukataoka/items/a3b4065e8210b8f372ff) including this issue!\n- 2.4.1 2019.08.11 Add --serial_device option as solution of [issue#12](https://github.com/UedaTakeyuki/mh-z19/issues/12). Thanks [Actpohomoc](https://github.com/Actpohomoc) and [TBR-BRD](https://github.com/TBR-BRD)!\n- 2.4.2 2019.12.12  Merge [Pull Request #15](https://github.com/UedaTakeyuki/mh-z19/pull/15). Thanks [WO15](https://github.com/WO15)!\n- 2.5.1 2020.05.16 Add **--serial_console_untouched** option to support **execution without sudo** asked as [issue#17](https://github.com/UedaTakeyuki/mh-z19/issues/17). Thanks [ralphbe91](https://github.com/ralphbe91)!\n- 2.5.2 2020.06.30  Update the link for datasheet of MH-Z19B from version 1.0 to version 1.5 based be pointed it out as [issue#18](https://github.com/UedaTakeyuki/mh-z19/issues/18). Thanks [WO15](https://github.com/WO15)!\n- 2.6.1 2020.07.07 Add **--detection_range_10000** option to support **Set 0~10000ppm detection range** asked as [issue#19](https://github.com/UedaTakeyuki/mh-z19/issues/19). Thanks [WO15](https://github.com/WO15)!\n- 2.6.3 2020.08.27 Fix [issue#21](https://github.com/UedaTakeyuki/mh-z19/issues/21). Thanks [idegre](https://github.com/idegre)!\n- 3.0.0 2021.02.05 [PWM support](https://github.com/UedaTakeyuki/mh-z19/wiki/PWM-support.).\n- 3.0.1 2021.02.17 Fix a degradation of not running with python3. Thank you **Masahiko OHKUBO** san for your report.\n- 3.0.2 2021.03.25 Fix to support RPi4 correctly as [issue#29](https://github.com/UedaTakeyuki/mh-z19/issues/29). Thanks [iperniaf](https://github.com/iperniaf)!\n- 3.0.3 2021.11.08 Fix [issue#35](https://github.com/UedaTakeyuki/mh-z19/issues/35). Thanks [false](https://github.com/false-git)!\n- 3.0.4 2011.11.11 Fix [issue#36](https://github.com/UedaTakeyuki/mh-z19/issues/36). Thanks [David Bock](https://github.com/DavidBock)\n- 3.0.5 2022.01.01 Fix [issue#38](https://github.com/UedaTakeyuki/mh-z19/issues/38). Thanks [kzehnter](https://github.com/kzehnter)!\n- 3.1.0 2022.01.22 add ``--co2valueonly`` option by merging [issue#39](https://github.com/UedaTakeyuki/mh-z19/issues/39) and [issue#40](https://github.com/UedaTakeyuki/mh-z19/issues/40). Thanks [jonesthefox](https://github.com/jonesthefox)!\n- 3.1.1 2022.01.23 remove code clone.\n- 3.1.2 2022.01.31 Fix [issue#41](https://github.com/UedaTakeyuki/mh-z19/issues/41). Thanks [Christopher M. Pierce](https://github.com/electronsandstuff)!\n- 3.1.3 2022.02.25 Fix [issue#43](https://github.com/UedaTakeyuki/mh-z19/issues/43). Thanks [Jannis Möller](https://github.com/jannismoeller)!\n- 3.1.4 2023.11.14 Don't install python2-pip if OS version is BullsEye or later.\n- 3.1.5 2024.05.06 FIx [issue#53](https://github.com/UedaTakeyuki/mh-z19/issues/53). Thanks [Tats Shibata](https://github.com/rewse)\n- 3.1.6 2024.08.29 FIx [issue#54](https://github.com/UedaTakeyuki/mh-z19/issues/54). Thanks [80kpc](https://github.com/ziyucao)\n- 3.1.7 2025.03.01 drop the RPi.GPIO dependenc. Thanks [mroelandts](https://github.com/mroelandts)\n"
  },
  {
    "path": "__init__.py",
    "content": " \n"
  },
  {
    "path": "autostart.ini",
    "content": "cmd=mh_z19\n"
  },
  {
    "path": "autostart.sh",
    "content": "#!/bin/bash\n\n################################################################\n# \n# Autostart setting\n# \n# usage: ./autostart.sh --on/--off\n#\n#\n# @author Dr. Takeyuki UEDA\n# @copyright Copyright© Atelier UEDA 2018 - All rights reserved.\n#\n. autostart.ini\nCMD=$cmd\nSCRIPT_DIR=$(cd $(dirname $0); pwd)\n#echo $cwd\n\nusage_exit(){\n\techo \"Usage: $0 [--on]/[--off]\" 1>&2\n  echo \"  [--on]:               Set autostart as ON. \" \t\t\t1>&2\n  echo \"  [--off]:              Set autostart as OFF. \" \t\t1>&2\n  echo \"  [--status]:           Show current status. \" \t\t  1>&2\n  exit 1\n}\n\non(){\n\tsed -i \"s@^WorkingDirectory=.*@WorkingDirectory=${SCRIPT_DIR}@\" ${CMD}.service\n\tsudo ln -s ${SCRIPT_DIR}\\/${CMD}.service /etc/systemd/system/${CMD}.service\n\tsudo systemctl daemon-reload\n\tsudo systemctl enable ${CMD}.service\n\tsudo systemctl start ${CMD}.service\n}\n\noff(){\n\tsudo systemctl stop ${CMD}.service\n\tsudo systemctl disable ${CMD}.service\n}\n\nstatus(){\n\tsudo systemctl status ${CMD}.service\n}\nwhile getopts \":-:\" OPT\ndo\n  case $OPT in\n    -)\n\t\t\t\tcase \"${OPTARG}\" in\n\t\t\t\t\ton)\n\t\t\t\t\t\t\t\ton\n\t\t\t\t\t\t\t\t;;\n\t\t\t\t\toff)\n\t\t\t\t\t\t\t\toff\n\t\t\t\t\t\t\t\t;;\n\t\t\t\t\tstatus)\n\t\t\t\t\t\t\t\tstatus\n\t\t\t\t\t\t\t\t;;\n\t\t\t\tesac\n\t\t\t\t;;\n    \\?) usage_exit\n        ;;\n  esac\ndone\n"
  },
  {
    "path": "config.save.toml",
    "content": "[[sensors]]\n  handler = \"mh_z19\"\n  [[sensors.values]]\n    name = \"co2\"\n    handlers = [\n#      \"send2monitor\", # with send2monitor.ini on the current directory.\n#      \"handlers.value.sender.send2m2x\", # with send2m2x.ini on the handler/value/sender/send2m2x\n      \"handlers.value.saver.save2strage\"\n  ]\n"
  },
  {
    "path": "config.toml",
    "content": "[[sensors]]\n  handler = \"mh_z19\"\n  [[sensors.values]]\n    name = \"co2\"\n    handlers = [\n      \"send2monitor\", # with send2monitor.ini on the current directory.\n#      \"handlers.value.sender.send2m2x\", # with send2m2x.ini on the handler/value/sender/send2m2x\n#      \"handlers.value.saver.save2strage\"\n  ]\n"
  },
  {
    "path": "loop.sh",
    "content": "#!/bin/bash\nSCRIPT_DIR=$(cd $(dirname $0); pwd)\nwhile true; do sudo python ${SCRIPT_DIR}/read.py; sleep 5m; done\n"
  },
  {
    "path": "mh_z19.py",
    "content": "# -*- coding: utf-8 -*-\n# original: https://raw.githubusercontent.com/UedaTakeyuki/slider/master/mh_z19.py\n#\n# © Takeyuki UEDA 2015 -\n\nimport serial\nimport time\nimport subprocess\nimport traceback\nimport getrpimodel\nimport struct\nimport platform\nimport argparse\nimport sys\nimport json\nimport os.path\n\n#import RPi.GPIO as GPIO\nfrom gpiozero import Button\n\n# setting\nversion = \"3.1.7\"\npimodel        = getrpimodel.model()\npimodel_strict = getrpimodel.model_strict()\nretry_count    = 3\n\n# exception\nclass GPIO_Edge_Timeout(Exception):\n  pass\n\nif pimodel == \"5\":\n  partial_serial_dev = 'ttyAMA0'\nelse:\n  if os.path.exists('/dev/serial0'):\n    partial_serial_dev = 'serial0'\n  elif pimodel == \"3 Model B\" or pimodel == \"4 Model B\" or pimodel_strict == \"Zero W\":\n    partial_serial_dev = 'ttyS0'\n  else:\n    partial_serial_dev = 'ttyAMA0'\n\nserial_dev = '/dev/%s' % partial_serial_dev\n#stop_getty = 'sudo systemctl stop serial-getty@%s.service' % partial_serial_dev\n#start_getty = 'sudo systemctl start serial-getty@%s.service' % partial_serial_dev\n\n# major version of running python\np_ver = platform.python_version_tuple()[0]\n\ndef start_getty():\n  start_getty = ['sudo', 'systemctl', 'start', 'serial-getty@%s.service' % partial_serial_dev]\n  p = subprocess.call(start_getty)\n\ndef stop_getty():\n  stop_getty = ['sudo', 'systemctl', 'stop', 'serial-getty@%s.service' % partial_serial_dev]\n  p = subprocess.call(stop_getty)\n\ndef set_serialdevice(serialdevicename):\n  global serial_dev\n  serial_dev = serialdevicename\n\ndef connect_serial():\n  return serial.Serial(serial_dev,\n                        baudrate=9600,\n                        bytesize=serial.EIGHTBITS,\n                        parity=serial.PARITY_NONE,\n                        stopbits=serial.STOPBITS_ONE,\n                        timeout=1.0)\n\ndef read_concentration():\n  try:\n    ser = connect_serial()\n    for retry in range(retry_count):\n      result=ser.write(b\"\\xff\\x01\\x86\\x00\\x00\\x00\\x00\\x00\\x79\")\n      s=ser.read(9)\n\n      if p_ver == '2':\n        if len(s) >= 4 and s[0] == \"\\xff\" and s[1] == \"\\x86\" and checksum(s[1:-1]) == s[-1]:\n          return ord(s[2])*256 + ord(s[3])\n      else:\n        if len(s) >= 4 and s[0] == 0xff and s[1] == 0x86 and ord(checksum(s[1:-1])) == s[-1]:\n          return s[2]*256 + s[3]\n  except:\n     traceback.print_exc()\n  return \"\"\n\ndef mh_z19():\n  co2 = read_concentration()\n  if not co2:\n    return {}\n  else:\n    return {'co2': co2}\n\ndef read(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n\n  result = mh_z19()\n\n  if not serial_console_untouched:\n    start_getty()\n  return result\n\ndef read_co2valueonly(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n\n  result = read_concentration()\n\n  if not serial_console_untouched:\n    start_getty()\n  return result\n\ndef read_all(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  try:\n    ser = connect_serial()\n    for retry in range(retry_count):\n      result=ser.write(b\"\\xff\\x01\\x86\\x00\\x00\\x00\\x00\\x00\\x79\")\n      s=ser.read(9)\n\n      if p_ver == '2':\n        if len(s) >= 9 and s[0] == \"\\xff\" and s[1] == \"\\x86\" and checksum(s[1:-1]) == s[-1]:\n          return {'co2': ord(s[2])*256 + ord(s[3]),\n                  'temperature': ord(s[4]) - 40,\n                  'TT': ord(s[4]),\n                  'SS': ord(s[5]),\n                  'UhUl': ord(s[6])*256 + ord(s[7])\n                  }\n        break\n      else:\n        if len(s) >= 9 and s[0] == 0xff and s[1] == 0x86 and ord(checksum(s[1:-1])) == s[-1]:\n          return {'co2': s[2]*256 + s[3],\n                  'temperature': s[4] - 40,\n                  'TT': s[4],\n                  'SS': s[5],\n                  'UhUl': s[6]*256 + s[7]\n                  }\n  except:\n     traceback.print_exc()\n\n  if not serial_console_untouched:\n    start_getty()\n  return {}\n\ndef abc_on(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  result=ser.write(b\"\\xff\\x01\\x79\\xa0\\x00\\x00\\x00\\x00\\xe6\")\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef abc_off(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  result=ser.write(b\"\\xff\\x01\\x79\\x00\\x00\\x00\\x00\\x00\\x86\")\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef span_point_calibration(span, serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  if p_ver == '2':\n    b3 = span / 256;\n  else:\n    b3 = span // 256;   \n  byte3 = struct.pack('B', b3)\n  b4 = span % 256; byte4 = struct.pack('B', b4)\n  c = checksum([0x01, 0x88, b3, b4])\n  request = b\"\\xff\\x01\\x88\" + byte3 + byte4 + b\"\\x00\\x00\\x00\" + c\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef zero_point_calibration(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x87\\x00\\x00\\x00\\x00\\x00\\x78\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef detection_range_10000(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x99\\x00\\x00\\x00\\x27\\x10\\x2F\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef detection_range_5000(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x99\\x00\\x00\\x00\\x13\\x88\\xcb\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef detection_range_2000(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x99\\x00\\x00\\x00\\x07\\xd0\\x8F\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef read_from_pwm(gpio=12, range=5000):\n  CYCLE_START_HIGHT_TIME = 2\n  TIMEOUT = 2000 # must be larger than PWM cycle time.\n\n  '''\n  GPIO.setmode(GPIO.BCM)\n  GPIO.setup(gpio,GPIO.IN)\n  '''\n  btn = Button(gpio)\n\n  # wait falling ¯¯|_ to see end of last cycle\n  '''\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  '''\n  starting = time.time() * 1000\n  btn.wait_for_press(2) # 2 sec for timeout because 1sec cycle of pwm\n  last_falling = time.time() * 1000\n  if last_falling - starting > 1000:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  # wait rising __|¯ to catch the start of this cycle\n  '''\n  channel = GPIO.wait_for_edge(gpio,GPIO.RISING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    rising = time.time() * 1000\n  '''\n  starting = time.time() * 1000\n  btn.wait_for_release(2) # 2 sec for timeout because 1sec cycle of pwm\n  rising   = time.time() * 1000\n  if rising - starting > 1000:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  # wait falling ¯¯|_ again to catch the end of TH duration\n  '''\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    falling = time.time() * 1000\n  '''\n  starting = time.time() * 1000\n  btn.wait_for_press(2) # 2 sec for timeout because 1sec cycle of pwm\n  falling  = time.time() * 1000\n  if falling - starting > 1000:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n\n  return {'co2': int(falling -rising - CYCLE_START_HIGHT_TIME) / 2 *(range/500)}\n\ndef checksum(array):\n  if p_ver == '2' and isinstance(array, str):\n    array = [ord(c) for c in array]\n  csum = sum(array) % 0x100\n  if csum == 0:\n    return struct.pack('B', 0)\n  else:\n    return struct.pack('B', 0xff - csum + 1)\n\nif __name__ == '__main__':\n#  value = read()\n#  print (value)\n  parser = argparse.ArgumentParser(\n    description='''return CO2 concentration as object as {'co2': 416}''',\n  )\n  parser.add_argument(\"--serial_device\",\n                      type=str,\n                      help='''Use this serial device file''')\n\n  parser.add_argument(\"--serial_console_untouched\",\n                      action='store_true',\n                      help='''Don't close/reopen serial console before/after sensor reading''')\n\n\n  group = parser.add_mutually_exclusive_group()\n\n  group.add_argument(\"--version\",\n                      action='store_true',\n                      help='''show version''')\n  group.add_argument(\"--all\",\n                      action='store_true',\n                      help='''return all (co2, temperature, TT, SS and UhUl) as json''')\n  group.add_argument(\"--co2valueonly\",\n                      action='store_true',\n                      help='''return co2 value alone, as unlabeled string''')\n  group.add_argument(\"--abc_on\",\n                      action='store_true',\n                      help='''Set ABC functionality on model B as ON.''')\n  group.add_argument(\"--abc_off\",\n                      action='store_true',\n                      help='''Set ABC functionality on model B as OFF.''')\n  \n  parser.add_argument(\"--span_point_calibration\",\n                      type=int,\n                      metavar=\"span\",\n                      help='''Call calibration function with SPAN point''')\n  parser.add_argument(\"--zero_point_calibration\",\n                      action='store_true',\n                      help='''Call calibration function with ZERO point''')\n  parser.add_argument(\"--detection_range_10000\",\n                      action='store_true',\n                      help='''Set detection range as 10000''')\n  parser.add_argument(\"--detection_range_5000\",\n                      action='store_true',\n                      help='''Set detection range as 5000''')\n  parser.add_argument(\"--detection_range_2000\",\n                      action='store_true',\n                      help='''Set detection range as 2000''')\n\n  parser.add_argument(\"--pwm\",\n                      action='store_true',\n                      help='''Read CO2 concentration from PWM, see also `--pwm_range` and/or `--pwm_gpio`''')\n\n  parser.add_argument(\"--pwm_range\",\n                      type=int,\n                      choices=[2000,5000,10000],\n                      default=5000,\n                      metavar=\"range\",\n                      help='''with --pwm, use this to compute co2 concentration, default is 5000''')\n\n  parser.add_argument(\"--pwm_gpio\",\n                      type=int,\n                      default=12,\n                      metavar=\"gpio(BCM)\",\n                      help='''with --pwm, read from this gpio pin on RPi, default is 12''')\n\n  args = parser.parse_args()\n\n  if args.serial_device is not None:\n    set_serialdevice(args.serial_device)\n\n  if args.abc_on:\n    abc_on(args.serial_console_untouched)\n    print (\"Set ABC logic as on.\")\n  elif args.abc_off:\n    abc_off(args.serial_console_untouched)\n    print (\"Set ABC logic as off.\")\n  elif args.span_point_calibration is not None:\n    span_point_calibration(args.span_point_calibration, args.serial_console_untouched)\n    print (\"Call Calibration with SPAN point.\")\n  elif args.zero_point_calibration:\n    print (\"Call Calibration with ZERO point.\")\n    zero_point_calibration(args.serial_console_untouched)\n  elif args.detection_range_10000:\n    detection_range_10000(args.serial_console_untouched)\n    print (\"Set Detection range as 10000.\")\n  elif args.detection_range_5000:\n    detection_range_5000(args.serial_console_untouched)\n    print (\"Set Detection range as 5000.\")\n  elif args.detection_range_2000:\n    detection_range_2000(args.serial_console_untouched)\n    print (\"Set Detection range as 2000.\")\n  elif args.pwm:\n    print (read_from_pwm(gpio=args.pwm_gpio, range=args.pwm_range))\n  elif args.version:\n    print (version)\n  elif args.all:\n    value = read_all(args.serial_console_untouched)\n    print (json.dumps(value))\n  elif args.co2valueonly:\n    value = read_co2valueonly(args.serial_console_untouched)\n    print (value)\n  else:\n    value = read(args.serial_console_untouched)\n    print (json.dumps(value))\n\n  sys.exit(0)\n"
  },
  {
    "path": "mh_z19.service",
    "content": "\n[Unit]\nDescription=Get temp, humid, and humiditydeficit data & Post to the monitor\nAfter=rc-local.service\n[Service]\nWorkingDirectory=/home/pi/mh-z19\nExecStart=/usr/bin/sudo /usr/bin/python -m pondslider --interval 5\nRestart=always\n#RestartSec=90\nRestartSec=30\nType=simple\nPIDFile=/var/run/mh-z19.pid\n[Install]\nWantedBy=multi-user.target\n\n"
  },
  {
    "path": "pypi/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Dr. Takeyuki Ueda\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "pypi/README.md",
    "content": "# mh-z19\nRead CO2 concentration from mh-z19 sensor\n\n![MH-Z19](https://camo.githubusercontent.com/8456a67ab97a13866d928d3a14dff59a57cdeccb/68747470733a2f2f63616d6f2e716969746175736572636f6e74656e742e636f6d2f613237306466313136326564356333626639393638623234303634623931656564306466636331312f3638373437343730373333613266326637313639363937343631326436393664363136373635326437333734366637323635326537333333326536313664363137613666366536313737373332653633366636643266333032663334333633353334333432663331333533373339363633393634363232643330363633343330326433373336363533383264333033353636333332643339333933333631333233343633333433373634333133383265373036653637)\n\n## install\n```\npip install mh_z19\n```\n## installs\n[![Downloads](https://pepy.tech/badge/mh-z19)](https://pepy.tech/project/mh-z19)\n[![Downloads](https://pepy.tech/badge/mh-z19/month)](https://pepy.tech/project/mh-z19)\n[![Downloads](https://pepy.tech/badge/mh-z19/week)](https://pepy.tech/project/mh-z19)\n\n## how to use\nUse as python script.\n```\npi@raspberrypi:~/mh-z19/pypi $ sudo python -m mh_z19\n{'co2': 500}\n```\n\nImport module and call read()\n```\npi@raspberrypi:~/mh-z19/pypi $ sudo python\nPython 2.7.13 (default, Nov 24 2017, 17:33:09) \n[GCC 6.3.0 20170516] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import mh_z19\n>>> mh_z19.read()\n{'co2': 477}\n>>> \n```\n\nThe ***sudo*** might be necessary because mh_z19 module use Serial.\n\nThe differences of the interface between each Raspberry Pi model are resolved inside this module. For example, serial device name is difference between Raspberry Pi 3 and older model, but mh-z19 module automatically detect the model and read from appropriate serial device.\n\nTo use mh-z19, once you need to set up enabling serial port device on the Raspberry Pi.\nFollowing [Wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-Enable-Serial-Port-hardware-on-the-Raspberry-Pi) page might be informative.\n\n## cabling\nConnect RPi & mh-z19 as:\n\n- 5V on RPi and Vin on mh-z19\n- GND(0v) on RPi and GND on mh-z19\n- TxD and RxD are connected to cross between RPi and mh-z18 \n\nFollowings are example of cabling, but you can free to use other 5v and 0v Pin on the RPi. \n\n![Cabling](https://camo.githubusercontent.com/3cd4c1b482ea902b7e66dca13d4260193c831a63/68747470733a2f2f63616d6f2e716969746175736572636f6e74656e742e636f6d2f313132616435666534316338326131363637316432383832303730333834313039633838363063632f36383734373437303733336132663266373136393639373436313264363936643631363736353264373337343666373236353265373333333265363136643631376136663665363137373733326536333666366432663330326633343336333533343334326633303338333233383333333033313334326433363338363433323264363333333634363532643331333633343334326433373633333836343339363233373632333633323636363432653661373036353637)\n\n```\npi@raspberrypi:~/mh-z19 $ gpio readall\n +-----+-----+---------+------+---+---Pi B+--+---+------+---------+-----+-----+\n | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |\n +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+\n |     |     |    3.3v |      |   |  1 || 2  |   |      | 5v      |     |     |\n |   2 |   8 |   SDA.1 |   IN | 1 |  3 || 4  |   |      | 5v      |     |     |  <---- Vin\n |   3 |   9 |   SCL.1 |   IN | 1 |  5 || 6  |   |      | 0v      |     |     |  <---- Gnd\n |   4 |   7 | GPIO. 7 |   IN | 1 |  7 || 8  | 1 | ALT0 | TxD     | 15  | 14  |  <---- RxD\n |     |     |      0v |      |   |  9 || 10 | 1 | ALT0 | RxD     | 16  | 15  |  <---- TxD\n |  17 |   0 | GPIO. 0 |   IN | 0 | 11 || 12 | 0 | IN   | GPIO. 1 | 1   | 18  |\n |  27 |   2 | GPIO. 2 |   IN | 0 | 13 || 14 |   |      | 0v      |     |     |\n |  22 |   3 | GPIO. 3 |   IN | 0 | 15 || 16 | 0 | IN   | GPIO. 4 | 4   | 23  |\n |     |     |    3.3v |      |   | 17 || 18 | 0 | IN   | GPIO. 5 | 5   | 24  |\n |  10 |  12 |    MOSI |   IN | 0 | 19 || 20 |   |      | 0v      |     |     |\n |   9 |  13 |    MISO |   IN | 0 | 21 || 22 | 0 | IN   | GPIO. 6 | 6   | 25  |\n |  11 |  14 |    SCLK |   IN | 0 | 23 || 24 | 1 | IN   | CE0     | 10  | 8   |\n |     |     |      0v |      |   | 25 || 26 | 1 | IN   | CE1     | 11  | 7   |\n |   0 |  30 |   SDA.0 |   IN | 1 | 27 || 28 | 1 | IN   | SCL.0   | 31  | 1   |\n |   5 |  21 | GPIO.21 |   IN | 1 | 29 || 30 |   |      | 0v      |     |     |\n |   6 |  22 | GPIO.22 |   IN | 1 | 31 || 32 | 0 | IN   | GPIO.26 | 26  | 12  |\n |  13 |  23 | GPIO.23 |   IN | 0 | 33 || 34 |   |      | 0v      |     |     |\n |  19 |  24 | GPIO.24 |   IN | 0 | 35 || 36 | 0 | IN   | GPIO.27 | 27  | 16  |\n |  26 |  25 | GPIO.25 |   IN | 0 | 37 || 38 | 0 | IN   | GPIO.28 | 28  | 20  |\n |     |     |      0v |      |   | 39 || 40 | 0 | IN   | GPIO.29 | 29  | 21  |\n +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+\n | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |\n +-----+-----+---------+------+---+---Pi B+--+---+------+---------+-----+-----+\n```\n\n## Watch CO2 concentration on your browser \n<img src=\"https://github.com/UedaTakeyuki/mh-z19/raw/master/pic/2018-11-20.11.23.19.png\" width=\"24%\">\n\n[MONITOR™](https://monitor3.uedasoft.com) is a free Remote Monitoring Service to show latest data on the web. You can see the current CO2 concentration value measured by your MH-Z19 device on your smartphone. For detail, please refer this [blog](https://monitorserviceatelierueda.blogspot.com/2018/11/how-to-measure-room-co2-concentration.html). \n\n\n## Calibration, Detection range settings, and ABC(Automatic Baseline Correction) logic on/off.\nFeatures about calibration (both MH-Z19 & MH-Z19B), detection range change (MH-Z19B) and ABC logic on/off(MH-Z19B) are implemented at version 0.2.1 or later.\n\nI'm afraid I've just only implemented these without test due to lack necessary devices and apparatus for the test, fx: standard concentration CO2 gas, also MH-Z19B module.\nIf you have these devices or apparatus and try to use these functions generously, I'm really appreciate your [issue report](https://github.com/UedaTakeyuki/mh-z19/issues) regardless result were positive or negative.\n\nFor detail please refer this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/CALIBRATION-&-detection-range).\n\n## Undocumented response values of 0x86 command.\nThe [Revspace/MHZ19](https://revspace.nl/MHZ19#Command_0x86_.28read_concentration.29) shows values undocumented on the official datasheets([MH-Z19](https://www.winsen-sensor.com/d/files/PDF/Infrared%20Gas%20Sensor/NDIR%20CO2%20SENSOR/MH-Z19%20CO2%20Ver1.0.pdf), [MH-Z19B](https://www.winsen-sensor.com/d/files/MH-Z19B.pdf)). In accordance with this, **--all** option add these values in the return json value as follows:\n\n```bash:\nsudo python -m mh_z19 --all\n{\"SS\": 232, \"UhUl\": 10752, \"TT\": 61, \"co2\": 818, \"temperature\": 21}\n\nsudo python3 -m mh_z19 --all\n{\"TT\": 61, \"co2\": 807, \"SS\": 232, \"temperature\": 21, \"UhUl\": 10752}\n```\n\nor call **read_all()** function as follows:\n\n```\n>>> import mh_z19\n>>> mh_z19.read_all()\n{'SS': 232, 'UhUl': 10738, 'TT': 61, 'co2': 734, 'temperature': 21}\n>>> \n```\n\n## Use specific serial device.\nIn case you should use specific serial device insted of Raspberry Pi default serial device which this library automatically select, for example in case to need to use /dev/ttyUSB0 for **FT232 usb-serial converter** as [issue#12](https://github.com/UedaTakeyuki/mh-z19/issues/12), you can specify serial device by **--serial_device** option as follows:\n\n```\nsudo python -m mh_z19 --serial_device /dev/ttyUSB0\n```\n\n## How to use without root permission.\nSee this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-use-without-root-permission.).\n\n## How to use in your program.\nSee this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/How-to-use-in-your-program.).\n\n## PWM support.\nSee this [wiki](https://github.com/UedaTakeyuki/mh-z19/wiki/PWM-support.).\n\n## In case you can't get the value.\nEven if cabling seems no problem and uart seems to be prepateted well but you can't get sensor value. As [nincube8](https://github.com/nincube8) suggested that the [pull up](https://github.com/UedaTakeyuki/mh-z19/issues/22#issuecomment-683393350) by [1-5kΩ register](https://github.com/UedaTakeyuki/mh-z19/issues/26#issuecomment-744039360) can be working solution. Thank you [nincube8](https://github.com/nincube8)!\n\n## Q&A\nThe forum is avai at [here](https://groups.google.com/g/mh_z19-users). Any questions, suggestions, reports are welcome!\n\n## Blog\n- [How to Measure ROOM CO2 concentration with 20$ sensor \"MH-Z19\" and Raspberry Pi.](https://monitorserviceatelierueda.blogspot.com/2018/11/how-to-measure-room-co2-concentration.html)\n- [Monitoring all over the world with 3G Network for not more than 10$ monthly payment.](https://monitorserviceatelierueda.blogspot.com/2018/10/continuous-monitoring-all-over-world.html)\n- [How to make shareable SD card by Raspberry Pi & PC.](https://monitorserviceatelierueda.blogspot.com/2018/09/how-to-make-shareable-sd-card-by.html)\n\n## References\n\n- [MH-H19B DataSheet version 1.5](https://www.winsen-sensor.com/d/files/MH-Z19B.pdf)\n- [MH-H19 DataSheet version 1.0](https://www.winsen-sensor.com/d/files/PDF/Infrared%20Gas%20Sensor/NDIR%20CO2%20SENSOR/MH-Z19%20CO2%20Ver1.0.pdf)\n- [MH-H19B DataSheet version 1.0](https://www.winsen-sensor.com/d/files/infrared-gas-sensor/mh-z19b-co2-ver1_0.pdf)\n- [RevSpace](https://revspace.nl/MHZ19#Setting_the_measurement_range)\n\n## history\n- 0.1.1  2018.11.05  first version self-forked from [slider](https://github.com/UedaTakeyuki/slider).\n- 0.1.3  2018.11.06  fix Readme.\n- 0.1.4  2018.11.15  revise Readme.\n- 0.1.6  2018.11.29  revise Readme.\n- 0.2.1  2019.01.18  add followings without test (sorry)\n                       abc_on(), abc_off(), span_point_calibration(),\n\t\t\t\t\t\t\t\t\t\t\t xero_point_calibration(), detection_range_5000(),\n\t\t\t\t\t\t\t\t\t\t\t detection_range_2000(), checksum()\n- 0.3.5  2019.01.22  Both Python2 & Python3 support\n- 0.3.6  2019.01.22  Merge [Pull Request #3](https://github.com/UedaTakeyuki/mh-z19/pull/3) & [Pull Request #4](https://github.com/UedaTakeyuki/mh-z19/pull/4). Thanks [David](https://github.com/kostaldavid8)!\n- 0.3.7  2019.02.25  Add --all option which requested as [issue#5](https://github.com/UedaTakeyuki/mh-z19/issues/5), thanks [Rafał](https://github.com/rzarajczyk)!\n- 0.3.8  2019.04.16  Merge [Pull Request #7](https://github.com/UedaTakeyuki/mh-z19/pull/7). Thanks [Alexander](https://github.com/belibak)!\n- 0.3.8.5  2019.04.21  Merge [Pull Request #9](https://github.com/UedaTakeyuki/mh-z19/pull/9). Thanks [WO15](https://github.com/WO15)!\n- 0.3.9  2019.05.06  Revise the serial port selection logic. Support using **PL011** uart on Raspberry Pi **Model 3 and Zero W** which is selected by setting dtoverlay=**pi3-miniuart-bt** or dtoverlay=**pi3-disable-bt**. Thanks **片岡さん** for your kindly [report](https://qiita.com/yukataoka/items/a3b4065e8210b8f372ff) including this issue!\n- 0.4.1 2019.08.11 Add --serial_device option as solution of [issue#12](https://github.com/UedaTakeyuki/mh-z19/issues/12). Thanks [Actpohomoc](https://github.com/Actpohomoc) and [TBR-BRD](https://github.com/TBR-BRD)!\n- 0.5.1 2020.05.16 Add **--serial_console_untouched** option to support **execution without sudo** asked as [issue#17](https://github.com/UedaTakeyuki/mh-z19/issues/17). Thanks [ralphbe91](https://github.com/ralphbe91)!\n- 0.5.2 2020.06.30 Update the link for datasheet of MH-Z19B from version 1.0 to version 1.5 based be pointed it out as [issue#18](https://github.com/UedaTakeyuki/mh-z19/issues/18). Thanks [WO15](https://github.com/WO15)!\n- 0.6.1 2020.07.07 Add **--detection_range_10000** option to support **Set 0~10000ppm detection range** asked as [issue#19](https://github.com/UedaTakeyuki/mh-z19/issues/19). Thanks [WO15](https://github.com/WO15)!\n- 0.6.3 2020.08.27 Fix [issue#21](https://github.com/UedaTakeyuki/mh-z19/issues/21). Thanks [idegre](https://github.com/idegre)!\n- 3.0.0 2021.02.05 [PWM support](https://github.com/UedaTakeyuki/mh-z19/wiki/PWM-support.).\n- 3.0.1 2021.02.17 Fix a degradation of not running with python3. Thank you **Masahiko OHKUBO** san for your report.\n- 3.0.2 2021.03.25 Fix to support RPi4 correctly as [issue#29](https://github.com/UedaTakeyuki/mh-z19/issues/29). Thanks [iperniaf](https://github.com/iperniaf)!\n- 3.0.3 2021.11.08 Fix [issue#35](https://github.com/UedaTakeyuki/mh-z19/issues/35). Thanks [false](https://github.com/false-git)!\n- 3.0.4 2011.11.11 Fix [issue#36](https://github.com/UedaTakeyuki/mh-z19/issues/36). Thanks [David Bock](https://github.com/DavidBock)\n- 3.0.5 2022.01.01 Fix [issue#38](https://github.com/UedaTakeyuki/mh-z19/issues/38). Thanks [kzehnter](https://github.com/kzehnter)!\n- 3.1.0 2022.01.22 add ``--co2valueonly`` option by merging [issue#39](https://github.com/UedaTakeyuki/mh-z19/issues/39) and [issue#40](https://github.com/UedaTakeyuki/mh-z19/issues/40). Thanks [jonesthefox](https://github.com/jonesthefox)!\n- 3.1.1 2022.01.23 remove code clone.\n- 3.1.2 2022.01.31 Fix [issue#41](https://github.com/UedaTakeyuki/mh-z19/issues/41). Thanks [Christopher M. Pierce](https://github.com/electronsandstuff)!\n- 3.1.3 2022.02.25 Fix [issue#43](https://github.com/UedaTakeyuki/mh-z19/issues/43). Thanks [Jannis Möller](https://github.com/jannismoeller)!\n- 3.1.5 2024.05.06 FIx [issue#53](https://github.com/UedaTakeyuki/mh-z19/issues/53). Thanks [Tats Shibata](https://github.com/rewse)\n- 3.1.6 2024.08.29 FIx [issue#54](https://github.com/UedaTakeyuki/mh-z19/issues/54). Thanks [80kpc](https://github.com/ziyucao)\n- 3.1.7 2025.03.01 drop the RPi.GPIO dependenc. Thanks [mroelandts](https://github.com/mroelandts)\n"
  },
  {
    "path": "pypi/mh_z19/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n# original: https://raw.githubusercontent.com/UedaTakeyuki/slider/master/mh_z19.py\n#\n# © Takeyuki UEDA 2015 -\n\nimport serial\nimport subprocess\nimport traceback\nimport getrpimodel\nimport struct\nimport platform\nimport os.path\n\n# import RPi.GPIO as GPIO\nimport mh_z19.pwm as pwm\n\n# setting\nversion = \"3.1.7\"\npimodel        = getrpimodel.model()\npimodel_strict = getrpimodel.model_strict()\nretry_count    = 3\n\nif pimodel == \"5\":\n  partial_serial_dev = 'ttyAMA0'\nelse:\n  if os.path.exists('/dev/serial0'):\n    partial_serial_dev = 'serial0'\n  elif pimodel == \"3 Model B\" or pimodel == \"4 Model B\" or pimodel_strict == \"Zero W\":\n    partial_serial_dev = 'ttyS0'\n  else:\n    partial_serial_dev = 'ttyAMA0'\n  \nserial_dev = '/dev/%s' % partial_serial_dev\n#stop_getty = 'sudo systemctl stop serial-getty@%s.service' % partial_serial_dev\n#start_getty = 'sudo systemctl start serial-getty@%s.service' % partial_serial_dev\n#start_getty = ['sudo', 'systemctl', 'start', 'serial-getty@%s.service' % partial_serial_dev]\n#stop_getty = ['sudo', 'systemctl', 'stop', 'serial-getty@%s.service' % partial_serial_dev]\n\n# major version of running python\np_ver = platform.python_version_tuple()[0]\n\ndef start_getty():\n#  p = subprocess.call(start_getty, stdout=subprocess.PIPE, shell=True)\n  start_getty = ['sudo', 'systemctl', 'start', 'serial-getty@%s.service' % partial_serial_dev]\n  p = subprocess.call(start_getty)\n\ndef stop_getty():\n#  p = subprocess.call(stop_getty, stdout=subprocess.PIPE, shell=True)\n  stop_getty = ['sudo', 'systemctl', 'stop', 'serial-getty@%s.service' % partial_serial_dev]\n  p = subprocess.call(stop_getty)\n\ndef set_serialdevice(serialdevicename):\n  global serial_dev\n  serial_dev = serialdevicename\n\ndef connect_serial():\n  return serial.Serial(serial_dev,\n                        baudrate=9600,\n                        bytesize=serial.EIGHTBITS,\n                        parity=serial.PARITY_NONE,\n                        stopbits=serial.STOPBITS_ONE,\n                        timeout=1.0)\n\ndef read_concentration():\n  try:\n    ser = connect_serial()\n    for retry in range(retry_count):\n      result=ser.write(b\"\\xff\\x01\\x86\\x00\\x00\\x00\\x00\\x00\\x79\")\n      s=ser.read(9)\n\n      if p_ver == '2':\n        if len(s) >= 4 and s[0] == \"\\xff\" and s[1] == \"\\x86\" and checksum(s[1:-1]) == s[-1]:\n          return ord(s[2])*256 + ord(s[3])\n      else:\n        if len(s) >= 4 and s[0] == 0xff and s[1] == 0x86 and ord(checksum(s[1:-1])) == s[-1]:\n          return s[2]*256 + s[3]\n  except:\n     traceback.print_exc()\n  return \"\"\n\ndef mh_z19():\n  co2 = read_concentration()\n  if not co2:\n    return {}\n  else:\n    return {'co2': co2}\n\ndef read(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n\n  result = mh_z19()\n\n  if not serial_console_untouched:\n    start_getty()\n  return result\n\ndef read_co2valueonly(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n\n  result = read_concentration()\n\n  if not serial_console_untouched:\n    start_getty()\n  return result\n\ndef read_all(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  try:\n    ser = connect_serial()\n    for retry in range(retry_count):\n      result=ser.write(b\"\\xff\\x01\\x86\\x00\\x00\\x00\\x00\\x00\\x79\")\n      s=ser.read(9)\n\n      if p_ver == '2':\n        if len(s) >= 9 and s[0] == \"\\xff\" and s[1] == \"\\x86\" and checksum(s[1:-1]) == s[-1]:\n          return {'co2': ord(s[2])*256 + ord(s[3]),\n                  'temperature': ord(s[4]) - 40,\n                  'TT': ord(s[4]),\n                  'SS': ord(s[5]),\n                  'UhUl': ord(s[6])*256 + ord(s[7])\n                  }\n        break\n      else:\n        if len(s) >= 9 and s[0] == 0xff and s[1] == 0x86 and ord(checksum(s[1:-1])) == s[-1]:\n          return {'co2': s[2]*256 + s[3],\n                  'temperature': s[4] - 40,\n                  'TT': s[4],\n                  'SS': s[5],\n                  'UhUl': s[6]*256 + s[7]\n                  }\n  except:\n     traceback.print_exc()\n\n  if not serial_console_untouched:\n    start_getty()\n  return {}\n\ndef abc_on(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  result=ser.write(b\"\\xff\\x01\\x79\\xa0\\x00\\x00\\x00\\x00\\xe6\")\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef abc_off(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  result=ser.write(b\"\\xff\\x01\\x79\\x00\\x00\\x00\\x00\\x00\\x86\")\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef span_point_calibration(span, serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  if p_ver == '2':\n    b3 = span / 256;\n  else:\n    b3 = span // 256;   \n  byte3 = struct.pack('B', b3)\n  b4 = span % 256; byte4 = struct.pack('B', b4)\n  c = checksum([0x01, 0x88, b3, b4])\n  request = b\"\\xff\\x01\\x88\" + byte3 + byte4 + b\"\\x00\\x00\\x00\" + c\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef zero_point_calibration(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x87\\x00\\x00\\x00\\x00\\x00\\x78\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef detection_range_10000(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x99\\x00\\x00\\x00\\x27\\x10\\x2F\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef detection_range_5000(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x99\\x00\\x00\\x00\\x13\\x88\\xcb\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef detection_range_2000(serial_console_untouched=False):\n  if not serial_console_untouched:\n    stop_getty()\n  ser = connect_serial()\n  request = b\"\\xff\\x01\\x99\\x00\\x00\\x00\\x07\\xd0\\x8F\"\n  result = ser.write(request)\n  ser.close()\n  if not serial_console_untouched:\n    start_getty()\n\ndef read_from_pwm(gpio=12, range=5000):\n#  if pimodel == \"5\":\n    return pwm.read_from_pwm_with_gpiozero(gpio=12, range=5000)\n#  else:\n#    return pwm.read_from_pwm_with_gpio(gpio=12, range=5000)\n'''\n  CYCLE_START_HIGHT_TIME = 2\n  TIMEOUT = 2000 # must be larger than PWM cycle time.\n\n  GPIO.setmode(GPIO.BCM)\n  GPIO.setup(gpio,GPIO.IN)\n\n  # wait falling ¯¯|_ to see end of last cycle\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  # wait rising __|¯ to catch the start of this cycle\n  channel = GPIO.wait_for_edge(gpio,GPIO.RISING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    rising = time.time() * 1000\n\n  # wait falling ¯¯|_ again to catch the end of TH duration\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    falling = time.time() * 1000\n\n  return {'co2': int(falling -rising - CYCLE_START_HIGHT_TIME) / 2 *(range/500)}\n'''\n\ndef checksum(array):\n  if p_ver == '2' and isinstance(array, str):\n    array = [ord(c) for c in array]\n  csum = sum(array) % 0x100\n  if csum == 0:\n    return struct.pack('B', 0)\n  else:\n    return struct.pack('B', 0xff - csum + 1)\n"
  },
  {
    "path": "pypi/mh_z19/__main__.py",
    "content": "# -*- coding: utf-8 -*-\n# original: https://raw.githubusercontent.com/UedaTakeyuki/slider/master/mh_z19.py\n#\n# © Takeyuki UEDA 2015 -\nimport sys\nimport argparse\nimport json\nimport mh_z19.__init__ as mh_z19\n#import __init__ as mh_z19\n\nparser = argparse.ArgumentParser(\n  description='''return CO2 concentration as object as {'co2': 416}''',\n)\nparser.add_argument(\"--serial_device\",\n                    type=str,\n                    help='''Use this serial device file''')\n\nparser.add_argument(\"--serial_console_untouched\",\n                    action='store_true',\n                    help='''Don't close/reopen serial console before/after sensor reading''')\n\n\ngroup = parser.add_mutually_exclusive_group()\n\ngroup.add_argument(\"--version\",\n                    action='store_true',\n                    help='''show version''')\ngroup.add_argument(\"--all\",\n                    action='store_true',\n                    help='''return all (co2, temperature, TT, SS and UhUl) as json''')\ngroup.add_argument(\"--co2valueonly\",\n                    action='store_true',\n                    help='''return co2 value alone, as unlabeled string''')\ngroup.add_argument(\"--abc_on\",\n                    action='store_true',\n                    help='''Set ABC functionality on model B as ON.''')\ngroup.add_argument(\"--abc_off\",\n                    action='store_true',\n                    help='''Set ABC functionality on model B as OFF.''')\n\nparser.add_argument(\"--span_point_calibration\",\n                    type=int,\n                    metavar=\"span\",\n                    help='''Call calibration function with SPAN point''')\nparser.add_argument(\"--zero_point_calibration\",\n                    action='store_true',\n                    help='''Call calibration function with ZERO point''')\nparser.add_argument(\"--detection_range_10000\",\n                    action='store_true',\n                    help='''Set detection range as 10000''')\nparser.add_argument(\"--detection_range_5000\",\n                    action='store_true',\n                    help='''Set detection range as 5000''')\nparser.add_argument(\"--detection_range_2000\",\n                    action='store_true',\n                    help='''Set detection range as 2000''')\n\nparser.add_argument(\"--pwm\",\n                    action='store_true',\n                    help='''Read CO2 concentration from PWM, see also `--pwm_range` and/or `--pwm_gpio`''')\n\nparser.add_argument(\"--pwm_range\",\n                    type=int,\n                    choices=[2000,5000,10000],\n                    default=5000,\n                    metavar=\"range\",\n                    help='''with --pwm, use this to compute co2 concentration, default is 5000''')\n\nparser.add_argument(\"--pwm_gpio\",\n                    type=int,\n                    default=12,\n                    metavar=\"gpio(BCM)\",\n                    help='''with --pwm, read from this gpio pin on RPi, default is 12''')\n\nargs = parser.parse_args()\n\nif args.serial_device is not None:\n  mh_z19.set_serialdevice(args.serial_device)\n\n#print(args.serial_console_untouched)\n\nif args.abc_on:\n  mh_z19.abc_on(args.serial_console_untouched)\n  print (\"Set ABC logic as on.\")\nelif args.abc_off:\n  mh_z19.abc_off(args.serial_console_untouched)\n  print (\"Set ABC logic as off.\")\nelif args.span_point_calibration is not None:\n  mh_z19.span_point_calibration(args.span_point_calibration, args.serial_console_untouched)\n  print (\"Call Calibration with SPAN point.\")\nelif args.zero_point_calibration:\n  print (\"Call Calibration with ZERO point.\")\n  mh_z19.zero_point_calibration(args.serial_console_untouched)\nelif args.detection_range_10000:\n  mh_z19.detection_range_10000(args.serial_console_untouched)\n  print (\"Set Detection range as 10000.\")\nelif args.detection_range_5000:\n  mh_z19.detection_range_5000(args.serial_console_untouched)\n  print (\"Set Detection range as 5000.\")\nelif args.detection_range_2000:\n  mh_z19.detection_range_2000(args.serial_console_untouched)\n  print (\"Set Detection range as 2000.\")\nelif args.pwm:\n  print (mh_z19.read_from_pwm(gpio=args.pwm_gpio, range=args.pwm_range))\nelif args.version:\n  print (mh_z19.version)\nelif args.all:\n  value = mh_z19.read_all(args.serial_console_untouched)\n  print (json.dumps(value))\nelif args.co2valueonly:\n  value = mh_z19.read_co2valueonly(args.serial_console_untouched)\n  print (value)\nelse:\n  value = mh_z19.read(args.serial_console_untouched)\n  print (json.dumps(value))\n\nsys.exit(0)"
  },
  {
    "path": "pypi/mh_z19/pwm.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# © Takeyuki UEDA 2024 -\nimport time\n\n# import RPi.GPIO as GPIO\nfrom gpiozero import Button\n\n# exception\nclass GPIO_Edge_Timeout(Exception):\n  pass\n\n'''\ndef read_from_pwm_with_gpio(gpio=12, range=5000):\n  CYCLE_START_HIGHT_TIME = 2\n  TIMEOUT = 2000 # must be larger than PWM cycle time.\n\n  GPIO.setmode(GPIO.BCM)\n  GPIO.setup(gpio,GPIO.IN)\n\n  # wait falling ¯¯|_ to see end of last cycle\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  # wait rising __|¯ to catch the start of this cycle\n  channel = GPIO.wait_for_edge(gpio,GPIO.RISING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    rising = time.time() * 1000\n\n  # wait falling ¯¯|_ again to catch the end of TH duration\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    falling = time.time() * 1000\n\n  return {'co2': int(falling -rising - CYCLE_START_HIGHT_TIME) / 2 *(range/500)}\n'''\n\n# refer https://gpiozero.readthedocs.io/en/latest/migrating_from_rpigpio.html#input-devices\ndef read_from_pwm_with_gpiozero(gpio=12, range=5000):\n  CYCLE_START_HIGHT_TIME = 2\n  TIMEOUT = 2000 # must be larger than PWM cycle time.\n\n  '''\n  GPIO.setmode(GPIO.BCM)\n  GPIO.setup(gpio,GPIO.IN)\n  '''\n  btn = Button(gpio)\n\n  # wait falling ¯¯|_ to see end of last cycle\n  '''  \n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  '''\n  starting = time.time() * 1000\n  btn.wait_for_press(2) # 2 sec for timeout because 1sec cycle of pwm\n  last_falling = time.time() * 1000\n  if last_falling - starting > 1000:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  # wait rising __|¯ to catch the start of this cycle\n  '''\n  channel = GPIO.wait_for_edge(gpio,GPIO.RISING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    rising = time.time() * 1000\n  '''\n  starting = time.time() * 1000\n  btn.wait_for_release(2) # 2 sec for timeout because 1sec cycle of pwm\n  rising   = time.time() * 1000\n  if rising - starting > 1000:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  # wait falling ¯¯|_ again to catch the end of TH duration\n  '''\n  channel = GPIO.wait_for_edge(gpio, GPIO.FALLING, timeout=TIMEOUT)\n  if channel is None:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n  else:\n    falling = time.time() * 1000\n  '''\n  starting = time.time() * 1000\n  btn.wait_for_press(2) # 2 sec for timeout because 1sec cycle of pwm\n  falling  = time.time() * 1000\n  if falling - starting > 1000:\n    raise GPIO_Edge_Timeout(\"gpio {} edge timeout\".format(gpio))\n\n  return {'co2': int(falling -rising - CYCLE_START_HIGHT_TIME) / 2 *(range/500)}\n"
  },
  {
    "path": "pypi/setup.cfg",
    "content": "[metadata]\ndescription-file = README.md\n"
  },
  {
    "path": "pypi/setup.py",
    "content": "from setuptools import setup\nimport platform\n\nif platform.python_version_tuple()[0] == '2':\n  with open(\"README.md\") as f:\n    long_description = f.read()\nelse:\n  with open(\"README.md\", encoding='utf8') as f:\n    long_description = f.read()\n\nsetup(\n  name = 'mh_z19',\n  packages = ['mh_z19'], # this must be the same as the name above\n  version = '3.1.7',\n  description = 'mh-z19 CO2 concentration sensor library for All models of Raspberry Pi',\n  long_description=long_description,\n  long_description_content_type=\"text/markdown\",\n  author = 'Takeyuki UEDA',\n  author_email = 'gde00107@nifty.com',\n  license='MIT',\n  url = 'https://github.com/UedaTakeyuki/mh-z19', # use the URL to the github repo\n  keywords = ['sensor', 'IoT', 'Raspberry Pi', 'mh-z19', 'CO2'], # arbitrary keywords\n  classifiers = ['Development Status :: 5 - Production/Stable',\n                 'Programming Language :: Python',\n                 'Topic :: Terminals'\n  ],\n  install_requires=[\n    'getrpimodel>=0.1.26',\n    'pyserial',\n    'requests',\n    'argparse',\n#    'RPi.GPIO',\n    'gpiozero',\n    'lgpio'\n  ]\n)\n"
  },
  {
    "path": "read.ini",
    "content": "[mode]\n#run_mode=dummy\nrun_mode=real\n\n[valueid]\nco2=\n"
  },
  {
    "path": "read.py",
    "content": "# coding:utf-8\n# Copy Right Atelier UEDA  © 2015 -\n#\n# require: 'lol_dht' https://github.com/technion/lol_dht22\n#          \n# return:  {\"temp\": , \"humidity\":}\n\nimport os\nimport sys\nimport ConfigParser\nimport mh_z19\nimport traceback\nimport urllib3\nimport json\nimport requests\nfrom urllib3.exceptions import InsecureRequestWarning\n# refer http://73spica.tech/blog/requests-insecurerequestwarning-disable/\nurllib3.disable_warnings(InsecureRequestWarning)\n\n# get configration\nconfigfile = os.path.dirname(os.path.abspath(__file__))+'/'+os.path.splitext(os.path.basename(__file__))[0]+'.ini'\nini = ConfigParser.SafeConfigParser()\nini.read(configfile)\n\ndef read():\n  global ini\n  try:\n    if ini.get(\"mode\", \"run_mode\") == \"dummy\":\n      result = {\"co2\":400}\n    else:\n      result = mh_z19.read()\n    return result\n  except:\n    traceback.print_exc()\n\ndef send(valueid, value):\n  r = requests.post('https://monitor3.uedasoft.com/postvalue.php', data={'valueid': valueid, 'value': value}, timeout=10, verify=False)\n  print r.text\n\nif __name__ == '__main__':\n  values = read()\n  print json.dumps(values)\n  if values is not None:\n    if ini.get(\"valueid\", \"co2\"):\n      print \"co2 concentration sending...\"\n      send(ini.get(\"valueid\", \"co2\"), values['co2'])\n\n\n"
  },
  {
    "path": "send2monitor.ini",
    "content": "[valueid]\nco2=vpgqargj\n\n[server]\nurl=https://monitor3.uedasoft.com/postvalue.php\n\n[error_recovery]\nrecover_on=true\n#recover_on=false\ncounterfile=/tmp/sendcounter.txt\nthreshold=3\nrecover_command=sudo reboot\n\n"
  },
  {
    "path": "setid.sh",
    "content": "#!/bin/bash\n\nfunction usage() {\ncat <<_EOT_\nUsage:\n  $0 [your_view_id]\nDescription:\n  Set [your_view_id]\nOptions:\n_EOT_\nexit 1\n}\n\nif [ $# -ne 1 ]; then\n  usage\nfi\n\nsed -i \"s/^co2=.*/co2=$1/\" send2monitor.ini\n"
  },
  {
    "path": "setup.sh",
    "content": "sudo apt-get install python3-pip git-core\nsudo pip3 install mh_z19 pondslider incremental_counter error_counter --break-system-packages\nif [ ${cat /etc/debian_version} -lt 11 ] ; then\n  sudo apt-get install python-pip\n  sudo pip install mh_z19 pondslider incremental_counter error_counter\nfi\ngit clone https://github.com/UedaTakeyuki/handlers\nln -s handlers/value/sender/send2monitor/send2monitor.py\nsudo sed -i \"s/^enable_uart=.*/enable_uart=1/\" /boot/config.txt\nread -p \"Would you like to reboot now?  (y/n) :\" YN\nif [ \"${YN}\" = \"y\" ]; then\n  sudo reboot\nelse\n  exit 1;\nfi\n"
  }
]