├── .circleci └── config.yml ├── .credo.exs ├── .formatter.exs ├── .gitignore ├── CHANGELOG.md ├── LICENSES ├── Apache-2.0.txt ├── CC-BY-4.0.txt └── CC0-1.0.txt ├── NOTICE ├── README.md ├── REUSE.toml ├── config └── config.exs ├── lib ├── circuits_sim.ex └── circuits_sim │ ├── application.ex │ ├── device │ ├── ads7138.ex │ ├── aht20.ex │ ├── at24c02.ex │ ├── b5ze.ex │ ├── bmp3xx.ex │ ├── gpio_button.ex │ ├── gpio_led.ex │ ├── mcp23008.ex │ ├── pi4ioe5v6416lex.ex │ ├── sgp30.ex │ ├── sht4x.ex │ ├── tm1620.ex │ ├── vcnl4040.ex │ └── veml7700.ex │ ├── device_registry.ex │ ├── gpio │ ├── backend.ex │ ├── gpio_device.ex │ ├── gpio_server.ex │ └── handle.ex │ ├── i2c │ ├── backend.ex │ ├── bus.ex │ ├── i2c_device.ex │ ├── i2c_server.ex │ └── simple_i2c_device.ex │ ├── spi │ ├── backend.ex │ ├── bus.ex │ ├── spi_device.ex │ └── spi_server.ex │ └── tools.ex ├── mix.exs ├── mix.lock └── test ├── circuits_sim └── device │ ├── ads7138_test.exs │ ├── aht20_test.exs │ ├── at24c02_test.exs │ ├── bmp3xx_test.exs │ ├── mcp23008_test.exs │ ├── sgp30_test.exs │ ├── sht4x_test.exs │ ├── tm1620_test.exs │ ├── vcnl4040_test.exs │ └── veml7700_test.exs ├── circuits_sim_test.exs └── test_helper.exs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | latest: &latest 4 | pattern: "^1.18.*-erlang-27.*$" 5 | 6 | tags: &tags 7 | [ 8 | 1.18.2-erlang-27.2.1-alpine-3.21.2, 9 | 1.17.3-erlang-27.2-alpine-3.20.3, 10 | 1.16.3-erlang-26.2.5-alpine-3.19.1, 11 | 1.15.7-erlang-26.2.1-alpine-3.18.4, 12 | 1.14.5-erlang-25.3.2-alpine-3.17.3, 13 | 1.13.4-erlang-24.3.4-alpine-3.15.3 14 | ] 15 | 16 | jobs: 17 | check-license: 18 | docker: 19 | - image: fsfe/reuse:latest 20 | steps: 21 | - checkout 22 | - run: reuse lint 23 | 24 | build-test: 25 | parameters: 26 | tag: 27 | type: string 28 | docker: 29 | - image: hexpm/elixir:<< parameters.tag >> 30 | working_directory: ~/repo 31 | environment: 32 | LC_ALL: C.UTF-8 33 | steps: 34 | - run: 35 | name: Install system dependencies 36 | command: apk add --no-cache build-base linux-headers git 37 | - checkout 38 | - run: 39 | name: Install hex and rebar 40 | command: | 41 | mix local.hex --force 42 | mix local.rebar --force 43 | - restore_cache: 44 | keys: 45 | - v1-mix-cache-<< parameters.tag >>-{{ checksum "mix.lock" }} 46 | - run: mix deps.get 47 | - run: mix compile --warnings-as-errors 48 | - run: MIX_ENV=test mix compile --warnings-as-errors 49 | - run: mix test 50 | - when: 51 | condition: 52 | matches: { <<: *latest, value: << parameters.tag >> } 53 | steps: 54 | - run: mix format --check-formatted 55 | - run: mix deps.unlock --check-unused 56 | - run: mix docs 57 | - run: mix hex.build 58 | - run: mix credo -a --strict 59 | - run: mix dialyzer 60 | - save_cache: 61 | key: v1-mix-cache-<< parameters.tag >>-{{ checksum "mix.lock" }} 62 | paths: 63 | - _build 64 | - deps 65 | publish: 66 | docker: 67 | - image: hexpm/elixir:1.18.2-erlang-27.2.1-alpine-3.21.2 68 | steps: 69 | - checkout 70 | - run: 71 | name: Install packages 72 | command: | 73 | apk add --no-cache build-base linux-headers git github-cli 74 | - run: 75 | name: Publish GitHub release 76 | command: | 77 | sed -n "/^## $CIRCLE_TAG/,/^## /p" CHANGELOG.md | sed '1d; /^## /d' > RELEASE_NOTES 78 | gh release create $CIRCLE_TAG --notes "$(cat RELEASE_NOTES)" 79 | - run: 80 | name: Publish to hex.pm 81 | command: | 82 | mix deps.get 83 | mix hex.publish --yes 84 | 85 | workflows: 86 | checks: 87 | jobs: 88 | - check-license: 89 | filters: 90 | tags: 91 | only: /.*/ 92 | - build-test: 93 | name: << matrix.tag >> 94 | matrix: 95 | parameters: 96 | tag: *tags 97 | filters: 98 | tags: 99 | only: /.*/ 100 | - publish: 101 | requires: 102 | - build-test 103 | filters: 104 | tags: 105 | only: /^v.*/ 106 | branches: 107 | ignore: /.*/ 108 | -------------------------------------------------------------------------------- /.credo.exs: -------------------------------------------------------------------------------- 1 | # .credo.exs 2 | %{ 3 | configs: [ 4 | %{ 5 | name: "default", 6 | files: %{ 7 | included: ["lib/", "examples/"], 8 | excluded: ["lib/i2c/i2c_nif.ex"] 9 | }, 10 | strict: true, 11 | checks: [ 12 | {CredoBinaryPatterns.Check.Consistency.Pattern}, 13 | {Credo.Check.Refactor.MapInto, false}, 14 | {Credo.Check.Warning.LazyLogging, false}, 15 | {Credo.Check.Readability.LargeNumbers, only_greater_than: 86400}, 16 | {Credo.Check.Readability.ParenthesesOnZeroArityDefs, parens: true}, 17 | {Credo.Check.Readability.Specs, tags: []}, 18 | {Credo.Check.Readability.StrictModuleLayout, tags: []} 19 | ] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter,.credo}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | circuits_sim-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## v0.1.2 4 | 5 | * Changes 6 | * Support I2C devices returning errors and add experimental support for this 7 | on the SHT4X 8 | * Fix `I2CServer.send_message/1` with `SimpleI2CDevice` (@bithium) 9 | 10 | ## v0.1.1 11 | 12 | * Changes 13 | * Fix warning when creating input GPIOs. (@pojiro) 14 | * Fix Elixir 1.17 warnings 15 | 16 | ## v0.1.0 17 | 18 | Initial release 19 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /LICENSES/CC-BY-4.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution 4.0 International 2 | 3 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 4 | 5 | Using Creative Commons Public Licenses 6 | 7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | 9 | Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. 10 | 11 | Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. 12 | 13 | Creative Commons Attribution 4.0 International Public License 14 | 15 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 16 | 17 | Section 1 – Definitions. 18 | 19 | a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 20 | 21 | b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 22 | 23 | c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 24 | 25 | d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 26 | 27 | e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 28 | 29 | f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 30 | 31 | g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 32 | 33 | h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. 34 | 35 | i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 36 | 37 | j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 38 | 39 | k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 40 | 41 | Section 2 – Scope. 42 | 43 | a. License grant. 44 | 45 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 46 | 47 | A. reproduce and Share the Licensed Material, in whole or in part; and 48 | 49 | B. produce, reproduce, and Share Adapted Material. 50 | 51 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 52 | 53 | 3. Term. The term of this Public License is specified in Section 6(a). 54 | 55 | 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 56 | 57 | 5. Downstream recipients. 58 | 59 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 60 | 61 | B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 62 | 63 | 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 64 | 65 | b. Other rights. 66 | 67 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 68 | 69 | 2. Patent and trademark rights are not licensed under this Public License. 70 | 71 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. 72 | 73 | Section 3 – License Conditions. 74 | 75 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 76 | 77 | a. Attribution. 78 | 79 | 1. If You Share the Licensed Material (including in modified form), You must: 80 | 81 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 82 | 83 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 84 | 85 | ii. a copyright notice; 86 | 87 | iii. a notice that refers to this Public License; 88 | 89 | iv. a notice that refers to the disclaimer of warranties; 90 | 91 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 92 | 93 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 94 | 95 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 96 | 97 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 98 | 99 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 100 | 101 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 102 | 103 | Section 4 – Sui Generis Database Rights. 104 | 105 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 106 | 107 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; 108 | 109 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 110 | 111 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 112 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 113 | 114 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 115 | 116 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 117 | 118 | b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 119 | 120 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 121 | 122 | Section 6 – Term and Termination. 123 | 124 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 125 | 126 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 127 | 128 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 129 | 130 | 2. upon express reinstatement by the Licensor. 131 | 132 | c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 133 | 134 | d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 135 | 136 | e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 137 | 138 | Section 7 – Other Terms and Conditions. 139 | 140 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 141 | 142 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 143 | 144 | Section 8 – Interpretation. 145 | 146 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 147 | 148 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 149 | 150 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 151 | 152 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 153 | 154 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 155 | 156 | Creative Commons may be contacted at creativecommons.org. 157 | -------------------------------------------------------------------------------- /LICENSES/CC0-1.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | CircuitsSim is open-source software licensed under the Apache License, Version 2 | 2.0. 3 | 4 | Copyright holders include Frank Hunleth, Frank Hunleth, Mark Sebald, Frank 5 | Hunleth, Mark Sebald, Matt Ludwigs, Frank Hunleth, Mark Sebald, Matt Ludwigs, 6 | Connor Rigby, Eric Oestrich, Frank Hunleth, Connor Rigby, Jon Carstens, 7 | Masatoshi Nishiguchi, Filipe Alves and Ryota Kinukawa. 8 | 9 | Authoritative REUSE-compliant copyright and license metadata available at 10 | https://hex.pm/packages/circuits_sim. 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CircuitsSim 2 | 3 | [![Hex version](https://img.shields.io/hexpm/v/circuits_sim.svg "Hex version")](https://hex.pm/packages/circuits_sim) 4 | [![API docs](https://img.shields.io/hexpm/v/circuits_sim.svg?label=hexdocs "API docs")](https://hexdocs.pm/circuits_sim/CircuitsSim.html) 5 | [![CircleCI](https://dl.circleci.com/status-badge/img/gh/elixir-circuits/circuits_sim/tree/main.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/elixir-circuits/circuits_sim/tree/main) 6 | [![REUSE status](https://api.reuse.software/badge/github.com/elixir-circuits/circuits_sim)](https://api.reuse.software/info/github.com/elixir-circuits/circuits_sim) 7 | 8 | Interact with simulated hardware 9 | 10 | ## Using 11 | 12 | CircuitsSim requires Elixir Circuits 2.0 libraries. 13 | 14 | You may need to add `override: true` since not many libraries have been updated 15 | to allow Circuits 2.0 versions. Circuits 2.0 is mostly backwards compatible, so 16 | this should be safe. 17 | 18 | CircuitsSim works by providing an alternative backend for interacting with 19 | hardware. This is setup via `config/config.exs`. In your project, you may only 20 | want the simulated backends for `MIX_ENV=test` configurations, so you'll want to 21 | add the following appropriately. For trying it out, it's fine to start with 22 | adding this to `config.exs`: 23 | 24 | ```elixir 25 | config :circuits_i2c, default_backend: CircuitsSim.I2C.Backend 26 | config :circuits_spi, default_backend: CircuitsSim.SPI.Backend 27 | config :circuits_gpio, default_backend: CircuitsSim.GPIO.Backend 28 | ``` 29 | 30 | Note that you don't need to replace all backends. If you're only using I2C, 31 | there's no need to bring in SPI and GPIO support. 32 | 33 | ## Demo 34 | 35 | CircuitsSim takes a configuration for how to set up the simulated I2C buses and 36 | devices. Here's an example configuration: 37 | 38 | ```elixir 39 | config :circuits_sim, 40 | config: [ 41 | {CircuitsSim.Device.MCP23008, bus_name: "i2c-0", address: 0x20}, 42 | {CircuitsSim.Device.AT24C02, bus_name: "i2c-0", address: 0x50}, 43 | {CircuitsSim.Device.ADS7138, bus_name: "i2c-1", address: 0x10}, 44 | {CircuitsSim.Device.MCP23008, bus_name: "i2c-1", address: 0x20}, 45 | {CircuitsSim.Device.MCP23008, bus_name: "i2c-1", address: 0x21}, 46 | {CircuitsSim.Device.TM1620, bus_name: "spidev0.0", render: :binary_clock}, 47 | {CircuitsSim.Device.GPIOLED, gpio_spec: 10}, 48 | {CircuitsSim.Device.GPIOButton, gpio_spec: 11} 49 | ] 50 | ``` 51 | 52 | This shows two simulated I2C buses, `"i2c-0"` and `"i2c-1"`, one SPI bus, 53 | and two GPIO. 54 | The `"i2c-0"` bus has two devices, an MCP23008 GPIO expander and an AT24C02 55 | EEPROM. 56 | 57 | Here's how it looks when you run IEx: 58 | 59 | ```shell 60 | $ iex -S mix 61 | 62 | Interactive Elixir (1.14.3) - press Ctrl+C to exit (type h() ENTER for help) 63 | iex> Circuits.I2C.detect_devices 64 | Devices on I2C bus "i2c-1": 65 | * 16 (0x10) 66 | * 32 (0x20) 67 | * 33 (0x21) 68 | 69 | Devices on I2C bus "i2c-0": 70 | * 32 (0x20) 71 | * 80 (0x50) 72 | 73 | 5 devices detected on 2 I2C buses 74 | ``` 75 | 76 | You can then read and write to the I2C devices similar to how you'd interact 77 | with them for real. While they're obviously not real and have limitations, they 78 | can be super helpful in mocking I2C devices or debugging I2C interactions 79 | without hardware in the loop. 80 | 81 | ## Adding an I2C device 82 | 83 | Many I2C devices follow a simple pattern of exposing all operations as register 84 | reads and writes. If this is the case for your device, create a new module and 85 | implement the `CircuitsSim.I2C.SimpleI2CDevice` protocol. See 86 | `CircuitsSim.Device.MCP23008` for an example. 87 | 88 | If your device has a fancier interface, you'll need to implement the 89 | `CircuitsSim.I2C.I2CDevice` protocol which just passes the reads and writes 90 | through and doesn't handle conveniences like auto-incrementing register 91 | addresses on multi-byte reads and writes. See `CircuitsSim.Device.ADS7138` for 92 | an example. 93 | 94 | ## Adding a SPI device 95 | 96 | Simulated SPI devices implement the `CircuitsSim.SPI.SPIDevice` protocols. See 97 | `CircuitsSim.Device.TM1620` for an example. 98 | -------------------------------------------------------------------------------- /REUSE.toml: -------------------------------------------------------------------------------- 1 | version = 1 2 | 3 | [[annotations]] 4 | path = [ 5 | ".circleci/config.yml", 6 | ".credo.exs", 7 | ".formatter.exs", 8 | ".gitignore", 9 | "CHANGELOG.md", 10 | "NOTICE", 11 | "REUSE.toml", 12 | "mix.exs", 13 | "mix.lock" 14 | ] 15 | precedence = "aggregate" 16 | SPDX-FileCopyrightText = "None" 17 | SPDX-License-Identifier = "CC0-1.0" 18 | 19 | [[annotations]] 20 | path = [ 21 | "README.md" 22 | ] 23 | precedence = "aggregate" 24 | SPDX-FileCopyrightText = "2023 Frank Hunleth" 25 | SPDX-License-Identifier = "CC-BY-4.0" 26 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | import Config 7 | 8 | # Simulate a few devices 9 | config :circuits_sim, 10 | config: [ 11 | {CircuitsSim.Device.MCP23008, bus_name: "i2c-0", address: 0x20}, 12 | {CircuitsSim.Device.AT24C02, bus_name: "i2c-0", address: 0x50}, 13 | {CircuitsSim.Device.ADS7138, bus_name: "i2c-1", address: 0x10}, 14 | {CircuitsSim.Device.MCP23008, bus_name: "i2c-1", address: 0x20}, 15 | {CircuitsSim.Device.MCP23008, bus_name: "i2c-1", address: 0x21}, 16 | {CircuitsSim.Device.AHT20, bus_name: "i2c-1", address: 0x38}, 17 | {CircuitsSim.Device.SHT4X, bus_name: "i2c-1", address: 0x44}, 18 | {CircuitsSim.Device.VEML7700, bus_name: "i2c-1", address: 0x48}, 19 | {CircuitsSim.Device.SGP30, bus_name: "i2c-1", address: 0x58}, 20 | {CircuitsSim.Device.BMP3XX, bus_name: "i2c-1", address: 0x77}, 21 | {CircuitsSim.Device.TM1620, bus_name: "spidev0.0", render: :binary_clock}, 22 | {CircuitsSim.Device.GPIOLED, gpio_spec: 10}, 23 | {CircuitsSim.Device.GPIOButton, gpio_spec: 11} 24 | ] 25 | 26 | # Default to simulated versions of I2C, SPI, and GPIO 27 | config :circuits_i2c, default_backend: CircuitsSim.I2C.Backend 28 | config :circuits_spi, default_backend: CircuitsSim.SPI.Backend 29 | config :circuits_gpio, default_backend: CircuitsSim.GPIO.Backend 30 | -------------------------------------------------------------------------------- /lib/circuits_sim.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim do 6 | @moduledoc """ 7 | Circuits Simulator 8 | """ 9 | 10 | alias CircuitsSim.DeviceRegistry 11 | alias CircuitsSim.GPIO.GPIOServer 12 | alias CircuitsSim.I2C.I2CServer 13 | alias CircuitsSim.SPI.SPIServer 14 | 15 | @doc """ 16 | Show information about all simulated devices 17 | """ 18 | @spec info() :: :ok 19 | def info() do 20 | [i2c_info(), ?\n, spi_info(), ?\n, gpio_info()] 21 | |> IO.ANSI.format() 22 | |> IO.puts() 23 | end 24 | 25 | defp i2c_info() do 26 | DeviceRegistry.bus_names(:i2c) 27 | |> Enum.map(&i2c_bus_info/1) 28 | end 29 | 30 | defp i2c_bus_info(bus_name) do 31 | result = 32 | for address <- 0..127 do 33 | info = I2CServer.render(bus_name, address) 34 | hex_addr = CircuitsSim.Tools.hex_byte(address) 35 | if info != [], do: ["Device 0x#{hex_addr}: \n", info, "\n"], else: [] 36 | end 37 | 38 | ["=== ", bus_name, " ===\n", result] 39 | end 40 | 41 | defp spi_info() do 42 | DeviceRegistry.bus_names(:spi) 43 | |> Enum.map(&spi_bus_info/1) 44 | end 45 | 46 | defp spi_bus_info(bus_name) do 47 | result = SPIServer.render(bus_name) 48 | ["=== ", bus_name, " ===\n", result] 49 | end 50 | 51 | defp gpio_info() do 52 | DeviceRegistry.bus_names(:gpio) 53 | |> Enum.map(&gpio_spec_info/1) 54 | end 55 | 56 | defp gpio_spec_info(gpio_spec) do 57 | result = GPIOServer.render(gpio_spec) 58 | ["=== GPIO ", inspect(gpio_spec), " ===\n", result] 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /lib/circuits_sim/application.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Application do 6 | # See https://hexdocs.pm/elixir/Application.html 7 | # for more information on OTP Applications 8 | @moduledoc false 9 | 10 | use Application 11 | 12 | @impl Application 13 | def start(_type, _args) do 14 | children = [ 15 | {Registry, keys: :unique, name: CircuitSim.DeviceRegistry}, 16 | {DynamicSupervisor, name: CircuitSim.DeviceSupervisor, strategy: :one_for_one}, 17 | {Task, &add_devices/0} 18 | ] 19 | 20 | opts = [strategy: :one_for_one, name: CircuitsSim.Supervisor] 21 | Supervisor.start_link(children, opts) 22 | end 23 | 24 | defp add_devices() do 25 | config = Application.get_env(:circuits_sim, :config, %{}) 26 | 27 | Enum.each(config, fn device_options -> 28 | {:ok, _} = 29 | DynamicSupervisor.start_child( 30 | CircuitSim.DeviceSupervisor, 31 | device_spec(device_options) 32 | ) 33 | end) 34 | end 35 | 36 | defp device_spec(device) when is_atom(device) do 37 | {device, []} 38 | end 39 | 40 | defp device_spec({device, options} = device_options) 41 | when is_atom(device) and is_list(options) do 42 | device_options 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/ads7138.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.ADS7138 do 7 | @moduledoc """ 8 | MCP23008 8-bit I/O Expander 9 | 10 | Small, 8-Channel, 12-Bit ADC with I2C interface, GPIOs, and CRC. Supports 11 | addresses 0x10 to 0x17 12 | 13 | See the [datasheet](https://www.ti.com/lit/ds/symlink/ads7138.pdf) for details. 14 | Many features aren't implemented. 15 | """ 16 | alias CircuitsSim.I2C.I2CDevice 17 | alias CircuitsSim.I2C.I2CServer 18 | alias CircuitsSim.Tools 19 | 20 | defstruct registers: %{}, current: 0 21 | @type t() :: %__MODULE__{registers: map(), current: non_neg_integer()} 22 | 23 | @spec child_spec(keyword()) :: Supervisor.child_spec() 24 | def child_spec(args) do 25 | device = __MODULE__.new() 26 | I2CServer.child_spec_helper(device, args) 27 | end 28 | 29 | @spec new() :: %__MODULE__{current: 0, registers: %{}} 30 | def new() do 31 | %__MODULE__{} 32 | end 33 | 34 | defimpl I2CDevice do 35 | @single_register_read 0b00010000 36 | @single_register_write 0b00001000 37 | @continuous_register_read 0b00110000 38 | @continuous_register_write 0b00101000 39 | 40 | @impl I2CDevice 41 | def read(state, count) do 42 | # This isn't really supported since ADS7138 always requires a command to set a register 43 | # for reading, but we'll include it here just in case. 44 | last = state.current + count 45 | result = for reg <- state.current..last, into: <<>>, do: read_register(state, reg) 46 | {{:ok, result}, %{state | current: last}} 47 | end 48 | 49 | @impl I2CDevice 50 | def write(state, <<@single_register_write, register, value::binary>>) do 51 | put_in(state.registers[register], value) 52 | end 53 | 54 | def write(state, <<@continuous_register_write, register, values::binary>>) do 55 | current = 56 | for <>, reduce: register do 57 | reg -> 58 | write_register(state, reg, val) 59 | reg + 1 60 | end 61 | 62 | %{state | current: current - 1} 63 | end 64 | 65 | def write(state, <<>>) do 66 | state 67 | end 68 | 69 | @impl I2CDevice 70 | def write_read(state, <<@single_register_read, register>>, 1) do 71 | {{:ok, read_register(state, register)}, %{state | current: register}} 72 | end 73 | 74 | def write_read(state, <<@continuous_register_read, register>>, count) do 75 | last = state.current + count 76 | result = for reg <- state.current..last, into: <<>>, do: read_register(state, reg) 77 | {{:ok, result}, %{state | current: register}} 78 | end 79 | 80 | @impl I2CDevice 81 | def render(state) do 82 | for {reg, data} <- state.registers do 83 | [ 84 | " ", 85 | Tools.hex_byte(reg), 86 | ": ", 87 | for(<>, do: to_string(b)), 88 | " (", 89 | reg_name(reg), 90 | ")\n" 91 | ] 92 | end 93 | end 94 | 95 | @impl I2CDevice 96 | def handle_message(state, _message) do 97 | {:not_implemented, state} 98 | end 99 | 100 | defp read_register(state, register) do 101 | state.registers[register] || <<0>> 102 | end 103 | 104 | # Section 8.5.2.4 - "Writing data to addresses that do not exist 105 | # in the register map of the device have no effect." 106 | defp write_register(state, register, val) when register < 0xEB do 107 | put_in(state.registers[register], val) 108 | end 109 | 110 | defp write_register(state, _reg, _val), do: state 111 | 112 | defp reg_name(0x0), do: "SYSTEM_STATUS" 113 | defp reg_name(0x1), do: "GENERAL_CFG" 114 | defp reg_name(0x2), do: "DATA_CFG" 115 | defp reg_name(0x3), do: "OSR_CFG" 116 | defp reg_name(0x4), do: "OPMODE_CFG" 117 | defp reg_name(0x5), do: "PIN_CFG" 118 | defp reg_name(0x7), do: "GPIO_CFG" 119 | defp reg_name(0x9), do: "GPO_DRIVE_CFG" 120 | defp reg_name(0xB), do: "GPO_VALUE" 121 | defp reg_name(0xD), do: "GPI_VALUE" 122 | defp reg_name(0x10), do: "SEQUENCE_CFG" 123 | defp reg_name(0x11), do: "CHANNEL_SEL" 124 | defp reg_name(0x12), do: "AUTO_SEQ_CH_SEL" 125 | defp reg_name(0x14), do: "ALERT_CH_SEL" 126 | defp reg_name(0x16), do: "ALERT_MAP" 127 | defp reg_name(0x17), do: "ALERT_PIN_CFG" 128 | defp reg_name(0x18), do: "EVENT_FLAG" 129 | defp reg_name(0x1A), do: "EVENT_HIGH_FLAG" 130 | defp reg_name(0x1C), do: "EVENT_LOW_FLAG" 131 | defp reg_name(0x1E), do: "EVENT_RGN" 132 | defp reg_name(0x20), do: "HYSTERESIS_CH0" 133 | defp reg_name(0x21), do: "HIGH_TH_CH0" 134 | defp reg_name(0x22), do: "EVENT_COUNT_CH0" 135 | defp reg_name(0x23), do: "LOW_TH_CH0" 136 | defp reg_name(0x24), do: "HYSTERESIS_CH1" 137 | defp reg_name(0x25), do: "HIGH_TH_CH1" 138 | defp reg_name(0x26), do: "EVENT_COUNT_CH1" 139 | defp reg_name(0x27), do: "LOW_TH_CH1" 140 | defp reg_name(0x28), do: "HYSTERESIS_CH2" 141 | defp reg_name(0x29), do: "HIGH_TH_CH2" 142 | defp reg_name(0x2A), do: "EVENT_COUNT_CH2" 143 | defp reg_name(0x2B), do: "LOW_TH_CH2" 144 | defp reg_name(0x2C), do: "HYSTERESIS_CH3" 145 | defp reg_name(0x2D), do: "HIGH_TH_CH3" 146 | defp reg_name(0x2E), do: "EVENT_COUNT_CH3" 147 | defp reg_name(0x2F), do: "LOW_TH_CH3" 148 | defp reg_name(0x30), do: "HYSTERESIS_CH4" 149 | defp reg_name(0x31), do: "HIGH_TH_CH4" 150 | defp reg_name(0x32), do: "EVENT_COUNT_CH4" 151 | defp reg_name(0x33), do: "LOW_TH_CH4" 152 | defp reg_name(0x34), do: "HYSTERESIS_CH5" 153 | defp reg_name(0x35), do: "HIGH_TH_CH5" 154 | defp reg_name(0x36), do: "EVENT_COUNT_CH5" 155 | defp reg_name(0x37), do: "LOW_TH_CH5" 156 | defp reg_name(0x38), do: "HYSTERESIS_CH6" 157 | defp reg_name(0x39), do: "HIGH_TH_CH6" 158 | defp reg_name(0x3A), do: "EVENT_COUNT_CH6" 159 | defp reg_name(0x3B), do: "LOW_TH_CH6" 160 | defp reg_name(0x3C), do: "HYSTERESIS_CH7" 161 | defp reg_name(0x3D), do: "HIGH_TH_CH7" 162 | defp reg_name(0x3E), do: "EVENT_COUNT_CH7" 163 | defp reg_name(0x3F), do: "LOW_TH_CH7" 164 | defp reg_name(0x60), do: "MAX_CH0_LSB" 165 | defp reg_name(0x61), do: "MAX_CH0_MSB" 166 | defp reg_name(0x62), do: "MAX_CH1_LSB" 167 | defp reg_name(0x63), do: "MAX_CH1_MSB" 168 | defp reg_name(0x64), do: "MAX_CH2_LSB" 169 | defp reg_name(0x65), do: "MAX_CH2_MSB" 170 | defp reg_name(0x66), do: "MAX_CH3_LSB" 171 | defp reg_name(0x67), do: "MAX_CH3_MSB" 172 | defp reg_name(0x68), do: "MAX_CH4_LSB" 173 | defp reg_name(0x69), do: "MAX_CH4_MSB" 174 | defp reg_name(0x6A), do: "MAX_CH5_LSB" 175 | defp reg_name(0x6B), do: "MAX_CH5_MSB" 176 | defp reg_name(0x6C), do: "MAX_CH6_LSB" 177 | defp reg_name(0x6D), do: "MAX_CH6_MSB" 178 | defp reg_name(0x6E), do: "MAX_CH7_LSB" 179 | defp reg_name(0x6F), do: "MAX_CH7_MSB" 180 | defp reg_name(0x80), do: "MIN_CH0_LSB" 181 | defp reg_name(0x81), do: "MIN_CH0_MSB" 182 | defp reg_name(0x82), do: "MIN_CH1_LSB" 183 | defp reg_name(0x83), do: "MIN_CH1_MSB" 184 | defp reg_name(0x84), do: "MIN_CH2_LSB" 185 | defp reg_name(0x85), do: "MIN_CH2_MSB" 186 | defp reg_name(0x86), do: "MIN_CH3_LSB" 187 | defp reg_name(0x87), do: "MIN_CH3_MSB" 188 | defp reg_name(0x88), do: "MIN_CH4_LSB" 189 | defp reg_name(0x89), do: "MIN_CH4_MSB" 190 | defp reg_name(0x8A), do: "MIN_CH5_LSB" 191 | defp reg_name(0x8B), do: "MIN_CH5_MSB" 192 | defp reg_name(0x8C), do: "MIN_CH6_LSB" 193 | defp reg_name(0x8D), do: "MIN_CH6_MSB" 194 | defp reg_name(0x8E), do: "MIN_CH7_LSB" 195 | defp reg_name(0x8F), do: "MIN_CH7_MSB" 196 | defp reg_name(0xA0), do: "RECENT_CH0_LSB" 197 | defp reg_name(0xA1), do: "RECENT_CH0_MSB" 198 | defp reg_name(0xA2), do: "RECENT_CH1_LSB" 199 | defp reg_name(0xA3), do: "RECENT_CH1_MSB" 200 | defp reg_name(0xA4), do: "RECENT_CH2_LSB" 201 | defp reg_name(0xA5), do: "RECENT_CH2_MSB" 202 | defp reg_name(0xA6), do: "RECENT_CH3_LSB" 203 | defp reg_name(0xA7), do: "RECENT_CH3_MSB" 204 | defp reg_name(0xA8), do: "RECENT_CH4_LSB" 205 | defp reg_name(0xA9), do: "RECENT_CH4_MSB" 206 | defp reg_name(0xAA), do: "RECENT_CH5_LSB" 207 | defp reg_name(0xAB), do: "RECENT_CH5_MSB" 208 | defp reg_name(0xAC), do: "RECENT_CH6_LSB" 209 | defp reg_name(0xAD), do: "RECENT_CH6_MSB" 210 | defp reg_name(0xAE), do: "RECENT_CH7_LSB" 211 | defp reg_name(0xAF), do: "RECENT_CH7_MSB" 212 | defp reg_name(0xC3), do: "GPO0_TRIG_EVENT_SEL" 213 | defp reg_name(0xC5), do: "GPO1_TRIG_EVENT_SEL" 214 | defp reg_name(0xC7), do: "GPO2_TRIG_EVENT_SEL" 215 | defp reg_name(0xC9), do: "GPO3_TRIG_EVENT_SEL" 216 | defp reg_name(0xCB), do: "GPO4_TRIG_EVENT_SEL" 217 | defp reg_name(0xCD), do: "GPO5_TRIG_EVENT_SEL" 218 | defp reg_name(0xCF), do: "GPO6_TRIG_EVENT_SEL" 219 | defp reg_name(0xD1), do: "GPO7_TRIG_EVENT_SEL" 220 | defp reg_name(0xE9), do: "GPO_TRIGGER_CFG" 221 | defp reg_name(0xEB), do: "GPO_VALUE_TRIG" 222 | end 223 | end 224 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/aht20.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # SPDX-FileCopyrightText: 2025 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.AHT20 do 7 | @moduledoc """ 8 | AHT20 temperature and humidity sensor 9 | 10 | Typically found at 0x38 11 | See the [datasheet](https://cdn-learn.adafruit.com/assets/assets/000/091/676/original/AHT20-datasheet-2020-4-16.pdf) 12 | Many features aren't implemented. 13 | 14 | Call `set_humidity_rh/3` and `set_temperature_c/3` to change the state of the sensor. 15 | """ 16 | alias CircuitsSim.I2C.I2CDevice 17 | alias CircuitsSim.I2C.I2CServer 18 | 19 | defstruct current: nil, humidity_rh: 50.0, temperature_c: 20.0 20 | @type t() :: %__MODULE__{current: atom(), humidity_rh: float(), temperature_c: float()} 21 | 22 | @spec child_spec(keyword()) :: Supervisor.child_spec() 23 | def child_spec(args) do 24 | device = __MODULE__.new() 25 | I2CServer.child_spec_helper(device, args) 26 | end 27 | 28 | @spec new() :: %__MODULE__{current: nil, humidity_rh: float(), temperature_c: float()} 29 | def new() do 30 | %__MODULE__{} 31 | end 32 | 33 | @spec set_humidity_rh(String.t(), Circuits.I2C.address(), number()) :: :ok 34 | def set_humidity_rh(bus_name, address, value) when is_number(value) do 35 | I2CServer.send_message(bus_name, address, {:set_humidity_rh, value}) 36 | end 37 | 38 | @spec set_temperature_c(String.t(), Circuits.I2C.address(), number()) :: :ok 39 | def set_temperature_c(bus_name, address, value) when is_number(value) do 40 | I2CServer.send_message(bus_name, address, {:set_temperature_c, value}) 41 | end 42 | 43 | ## protocol implementation 44 | 45 | defimpl I2CDevice do 46 | @impl I2CDevice 47 | def read(%{current: :measure} = state, count) do 48 | result = raw_sample(state) |> trim_pad(count) 49 | {{:ok, result}, %{state | current: nil}} 50 | end 51 | 52 | def read(state, count) do 53 | {{:ok, :binary.copy(<<0>>, count)}, %{state | current: nil}} 54 | end 55 | 56 | @impl I2CDevice 57 | def write(state, <<0xBA>>), do: %{state | current: :reset} 58 | def write(state, <<0xBE, 0x08, 0x00>>), do: %{state | current: :init} 59 | def write(state, <<0xAC, 0x33, 0x00>>), do: %{state | current: :measure} 60 | def write(state, _), do: state 61 | 62 | @impl I2CDevice 63 | def write_read(state, _to_write, read_count) do 64 | {{:ok, :binary.copy(<<0>>, read_count)}, %{state | current: :reset}} 65 | end 66 | 67 | defp trim_pad(x, count) when byte_size(x) >= count, do: :binary.part(x, 0, count) 68 | defp trim_pad(x, count), do: x <> :binary.copy(<<0>>, count - byte_size(x)) 69 | 70 | @impl I2CDevice 71 | def render(state) do 72 | humidity_rh = Float.round(state.humidity_rh * 1.0, 3) 73 | temperature_c = Float.round(state.temperature_c * 1.0, 3) 74 | "Temperature: #{temperature_c}°C, Relative humidity: #{humidity_rh}%" 75 | end 76 | 77 | @impl I2CDevice 78 | def handle_message(state, {:set_humidity_rh, value}) do 79 | {:ok, %{state | humidity_rh: value}} 80 | end 81 | 82 | def handle_message(state, {:set_temperature_c, value}) do 83 | {:ok, %{state | temperature_c: value}} 84 | end 85 | 86 | defp raw_sample(state) do 87 | raw_humidity = round(1_048_576 * state.humidity_rh / 100) 88 | raw_temperature = round((state.temperature_c + 50) * 1_048_576 / 200) 89 | <<0, raw_humidity::20, raw_temperature::20, 0>> 90 | end 91 | end 92 | end 93 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/at24c02.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.AT24C02 do 7 | @moduledoc """ 8 | This is a 2 Kb (256 byte) I2C EEPROM 9 | 10 | This does not implementing the paging, so it's forgiving of writes across 11 | EEPROM write pages. If you use a real AT24C02, make sure not to cross 8-byte 12 | boundaries when writing more than one byte. 13 | """ 14 | alias CircuitsSim.I2C.I2CServer 15 | alias CircuitsSim.I2C.SimpleI2CDevice 16 | alias CircuitsSim.Tools 17 | 18 | defstruct [:contents] 19 | 20 | # There's got to be a better way to type a 256-tuple 21 | @type t() :: %__MODULE__{ 22 | contents: 23 | {:_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 24 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 25 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 26 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 27 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 28 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 29 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 30 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 31 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 32 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 33 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 34 | :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, :_, 35 | :_, :_, :_, :_} 36 | } 37 | 38 | @spec child_spec(keyword()) :: Supervisor.child_spec() 39 | def child_spec(args) do 40 | device = __MODULE__.new() 41 | I2CServer.child_spec_helper(device, args) 42 | end 43 | 44 | @spec new() :: t() 45 | def new() do 46 | %__MODULE__{contents: Tuple.duplicate(0xFF, 256)} 47 | end 48 | 49 | defimpl SimpleI2CDevice do 50 | @impl SimpleI2CDevice 51 | def write_register(state, reg, value) do 52 | %{state | contents: put_elem(state.contents, reg, value)} 53 | end 54 | 55 | @impl SimpleI2CDevice 56 | def read_register(state, reg) do 57 | {elem(state.contents, reg), state} 58 | end 59 | 60 | @impl SimpleI2CDevice 61 | def render(state) do 62 | header = for i <- 0..15, do: [" ", Integer.to_string(i, 16)] 63 | 64 | [ 65 | " ", 66 | header, 67 | "\n", 68 | for i <- 0..255 do 69 | front = if rem(i, 16) == 0, do: [Tools.hex_byte(i), ": "], else: [] 70 | v = elem(state.contents, i) 71 | term = if rem(i, 16) == 15, do: "\n", else: " " 72 | [front, Tools.hex_byte(v), term] 73 | end 74 | ] 75 | end 76 | 77 | @impl SimpleI2CDevice 78 | def handle_message(state, _message) do 79 | state 80 | end 81 | end 82 | end 83 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/b5ze.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.B5ZE do 7 | @moduledoc """ 8 | Abracon AB-RTCMC-32.768kHz-IBO5-S3 RTC 9 | 10 | Typically found at 0x68 11 | 12 | See the [datasheet](https://abracon.com/Support/AppsManuals/Precisiontiming/Application%20Manual%20AB-RTCMC-32.768kHz-IBO5-S3.pdf) for details. 13 | """ 14 | alias CircuitsSim.I2C.I2CServer 15 | alias CircuitsSim.I2C.SimpleI2CDevice 16 | alias CircuitsSim.Tools 17 | 18 | @spec child_spec(keyword()) :: Supervisor.child_spec() 19 | def child_spec(args) do 20 | device = __MODULE__.new() 21 | I2CServer.child_spec_helper(device, args) 22 | end 23 | 24 | defstruct registers: %{} 25 | 26 | @type t() :: %__MODULE__{registers: map()} 27 | 28 | @spec new() :: t() 29 | def new() do 30 | %__MODULE__{registers: for(r <- 0x00..0x13, into: %{}, do: {r, <<0>>})} 31 | end 32 | 33 | defimpl SimpleI2CDevice do 34 | @impl SimpleI2CDevice 35 | def write_register(state, reg, value), do: put_in(state.registers[reg], <>) 36 | 37 | @impl SimpleI2CDevice 38 | def read_register(state, reg), do: {state.registers[reg], state} 39 | 40 | @impl SimpleI2CDevice 41 | def render(state) do 42 | for {reg, data} <- state.registers do 43 | [ 44 | " ", 45 | Tools.hex_byte(reg), 46 | ": ", 47 | for(<>, do: to_string(b)), 48 | " (", 49 | reg_name(reg), 50 | ")\n" 51 | ] 52 | end 53 | end 54 | 55 | @impl SimpleI2CDevice 56 | def handle_message(state, _message) do 57 | state 58 | end 59 | 60 | defp reg_name(0x00), do: "Control 1" 61 | defp reg_name(0x01), do: "Control 2" 62 | defp reg_name(0x02), do: "Control 3" 63 | defp reg_name(0x03), do: "Seconds" 64 | defp reg_name(0x04), do: "Minutes" 65 | defp reg_name(0x05), do: "Hours" 66 | defp reg_name(0x06), do: "Days" 67 | defp reg_name(0x07), do: "Weekdays" 68 | defp reg_name(0x08), do: "Months" 69 | defp reg_name(0x09), do: "Years" 70 | defp reg_name(0x0A), do: "Minute Alarm" 71 | defp reg_name(0x0B), do: "Hour Alarm" 72 | defp reg_name(0x0C), do: "Day Alarm" 73 | defp reg_name(0x0D), do: "Weekday Alarm" 74 | defp reg_name(0x0E), do: "Frequency Offset" 75 | defp reg_name(0x0F), do: "Timer & CLKOUT" 76 | defp reg_name(0x10), do: "Timer A Clock" 77 | defp reg_name(0x11), do: "Timer A" 78 | defp reg_name(0x12), do: "Timer B Clock" 79 | defp reg_name(0x13), do: "Timer B" 80 | end 81 | end 82 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/bmp3xx.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.BMP3XX do 6 | @moduledoc """ 7 | Bosch BMP3XX sensors. 8 | 9 | Most sensors are at address 0x77, but some are at 0x76. 10 | See the [datasheet](https://www.mouser.com/datasheet/2/783/BST-BME280-DS002-1509607.pdf) for details. 11 | Many features aren't implemented. 12 | """ 13 | alias CircuitsSim.I2C.I2CServer 14 | alias CircuitsSim.I2C.SimpleI2CDevice 15 | 16 | @spec child_spec(keyword()) :: Supervisor.child_spec() 17 | def child_spec(args) do 18 | device_options = Keyword.take(args, [:sensor_type]) 19 | device = __MODULE__.new(device_options) 20 | I2CServer.child_spec_helper(device, args) 21 | end 22 | 23 | defstruct registers: %{}, sensor_type: nil 24 | 25 | @type sensor_type() :: :bmp380 | :bmp390 | :bmp180 | :bmp280 | :bme280 | :bme680 26 | @type options() :: [sensor_type: sensor_type()] 27 | @type t() :: %__MODULE__{registers: map(), sensor_type: sensor_type()} 28 | 29 | @spec new(options()) :: t() 30 | def new(options \\ []) do 31 | sensor_type = options[:sensor_type] || :bmp380 32 | %__MODULE__{registers: default_registers(sensor_type), sensor_type: sensor_type} 33 | end 34 | 35 | @spec default_registers(atom) :: %{byte => byte} 36 | def default_registers(sensor_type) do 37 | for(r <- 0x00..0xFF, into: %{}, do: {r, 0}) 38 | |> Map.merge(sensor_type_register(sensor_type)) 39 | |> Map.merge(calibration_registers(sensor_type)) 40 | |> Map.merge(measurement_registers(sensor_type)) 41 | end 42 | 43 | defp sensor_type_register(:bmp380), do: %{0x00 => 0x50} 44 | defp sensor_type_register(:bmp390), do: %{0x00 => 0x60} 45 | defp sensor_type_register(:bmp180), do: %{0xD0 => 0x55} 46 | defp sensor_type_register(:bmp280), do: %{0xD0 => 0x58} 47 | defp sensor_type_register(:bme280), do: %{0xD0 => 0x60} 48 | defp sensor_type_register(:bme680), do: %{0xD0 => 0x61} 49 | 50 | @spec calibration_registers(atom) :: %{byte => byte} 51 | def calibration_registers(sensor_type) when sensor_type in [:bmp380, :bmp390] do 52 | <<0x236B5849F65CFFCEF42300EA636E79F3F6AA4312C4::8*21>> 53 | |> binary_to_address_byte_map({0x31, 21}) 54 | end 55 | 56 | def calibration_registers(:bmp180) do 57 | <<0x1926FBB9C8C885D5644C3F81197300288000D1F60968::8*22>> 58 | |> binary_to_address_byte_map({0xAA, 22}) 59 | end 60 | 61 | def calibration_registers(:bmp280) do 62 | <<0x1D6EAD6632001B8F38D6D00B542B0FFFF9FF0C3020D18813::8*24>> 63 | |> binary_to_address_byte_map({0x88, 24}) 64 | end 65 | 66 | def calibration_registers(:bme280) do 67 | calib00 = 68 | <<0x1D6EAD6632001B8F38D6D00B542B0FFFF9FF0C3020D18813004B::8*26>> 69 | |> binary_to_address_byte_map({0x88, 26}) 70 | 71 | calib26 = 72 | <<82, 1, 0, 23, 44, 3, 30>> 73 | |> binary_to_address_byte_map({0xE1, 7}) 74 | 75 | Map.merge(calib00, calib26) 76 | end 77 | 78 | def calibration_registers(:bme680) do 79 | coeff1 = 80 | <<0xB2660310438A5BD75800E4128AFF1A1E000003FDD9F21E::8*23>> 81 | |> binary_to_address_byte_map({0x8A, 23}) 82 | 83 | coeff2 = 84 | <<63, 221, 44, 0, 45, 20, 120, 156, 83, 102, 175, 232, 226, 18>> 85 | |> binary_to_address_byte_map({0xE1, 14}) 86 | 87 | coeff3 = 88 | <<50, 170, 22, 74, 19>> 89 | |> binary_to_address_byte_map({0x00, 5}) 90 | 91 | coeff1 |> Map.merge(coeff2) |> Map.merge(coeff3) 92 | end 93 | 94 | @spec measurement_registers(atom, any) :: %{byte => byte} 95 | def measurement_registers(_sensor_type, _options \\ nil) 96 | 97 | def measurement_registers(sensor_type, _) when sensor_type in [:bmp380, :bmp390] do 98 | <<151, 159, 109, 115, 216, 133>> 99 | |> binary_to_address_byte_map({0x04, 6}) 100 | end 101 | 102 | def measurement_registers(:bmp180, :temperature) do 103 | <<95, 16, 0>> 104 | |> binary_to_address_byte_map({0xF6, 3}) 105 | end 106 | 107 | def measurement_registers(:bmp180, :pressure) do 108 | <<161, 135, 0>> 109 | |> binary_to_address_byte_map({0xF6, 3}) 110 | end 111 | 112 | def measurement_registers(:bmp180, _) do 113 | temperature = measurement_registers(:bmp180, :temperature) 114 | pressure = measurement_registers(:bmp180, :pressure) 115 | Map.merge(temperature, pressure) 116 | end 117 | 118 | def measurement_registers(:bmp280, _) do 119 | <<69, 89, 64, 130, 243, 0>> 120 | |> binary_to_address_byte_map({0xF7, 6}) 121 | end 122 | 123 | def measurement_registers(:bme280, _) do 124 | <<69, 89, 64, 130, 243, 0, 137, 109>> 125 | |> binary_to_address_byte_map({0xF7, 8}) 126 | end 127 | 128 | def measurement_registers(:bme680, _) do 129 | pres_msb = 130 | <<96, 30, 144, 117, 93, 192, 65, 180>> 131 | |> binary_to_address_byte_map({0x1F, 8}) 132 | 133 | gas_r_msb = 134 | <<166, 139>> 135 | |> binary_to_address_byte_map({0x2A, 2}) 136 | 137 | Map.merge(pres_msb, gas_r_msb) 138 | end 139 | 140 | defp binary_to_address_byte_map(data, {address, how_many}) do 141 | addresses = address..(address + how_many - 1) 142 | bytes = for(<>, do: r) 143 | Enum.zip(addresses, bytes) |> Map.new() 144 | end 145 | 146 | ## protocol implementation 147 | 148 | defimpl SimpleI2CDevice do 149 | alias CircuitsSim.Device.BMP3XX, as: BMP3Sim 150 | 151 | # https://cdn-shop.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf 152 | @bmp180_reg_control_measurement 0xF4 153 | @bmp180_pressure_measurement 0x34 154 | @bmp180_temperature_measurement 0x2E 155 | @bme680_reg_status0 0x1D 156 | 157 | @impl SimpleI2CDevice 158 | def write_register(state, @bmp180_reg_control_measurement, @bmp180_pressure_measurement) 159 | when state.sensor_type == :bmp180 do 160 | registers = Map.merge(state.registers, BMP3Sim.measurement_registers(:bmp180, :pressure)) 161 | %{state | registers: registers} 162 | end 163 | 164 | def write_register(state, @bmp180_reg_control_measurement, @bmp180_temperature_measurement) 165 | when state.sensor_type == :bmp180 do 166 | registers = Map.merge(state.registers, BMP3Sim.measurement_registers(:bmp180, :temperature)) 167 | %{state | registers: registers} 168 | end 169 | 170 | def write_register(state, reg, value) do 171 | put_in(state.registers[reg], value) 172 | end 173 | 174 | @impl SimpleI2CDevice 175 | def read_register(state, @bme680_reg_status0) when state.sensor_type == :bme680 do 176 | registers = Map.merge(state.registers, BMP3Sim.measurement_registers(:bme680)) 177 | 178 | new_data = 1 179 | result = <> 180 | {result, %{state | registers: registers}} 181 | end 182 | 183 | def read_register(state, reg) do 184 | {state.registers[reg], state} 185 | end 186 | 187 | @impl SimpleI2CDevice 188 | def render(state) do 189 | "Sensor type: #{state.sensor_type}" 190 | end 191 | 192 | @impl SimpleI2CDevice 193 | def handle_message(state, _message) do 194 | {:not_implemented, state} 195 | end 196 | end 197 | end 198 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/gpio_button.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.GPIOButton do 6 | @moduledoc """ 7 | This is simple GPIO-connected button 8 | 9 | Buttons can be connected in a few ways: 10 | 11 | * `:external_pullup` - 0 is pressed, 1 is released 12 | * `:external_pulldown` - 1 is pressed, 0 is released 13 | * `:internal_pullup` - 0 is pressed. The GPIO will need to be configured in pullup mode for releases to be 1. 14 | * `:internal_pulldown` - 1 is pressed. The GPIO will need to be configured in pulldown mode for releases to be 0. 15 | 16 | Call `press/1` and `release/1` to change the state of the button. 17 | """ 18 | alias Circuits.GPIO 19 | alias CircuitsSim.GPIO.GPIODevice 20 | alias CircuitsSim.GPIO.GPIOServer 21 | 22 | @type connection_mode() :: 23 | :external_pullup | :external_pulldown | :internal_pullup | :internal_pulldown 24 | 25 | defstruct state: :released, connection: :external_pullup 26 | 27 | @type t() :: %__MODULE__{state: :pressed | :released, connection: connection_mode()} 28 | 29 | @type options() :: [connection: connection_mode()] 30 | 31 | @spec child_spec(options()) :: %{ 32 | id: GPIOServer, 33 | start: {GPIOServer, :start_link, [[keyword()], ...]} 34 | } 35 | def child_spec(args) do 36 | device = new(args) 37 | GPIOServer.child_spec_helper(device, args) 38 | end 39 | 40 | @spec new(options()) :: t() 41 | def new(options) do 42 | %__MODULE__{connection: Keyword.get(options, :connection, :external_pullup)} 43 | end 44 | 45 | @doc """ 46 | Press the button 47 | 48 | Pass in a duration in milliseconds to automatically release the button after 49 | a timeout. 50 | """ 51 | @spec press(GPIO.gpio_spec(), non_neg_integer() | :infinity) :: :ok 52 | def press(gpio_spec, duration \\ :infinity) 53 | when duration == :infinity or (duration > 0 and duration < 10000) do 54 | GPIOServer.send_message(gpio_spec, {:press, duration}) 55 | end 56 | 57 | @doc """ 58 | Release the button 59 | """ 60 | @spec release(GPIO.gpio_spec()) :: :ok 61 | def release(gpio_spec) do 62 | GPIOServer.send_message(gpio_spec, :release) 63 | end 64 | 65 | defimpl GPIODevice do 66 | @impl GPIODevice 67 | def write(state, _value) do 68 | # Ignore 69 | state 70 | end 71 | 72 | @impl GPIODevice 73 | def read(%{state: :pressed, connection: :external_pullup}), do: 0 74 | def read(%{state: :released, connection: :external_pullup}), do: 1 75 | def read(%{state: :pressed, connection: :external_pulldown}), do: 1 76 | def read(%{state: :released, connection: :external_pulldown}), do: 0 77 | def read(%{state: :pressed, connection: :internal_pullup}), do: 0 78 | def read(%{state: :released, connection: :internal_pullup}), do: :hi_z 79 | def read(%{state: :pressed, connection: :internal_pulldown}), do: 1 80 | def read(%{state: :released, connection: :internal_pulldown}), do: :hi_z 81 | 82 | @impl GPIODevice 83 | def render(state) do 84 | "Button #{state.state} connected with #{state.connection}" 85 | end 86 | 87 | @impl GPIODevice 88 | def handle_message(state, {:press, duration}) do 89 | if duration != :infinity do 90 | # Don't try to do anything fancy with timeouts 91 | _ = Process.send_after(self(), :release, duration) 92 | :ok 93 | end 94 | 95 | {:ok, %{state | state: :pressed}} 96 | end 97 | 98 | def handle_message(state, :release) do 99 | {:ok, %{state | state: :released}} 100 | end 101 | 102 | @impl GPIODevice 103 | def handle_info(state, :release) do 104 | %{state | state: :released} 105 | end 106 | end 107 | end 108 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/gpio_led.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.GPIOLED do 6 | @moduledoc """ 7 | This is simple GPIO-connected LED 8 | """ 9 | 10 | alias CircuitsSim.GPIO.GPIODevice 11 | alias CircuitsSim.GPIO.GPIOServer 12 | 13 | defstruct value: 0 14 | @type t() :: %__MODULE__{value: 0 | 1} 15 | 16 | @spec child_spec(keyword()) :: Supervisor.child_spec() 17 | def child_spec(args) do 18 | device = __MODULE__.new() 19 | GPIOServer.child_spec_helper(device, args) 20 | end 21 | 22 | @spec new() :: %__MODULE__{value: 0} 23 | def new() do 24 | %__MODULE__{} 25 | end 26 | 27 | defimpl GPIODevice do 28 | @impl GPIODevice 29 | def write(state, value) do 30 | %{state | value: value} 31 | end 32 | 33 | @impl GPIODevice 34 | def read(_state) do 35 | :hi_z 36 | end 37 | 38 | @impl GPIODevice 39 | def render(state) do 40 | ["LED ", led_string(state.value)] 41 | end 42 | 43 | defp led_string(0), do: "off" 44 | defp led_string(1), do: "on" 45 | 46 | @impl GPIODevice 47 | def handle_message(state, _message) do 48 | {:ok, state} 49 | end 50 | 51 | @impl GPIODevice 52 | def handle_info(state, :release) do 53 | state 54 | end 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/mcp23008.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.MCP23008 do 6 | @moduledoc """ 7 | MCP23008 8-bit I/O Expander 8 | 9 | This is a simple I2C GPIO Expander that's normally found at I2C addresses between 0x20 and 0x27. 10 | 11 | See the [datasheet](https://www.microchip.com/en-us/product/MCP23008) for details. 12 | Many features aren't implemented. 13 | """ 14 | alias CircuitsSim.I2C.I2CServer 15 | alias CircuitsSim.I2C.SimpleI2CDevice 16 | 17 | @spec child_spec(keyword()) :: Supervisor.child_spec() 18 | def child_spec(args) do 19 | device = __MODULE__.new() 20 | I2CServer.child_spec_helper(device, args) 21 | end 22 | 23 | defstruct [ 24 | :iodir, 25 | :ipol, 26 | :gpinten, 27 | :defval, 28 | :intcon, 29 | :iocon, 30 | :gppu, 31 | :intf, 32 | :intcap, 33 | :gpio, 34 | :olat 35 | ] 36 | 37 | @type t() :: %__MODULE__{ 38 | iodir: byte(), 39 | ipol: byte(), 40 | gpinten: byte(), 41 | defval: byte(), 42 | intcon: byte(), 43 | iocon: byte(), 44 | gppu: byte(), 45 | intf: byte(), 46 | intcap: byte(), 47 | gpio: byte(), 48 | olat: byte() 49 | } 50 | 51 | @spec new() :: %__MODULE__{ 52 | :defval => 0, 53 | :gpinten => 0, 54 | :gpio => 0, 55 | :gppu => 0, 56 | :intcap => 0, 57 | :intcon => 0, 58 | :intf => 0, 59 | :iocon => 0, 60 | :iodir => 255, 61 | :ipol => 0, 62 | :olat => 0 63 | } 64 | def new() do 65 | %__MODULE__{ 66 | iodir: 0xFF, 67 | ipol: 0, 68 | gpinten: 0, 69 | defval: 0, 70 | intcon: 0, 71 | iocon: 0, 72 | gppu: 0, 73 | intf: 0, 74 | intcap: 0, 75 | gpio: 0, 76 | olat: 0 77 | } 78 | end 79 | 80 | defimpl SimpleI2CDevice do 81 | @impl SimpleI2CDevice 82 | def write_register(state, 0, value), do: %{state | iodir: value} 83 | def write_register(state, 1, value), do: %{state | ipol: value} 84 | def write_register(state, 2, value), do: %{state | gpinten: value} 85 | def write_register(state, 3, value), do: %{state | defval: value} 86 | def write_register(state, 4, value), do: %{state | intcon: value} 87 | def write_register(state, 5, value), do: %{state | iocon: Bitwise.band(value, 0x3E)} 88 | def write_register(state, 6, value), do: %{state | gppu: value} 89 | def write_register(state, 7, _value), do: state 90 | def write_register(state, 8, _value), do: state 91 | 92 | def write_register(state, 9, value) do 93 | result = Bitwise.band(Bitwise.bnot(state.iodir), value) 94 | %{state | gpio: result, olat: result} 95 | end 96 | 97 | def write_register(state, 10, value), do: write_register(state, 9, value) 98 | def write_register(state, _other, _value), do: state 99 | 100 | @impl SimpleI2CDevice 101 | def read_register(state, 0), do: {state.iodir, state} 102 | def read_register(state, 1), do: {state.ipol, state} 103 | def read_register(state, 2), do: {state.gpinten, state} 104 | def read_register(state, 3), do: {state.defval, state} 105 | def read_register(state, 4), do: {state.intcon, state} 106 | def read_register(state, 5), do: {state.iocon, state} 107 | def read_register(state, 6), do: {state.gppu, state} 108 | def read_register(state, 7), do: {state.intf, state} 109 | def read_register(state, 8), do: {state.intcap, state} 110 | def read_register(state, 9), do: {state.gpio, state} 111 | def read_register(state, 10), do: {state.olat, state} 112 | def read_register(state, _other), do: {0, state} 113 | 114 | @impl SimpleI2CDevice 115 | def render(state) do 116 | {pin, io, values} = 117 | for i <- 7..0//-1 do 118 | mask = Bitwise.bsl(1, i) 119 | 120 | iodir = if Bitwise.band(state.iodir, mask) == 0, do: "O", else: "I" 121 | gpio = if Bitwise.band(state.gpio, mask) == 0, do: "0", else: "1" 122 | {to_string(i), iodir, gpio} 123 | end 124 | |> unzip3() 125 | 126 | [" Pin: ", pin, "\n IODIR: ", io, "\n GPIO: ", values, "\n"] 127 | end 128 | 129 | @impl SimpleI2CDevice 130 | def handle_message(state, _message) do 131 | state 132 | end 133 | 134 | defp unzip3(list, acc \\ {[], [], []}) 135 | 136 | defp unzip3([], {a, b, c}) do 137 | {Enum.reverse(a), Enum.reverse(b), Enum.reverse(c)} 138 | end 139 | 140 | defp unzip3([{x, y, z} | rest], {a, b, c}) do 141 | unzip3(rest, {[x | a], [y | b], [z | c]}) 142 | end 143 | end 144 | end 145 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/pi4ioe5v6416lex.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.PI4IOE5V6416LEX do 7 | @moduledoc """ 8 | Low-Voltage Translating 16-bit I2C-bus I/O Expander 9 | 10 | Typically found at 0x20 11 | 12 | See the datasheet for more information: 13 | https://www.mouser.com/datasheet/2/115/DIOD_S_A0006645136_1-2542969.pdf 14 | """ 15 | alias CircuitsSim.I2C.I2CServer 16 | alias CircuitsSim.I2C.SimpleI2CDevice 17 | alias CircuitsSim.Tools 18 | 19 | @spec child_spec(keyword()) :: Supervisor.child_spec() 20 | def child_spec(args) do 21 | device = __MODULE__.new() 22 | I2CServer.child_spec_helper(device, args) 23 | end 24 | 25 | defstruct registers: %{} 26 | 27 | @type t() :: %__MODULE__{registers: %{}} 28 | 29 | @spec new() :: t() 30 | def new() do 31 | %__MODULE__{registers: %{}} 32 | end 33 | 34 | defimpl SimpleI2CDevice do 35 | @impl SimpleI2CDevice 36 | def write_register(state, reg, value), do: put_in(state.registers[reg], <>) 37 | 38 | @impl SimpleI2CDevice 39 | def read_register(state, reg), do: {state.registers[reg] || <<0>>, state} 40 | 41 | @impl SimpleI2CDevice 42 | def render(state) do 43 | for {reg, data} <- state.registers do 44 | [ 45 | " ", 46 | Tools.hex_byte(reg), 47 | ": ", 48 | for(<>, do: to_string(b)), 49 | " (", 50 | reg_name(reg), 51 | ")\n" 52 | ] 53 | end 54 | end 55 | 56 | @impl SimpleI2CDevice 57 | def handle_message(state, _message) do 58 | state 59 | end 60 | 61 | defp reg_name(0x00), do: "Input port 0" 62 | defp reg_name(0x01), do: "Input port 1" 63 | defp reg_name(0x02), do: "Output port 0" 64 | defp reg_name(0x03), do: "Output port 1" 65 | defp reg_name(0x04), do: "Polarity Inversion port 0" 66 | defp reg_name(0x05), do: "Polarity Inversion port 1" 67 | defp reg_name(0x06), do: "Configuration port 0 " 68 | defp reg_name(0x07), do: "Configuration port 1" 69 | defp reg_name(0x40), do: "Output drive strength register 0" 70 | defp reg_name(0x41), do: "Output drive strength register 0" 71 | defp reg_name(0x42), do: "Output drive strength register 1" 72 | defp reg_name(0x43), do: "Output drive strength register 1" 73 | defp reg_name(0x44), do: "Input latch register 0" 74 | defp reg_name(0x45), do: "Input latch register 1" 75 | defp reg_name(0x46), do: "Pull-up/pull-down enable register 0" 76 | defp reg_name(0x47), do: "Pull-up/pull-down enable register 1" 77 | defp reg_name(0x48), do: "Pull-up/pull-down selection register 0" 78 | defp reg_name(0x49), do: "Pull-up/pull-down selection register 1" 79 | defp reg_name(0x4A), do: "Interrupt mask register 0" 80 | defp reg_name(0x4B), do: "Interrupt mask register 1" 81 | defp reg_name(0x4C), do: "Interrupt status register 0" 82 | defp reg_name(0x4D), do: "Interrupt status register 1" 83 | defp reg_name(0x4F), do: "Output port configuration register" 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/sgp30.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # SPDX-FileCopyrightText: 2025 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.SGP30 do 7 | @moduledoc """ 8 | Sensirion SGP30 gas sensor 9 | 10 | Typically found at 0x58 11 | See the [datasheet](https://www.mouser.com/datasheet/2/682/Sensirion_Gas_Sensors_SGP30_Datasheet_EN-1148053.pdf) 12 | Many features aren't implemented. 13 | 14 | Call the following functions to change the state of the sensor. 15 | 16 | * `set_tvoc_ppb/3` 17 | * `set_co2_eq_ppm/3` 18 | * `set_h2_raw/3` 19 | * `set_ethanol_raw/3` 20 | """ 21 | alias CircuitsSim.I2C.I2CDevice 22 | alias CircuitsSim.I2C.I2CServer 23 | 24 | defstruct current: nil, serial: 0, tvoc_ppb: 0, co2_eq_ppm: 0, h2_raw: 0, ethanol_raw: 0 25 | 26 | @type t() :: %__MODULE__{ 27 | current: atom(), 28 | serial: integer(), 29 | tvoc_ppb: integer(), 30 | co2_eq_ppm: integer(), 31 | h2_raw: integer(), 32 | ethanol_raw: integer() 33 | } 34 | 35 | @spec child_spec(keyword()) :: Supervisor.child_spec() 36 | def child_spec(args) do 37 | device_options = Keyword.take(args, [:serial]) 38 | device = __MODULE__.new(device_options) 39 | I2CServer.child_spec_helper(device, args) 40 | end 41 | 42 | @type options() :: [serial: integer()] 43 | 44 | @spec new(options()) :: %__MODULE__{ 45 | current: nil, 46 | serial: 0, 47 | tvoc_ppb: 0, 48 | co2_eq_ppm: 0, 49 | h2_raw: 0, 50 | ethanol_raw: 0 51 | } 52 | def new(options \\ []) do 53 | serial = options[:serial] || 0 54 | %__MODULE__{serial: serial} 55 | end 56 | 57 | @spec set_tvoc_ppb(String.t(), Circuits.I2C.address(), integer()) :: :ok 58 | def set_tvoc_ppb(bus_name, address, value) when is_integer(value) do 59 | I2CServer.send_message(bus_name, address, {:set_tvoc_ppb, value}) 60 | end 61 | 62 | @spec set_co2_eq_ppm(String.t(), Circuits.I2C.address(), integer()) :: :ok 63 | def set_co2_eq_ppm(bus_name, address, value) when is_integer(value) do 64 | I2CServer.send_message(bus_name, address, {:set_co2_eq_ppm, value}) 65 | end 66 | 67 | @spec set_h2_raw(String.t(), Circuits.I2C.address(), integer()) :: :ok 68 | def set_h2_raw(bus_name, address, value) when is_integer(value) do 69 | I2CServer.send_message(bus_name, address, {:set_h2_raw, value}) 70 | end 71 | 72 | @spec set_ethanol_raw(String.t(), Circuits.I2C.address(), integer()) :: :ok 73 | def set_ethanol_raw(bus_name, address, value) when is_integer(value) do 74 | I2CServer.send_message(bus_name, address, {:set_ethanol_raw, value}) 75 | end 76 | 77 | ## protocol implementation 78 | 79 | defimpl I2CDevice do 80 | @crc_alg :cerlc.init({8, 0x31, 0xFF, 0x00, false}) 81 | 82 | @impl I2CDevice 83 | def read(%{current: :iaq_measure} = state, count) do 84 | result = binary_for_measure(state) |> trim_pad(count) 85 | {{:ok, result}, %{state | current: nil}} 86 | end 87 | 88 | def read(%{current: :iaq_measure_raw} = state, count) do 89 | result = binary_for_measure_raw(state) |> trim_pad(count) 90 | {{:ok, result}, %{state | current: nil}} 91 | end 92 | 93 | def read(state, count) do 94 | {{:ok, :binary.copy(<<0>>, count)}, %{state | current: nil}} 95 | end 96 | 97 | @impl I2CDevice 98 | def write(state, <<0x20, 0x03>>), do: %{state | current: :iaq_init} 99 | def write(state, <<0x20, 0x08>>), do: %{state | current: :iaq_measure} 100 | def write(state, <<0x20, 0x50>>), do: %{state | current: :iaq_measure_raw} 101 | def write(state, _), do: state 102 | 103 | @impl I2CDevice 104 | def write_read(state, <<0x36, 0x82>>, count) do 105 | result = binary_for_serial(state) |> trim_pad(count) 106 | {{:ok, result}, %{state | current: nil}} 107 | end 108 | 109 | def write_read(state, _to_write, read_count) do 110 | {:binary.copy(<<0>>, read_count), %{state | current: nil}} 111 | end 112 | 113 | defp trim_pad(x, count) when byte_size(x) >= count, do: :binary.part(x, 0, count) 114 | defp trim_pad(x, count), do: x <> :binary.copy(<<0>>, count - byte_size(x)) 115 | 116 | @impl I2CDevice 117 | def render(state) do 118 | [ 119 | "tvoc_ppb: #{state.tvoc_ppb}", 120 | "co2_eq_ppm: #{state.co2_eq_ppm}", 121 | "h2_raw: #{state.h2_raw}", 122 | "ethanol_raw: #{state.ethanol_raw}" 123 | ] 124 | |> Enum.join(", ") 125 | end 126 | 127 | @impl I2CDevice 128 | def handle_message(state, {:set_tvoc_ppb, value}) do 129 | {:ok, %{state | tvoc_ppb: value}} 130 | end 131 | 132 | def handle_message(state, {:set_co2_eq_ppm, value}) do 133 | {:ok, %{state | co2_eq_ppm: value}} 134 | end 135 | 136 | def handle_message(state, {:set_h2_raw, value}) do 137 | {:ok, %{state | h2_raw: value}} 138 | end 139 | 140 | def handle_message(state, {:set_ethanol_raw, value}) do 141 | {:ok, %{state | ethanol_raw: value}} 142 | end 143 | 144 | defp binary_for_serial(state) do 145 | <> |> add_crcs() 146 | end 147 | 148 | defp binary_for_measure(state) do 149 | co2_eq_ppm = state.co2_eq_ppm 150 | tvoc_ppb = state.tvoc_ppb 151 | 152 | <> |> add_crcs() 153 | end 154 | 155 | defp binary_for_measure_raw(state) do 156 | h2_raw = state.h2_raw 157 | ethanol_raw = state.ethanol_raw 158 | 159 | <> |> add_crcs() 160 | end 161 | 162 | defp add_crcs(data) do 163 | for <>, into: <<>> do 164 | crc = :cerlc.calc_crc(<>, @crc_alg) 165 | <> 166 | end 167 | end 168 | end 169 | end 170 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/sht4x.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # SPDX-FileCopyrightText: 2024 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.SHT4X do 7 | @moduledoc """ 8 | Sensirion SHT4x sensors 9 | 10 | Typically found at 0x44 11 | See the [datasheet](https://cdn-learn.adafruit.com/assets/assets/000/099/223/original/Sensirion_Humidity_Sensors_SHT4x_Datasheet.pdf) for details. 12 | 13 | Call `set_humidity_rh/3` and `set_temperature_c/3` to change the state of the sensor. 14 | """ 15 | alias CircuitsSim.I2C.I2CDevice 16 | alias CircuitsSim.I2C.I2CServer 17 | 18 | defstruct current: nil, 19 | serial_number: 0x12345678, 20 | humidity_rh: 30.0, 21 | temperature_c: 22.2, 22 | crc_injection_count: 0, 23 | broken: nil, 24 | acc: <<>> 25 | 26 | @type t() :: %__MODULE__{ 27 | current: atom(), 28 | serial_number: integer(), 29 | humidity_rh: float(), 30 | temperature_c: float(), 31 | crc_injection_count: non_neg_integer(), 32 | broken: nil | {:error, any()}, 33 | acc: binary() 34 | } 35 | 36 | @spec child_spec(keyword()) :: Supervisor.child_spec() 37 | def child_spec(args) do 38 | device_options = Keyword.take(args, [:serial_number]) 39 | device = __MODULE__.new(device_options) 40 | I2CServer.child_spec_helper(device, args) 41 | end 42 | 43 | @type options() :: [serial_number: integer()] 44 | 45 | @spec new(options()) :: %__MODULE__{ 46 | current: nil, 47 | serial_number: integer(), 48 | humidity_rh: float(), 49 | temperature_c: float(), 50 | crc_injection_count: non_neg_integer(), 51 | acc: binary() 52 | } 53 | def new(options \\ []) do 54 | serial_number = options[:serial_number] || 0 55 | %__MODULE__{serial_number: serial_number} 56 | end 57 | 58 | @spec set_humidity_rh(String.t(), Circuits.I2C.address(), number()) :: :ok 59 | def set_humidity_rh(bus_name, address, value) when is_number(value) do 60 | I2CServer.send_message(bus_name, address, {:set_humidity_rh, value}) 61 | end 62 | 63 | @spec set_temperature_c(String.t(), Circuits.I2C.address(), number()) :: :ok 64 | def set_temperature_c(bus_name, address, value) when is_number(value) do 65 | I2CServer.send_message(bus_name, address, {:set_temperature_c, value}) 66 | end 67 | 68 | @doc """ 69 | Inject CRC errors into the next n CRC fields 70 | 71 | Currently all messages have 2 CRC fields, so this will cause CRC mismatch 72 | errors on the next n/2 messages. 73 | """ 74 | @spec inject_crc_errors(String.t(), Circuits.I2C.address(), non_neg_integer()) :: :ok 75 | def inject_crc_errors(bus_name, address, count) when is_integer(count) do 76 | I2CServer.send_message(bus_name, address, {:inject_crc_errors, count}) 77 | end 78 | 79 | @doc """ 80 | Experimental API to return I2C errors on read/read_writes 81 | 82 | Set the 3rd argument to an error tuple to be returned or `nil` to work 83 | normally. 84 | """ 85 | @spec set_broken(String.t(), Circuits.I2C.address(), nil | {:error, any()}) :: :ok 86 | def set_broken(bus_name, address, broken) do 87 | I2CServer.send_message(bus_name, address, {:set_broken, broken}) 88 | end 89 | 90 | ## protocol implementation 91 | 92 | defimpl I2CDevice do 93 | @crc_alg :cerlc.init(:crc8_sensirion) 94 | 95 | @impl I2CDevice 96 | def read(%{broken: result} = state, _count) when is_tuple(result) do 97 | {result, state} 98 | end 99 | 100 | def read(%{current: :serial_number} = state, count) do 101 | state |> binary_for_serial_number() |> flush_read_to_result(count) 102 | end 103 | 104 | def read(%{current: op} = state, count) 105 | when op in [ 106 | :measure_high_repeatability, 107 | :measure_medium_repeatability, 108 | :measure_low_repeatability 109 | ] do 110 | state |> raw_sample() |> flush_read_to_result(count) 111 | end 112 | 113 | def read(state, count) do 114 | flush_read_to_result(state, count) 115 | end 116 | 117 | defp flush_read_to_result(state, count) do 118 | {{:ok, trim_pad(state.acc, count)}, %{state | current: nil, acc: <<>>}} 119 | end 120 | 121 | @impl I2CDevice 122 | def write(state, <<0x89>>), do: %{state | current: :serial_number} 123 | def write(state, <<0xFD>>), do: %{state | current: :measure_high_repeatability} 124 | def write(state, <<0xF6>>), do: %{state | current: :measure_medium_repeatability} 125 | def write(state, <<0xE0>>), do: %{state | current: :measure_low_repeatability} 126 | def write(state, _), do: state 127 | 128 | @impl I2CDevice 129 | def write_read(%{broken: result} = state, _to_write, _read_count) when is_tuple(result) do 130 | {result, state} 131 | end 132 | 133 | def write_read(state, _to_write, read_count) do 134 | {{:ok, :binary.copy(<<0>>, read_count)}, %{state | current: nil}} 135 | end 136 | 137 | defp trim_pad(x, count) when byte_size(x) >= count, do: :binary.part(x, 0, count) 138 | defp trim_pad(x, count), do: x <> :binary.copy(<<0>>, count - byte_size(x)) 139 | 140 | @impl I2CDevice 141 | def render(state) do 142 | humidity_rh = Float.round(state.humidity_rh, 3) 143 | temperature_c = Float.round(state.temperature_c, 3) 144 | "Temperature: #{temperature_c}°C, Relative humidity: #{humidity_rh}%" 145 | end 146 | 147 | @impl I2CDevice 148 | def handle_message(state, {:set_humidity_rh, value}) do 149 | {:ok, %{state | humidity_rh: value}} 150 | end 151 | 152 | def handle_message(state, {:set_temperature_c, value}) do 153 | {:ok, %{state | temperature_c: value}} 154 | end 155 | 156 | def handle_message(state, {:inject_crc_errors, count}) do 157 | {:ok, %{state | crc_injection_count: count}} 158 | end 159 | 160 | def handle_message(state, {:set_broken, value}) do 161 | {:ok, %{state | broken: value}} 162 | end 163 | 164 | defp binary_for_serial_number(state) do 165 | state |> add_crcs(<>) 166 | end 167 | 168 | defp raw_sample(state) do 169 | raw_rh = round((state.humidity_rh + 6) * (0xFFFF - 1) / 125) 170 | raw_t = round((state.temperature_c + 45) * (0xFFFF - 1) / 175) 171 | 172 | state |> add_crcs(<>) 173 | end 174 | 175 | defp add_crcs(state, <<>>), do: state 176 | 177 | defp add_crcs(state, <>) do 178 | {next_state, crc} = crc(state, val) 179 | this_part = <> 180 | add_crcs(%{next_state | acc: state.acc <> this_part}, rest) 181 | end 182 | 183 | defp crc(%{crc_injection_count: 0} = state, v) do 184 | {state, :cerlc.calc_crc(v, @crc_alg)} 185 | end 186 | 187 | defp crc(%{crc_injection_count: n} = state, v) do 188 | {%{state | crc_injection_count: n - 1}, :cerlc.calc_crc(v, @crc_alg) |> Bitwise.bxor(1)} 189 | end 190 | end 191 | end 192 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/tm1620.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.TM1620 do 6 | @moduledoc """ 7 | TM1620 LED Driver 8 | 9 | See the [datasheet](https://github.com/fhunleth/binary_clock/blob/main/datasheets/TM1620-English.pdf) for details. 10 | Many features aren't implemented. 11 | """ 12 | 13 | alias CircuitsSim.SPI.SPIDevice 14 | alias CircuitsSim.SPI.SPIServer 15 | 16 | @typedoc """ 17 | Render mode is how to pretty print the expected LED output 18 | 19 | Modes: 20 | 21 | * `:grid` - a grid of LEDs. Grid dimensions depend on the TM1620 mode 22 | * `:seven_segment` - render LEDs like they're hooked up to a 7 segment display 23 | * `:binary_clock` - render LEDs like the Nerves binary clock 24 | """ 25 | @type render_mode() :: :grid | :seven_segment | :binary_clock 26 | 27 | defstruct digits: 4, 28 | mode: :auto, 29 | pulse16: 0, 30 | data: :binary.copy(<<0>>, 0xC), 31 | render: :grid 32 | 33 | @type t() :: %__MODULE__{ 34 | data: <<_::88>>, 35 | digits: pos_integer(), 36 | mode: :auto, 37 | pulse16: pos_integer(), 38 | render: render_mode() 39 | } 40 | 41 | @spec child_spec(keyword()) :: Supervisor.child_spec() 42 | def child_spec(args) do 43 | device = new(args) 44 | SPIServer.child_spec_helper(device, args) 45 | end 46 | 47 | @spec new(keyword()) :: t() 48 | def new(args) do 49 | struct(__MODULE__, args) 50 | end 51 | 52 | @doc """ 53 | Process a TM1620 command 54 | """ 55 | @spec command(binary(), t()) :: t() 56 | def command(data, state) 57 | 58 | # Display mode 59 | def command(<<0::2, _::4, 0::2, _::binary>>, state), do: %{state | digits: 4} 60 | def command(<<0::2, _::4, 1::2, _::binary>>, state), do: %{state | digits: 5} 61 | def command(<<0::2, _::4, 2::2, _::binary>>, state), do: %{state | digits: 6} 62 | 63 | # Data command 64 | def command(<<1::2, _::2, _::2, 0::2, _::binary>>, state), do: %{state | mode: :auto} 65 | 66 | # Display control 67 | def command(<<2::2, _::2, 0::1, _::3, _::binary>>, state), do: %{state | pulse16: 0} 68 | def command(<<2::2, _::2, 1::1, 0::3, _::binary>>, state), do: %{state | pulse16: 1} 69 | def command(<<2::2, _::2, 1::1, 1::3, _::binary>>, state), do: %{state | pulse16: 2} 70 | def command(<<2::2, _::2, 1::1, 2::3, _::binary>>, state), do: %{state | pulse16: 4} 71 | def command(<<2::2, _::2, 1::1, 3::3, _::binary>>, state), do: %{state | pulse16: 10} 72 | def command(<<2::2, _::2, 1::1, 4::3, _::binary>>, state), do: %{state | pulse16: 11} 73 | def command(<<2::2, _::2, 1::1, 5::3, _::binary>>, state), do: %{state | pulse16: 12} 74 | def command(<<2::2, _::2, 1::1, 6::3, _::binary>>, state), do: %{state | pulse16: 13} 75 | def command(<<2::2, _::2, 1::1, 7::3, _::binary>>, state), do: %{state | pulse16: 14} 76 | 77 | # Address command 78 | def command(<<3::2, _::2, address::4, data::binary>>, state) when address < 12 do 79 | %{state | data: update_data(state.data, address, data)} 80 | end 81 | 82 | # Ignore anything else 83 | def command(_other, state), do: state 84 | 85 | defp update_data(data, _address, <<>>), do: data 86 | defp update_data(data, address, _updates) when address > 0xB, do: data 87 | 88 | defp update_data(data, address, <>) do 89 | new_data = put_byte(data, address, b) 90 | update_data(new_data, address + 1, rest) 91 | end 92 | 93 | defp put_byte(data, index, value) do 94 | <> = data 95 | <> 96 | end 97 | 98 | @doc """ 99 | Draw out 7-segment display digits using TM1620 data 100 | """ 101 | @spec seven_segment(binary()) :: IO.ANSI.ansidata() 102 | def seven_segment(data) do 103 | for row <- 0..2 do 104 | [ 105 | for <> do 106 | for col <- 0..3, do: seg({row, col}, grid) 107 | end, 108 | ?\n 109 | ] 110 | end 111 | end 112 | 113 | # Bits are reversed in Elixir from how they're shown in the datasheet. 114 | # I.e., Elixir goes bit 7 on the left to bit 0 on the right. The datasheet 115 | # counts up. 116 | 117 | # ----a---- 118 | # | | 119 | # f| |b 120 | # | | 121 | # ----g---- 122 | # | | 123 | # e| |c 124 | # | | 125 | # ----d---- . dp 126 | 127 | # Seg1, bit 0 --> a 128 | # .. 129 | # Seg8, bit 7 --> dp 130 | defp seg({0, 1}, <<_::1, _::1, _::1, _::1, _::1, _::1, _::1, 1::1, _>>), do: "_" 131 | defp seg({1, 0}, <<_::1, _::1, 1::1, _::1, _::1, _::1, _::1, _::1, _>>), do: "|" 132 | defp seg({1, 1}, <<_::1, 1::1, _::1, _::1, _::1, _::1, _::1, _::1, _>>), do: "_" 133 | defp seg({1, 2}, <<_::1, _::1, _::1, _::1, _::1, _::1, 1::1, _::1, _>>), do: "|" 134 | defp seg({2, 0}, <<_::1, _::1, _::1, 1::1, _::1, _::1, _::1, _::1, _>>), do: "|" 135 | defp seg({2, 1}, <<_::1, _::1, _::1, _::1, 1::1, _::1, _::1, _::1, _>>), do: "_" 136 | defp seg({2, 2}, <<_::1, _::1, _::1, _::1, _::1, 1::1, _::1, _::1, _>>), do: "|" 137 | defp seg({2, 3}, <<1::1, _::1, _::1, _::1, _::1, _::1, _::1, _::1, _>>), do: "." 138 | defp seg(_, _), do: " " 139 | 140 | @doc """ 141 | Display registers as a grid 142 | """ 143 | @spec grid(4..6, binary()) :: IO.ANSI.ansidata() 144 | def grid(digits, data) do 145 | valid_data = :binary.part(data, 0, digits * 2) 146 | for <>, do: grid_row(digits, row_data) 147 | end 148 | 149 | defp grid_row(4, <>) do 150 | [led(a), led(b), led(c), led(d), led(e), led(f), led(g), led(h), led(i), led(j), ?\n] 151 | end 152 | 153 | defp grid_row(5, <>) do 154 | [led(a), led(b), led(c), led(d), led(e), led(f), led(g), led(h), led(i), ?\n] 155 | end 156 | 157 | defp grid_row(6, <>) do 158 | [led(a), led(b), led(c), led(d), led(e), led(f), led(g), led(h), ?\n] 159 | end 160 | 161 | defp led(0), do: 0x20 162 | defp led(1), do: ?* 163 | 164 | # The binary clock board has the TM1620 hooked up in 6x8 mode. Each segment 165 | # is another binary digit in the order hhmmss. Seg 0 is the tens digit of hours. 166 | # 167 | # Row 0: 3 3 3 168 | # Row 1: 2 2 2 169 | # Row 2: 1 1 1 1 1 1 170 | # Row 3: 0 0 0 0 0 0 171 | # Seg0 Seg1 Seg2 Seg3 Seg4 Seg5 172 | # Hours Minutes Seconds 173 | @spec binary_clock(binary()) :: IO.ANSI.ansidata() 174 | def binary_clock(data) do 175 | m = leds_to_map(6, data) 176 | 177 | [ 178 | [" ", c(m, 1, 3), " ", c(m, 3, 3), " ", c(m, 5, 3), ?\n], 179 | [" ", c(m, 1, 2), " ", c(m, 3, 2), " ", c(m, 5, 2), ?\n], 180 | [c(m, 0, 1), c(m, 1, 1), " ", c(m, 2, 1), c(m, 3, 1), " ", c(m, 4, 1), c(m, 5, 1), ?\n], 181 | [c(m, 0, 0), c(m, 1, 0), " ", c(m, 2, 0), c(m, 3, 0), " ", c(m, 4, 0), c(m, 5, 0), ?\n] 182 | ] 183 | end 184 | 185 | defp c(m, seg, bit) do 186 | case m[{seg, bit}] do 187 | 0 -> "." 188 | 1 -> "o" 189 | end 190 | end 191 | 192 | defp leds_to_map(digits, data) do 193 | for segment <- 0..(digits - 1), reduce: %{} do 194 | acc -> 195 | row_data = :binary.part(data, segment * 2, 2) 196 | led_status(acc, digits, segment, row_data) 197 | end 198 | end 199 | 200 | # Not used yet. Comment out to avoid Dialyzer warnings 201 | # defp led_status(acc, 4, segment, <<_::8, _::4, j::1, _::3>> = data) do 202 | # acc |> led_status(5, segment, data) |> Map.put({segment, 9}, j) 203 | # end 204 | 205 | # defp led_status(acc, 5, segment, <<_::8, _::5, i::1, _::2>> = data) do 206 | # acc |> led_status(6, segment, data) |> Map.put({segment, 8}, i) 207 | # end 208 | 209 | defp led_status(acc, 6, segment, <>) do 210 | Map.merge( 211 | acc, 212 | %{ 213 | {segment, 0} => a, 214 | {segment, 1} => b, 215 | {segment, 2} => c, 216 | {segment, 3} => d, 217 | {segment, 4} => e, 218 | {segment, 5} => f, 219 | {segment, 6} => g, 220 | {segment, 7} => h 221 | } 222 | ) 223 | end 224 | 225 | defimpl SPIDevice do 226 | alias CircuitsSim.Device.TM1620 227 | 228 | @impl SPIDevice 229 | def transfer(state, data) do 230 | # The device is write only, so just return zeros. 231 | result = :binary.copy(<<0>>, byte_size(data)) 232 | {result, TM1620.command(data, state)} 233 | end 234 | 235 | @impl SPIDevice 236 | def render(state) do 237 | [ 238 | "Mode: #{state.digits} digits, #{14 - state.digits} segments\n", 239 | "Brightness: #{state.pulse16}/16\n", 240 | case state.render do 241 | :grid -> TM1620.grid(state.digits, state.data) 242 | :seven_segment -> TM1620.seven_segment(state.data) 243 | :binary_clock -> TM1620.binary_clock(state.data) 244 | end 245 | ] 246 | end 247 | 248 | @impl SPIDevice 249 | def handle_message(state, _message) do 250 | {:unimplemented, state} 251 | end 252 | end 253 | end 254 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/vcnl4040.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Eric Oestrich 2 | # SPDX-FileCopyrightText: 2025 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.VCNL4040 do 7 | @moduledoc """ 8 | VCNL4040 ambient light and proximity sensor 9 | 10 | Typically found at 0x60 11 | See the [datasheet](https://www.vishay.com/docs/84274/vcnl4040.pdf) 12 | Many configuration options aren't implemented. 13 | 14 | Call `set_proximity/3`, `set_ambient_light/3`, and `set_white_light/3` to 15 | change the state of the sensor. 16 | """ 17 | alias CircuitsSim.I2C.I2CDevice 18 | alias CircuitsSim.I2C.I2CServer 19 | 20 | defstruct als_config: 0x0000, 21 | als_low_threshold: 0x0000, 22 | als_high_threshold: 0x0000, 23 | ps_low_threshold: 0x0000, 24 | ps_high_threshold: 0x0000, 25 | ps_config_1: 0x0000, 26 | ps_config_2: 0x0000, 27 | ps_cancellation_level: 0x0000, 28 | proximity_raw: 0, 29 | ambient_light_raw: 0, 30 | white_light_raw: 0 31 | 32 | @type t() :: %__MODULE__{ 33 | als_config: 0..0xFFFF, 34 | als_low_threshold: 0..0xFFFF, 35 | als_high_threshold: 0..0xFFFF, 36 | ps_low_threshold: 0..0xFFFF, 37 | ps_high_threshold: 0..0xFFFF, 38 | ps_config_1: 0..0xFFFF, 39 | ps_config_2: 0..0xFFFF, 40 | ps_cancellation_level: 0..0xFFFF, 41 | proximity_raw: 0..0xFFFF, 42 | ambient_light_raw: 0..0xFFFF, 43 | white_light_raw: 0..0xFFFF 44 | } 45 | 46 | @spec child_spec(keyword()) :: Supervisor.child_spec() 47 | def child_spec(args) do 48 | device = __MODULE__.new(Keyword.get(args, :state, [])) 49 | I2CServer.child_spec_helper(device, args) 50 | end 51 | 52 | @spec new(keyword) :: t() 53 | def new(options \\ []) do 54 | struct!(__MODULE__, options) 55 | end 56 | 57 | @spec set_proximity(String.t(), Circuits.I2C.address(), number()) :: :ok 58 | def set_proximity(bus_name, address, value) do 59 | I2CServer.send_message(bus_name, address, {:set_proximity, value}) 60 | end 61 | 62 | @spec set_ambient_light(String.t(), Circuits.I2C.address(), number()) :: :ok 63 | def set_ambient_light(bus_name, address, value) do 64 | I2CServer.send_message(bus_name, address, {:set_ambient_light, value}) 65 | end 66 | 67 | @spec set_white_light(String.t(), Circuits.I2C.address(), number()) :: :ok 68 | def set_white_light(bus_name, address, value) do 69 | I2CServer.send_message(bus_name, address, {:set_white_light, value}) 70 | end 71 | 72 | defimpl I2CDevice do 73 | require Logger 74 | 75 | # read/write 76 | @als_config_register 0x00 77 | @als_high_threshold_register 0x01 78 | @als_low_threshold_register 0x02 79 | @ps_config_register_1 0x03 80 | @ps_config_register_2 0x04 81 | @ps_cancellation_register 0x05 82 | @ps_low_threshold_register 0x06 83 | @ps_high_threshold_register 0x07 84 | 85 | # read only 86 | @ps_data_register 0x08 87 | @als_data_register 0x09 88 | @white_data_register 0x0A 89 | @als_ps_interrupt_flag_register 0x0B 90 | @cmd_device_id 0x0C 91 | 92 | @impl I2CDevice 93 | def read(state, count) do 94 | {{:ok, :binary.copy(<<0>>, count)}, state} 95 | end 96 | 97 | @impl I2CDevice 98 | # second byte is reserved and should always be 0b0000_0000 99 | def write(state, <<@als_config_register, config, 0>>) do 100 | <> = <> 101 | 102 | config = %{ 103 | integration_time: time, 104 | interrupt_persistence: interrupt_persistence, 105 | interrupt_enable: interrupt, 106 | power_enable: power 107 | } 108 | 109 | Logger.debug("[VCNL4040] Ambient Light Sensor Config - #{inspect(config)}") 110 | 111 | %{state | als_config: config} 112 | end 113 | 114 | def write(state, <<@als_high_threshold_register, high::little-16>>) do 115 | Logger.debug("[VCNL4040] Ambient Light Sensor High Threshold - #{high}") 116 | %{state | als_high_threshold: high} 117 | end 118 | 119 | def write(state, <<@als_low_threshold_register, low::little-16>>) do 120 | Logger.debug("[VCNL4040] Ambient Light Sensor Low Threshold - #{low}") 121 | %{state | als_low_threshold: low} 122 | end 123 | 124 | def write(state, <<@ps_config_register_1, low, high>>) do 125 | <> = <> 126 | <<0::4, output_bits::1, 0::1, interrupt::2>> = <> 127 | 128 | config = %{ 129 | duty_ratio: duty, 130 | interrupt_persistence: interrupt_persistence, 131 | interrupt_enabled: interrupt, 132 | integration_time: time, 133 | output_bits: output_bits, 134 | power_enable: power 135 | } 136 | 137 | Logger.debug("[VCNL4040] Proximity Sensor Config - #{inspect(config)}") 138 | 139 | %{state | ps_config_1: config} 140 | end 141 | 142 | def write(state, <<@ps_config_register_2, low, high>>) do 143 | <<0::1, proximity_mps::2, smart_persistence::1, af::1, af_trigger::1, 0::1, sunlight::1>> = 144 | <> 145 | 146 | <> = <> 147 | 148 | config = %{ 149 | proximity_mps: proximity_mps, 150 | smart_persistence: smart_persistence, 151 | active_force_mode: af, 152 | active_force_trigger: af_trigger, 153 | sunlight_cancel_enabled: sunlight, 154 | white_channel_enabled: white_channel, 155 | proximity_mode: proximity, 156 | led_current: led 157 | } 158 | 159 | Logger.debug("[VCNL4040] Proximity Sensor Config 2 - #{inspect(config)}") 160 | 161 | %{state | ps_config_2: config} 162 | end 163 | 164 | def write(state, <<@ps_cancellation_register, level::little-16>>) do 165 | Logger.debug("[VCNL4040] Proximity Sensor Cancellation Level - #{level}") 166 | %{state | ps_cancellation_level: level} 167 | end 168 | 169 | def write(state, <<@ps_low_threshold_register, low::little-16>>) do 170 | Logger.debug("[VCNL4040] Proximity Sensor Low Threshold - #{low}") 171 | %{state | ps_low_threshold: low} 172 | end 173 | 174 | def write(state, <<@ps_high_threshold_register, high::little-16>>) do 175 | Logger.debug("[VCNL4040] Proximity Sensor High Threshold - #{high}") 176 | %{state | ps_high_threshold: high} 177 | end 178 | 179 | def write(state, data) do 180 | Logger.debug("[VCNL4040] Unknown write - #{inspect(data)}") 181 | state 182 | end 183 | 184 | @impl I2CDevice 185 | def write_read(state, <<@ps_data_register>>, 2) do 186 | {{:ok, <>}, state} 187 | end 188 | 189 | def write_read(state, <<@als_data_register>>, 2) do 190 | {{:ok, <>}, state} 191 | end 192 | 193 | def write_read(state, <<@white_data_register>>, 2) do 194 | {{:ok, <>}, state} 195 | end 196 | 197 | def write_read(state, <<@als_ps_interrupt_flag_register>>, 2) do 198 | {{:ok, <<0x00, 0x00>>}, state} 199 | end 200 | 201 | def write_read(state, <<@cmd_device_id>>, 2) do 202 | {{:ok, <<0x86, 0x01>>}, state} 203 | end 204 | 205 | def write_read(state, _value, read_count) do 206 | {{:ok, :binary.copy(<<0>>, read_count)}, state} 207 | end 208 | 209 | @impl I2CDevice 210 | def render(state) do 211 | """ 212 | Ambient light sensor output 213 | 214 | Proximity: #{state.proximity_raw} 215 | Ambient Light: #{state.ambient_light_raw} 216 | White Light: #{state.white_light_raw} 217 | """ 218 | end 219 | 220 | @impl I2CDevice 221 | def handle_message(state, {:set_proximity, value}) do 222 | {:ok, %{state | proximity_raw: value}} 223 | end 224 | 225 | def handle_message(state, {:set_ambient_light, value}) do 226 | {:ok, %{state | ambient_light_raw: value}} 227 | end 228 | 229 | def handle_message(state, {:set_white_light, value}) do 230 | {:ok, %{state | white_light_raw: value}} 231 | end 232 | end 233 | end 234 | -------------------------------------------------------------------------------- /lib/circuits_sim/device/veml7700.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # SPDX-FileCopyrightText: 2025 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.VEML7700 do 7 | @moduledoc """ 8 | Vishay VEML7700 ambient light sensors. This sim works for VEML6030 as well. 9 | 10 | VEML7700 sensors are at address 0x10; VEML6030 typically at 0x48. 11 | See the [datasheet](https://www.vishay.com/docs/84286/veml7700.pdf) for details. 12 | 13 | Call `set_state/3` to change the state of the sensor. 14 | """ 15 | alias CircuitsSim.I2C.I2CDevice 16 | alias CircuitsSim.I2C.I2CServer 17 | 18 | defstruct als_config: 0x0000, 19 | als_threshold_high: 0x0000, 20 | als_threshold_low: 0x0000, 21 | als_power_saving: 0x0000, 22 | als_output: 0x0000, 23 | white_output: 0x0000, 24 | interrupt_status: 0x0000 25 | 26 | @type t() :: %__MODULE__{ 27 | als_config: 0..0xFFFF, 28 | als_threshold_high: 0..0xFFFF, 29 | als_threshold_low: 0..0xFFFF, 30 | als_power_saving: 0..0xFFFF, 31 | als_output: 0..0xFFFF, 32 | white_output: 0..0xFFFF, 33 | interrupt_status: 0..0xFFFF 34 | } 35 | 36 | @spec child_spec(keyword()) :: Supervisor.child_spec() 37 | def child_spec(args) do 38 | device = __MODULE__.new() 39 | I2CServer.child_spec_helper(device, args) 40 | end 41 | 42 | @spec new(keyword) :: t() 43 | def new(_options \\ []) do 44 | %__MODULE__{} 45 | end 46 | 47 | @spec set_state(String.t(), Circuits.I2C.address(), keyword()) :: :ok 48 | def set_state(bus_name, address, kv) do 49 | I2CServer.send_message(bus_name, address, {:set_state, kv}) 50 | end 51 | 52 | ## protocol implementation 53 | 54 | defimpl I2CDevice do 55 | @cmd_als_config 0 56 | @cmd_als_threshold_high 1 57 | @cmd_als_threshold_low 2 58 | @cmd_als_power_saving 3 59 | @cmd_als_output 4 60 | @cmd_white_output 5 61 | @cmd_interrupt_status 6 62 | 63 | @impl I2CDevice 64 | def read(state, count) do 65 | {{:ok, :binary.copy(<<0>>, count)}, state} 66 | end 67 | 68 | @impl I2CDevice 69 | def write(state, <<@cmd_als_config, value::little-16>>) do 70 | %{state | als_config: value} 71 | end 72 | 73 | def write(state, <<@cmd_als_threshold_high, data::little-16>>) do 74 | %{state | als_threshold_high: data} 75 | end 76 | 77 | def write(state, <<@cmd_als_threshold_low, data::little-16>>) do 78 | %{state | als_threshold_low: data} 79 | end 80 | 81 | def write(state, <<@cmd_als_power_saving, data::little-16>>) do 82 | %{state | als_power_saving: data} 83 | end 84 | 85 | def write(state, _), do: state 86 | 87 | @impl I2CDevice 88 | def write_read(state, <<@cmd_als_config>>, read_count) do 89 | result = <> |> trim_pad(read_count) 90 | {{:ok, result}, state} 91 | end 92 | 93 | def write_read(state, <<@cmd_als_threshold_high>>, read_count) do 94 | result = <> |> trim_pad(read_count) 95 | {{:ok, result}, state} 96 | end 97 | 98 | def write_read(state, <<@cmd_als_threshold_low>>, read_count) do 99 | result = <> |> trim_pad(read_count) 100 | {{:ok, result}, state} 101 | end 102 | 103 | def write_read(state, <<@cmd_als_power_saving>>, read_count) do 104 | result = <> |> trim_pad(read_count) 105 | {{:ok, result}, state} 106 | end 107 | 108 | def write_read(state, <<@cmd_als_output>>, read_count) do 109 | result = <> |> trim_pad(read_count) 110 | {{:ok, result}, state} 111 | end 112 | 113 | def write_read(state, <<@cmd_white_output>>, read_count) do 114 | result = <> |> trim_pad(read_count) 115 | {{:ok, result}, state} 116 | end 117 | 118 | def write_read(state, <<@cmd_interrupt_status>>, read_count) do 119 | result = <> |> trim_pad(read_count) 120 | {{:ok, result}, state} 121 | end 122 | 123 | def write_read(state, _to_write, read_count) do 124 | {{:ok, :binary.copy(<<0>>, read_count)}, state} 125 | end 126 | 127 | defp trim_pad(x, count) when byte_size(x) >= count, do: :binary.part(x, 0, count) 128 | defp trim_pad(x, count), do: x <> :binary.copy(<<0>>, count - byte_size(x)) 129 | 130 | @impl I2CDevice 131 | def render(state) do 132 | "Ambient light sensor raw output: #{state.als_output}" 133 | end 134 | 135 | @impl I2CDevice 136 | @spec handle_message(struct, {:set_state, keyword}) :: {:ok, struct} 137 | def handle_message(state, {:set_state, kv}) do 138 | {:ok, struct!(state, kv)} 139 | end 140 | end 141 | end 142 | -------------------------------------------------------------------------------- /lib/circuits_sim/device_registry.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.DeviceRegistry do 6 | @moduledoc false 7 | 8 | alias Circuits.GPIO 9 | alias Circuits.I2C 10 | 11 | @type type() :: :i2c | :spi | :gpio | :all 12 | 13 | @spec via_name(type(), String.t() | GPIO.gpio_spec(), I2C.address()) :: 14 | {:via, Registry, tuple()} 15 | def via_name(type, bus, address) do 16 | {:via, Registry, {CircuitSim.DeviceRegistry, {type, bus, address}}} 17 | end 18 | 19 | @spec bus_names(type()) :: [String.t() | GPIO.gpio_spec()] 20 | def bus_names(type) do 21 | # The select returns [{{:i2c, "i2c-0", 32}}] 22 | Registry.select(CircuitSim.DeviceRegistry, [{{:"$1", :_, :_}, [], [{{:"$1"}}]}]) 23 | |> Enum.filter(fn {{bus_type, _, _}} -> bus_type == type or type == :all end) 24 | |> Enum.map(&extract_bus_name/1) 25 | |> Enum.uniq() 26 | end 27 | 28 | defp extract_bus_name({{_type, bus_name, _address}}), do: bus_name 29 | end 30 | -------------------------------------------------------------------------------- /lib/circuits_sim/gpio/backend.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2024 Ryota Kinukawa 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.GPIO.Backend do 7 | @moduledoc """ 8 | Circuits.GPIO backend for virtual GPIO devices 9 | """ 10 | @behaviour Circuits.GPIO.Backend 11 | 12 | alias Circuits.GPIO.Backend 13 | alias CircuitsSim.DeviceRegistry 14 | alias CircuitsSim.GPIO.GPIOServer 15 | alias CircuitsSim.GPIO.Handle 16 | 17 | @impl Backend 18 | def enumerate(_options) do 19 | DeviceRegistry.bus_names(:gpio) 20 | end 21 | 22 | @impl Backend 23 | def identifiers(gpio_spec, _options) do 24 | # Simplest possible implementation for now. 25 | {:ok, %{controller: "sim", label: "unknown", location: gpio_spec}} 26 | end 27 | 28 | @impl Backend 29 | def status(_gpio_spec, _options) do 30 | {:error, :unimplemented} 31 | end 32 | 33 | @doc """ 34 | Open an GPIO handle 35 | """ 36 | @impl Backend 37 | def open(gpio_spec, direction, options) do 38 | with {:ok, identifiers} <- identifiers(gpio_spec, options), 39 | handle = %Handle{gpio_spec: identifiers.location}, 40 | :ok <- GPIOServer.set_direction(identifiers.location, direction), 41 | :ok <- set_pull_mode(identifiers.location, options[:pull_mode]), 42 | :ok <- set_initial_value(direction, identifiers.location, options[:initial_value]) do 43 | {:ok, handle} 44 | end 45 | end 46 | 47 | defp set_pull_mode(_gpio_spec, :not_set), do: :ok 48 | defp set_pull_mode(gpio_spec, pull_mode), do: GPIOServer.set_pull_mode(gpio_spec, pull_mode) 49 | 50 | defp set_initial_value(:output, gpio_spec, value), do: GPIOServer.write(gpio_spec, value) 51 | defp set_initial_value(:input, _gpio_spec, _value), do: :ok 52 | 53 | @doc """ 54 | Return information about this backend 55 | """ 56 | @impl Backend 57 | def backend_info() do 58 | %{backend: __MODULE__} 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /lib/circuits_sim/gpio/gpio_device.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defprotocol CircuitsSim.GPIO.GPIODevice do 6 | @moduledoc """ 7 | A protocol for GPIO devices 8 | """ 9 | alias Circuits.GPIO 10 | 11 | @doc """ 12 | Read state 13 | 14 | This is only called when the GPIO is an input. If the GPIO is an output, the most recently 15 | written value is returned without making this call. 16 | 17 | If the wire is not being driven (i.e., high impedance state or disconnected), return `:hi_z`. 18 | """ 19 | @spec read(t()) :: GPIO.value() | :hi_z 20 | def read(dev) 21 | 22 | @doc """ 23 | Write state 24 | 25 | This is only called when the GPIO is set as an output. 26 | """ 27 | @spec write(t(), GPIO.value()) :: t() 28 | def write(dev, value) 29 | 30 | @doc """ 31 | Return the internal state as ASCII art 32 | """ 33 | @spec render(t()) :: IO.ANSI.ansidata() 34 | def render(dev) 35 | 36 | @doc """ 37 | Handle an user message 38 | 39 | User messages are used to modify the state of the simulated device outside of 40 | I2C. This can be used to simulate real world changes like temperature changes 41 | affecting a simulated temperature sensor. Another use is as a hook for getting 42 | internal state. 43 | """ 44 | @spec handle_message(t(), any()) :: {any(), t()} 45 | def handle_message(dev, message) 46 | 47 | @doc """ 48 | Handle a message sent to the GenServer running the device 49 | 50 | These are used for timeouts or other events 51 | """ 52 | @spec handle_info(t(), any()) :: t() 53 | def handle_info(dev, message) 54 | end 55 | -------------------------------------------------------------------------------- /lib/circuits_sim/gpio/gpio_server.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.GPIO.GPIOServer do 6 | @moduledoc false 7 | 8 | use GenServer 9 | 10 | alias Circuits.GPIO 11 | alias CircuitsSim.DeviceRegistry 12 | alias CircuitsSim.GPIO.GPIODevice 13 | 14 | require Logger 15 | 16 | defstruct gpio_spec: nil, 17 | device: nil, 18 | direction: :input, 19 | pull_mode: :none, 20 | cached_value: 0, 21 | interrupt_receiver: nil, 22 | interrupt_trigger: :none 23 | 24 | @type init_args :: [gpio_spec: GPIO.gpio_spec()] 25 | 26 | @doc """ 27 | Helper for creating child_specs for simple I2C implementations 28 | """ 29 | @spec child_spec_helper(GPIODevice.t(), init_args()) :: %{ 30 | :id => __MODULE__, 31 | :start => {__MODULE__, :start_link, [[any()], ...]} 32 | } 33 | def child_spec_helper(device, args) do 34 | gpio_spec = Keyword.fetch!(args, :gpio_spec) 35 | 36 | combined_args = Keyword.merge([device: device, name: via_name(gpio_spec)], args) 37 | 38 | %{ 39 | id: __MODULE__, 40 | start: {__MODULE__, :start_link, [combined_args]} 41 | } 42 | end 43 | 44 | @spec start_link(keyword()) :: GenServer.on_start() 45 | def start_link(init_args) do 46 | gpio_spec = Keyword.fetch!(init_args, :gpio_spec) 47 | 48 | GenServer.start_link(__MODULE__, init_args, name: via_name(gpio_spec)) 49 | end 50 | 51 | # Helper for constructing the via_name for GPIODevice servers 52 | defp via_name(gpio_spec) do 53 | DeviceRegistry.via_name(:gpio, gpio_spec, 0) 54 | end 55 | 56 | @spec write(GPIO.gpio_spec(), GPIO.value()) :: :ok 57 | def write(gpio_spec, value) do 58 | GenServer.call(via_name(gpio_spec), {:write, value}) 59 | end 60 | 61 | @spec read(GPIO.gpio_spec()) :: GPIO.value() 62 | def read(gpio_spec) do 63 | GenServer.call(via_name(gpio_spec), :read) 64 | end 65 | 66 | @spec set_direction(GPIO.gpio_spec(), GPIO.direction()) :: :ok | {:error, atom()} 67 | def set_direction(gpio_spec, direction) do 68 | GenServer.call(via_name(gpio_spec), {:set_direction, direction}) 69 | end 70 | 71 | @spec set_interrupts(GPIO.gpio_spec(), GPIO.trigger(), GPIO.interrupt_options()) :: 72 | :ok | {:error, atom()} 73 | def set_interrupts(gpio_spec, trigger, options) do 74 | receiver = options[:receiver] || self() 75 | GenServer.call(via_name(gpio_spec), {:set_interrupts, trigger, receiver}) 76 | end 77 | 78 | @spec set_pull_mode(GPIO.gpio_spec(), GPIO.pull_mode()) :: :ok | {:error, atom()} 79 | def set_pull_mode(gpio_spec, pull_mode) do 80 | GenServer.call(via_name(gpio_spec), {:set_pull_mode, pull_mode}) 81 | end 82 | 83 | @spec render(GPIO.gpio_spec()) :: IO.ANSI.ansidata() 84 | def render(gpio_spec) do 85 | GenServer.call(via_name(gpio_spec), :render) 86 | end 87 | 88 | @spec send_message(GPIO.gpio_spec(), any()) :: any() 89 | def send_message(gpio_spec, message) do 90 | GenServer.call(via_name(gpio_spec), {:send_message, message}) 91 | end 92 | 93 | @impl GenServer 94 | def init(init_args) do 95 | gpio_spec = Keyword.fetch!(init_args, :gpio_spec) 96 | device = Keyword.fetch!(init_args, :device) 97 | 98 | {:ok, %__MODULE__{gpio_spec: gpio_spec, device: device}} 99 | end 100 | 101 | @impl GenServer 102 | def handle_call({:write, value}, _from, state) do 103 | case state.direction do 104 | :output -> 105 | new_device = GPIODevice.write(state.device, value) 106 | handle_gpio_change(state, state.cached_value, value) 107 | 108 | {:reply, :ok, %{state | device: new_device, cached_value: value}} 109 | 110 | :input -> 111 | Logger.warning("Ignoring write to input GPIO #{inspect(state.gpio_spec)}") 112 | {:reply, :ok, state} 113 | end 114 | end 115 | 116 | def handle_call(:read, _from, state) do 117 | {value, new_state} = do_read(state) 118 | {:reply, value, new_state} 119 | end 120 | 121 | def handle_call({:set_direction, direction}, _from, state) do 122 | {:reply, :ok, %{state | direction: direction}} 123 | end 124 | 125 | def handle_call({:set_pull_mode, mode}, _from, state) do 126 | {:reply, :ok, %{state | pull_mode: mode}} 127 | end 128 | 129 | def handle_call({:set_interrupts, trigger, receiver}, _from, state) do 130 | new_state = %{state | interrupt_receiver: receiver, interrupt_trigger: trigger} 131 | 132 | {:reply, :ok, new_state} 133 | end 134 | 135 | def handle_call(:render, _from, state) do 136 | {:reply, GPIODevice.render(state.device), state} 137 | end 138 | 139 | def handle_call({:send_message, message}, _from, state) do 140 | {result, new_device} = GPIODevice.handle_message(state.device, message) 141 | state = %{state | device: new_device} 142 | 143 | # Perform a read just in case the state changed and interrupt messages 144 | # need to be sent. 145 | {_value, state} = do_read(state) 146 | 147 | {:reply, result, state} 148 | end 149 | 150 | @impl GenServer 151 | def handle_info(message, state) do 152 | new_device = GPIODevice.handle_info(state.device, message) 153 | state = %{state | device: new_device} 154 | 155 | # Perform a read just in case the state changed and interrupt messages 156 | # need to be sent. 157 | {_value, state} = do_read(state) 158 | 159 | {:noreply, state} 160 | end 161 | 162 | defp do_read(state) do 163 | case state.direction do 164 | :output -> 165 | {state.cached_value, state} 166 | 167 | :input -> 168 | raw_value = GPIODevice.read(state.device) 169 | value = process_read(state, raw_value) 170 | handle_gpio_change(state, state.cached_value, value) 171 | {value, %{state | cached_value: value}} 172 | end 173 | end 174 | 175 | defp process_read(_state, value) when is_integer(value), do: value 176 | defp process_read(%{pull_mode: :pullup}, :hi_z), do: 1 177 | defp process_read(%{pull_mode: :pulldown}, :hi_z), do: 0 178 | 179 | defp process_read(state, :hi_z) do 180 | Logger.warning( 181 | "GPIO #{inspect(state.gpio_spec)} is in high impedance state. Set pull mode to reliably read." 182 | ) 183 | 184 | 0 185 | end 186 | 187 | defp handle_gpio_change(%{interrupt_receiver: nil}, _old_value, _value), do: :ok 188 | 189 | defp handle_gpio_change(%{interrupt_trigger: :both} = state, old_value, value) 190 | when old_value != value do 191 | send_interrupt_message(state, value) 192 | end 193 | 194 | defp handle_gpio_change(%{interrupt_trigger: :rising} = state, old_value, value) 195 | when old_value < value do 196 | send_interrupt_message(state, value) 197 | end 198 | 199 | defp handle_gpio_change(%{interrupt_trigger: :falling} = state, old_value, value) 200 | when old_value > value do 201 | send_interrupt_message(state, value) 202 | end 203 | 204 | defp handle_gpio_change(_state, _old_value, _value), do: :ok 205 | 206 | defp send_interrupt_message(state, value) do 207 | {uptime_ms, _} = :erlang.statistics(:wall_clock) 208 | uptime_ns = uptime_ms * 1_000_000 209 | send(state.interrupt_receiver, {:circuits_gpio, state.gpio_spec, uptime_ns, value}) 210 | end 211 | end 212 | -------------------------------------------------------------------------------- /lib/circuits_sim/gpio/handle.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.GPIO.Handle do 6 | @moduledoc false 7 | 8 | alias Circuits.GPIO.Handle 9 | alias CircuitsSim.GPIO.GPIOServer 10 | 11 | defstruct [:gpio_spec] 12 | 13 | @type t() :: %__MODULE__{ 14 | gpio_spec: Circuits.GPIO.gpio_spec() 15 | } 16 | 17 | @spec render(t()) :: String.t() 18 | def render(%__MODULE__{} = handle) do 19 | GPIOServer.render(handle.gpio_spec) 20 | |> IO.ANSI.format() 21 | |> IO.chardata_to_string() 22 | end 23 | 24 | defimpl Handle do 25 | alias CircuitsSim.GPIO.GPIOServer 26 | 27 | @impl Handle 28 | def read(%CircuitsSim.GPIO.Handle{} = handle) do 29 | GPIOServer.read(handle.gpio_spec) 30 | end 31 | 32 | @impl Handle 33 | def write(%CircuitsSim.GPIO.Handle{} = handle, value) do 34 | GPIOServer.write(handle.gpio_spec, value) 35 | end 36 | 37 | @impl Handle 38 | def set_direction(%CircuitsSim.GPIO.Handle{} = handle, direction) do 39 | GPIOServer.set_direction(handle.gpio_spec, direction) 40 | end 41 | 42 | @impl Handle 43 | def set_interrupts(%CircuitsSim.GPIO.Handle{} = handle, trigger, options) do 44 | GPIOServer.set_interrupts(handle.gpio_spec, trigger, options) 45 | end 46 | 47 | @impl Handle 48 | def set_pull_mode(%CircuitsSim.GPIO.Handle{} = handle, pull_mode) do 49 | GPIOServer.set_pull_mode(handle.gpio_spec, pull_mode) 50 | end 51 | 52 | @impl Handle 53 | def close(%CircuitsSim.GPIO.Handle{}), do: :ok 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /lib/circuits_sim/i2c/backend.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.I2C.Backend do 6 | @moduledoc """ 7 | Circuits.I2C backend for virtual I2C devices 8 | """ 9 | @behaviour Circuits.I2C.Backend 10 | 11 | alias Circuits.I2C.Backend 12 | alias CircuitsSim.DeviceRegistry 13 | alias CircuitsSim.I2C.Bus 14 | 15 | @doc """ 16 | Return the I2C bus names on this system 17 | 18 | No supported options 19 | """ 20 | @impl Backend 21 | def bus_names(_options) do 22 | DeviceRegistry.bus_names(:i2c) 23 | end 24 | 25 | @doc """ 26 | Open an I2C bus 27 | """ 28 | @impl Backend 29 | def open(bus_name, options) do 30 | if bus_name in bus_names(options) do 31 | {:ok, %Bus{bus_name: bus_name}} 32 | else 33 | {:error, "Unknown controller #{bus_name}"} 34 | end 35 | end 36 | 37 | @doc """ 38 | Return information about this backend 39 | """ 40 | @impl Backend 41 | def info() do 42 | %{backend: __MODULE__} 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /lib/circuits_sim/i2c/bus.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.I2C.Bus do 7 | @moduledoc false 8 | 9 | alias Circuits.I2C.Bus 10 | alias CircuitsSim.I2C.I2CServer 11 | alias CircuitsSim.Tools 12 | 13 | defstruct [:bus_name] 14 | @type t() :: %__MODULE__{bus_name: String.t()} 15 | 16 | @spec render(t()) :: String.t() 17 | def render(%__MODULE__{} = bus) do 18 | for address <- 0..127 do 19 | info = I2CServer.render(bus.bus_name, address) 20 | hex_addr = Tools.hex_byte(address) 21 | if info != [], do: ["Device 0x#{hex_addr}: \n", info, "\n"], else: [] 22 | end 23 | |> IO.ANSI.format() 24 | |> IO.chardata_to_string() 25 | end 26 | 27 | defimpl Bus do 28 | @impl Bus 29 | def flags(%CircuitsSim.I2C.Bus{}) do 30 | [:supports_empty_write] 31 | end 32 | 33 | @impl Bus 34 | def read(%CircuitsSim.I2C.Bus{} = bus, address, count, _options) do 35 | I2CServer.read(bus.bus_name, address, count) 36 | end 37 | 38 | @impl Bus 39 | def write(%CircuitsSim.I2C.Bus{} = bus, address, data, _options) do 40 | I2CServer.write(bus.bus_name, address, data) 41 | end 42 | 43 | @impl Bus 44 | def write_read( 45 | %CircuitsSim.I2C.Bus{} = bus, 46 | address, 47 | write_data, 48 | read_count, 49 | _options 50 | ) do 51 | I2CServer.write_read(bus.bus_name, address, write_data, read_count) 52 | end 53 | 54 | @impl Bus 55 | def close(%CircuitsSim.I2C.Bus{}), do: :ok 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /lib/circuits_sim/i2c/i2c_device.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defprotocol CircuitsSim.I2C.I2CDevice do 6 | @moduledoc """ 7 | A protocol for I2C devices 8 | 9 | See `Circuits.I2C.SimpleI2CDevice` if you have a simple register-based I2C device. 10 | """ 11 | 12 | @doc """ 13 | Read count bytes 14 | 15 | The first item in the returned tuple is what's returned from the original 16 | call to Circuits.I2C.read/2. Try to make the errors consistent with that 17 | function if possible. 18 | """ 19 | @spec read(t(), non_neg_integer()) :: {{:ok, binary()} | {:error, any()}, t()} 20 | def read(dev, count) 21 | 22 | @doc """ 23 | Write data to the device 24 | """ 25 | @spec write(t(), binary()) :: t() 26 | def write(dev, data) 27 | 28 | @doc """ 29 | Write data to the device and immediately follow it with a read 30 | """ 31 | @spec write_read(t(), binary(), non_neg_integer()) :: {{:ok, binary()} | {:error, any()}, t()} 32 | def write_read(dev, data, read_count) 33 | 34 | @doc """ 35 | Return the internal state as ASCII art 36 | """ 37 | @spec render(t()) :: IO.ANSI.ansidata() 38 | def render(dev) 39 | 40 | @doc """ 41 | Handle an user message 42 | 43 | User messages are used to modify the state of the simulated device outside of 44 | I2C. This can be used to simulate real world changes like temperature changes 45 | affecting a simulated temperature sensor. Another use is as a hook for getting 46 | internal state. 47 | """ 48 | @spec handle_message(t(), any()) :: {any(), t()} 49 | def handle_message(dev, message) 50 | end 51 | -------------------------------------------------------------------------------- /lib/circuits_sim/i2c/i2c_server.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 4 | # SPDX-FileCopyrightText: 2024 Filipe Alves 5 | # 6 | # SPDX-License-Identifier: Apache-2.0 7 | # 8 | defmodule CircuitsSim.I2C.I2CServer do 9 | @moduledoc false 10 | 11 | use GenServer 12 | 13 | alias Circuits.I2C 14 | alias CircuitsSim.DeviceRegistry 15 | alias CircuitsSim.I2C.I2CDevice 16 | alias CircuitsSim.I2C.SimpleI2CDevice 17 | 18 | defstruct [:device, :protocol, :register] 19 | 20 | @type init_args :: [bus_name: String.t(), address: Circuits.I2C.address()] 21 | 22 | @doc """ 23 | Helper for creating child_specs for simple I2C implementations 24 | """ 25 | @spec child_spec_helper(I2CDevice.t() | SimpleI2CDevice.t(), init_args()) :: %{ 26 | :id => __MODULE__, 27 | :start => {__MODULE__, :start_link, [[any()], ...]} 28 | } 29 | def child_spec_helper(device, args) do 30 | bus_name = Keyword.fetch!(args, :bus_name) 31 | address = Keyword.fetch!(args, :address) 32 | 33 | combined_args = Keyword.merge([device: device, name: via_name(bus_name, address)], args) 34 | 35 | %{ 36 | id: __MODULE__, 37 | start: {__MODULE__, :start_link, [combined_args]} 38 | } 39 | end 40 | 41 | @spec start_link(keyword()) :: GenServer.on_start() 42 | def start_link(init_args) do 43 | bus_name = Keyword.fetch!(init_args, :bus_name) 44 | address = Keyword.fetch!(init_args, :address) 45 | 46 | GenServer.start_link(__MODULE__, init_args, name: via_name(bus_name, address)) 47 | end 48 | 49 | # Helper for constructing the via_name for I2CDevice servers 50 | defp via_name(bus_name, address) do 51 | DeviceRegistry.via_name(:i2c, bus_name, address) 52 | end 53 | 54 | # Helper for calling GenServer.call/2 for I2CDevice servers 55 | # 56 | # If the server is down, it naks just like a broken I2C device would 57 | defp gen_call(bus_name, address, message) do 58 | GenServer.call(via_name(bus_name, address), message) 59 | catch 60 | :exit, {:noproc, _} -> {:error, :nak} 61 | end 62 | 63 | @spec read(String.t(), I2C.address(), non_neg_integer()) :: 64 | {:ok, binary()} | {:error, any()} 65 | def read(bus_name, address, count) do 66 | gen_call(bus_name, address, {:read, count}) 67 | end 68 | 69 | @spec write(String.t(), I2C.address(), iodata()) :: :ok | {:error, any()} 70 | def write(bus_name, address, data) do 71 | gen_call(bus_name, address, {:write, data}) 72 | end 73 | 74 | @spec write_read(String.t(), I2C.address(), iodata(), non_neg_integer()) :: 75 | {:ok, binary()} | {:error, any()} 76 | def write_read(bus_name, address, data, read_count) do 77 | gen_call(bus_name, address, {:write_read, data, read_count}) 78 | end 79 | 80 | @spec render(String.t(), I2C.address()) :: IO.ANSI.ansidata() 81 | def render(bus_name, address) do 82 | case gen_call(bus_name, address, :render) do 83 | {:error, _} -> [] 84 | info -> info 85 | end 86 | end 87 | 88 | @spec send_message(String.t(), I2C.address(), any()) :: any() 89 | def send_message(bus_name, address, message) do 90 | GenServer.call(via_name(bus_name, address), {:send_message, message}) 91 | end 92 | 93 | @impl GenServer 94 | def init(init_args) do 95 | device = Keyword.fetch!(init_args, :device) 96 | protocol = protocol_for(device) 97 | 98 | {:ok, %__MODULE__{device: device, protocol: protocol, register: 0}} 99 | end 100 | 101 | # Seems like there ought to have been a better way to write this... 102 | defp protocol_for(s) do 103 | known_protocols = [I2CDevice, SimpleI2CDevice] 104 | 105 | protocol = 106 | Enum.find(known_protocols, fn p -> 107 | impl = Module.concat(p, s.__struct__) 108 | {:module, impl} == Code.ensure_loaded(impl) 109 | end) 110 | 111 | protocol || 112 | raise "Was expecting #{inspect(s.__struct__)} to implement one of #{inspect(known_protocols)}" 113 | end 114 | 115 | @impl GenServer 116 | def handle_call({:read, count}, _from, state) do 117 | {result, new_state} = do_read(state, count) 118 | {:reply, result, new_state} 119 | end 120 | 121 | def handle_call({:write, data}, _from, state) do 122 | new_state = do_write(state, IO.iodata_to_binary(data)) 123 | {:reply, :ok, new_state} 124 | end 125 | 126 | def handle_call({:write_read, data, read_count}, _from, state) do 127 | {result, new_state} = do_write_read(state, IO.iodata_to_binary(data), read_count) 128 | {:reply, result, new_state} 129 | end 130 | 131 | def handle_call(:render, _from, state) do 132 | {:reply, do_render(state), state} 133 | end 134 | 135 | def handle_call({:send_message, message}, _from, state) do 136 | {result, new_device} = do_send_message(state, message) 137 | {:reply, result, %{state | device: new_device}} 138 | end 139 | 140 | defp do_read(%{protocol: I2CDevice} = state, count) do 141 | {result, new_device} = I2CDevice.read(state.device, count) 142 | {result, %{state | device: new_device}} 143 | end 144 | 145 | defp do_read(%{protocol: SimpleI2CDevice} = state, count) do 146 | simple_read(state, count, []) 147 | end 148 | 149 | defp do_write(%{protocol: I2CDevice} = state, data) do 150 | new_device = I2CDevice.write(state.device, data) 151 | %{state | device: new_device} 152 | end 153 | 154 | defp do_write(%{protocol: SimpleI2CDevice} = state, data) do 155 | simple_write(state, data) 156 | end 157 | 158 | defp do_write_read(%{protocol: I2CDevice} = state, data, read_count) do 159 | {result, new_device} = I2CDevice.write_read(state.device, data, read_count) 160 | {result, %{state | device: new_device}} 161 | end 162 | 163 | defp do_write_read(%{protocol: SimpleI2CDevice} = state, data, read_count) do 164 | state |> simple_write(data) |> simple_read(read_count, []) 165 | end 166 | 167 | defp do_render(%{protocol: I2CDevice} = state) do 168 | I2CDevice.render(state.device) 169 | end 170 | 171 | defp do_render(%{protocol: SimpleI2CDevice} = state) do 172 | SimpleI2CDevice.render(state.device) 173 | end 174 | 175 | defp do_send_message(%{protocol: I2CDevice} = state, message) do 176 | I2CDevice.handle_message(state.device, message) 177 | end 178 | 179 | defp do_send_message(%{protocol: SimpleI2CDevice} = state, message) do 180 | SimpleI2CDevice.handle_message(state.device, message) 181 | end 182 | 183 | defp simple_read(state, 0, acc) do 184 | result = acc |> Enum.reverse() |> :binary.list_to_bin() 185 | {{:ok, result}, state} 186 | end 187 | 188 | defp simple_read(state, count, acc) do 189 | reg = state.register 190 | 191 | {v, device} = SimpleI2CDevice.read_register(state.device, reg) 192 | new_state = %{state | device: device, register: inc8(reg)} 193 | 194 | simple_read(new_state, count - 1, [v | acc]) 195 | end 196 | 197 | defp simple_write(state, <<>>), do: state 198 | defp simple_write(state, <>), do: %{state | register: reg} 199 | 200 | defp simple_write(state, <>) do 201 | device = SimpleI2CDevice.write_register(state.device, reg, value) 202 | %{state | device: device, register: inc8(reg)} 203 | end 204 | 205 | defp simple_write(state, <>) do 206 | device = SimpleI2CDevice.write_register(state.device, reg, value) 207 | register = inc8(reg) 208 | 209 | new_state = %{state | device: device, register: register} 210 | 211 | do_write(new_state, <>) 212 | end 213 | 214 | defp inc8(255), do: 0 215 | defp inc8(x), do: x + 1 216 | end 217 | -------------------------------------------------------------------------------- /lib/circuits_sim/i2c/simple_i2c_device.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defprotocol CircuitsSim.I2C.SimpleI2CDevice do 6 | @moduledoc """ 7 | A protocol that makes register-based I2C devices easier to simulate 8 | """ 9 | 10 | @doc """ 11 | Write a value to a register 12 | """ 13 | @spec write_register(t(), non_neg_integer(), non_neg_integer()) :: t() 14 | def write_register(dev, reg, value) 15 | 16 | @doc """ 17 | Read a register 18 | """ 19 | @spec read_register(t(), non_neg_integer()) :: {non_neg_integer(), t()} 20 | def read_register(dev, reg) 21 | 22 | @doc """ 23 | Return a pretty printable view the the state 24 | """ 25 | @spec render(t()) :: IO.ANSI.ansidata() 26 | def render(dev) 27 | 28 | @doc """ 29 | Handle an user message 30 | 31 | User messages are used to modify the state of the simulated device outside of 32 | I2C. This can be used to simulate real world changes like temperature changes 33 | affecting a simulated temperature sensor. Another use is as a hook for getting 34 | internal state. 35 | """ 36 | @spec handle_message(t(), any()) :: {any(), t()} 37 | def handle_message(dev, message) 38 | end 39 | -------------------------------------------------------------------------------- /lib/circuits_sim/spi/backend.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.SPI.Backend do 6 | @moduledoc """ 7 | Circuits.SPI backend for virtual SPI devices 8 | """ 9 | @behaviour Circuits.SPI.Backend 10 | 11 | alias Circuits.SPI.Backend 12 | alias CircuitsSim.DeviceRegistry 13 | alias CircuitsSim.SPI.Bus 14 | 15 | @doc """ 16 | Return the I2C bus names on this system 17 | 18 | No supported options 19 | """ 20 | @impl Backend 21 | def bus_names(_options) do 22 | DeviceRegistry.bus_names(:spi) 23 | end 24 | 25 | @doc """ 26 | Open an I2C bus 27 | """ 28 | @impl Backend 29 | def open(bus_name, options) do 30 | if bus_name in bus_names(options) do 31 | mode = Keyword.get(options, :mode, 0) 32 | bits_per_word = Keyword.get(options, :bits_per_word, 8) 33 | speed_hz = Keyword.get(options, :speed_hz, 1_000_000) 34 | delay_us = Keyword.get(options, :delay_us, 10) 35 | lsb_first = Keyword.get(options, :lsb_first, false) 36 | 37 | config = %{ 38 | mode: mode, 39 | bits_per_word: bits_per_word, 40 | speed_hz: speed_hz, 41 | delay_us: delay_us, 42 | lsb_first: lsb_first, 43 | sw_lsb_first: lsb_first 44 | } 45 | 46 | {:ok, %Bus{bus_name: bus_name, config: config}} 47 | else 48 | {:error, "Unknown controller #{bus_name}"} 49 | end 50 | end 51 | 52 | @doc """ 53 | Return information about this backend 54 | """ 55 | @impl Backend 56 | def info() do 57 | %{backend: __MODULE__} 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /lib/circuits_sim/spi/bus.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.SPI.Bus do 6 | @moduledoc false 7 | 8 | alias Circuits.SPI.Bus 9 | alias CircuitsSim.SPI.SPIServer 10 | 11 | defstruct [:bus_name, :config] 12 | @type t() :: %__MODULE__{bus_name: String.t(), config: Circuits.SPI.spi_option_map()} 13 | 14 | @spec render(t()) :: String.t() 15 | def render(%__MODULE__{} = bus) do 16 | SPIServer.render(bus.bus_name) 17 | |> IO.ANSI.format() 18 | |> IO.chardata_to_string() 19 | end 20 | 21 | defimpl Bus do 22 | @impl Bus 23 | def config(%CircuitsSim.SPI.Bus{} = bus) do 24 | {:ok, bus.config} 25 | end 26 | 27 | @impl Bus 28 | def transfer(%CircuitsSim.SPI.Bus{} = bus, data) do 29 | SPIServer.transfer(bus.bus_name, data) 30 | end 31 | 32 | @impl Bus 33 | def close(%CircuitsSim.SPI.Bus{}), do: :ok 34 | 35 | @impl Bus 36 | def max_transfer_size(%CircuitsSim.SPI.Bus{}), do: 1024 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /lib/circuits_sim/spi/spi_device.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defprotocol CircuitsSim.SPI.SPIDevice do 6 | @moduledoc """ 7 | A protocol for SPI devices 8 | """ 9 | 10 | @doc """ 11 | Transfer data 12 | """ 13 | @spec transfer(t(), binary()) :: {binary(), t()} 14 | def transfer(dev, count) 15 | 16 | @doc """ 17 | Return the internal state as ASCII art 18 | """ 19 | @spec render(t()) :: IO.ANSI.ansidata() 20 | def render(dev) 21 | 22 | @doc """ 23 | Handle an user message 24 | 25 | User messages are used to modify the state of the simulated device outside of 26 | SPI. This can be used to simulate real world changes like temperature changes 27 | affecting a simulated temperature sensor. Another use is as a hook for getting 28 | internal state. 29 | """ 30 | @spec handle_message(t(), any()) :: {any(), t()} 31 | def handle_message(dev, message) 32 | end 33 | -------------------------------------------------------------------------------- /lib/circuits_sim/spi/spi_server.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | defmodule CircuitsSim.SPI.SPIServer do 8 | @moduledoc false 9 | 10 | use GenServer 11 | 12 | alias CircuitsSim.DeviceRegistry 13 | alias CircuitsSim.SPI.SPIDevice 14 | 15 | defstruct [:device] 16 | 17 | @type init_args :: [bus_name: String.t()] 18 | 19 | @doc """ 20 | Helper for creating child_specs for simple I2C implementations 21 | """ 22 | @spec child_spec_helper(SPIDevice.t(), init_args()) :: %{ 23 | :id => __MODULE__, 24 | :start => {__MODULE__, :start_link, [[any()], ...]} 25 | } 26 | def child_spec_helper(device, args) do 27 | bus_name = Keyword.fetch!(args, :bus_name) 28 | 29 | combined_args = Keyword.merge([device: device, name: via_name(bus_name)], args) 30 | 31 | %{ 32 | id: __MODULE__, 33 | start: {__MODULE__, :start_link, [combined_args]} 34 | } 35 | end 36 | 37 | @spec start_link(keyword()) :: GenServer.on_start() 38 | def start_link(init_args) do 39 | bus_name = Keyword.fetch!(init_args, :bus_name) 40 | 41 | GenServer.start_link(__MODULE__, init_args, name: via_name(bus_name)) 42 | end 43 | 44 | # Helper for constructing the via_name for SPIDevice servers 45 | defp via_name(bus_name) do 46 | DeviceRegistry.via_name(:spi, bus_name, 0) 47 | end 48 | 49 | # Helper for calling GenServer.call/2 for SPIDevice servers 50 | # 51 | # If the server is down, return an error rather than raise so 52 | # functions can blindly poll. 53 | defp gen_call(bus_name, message) do 54 | GenServer.call(via_name(bus_name), message) 55 | catch 56 | :exit, {:noproc, _} -> {:error, :not_running} 57 | end 58 | 59 | @doc """ 60 | Transfer data to a simulated SPI device 61 | 62 | This returns junk on errors just like a normal SPI device would. 63 | """ 64 | @spec transfer(String.t(), iodata()) :: {:ok, binary()} 65 | def transfer(bus_name, data) do 66 | GenServer.call(via_name(bus_name), {:transfer, data}) 67 | catch 68 | :exit, {:noproc, _} -> 69 | junk = :binary.copy(<<0>>, IO.iodata_length(data)) 70 | {:ok, junk} 71 | end 72 | 73 | @spec render(String.t()) :: IO.ANSI.ansidata() 74 | def render(bus_name) do 75 | gen_call(bus_name, :render) 76 | end 77 | 78 | @spec send_message(String.t(), any()) :: any() 79 | def send_message(bus_name, message) do 80 | GenServer.call(via_name(bus_name), {:send_message, message}) 81 | end 82 | 83 | @impl GenServer 84 | def init(init_args) do 85 | device = Keyword.fetch!(init_args, :device) 86 | 87 | {:ok, %__MODULE__{device: device}} 88 | end 89 | 90 | @impl GenServer 91 | def handle_call({:transfer, data}, _from, state) do 92 | {result, new_device} = SPIDevice.transfer(state.device, data) 93 | {:reply, result, %{state | device: new_device}} 94 | end 95 | 96 | def handle_call(:render, _from, state) do 97 | {:reply, SPIDevice.render(state.device), state} 98 | end 99 | 100 | def handle_call({:send_message, message}, _from, state) do 101 | {result, new_device} = SPIDevice.handle_message(state.device, message) 102 | {:reply, result, %{state | device: new_device}} 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /lib/circuits_sim/tools.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Jon Carstens 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Tools do 7 | @moduledoc false 8 | 9 | @spec hex_byte(byte()) :: String.t() 10 | def hex_byte(x) when x >= 0 and x <= 255 do 11 | Integer.to_string(div(x, 16), 16) <> Integer.to_string(rem(x, 16), 16) 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule CircuitsSim.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.1.2" 5 | @description "Simulated hardware for Elixir Circuits" 6 | @source_url "https://github.com/elixir-circuits/circuits_sim" 7 | 8 | def project do 9 | [ 10 | app: :circuits_sim, 11 | version: @version, 12 | elixir: "~> 1.13", 13 | description: @description, 14 | package: package(), 15 | source_url: @source_url, 16 | docs: docs(), 17 | start_permanent: Mix.env() == :prod, 18 | dialyzer: [ 19 | flags: [:missing_return, :extra_return, :unmatched_returns, :error_handling, :underspecs] 20 | ], 21 | deps: deps(), 22 | preferred_cli_env: %{ 23 | docs: :docs, 24 | "hex.publish": :docs, 25 | "hex.build": :docs 26 | } 27 | ] 28 | end 29 | 30 | def application do 31 | [ 32 | extra_applications: [:logger], 33 | mod: {CircuitsSim.Application, []} 34 | ] 35 | end 36 | 37 | defp package do 38 | [ 39 | files: [ 40 | "CHANGELOG.md", 41 | "lib", 42 | "LICENSES", 43 | "mix.exs", 44 | "NOTICE", 45 | "README.md", 46 | "REUSE.toml" 47 | ], 48 | licenses: ["Apache-2.0"], 49 | links: %{ 50 | "GitHub" => @source_url, 51 | "REUSE Compliance" => 52 | "https://api.reuse.software/info/github.com/elixir-circuits/circuits_sim" 53 | } 54 | ] 55 | end 56 | 57 | defp deps() do 58 | [ 59 | {:circuits_i2c, "~> 2.0"}, 60 | {:circuits_spi, "~> 2.0"}, 61 | {:circuits_gpio, "~> 2.0"}, 62 | {:bmp280, "~> 0.2.12", only: [:dev, :test]}, 63 | {:bmp3xx, "~> 0.1.5", only: [:dev, :test]}, 64 | {:sgp30, github: "jjcarstens/sgp30", branch: "main", only: [:dev, :test]}, 65 | {:cerlc, "~> 0.2.1"}, 66 | {:aht20, "~> 0.4.0", only: [:dev, :test]}, 67 | {:sht4x, "~> 0.2.0", only: [:dev, :test]}, 68 | {:ex_doc, "~> 0.22", only: :docs, runtime: false}, 69 | {:credo, "~> 1.6", only: :dev, runtime: false}, 70 | {:credo_binary_patterns, "~> 0.2.2", only: :dev, runtime: false}, 71 | {:dialyxir, "~> 1.2", only: :dev, runtime: false} 72 | ] 73 | end 74 | 75 | defp docs do 76 | [ 77 | extras: ["README.md"], 78 | main: "readme", 79 | source_ref: "v#{@version}", 80 | source_url: @source_url 81 | ] 82 | end 83 | end 84 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "aht20": {:hex, :aht20, "0.4.3", "c650cf3459b37278b0f6c07750519d311591cfb91ac45dac993d43924e999b8e", [:mix], [{:circuits_i2c, "~> 0.3.0 or ~> 1.0 or ~> 2.0", [hex: :circuits_i2c, repo: "hexpm", optional: false]}], "hexpm", "290f47a23a0bf881e0265f5b2571dbbca1739f75acb39c14f83f66948f3cc57c"}, 3 | "bmp280": {:hex, :bmp280, "0.2.13", "2599e8cd7cbc11762f5f0da00ef42238bd20bb5c6b9a90291200f6171f62068b", [:mix], [{:circuits_i2c, "~> 0.3.0 or ~> 1.0 or ~> 2.0", [hex: :circuits_i2c, repo: "hexpm", optional: false]}], "hexpm", "01bb119684be8a82a03f51b0540c816b7a68667b3958bbb8009f830ac198c883"}, 4 | "bmp3xx": {:hex, :bmp3xx, "0.1.7", "21fd96f175552bb829d3b17548e687c35771633e372fcf939508bdf43857b81f", [:mix], [{:circuits_i2c, "~> 0.3 or ~> 1.0 or ~> 2.0", [hex: :circuits_i2c, repo: "hexpm", optional: false]}], "hexpm", "263f58bbea8c2ce88ff85ce4c196e76f7cb9676daaf2624ce461be35bd6e62dc"}, 5 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 6 | "cerlc": {:hex, :cerlc, "0.2.1", "cfe0880aa049ebcca079ca49578055aa48e7f2e9ed8ae08bd1f919d59015d03f", [:rebar3], [], "hexpm", "37f0d74a4277dcbaf64c7c47e9953dcc8060d26d86bb466ab2a86928e0181a7d"}, 7 | "circuits_gpio": {:hex, :circuits_gpio, "2.1.2", "b4efcf84e6a74910b9fd0488d9fc8177d1cf80bb585782caaafc91bb035a74a4", [:make, :mix], [{:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "4b7c9de074a3c00937c01b0cd8781dd9114b1eb4705e99e7a22d46ad4899e157"}, 8 | "circuits_i2c": {:hex, :circuits_i2c, "2.0.7", "3f0981743e9f43041edc43eda3964791e71d1231c0fbfebd50595ca564aee1ea", [:make, :mix], [{:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "57b556e5a7985e80518f23c9cbefc1bc333890a30252b690c049f6ac4c3f9911"}, 9 | "circuits_spi": {:hex, :circuits_spi, "2.0.4", "b75f64c0401e3c64319dcfc76a9bc17466e4469adc5daf34165f4c4b11cf12ee", [:make, :mix], [{:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "ccf034065091f26c624dee777ea3f48ce64696af812622e1d060b2cffdbf90e4"}, 10 | "credo": {:hex, :credo, "1.7.11", "d3e805f7ddf6c9c854fd36f089649d7cf6ba74c42bc3795d587814e3c9847102", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "56826b4306843253a66e47ae45e98e7d284ee1f95d53d1612bb483f88a8cf219"}, 11 | "credo_binary_patterns": {:hex, :credo_binary_patterns, "0.2.6", "cfcaca0bc5c6447b96c5a03eff175c28f86c486be8e95d55b360fb90c2dd18bd", [:mix], [{:credo, "~> 1.6", [hex: :credo, repo: "hexpm", optional: false]}], "hexpm", "d36a2b56ad72bdf3183ccc81d7e7821e78c97de7c127bc8dd99a5f05ca702187"}, 12 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 13 | "earmark_parser": {:hex, :earmark_parser, "1.4.43", "34b2f401fe473080e39ff2b90feb8ddfeef7639f8ee0bbf71bb41911831d77c5", [:mix], [], "hexpm", "970a3cd19503f5e8e527a190662be2cee5d98eed1ff72ed9b3d1a3d466692de8"}, 14 | "elixir_make": {:hex, :elixir_make, "0.9.0", "6484b3cd8c0cee58f09f05ecaf1a140a8c97670671a6a0e7ab4dc326c3109726", [:mix], [], "hexpm", "db23d4fd8b757462ad02f8aa73431a426fe6671c80b200d9710caf3d1dd0ffdb"}, 15 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 16 | "ex_doc": {:hex, :ex_doc, "0.37.0", "970f92b39e62c460aa8a367508e938f5e4da6e2ff3eaed3f8530b25870f45471", [:mix], [{:earmark_parser, "~> 1.4.42", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "b0ee7f17373948e0cf471e59c3a0ee42f3bd1171c67d91eb3626456ef9c6202c"}, 17 | "file_system": {:hex, :file_system, "1.1.0", "08d232062284546c6c34426997dd7ef6ec9f8bbd090eb91780283c9016840e8f", [:mix], [], "hexpm", "bfcf81244f416871f2a2e15c1b515287faa5db9c6bcf290222206d120b3d43f6"}, 18 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 19 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 20 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 21 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.2", "03e1804074b3aa64d5fad7aa64601ed0fb395337b982d9bcf04029d68d51b6a7", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "af33ff7ef368d5893e4a267933e7744e46ce3cf1f61e2dccf53a111ed3aa3727"}, 22 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, 23 | "sgp30": {:git, "https://github.com/jjcarstens/sgp30.git", "c5d1ed63b5449ca37bbe60bc906db1f81d05fd46", [branch: "main"]}, 24 | "sht4x": {:hex, :sht4x, "0.2.3", "4dc5a97144037ebc12c6c7cb102d965c8a693bc89bb2b08f4558cd6c7a5e342c", [:mix], [{:cerlc, "~> 0.2.0", [hex: :cerlc, repo: "hexpm", optional: false]}, {:circuits_i2c, "~> 1.0 or ~> 2.0", [hex: :circuits_i2c, repo: "hexpm", optional: false]}, {:typed_struct, "~> 0.3.0", [hex: :typed_struct, repo: "hexpm", optional: false]}], "hexpm", "6e7dc1219e6490e725e21fdfe634b9d849b89f6d211bc38d1a38afb4c93cdac4"}, 25 | "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, 26 | "typed_struct": {:hex, :typed_struct, "0.3.0", "939789e3c1dca39d7170c87f729127469d1315dcf99fee8e152bb774b17e7ff7", [:mix], [], "hexpm", "c50bd5c3a61fe4e198a8504f939be3d3c85903b382bde4865579bc23111d1b6d"}, 27 | } 28 | -------------------------------------------------------------------------------- /test/circuits_sim/device/ads7138_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.ADS7138Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.Device.ADS7138 9 | alias CircuitsSim.I2C.I2CDevice 10 | 11 | test "supports empty writes" do 12 | device = ADS7138.new() 13 | 14 | # Test that it doesn't crash 15 | assert _ = I2CDevice.write(device, <<>>) 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /test/circuits_sim/device/aht20_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.AHT20Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.I2C.I2CServer 9 | alias CircuitsSim.Device.AHT20, as: AHT20Sim 10 | 11 | @i2c_address 0x38 12 | 13 | test "setting AHT20 state", %{test: test_name} do 14 | i2c_bus = to_string(test_name) 15 | start_supervised!({AHT20Sim, bus_name: i2c_bus, address: @i2c_address}) 16 | 17 | AHT20Sim.set_humidity_rh(i2c_bus, @i2c_address, 12.3) 18 | AHT20Sim.set_temperature_c(i2c_bus, @i2c_address, 32.1) 19 | 20 | assert I2CServer.render(i2c_bus, @i2c_address) == 21 | "Temperature: 32.1°C, Relative humidity: 12.3%" 22 | end 23 | 24 | test "supports AHT20 package", %{test: test_name} do 25 | i2c_bus = to_string(test_name) 26 | start_supervised!({AHT20Sim, bus_name: i2c_bus, address: @i2c_address}) 27 | 28 | aht_pid = 29 | start_supervised!({AHT20, bus_name: i2c_bus, address: @i2c_address, name: test_name}) 30 | 31 | AHT20Sim.set_temperature_c(i2c_bus, @i2c_address, 11.1) 32 | AHT20Sim.set_humidity_rh(i2c_bus, @i2c_address, 33.3) 33 | 34 | {:ok, measurement} = AHT20.measure(aht_pid) 35 | assert_in_delta measurement.humidity_rh, 33.3, 0.1 36 | assert_in_delta measurement.temperature_c, 11.1, 0.1 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /test/circuits_sim/device/at24c02_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.AT24C02Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.Device.AT24C02 9 | alias CircuitsSim.I2C.SimpleI2CDevice 10 | 11 | test "reads and writes EEPROM" do 12 | eeprom = AT24C02.new() 13 | 14 | eeprom = SimpleI2CDevice.write_register(eeprom, 0, 5) 15 | {result, eeprom} = SimpleI2CDevice.read_register(eeprom, 0) 16 | assert result == 5 17 | 18 | eeprom = SimpleI2CDevice.write_register(eeprom, 255, 123) 19 | {result, _eeprom} = SimpleI2CDevice.read_register(eeprom, 255) 20 | assert result == 123 21 | end 22 | 23 | test "renders" do 24 | eeprom = 25 | Enum.reduce(0..255, AT24C02.new(), fn i, acc -> 26 | SimpleI2CDevice.write_register(acc, i, i) 27 | end) 28 | 29 | actual = SimpleI2CDevice.render(eeprom) |> IO.ANSI.format(false) |> IO.chardata_to_string() 30 | 31 | expected = """ 32 | 0 1 2 3 4 5 6 7 8 9 A B C D E F 33 | 00: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 34 | 10: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 35 | 20: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 36 | 30: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 37 | 40: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 38 | 50: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 39 | 60: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 40 | 70: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 41 | 80: 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 42 | 90: 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F 43 | A0: A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF 44 | B0: B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF 45 | C0: C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF 46 | D0: D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF 47 | E0: E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF 48 | F0: F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF 49 | """ 50 | 51 | assert expected == actual 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /test/circuits_sim/device/bmp3xx_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.BMP3XXTest do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.I2C.I2CServer 9 | alias CircuitsSim.Device.BMP3XX, as: BMP3XXSim 10 | 11 | @i2c_address 0x77 12 | 13 | test "setting BMP3XX state", %{test: test_name} do 14 | i2c_bus = to_string(test_name) 15 | start_supervised!({BMP3XXSim, bus_name: i2c_bus, address: @i2c_address, sensor_type: :bme680}) 16 | 17 | rendered = I2CServer.render(i2c_bus, @i2c_address) 18 | assert rendered == "Sensor type: bme680" 19 | end 20 | 21 | describe "BMP3XX package" do 22 | setup context do 23 | i2c_bus = to_string(context.test) 24 | bmp_name = context.test 25 | 26 | {BMP3XXSim, bus_name: i2c_bus, address: @i2c_address, sensor_type: context.sensor_type} 27 | |> start_supervised!() 28 | 29 | {BMP3XX, bus_name: i2c_bus, address: @i2c_address, name: bmp_name} 30 | |> start_supervised!() 31 | 32 | # wait for initial measurement 33 | Process.sleep(100) 34 | 35 | {:ok, bmp_name: bmp_name} 36 | end 37 | 38 | @tag sensor_type: :bmp380 39 | test "supports bmp380", %{bmp_name: bmp_name} do 40 | :ok = BMP3XX.force_altitude(bmp_name, 100) 41 | {:ok, measurement} = BMP3XX.measure(bmp_name) 42 | assert_in_delta measurement.temperature_c, 30.49, 0.1 43 | assert_in_delta measurement.pressure_pa, 100_876, 1 44 | assert measurement.humidity_rh == :unknown 45 | assert measurement.dew_point_c == :unknown 46 | assert measurement.gas_resistance_ohms == :unknown 47 | end 48 | 49 | @tag sensor_type: :bmp390 50 | test "supports bmp390", %{bmp_name: bmp_name} do 51 | :ok = BMP3XX.force_altitude(bmp_name, 100) 52 | {:ok, measurement} = BMP3XX.measure(bmp_name) 53 | assert_in_delta measurement.temperature_c, 30.49, 0.1 54 | assert_in_delta measurement.pressure_pa, 100_876, 1 55 | assert measurement.humidity_rh == :unknown 56 | assert measurement.dew_point_c == :unknown 57 | assert measurement.gas_resistance_ohms == :unknown 58 | end 59 | 60 | @tag sensor_type: :bmp180 61 | test "supports bmp180", %{bmp_name: bmp_name} do 62 | :ok = BMP3XX.force_altitude(bmp_name, 100) 63 | {:ok, measurement} = BMP3XX.measure(bmp_name) 64 | assert_in_delta measurement.temperature_c, 22.3, 0.1 65 | assert_in_delta measurement.pressure_pa, 101_132, 1 66 | assert measurement.humidity_rh == :unknown 67 | assert measurement.dew_point_c == :unknown 68 | assert measurement.gas_resistance_ohms == :unknown 69 | end 70 | 71 | @tag sensor_type: :bmp280 72 | test "supports bmp280", %{bmp_name: bmp_name} do 73 | :ok = BMP3XX.force_altitude(bmp_name, 100) 74 | {:ok, measurement} = BMP3XX.measure(bmp_name) 75 | assert_in_delta measurement.temperature_c, 26.7, 0.1 76 | assert_in_delta measurement.pressure_pa, 100_391, 1 77 | assert measurement.humidity_rh == :unknown 78 | assert measurement.dew_point_c == :unknown 79 | assert measurement.gas_resistance_ohms == :unknown 80 | end 81 | 82 | @tag sensor_type: :bme280 83 | test "supports bme280", %{bmp_name: bmp_name} do 84 | :ok = BMP3XX.force_altitude(bmp_name, 100) 85 | {:ok, measurement} = BMP3XX.measure(bmp_name) 86 | assert_in_delta measurement.temperature_c, 26.7, 0.1 87 | assert_in_delta measurement.pressure_pa, 100_391, 1 88 | assert_in_delta measurement.humidity_rh, 59.2, 0.1 89 | assert_in_delta measurement.dew_point_c, 18.1, 0.1 90 | assert measurement.gas_resistance_ohms == :unknown 91 | end 92 | 93 | @tag sensor_type: :bme680 94 | test "supports bme680", %{bmp_name: bmp_name} do 95 | :ok = BMP3XX.force_altitude(bmp_name, 100) 96 | {:ok, measurement} = BMP3XX.measure(bmp_name) 97 | assert_in_delta measurement.temperature_c, 19.3, 0.1 98 | assert_in_delta measurement.pressure_pa, 100_977, 1 99 | assert_in_delta measurement.humidity_rh, 25.2, 0.1 100 | assert_in_delta measurement.dew_point_c, -1.1, 0.1 101 | assert_in_delta measurement.gas_resistance_ohms, 3503.6, 0.1 102 | end 103 | end 104 | 105 | describe "BMP280 package" do 106 | setup context do 107 | i2c_bus = to_string(context.test) 108 | bmp_name = context.test 109 | 110 | {BMP3XXSim, bus_name: i2c_bus, address: @i2c_address, sensor_type: context.sensor_type} 111 | |> start_supervised!() 112 | 113 | {BMP280, bus_name: i2c_bus, address: @i2c_address, name: bmp_name} 114 | |> start_supervised!() 115 | 116 | # wait for initial measurement 117 | Process.sleep(100) 118 | 119 | {:ok, bmp_name: bmp_name} 120 | end 121 | 122 | @tag sensor_type: :bmp180 123 | test "supports bmp180", %{bmp_name: bmp_name} do 124 | :ok = BMP280.force_altitude(bmp_name, 100) 125 | {:ok, measurement} = BMP280.measure(bmp_name) 126 | assert_in_delta measurement.temperature_c, 22.3, 0.1 127 | assert_in_delta measurement.pressure_pa, 101_132, 1 128 | assert measurement.humidity_rh == :unknown 129 | assert measurement.dew_point_c == :unknown 130 | assert measurement.gas_resistance_ohms == :unknown 131 | end 132 | 133 | @tag sensor_type: :bmp280 134 | test "supports bmp280", %{bmp_name: bmp_name} do 135 | :ok = BMP280.force_altitude(bmp_name, 100) 136 | {:ok, measurement} = BMP280.measure(bmp_name) 137 | assert_in_delta measurement.temperature_c, 26.7, 0.1 138 | assert_in_delta measurement.pressure_pa, 100_391, 1 139 | assert measurement.humidity_rh == :unknown 140 | assert measurement.dew_point_c == :unknown 141 | assert measurement.gas_resistance_ohms == :unknown 142 | end 143 | 144 | @tag sensor_type: :bme280 145 | test "supports bme280", %{bmp_name: bmp_name} do 146 | :ok = BMP280.force_altitude(bmp_name, 100) 147 | {:ok, measurement} = BMP280.measure(bmp_name) 148 | assert_in_delta measurement.temperature_c, 26.7, 0.1 149 | assert_in_delta measurement.pressure_pa, 100_391, 1 150 | assert_in_delta measurement.humidity_rh, 59.2, 0.1 151 | assert_in_delta measurement.dew_point_c, 18.1, 0.1 152 | assert measurement.gas_resistance_ohms == :unknown 153 | end 154 | 155 | @tag sensor_type: :bme680 156 | test "supports bme680", %{bmp_name: bmp_name} do 157 | :ok = BMP280.force_altitude(bmp_name, 100) 158 | {:ok, measurement} = BMP280.measure(bmp_name) 159 | assert_in_delta measurement.temperature_c, 19.3, 0.1 160 | assert_in_delta measurement.pressure_pa, 100_977, 1 161 | assert_in_delta measurement.humidity_rh, 25.2, 0.1 162 | assert_in_delta measurement.dew_point_c, -1.1, 0.1 163 | assert_in_delta measurement.gas_resistance_ohms, 3503.6, 0.1 164 | end 165 | end 166 | end 167 | -------------------------------------------------------------------------------- /test/circuits_sim/device/mcp23008_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.MCP23008Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.Device.MCP23008 9 | alias CircuitsSim.I2C.SimpleI2CDevice 10 | 11 | test "reads and writes GPIOs" do 12 | mcp23008 = MCP23008.new() 13 | 14 | # Set the low 4 I/Os to output mode (reg 0) 15 | mcp23008 = SimpleI2CDevice.write_register(mcp23008, 0, 0xF0) 16 | {result, mcp23008} = SimpleI2CDevice.read_register(mcp23008, 0) 17 | assert result == 0xF0 18 | 19 | # Set the low GPIOs (reg 9) and bogusly set one of the inputs 20 | mcp23008 = SimpleI2CDevice.write_register(mcp23008, 9, 0x55) 21 | {result, _mcp23008} = SimpleI2CDevice.read_register(mcp23008, 9) 22 | assert result == 0x05 23 | end 24 | 25 | test "renders" do 26 | mcp23008 = 27 | MCP23008.new() 28 | |> SimpleI2CDevice.write_register(0, 0xF0) 29 | |> SimpleI2CDevice.write_register(9, 0x05) 30 | 31 | actual = SimpleI2CDevice.render(mcp23008) |> IO.ANSI.format(false) |> IO.chardata_to_string() 32 | 33 | expected = """ 34 | Pin: 76543210 35 | IODIR: IIIIOOOO 36 | GPIO: 00000101 37 | """ 38 | 39 | assert expected == actual 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /test/circuits_sim/device/sgp30_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.SGP30Test do 6 | use ExUnit.Case 7 | alias CircuitsSim.I2C.I2CServer 8 | alias CircuitsSim.Device.SGP30, as: SGP30Sim 9 | 10 | @i2c_address 0x59 11 | 12 | test "setting SGP30 state", %{test: test_name} do 13 | i2c_bus = to_string(test_name) 14 | start_supervised!({SGP30Sim, bus_name: i2c_bus, address: @i2c_address}) 15 | 16 | SGP30Sim.set_tvoc_ppb(i2c_bus, @i2c_address, 10) 17 | SGP30Sim.set_co2_eq_ppm(i2c_bus, @i2c_address, 410) 18 | SGP30Sim.set_h2_raw(i2c_bus, @i2c_address, 13610) 19 | SGP30Sim.set_ethanol_raw(i2c_bus, @i2c_address, 18858) 20 | 21 | assert I2CServer.render(i2c_bus, @i2c_address) == 22 | "tvoc_ppb: 10, co2_eq_ppm: 410, h2_raw: 13610, ethanol_raw: 18858" 23 | end 24 | 25 | test "supports SGP30 package", %{test: test_name} do 26 | i2c_bus = to_string(test_name) 27 | start_supervised!({SGP30Sim, bus_name: i2c_bus, address: @i2c_address, serial: 438}) 28 | 29 | sgp_pid = 30 | start_supervised!({SGP30, bus_name: i2c_bus, address: @i2c_address, name: test_name}) 31 | 32 | SGP30Sim.set_tvoc_ppb(i2c_bus, @i2c_address, 2) 33 | SGP30Sim.set_co2_eq_ppm(i2c_bus, @i2c_address, 500) 34 | SGP30Sim.set_h2_raw(i2c_bus, @i2c_address, 12345) 35 | SGP30Sim.set_ethanol_raw(i2c_bus, @i2c_address, 23456) 36 | 37 | # SGP30 requires me measurements at specific intervals, so it may take 900ms on startup 38 | # before the first one. Since this is a mock device and we don't want 39 | # to wait in tests, just send the message to force the measurement now 40 | send(sgp_pid, :measure) 41 | Process.sleep(10) 42 | 43 | sgp_state = SGP30.state(sgp_pid) 44 | assert sgp_state.tvoc_ppb == 2 45 | assert sgp_state.co2_eq_ppm == 500 46 | assert sgp_state.h2_raw == 12345 47 | assert sgp_state.ethanol_raw == 23456 48 | assert sgp_state.serial == 438 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /test/circuits_sim/device/sht4x_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSim.Device.SHT4XTest do 7 | use ExUnit.Case 8 | 9 | alias CircuitsSim.I2C.I2CServer 10 | alias CircuitsSim.Device.SHT4X, as: SHT4XSim 11 | 12 | @i2c_address 0x44 13 | 14 | test "setting SHT4X state", %{test: test_name} do 15 | i2c_bus = to_string(test_name) 16 | start_supervised!({SHT4XSim, bus_name: i2c_bus, address: @i2c_address}) 17 | 18 | SHT4XSim.set_humidity_rh(i2c_bus, @i2c_address, 12.3) 19 | SHT4XSim.set_temperature_c(i2c_bus, @i2c_address, 32.1) 20 | 21 | assert I2CServer.render(i2c_bus, @i2c_address) == 22 | "Temperature: 32.1°C, Relative humidity: 12.3%" 23 | end 24 | 25 | test "supports SHT4X package", %{test: test_name} do 26 | i2c_bus = to_string(test_name) 27 | start_supervised!({SHT4XSim, bus_name: i2c_bus, address: @i2c_address}) 28 | 29 | sht_pid = 30 | start_supervised!({SHT4X, bus_name: i2c_bus, address: @i2c_address, name: test_name}) 31 | 32 | SHT4XSim.set_temperature_c(i2c_bus, @i2c_address, 11.1) 33 | SHT4XSim.set_humidity_rh(i2c_bus, @i2c_address, 33.3) 34 | 35 | measurement = SHT4X.get_sample(sht_pid) 36 | assert_in_delta measurement.humidity_rh, 33.3, 0.1 37 | assert_in_delta measurement.temperature_c, 11.1, 0.1 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /test/circuits_sim/device/tm1620_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.TM1620Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.Device.TM1620 9 | alias CircuitsSim.SPI.SPIDevice 10 | 11 | test "simple usage" do 12 | leds = TM1620.new(render: :binary_clock) 13 | 14 | # Initialize and display 12:34:56 on the clock 15 | {_, leds} = SPIDevice.transfer(leds, <<0b00000010>>) 16 | {_, leds} = SPIDevice.transfer(leds, <<0x40>>) 17 | {_, leds} = SPIDevice.transfer(leds, <<0xC0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0>>) 18 | {_, leds} = SPIDevice.transfer(leds, <<0x88>>) 19 | 20 | actual = 21 | SPIDevice.render(leds) 22 | |> IO.ANSI.format(false) 23 | |> IO.chardata_to_string() 24 | 25 | expected = 26 | [ 27 | "Mode: 6 digits, 8 segments\n", 28 | "Brightness: 1/16\n", 29 | " . . .\n", 30 | " . o o\n", 31 | ".o o. .o\n", 32 | "o. o. o.\n" 33 | ] 34 | |> IO.chardata_to_string() 35 | 36 | assert actual == expected 37 | end 38 | 39 | describe "seven segment ascii art" do 40 | test "each segment" do 41 | # Light up all LEDs except a, b, c, ..., g, dp. 42 | actual = 43 | TM1620.seven_segment( 44 | <<0xFE, 0, 0xFD, 0, 0xFB, 0, 0xF7, 0, 0xEF, 0, 0xDF, 0, 0xBF, 0, 0x7F, 0>> 45 | ) 46 | |> IO.ANSI.format(false) 47 | |> IO.chardata_to_string() 48 | 49 | expected = 50 | [ 51 | " _ _ _ _ _ _ _ \n", 52 | "|_| |_ |_| |_| |_| _| | | |_| \n", 53 | "|_|.|_|.|_ .| |. _|.|_|.|_|.|_| \n" 54 | ] 55 | |> IO.chardata_to_string() 56 | 57 | assert actual == expected 58 | end 59 | 60 | test "numbers" do 61 | # Light up all LEDs as numbers 62 | actual = 63 | TM1620.seven_segment( 64 | # 0 1 2 3 4 5 6 7 8 9 65 | <<0x3F, 0, 0x06, 0, 0x5B, 0, 0x4F, 0, 0x66, 0, 0x6D, 0, 0x7D, 0, 0x07, 0, 0x7F, 0, 0x6F, 66 | 0>> 67 | ) 68 | |> IO.ANSI.format(false) 69 | |> IO.chardata_to_string() 70 | 71 | expected = 72 | [ 73 | " _ _ _ _ _ _ _ _ \n", 74 | "| | | _| _| |_| |_ |_ | |_| |_| \n", 75 | "|_| | |_ _| | _| |_| | |_| _| \n" 76 | ] 77 | |> IO.chardata_to_string() 78 | 79 | assert actual == expected 80 | end 81 | end 82 | 83 | describe "grid ascii art" do 84 | test "10x4" do 85 | actual = 86 | TM1620.grid(4, <<0xAA, 0x08, 0x55, 0x04, 0xAA, 0x08, 0x55, 0x04, 0xFF, 0xFF, 0xFF, 0xFF>>) 87 | |> IO.ANSI.format(false) 88 | |> IO.chardata_to_string() 89 | 90 | expected = 91 | [" * * * * *\n", "* * * * * \n", " * * * * *\n", "* * * * * \n"] 92 | |> IO.chardata_to_string() 93 | 94 | assert actual == expected 95 | end 96 | 97 | test "9x5" do 98 | actual = 99 | TM1620.grid(5, <<0xAA, 0xFB, 0x55, 0x04, 0xAA, 0xFB, 0x55, 0x04, 0xAA, 0xFB, 0xFF, 0xFF>>) 100 | |> IO.ANSI.format(false) 101 | |> IO.chardata_to_string() 102 | 103 | expected = 104 | [" * * * * \n", "* * * * *\n", " * * * * \n", "* * * * *\n", " * * * * \n"] 105 | |> IO.chardata_to_string() 106 | 107 | assert actual == expected 108 | end 109 | 110 | test "8x6" do 111 | actual = 112 | TM1620.grid(6, <<0xAA, 0xFF, 0x55, 0xFF, 0xAA, 0xFF, 0x55, 0xFF, 0xAA, 0xFF, 0x55, 0xFF>>) 113 | |> IO.ANSI.format(false) 114 | |> IO.chardata_to_string() 115 | 116 | expected = 117 | [" * * * *\n", "* * * * \n", " * * * *\n", "* * * * \n", " * * * *\n", "* * * * \n"] 118 | |> IO.chardata_to_string() 119 | 120 | assert actual == expected 121 | end 122 | end 123 | 124 | test "binary clock ascii art" do 125 | actual = 126 | TM1620.binary_clock(<<1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0>>) 127 | |> IO.ANSI.format(false) 128 | |> IO.chardata_to_string() 129 | 130 | expected = """ 131 | . . . 132 | . o o 133 | .o o. .o 134 | o. o. o. 135 | """ 136 | 137 | assert actual == expected 138 | end 139 | end 140 | -------------------------------------------------------------------------------- /test/circuits_sim/device/vcnl4040_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Eric Oestrich 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.VCNL4040Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.I2C.I2CServer 9 | alias CircuitsSim.Device.VCNL4040, as: VCNL4040Sim 10 | 11 | @i2c_address 0x60 12 | @ps_data 0x08 13 | @als_data 0x09 14 | @wl_data 0x0A 15 | 16 | test "rendering the sensor", %{test: test_name} do 17 | i2c_bus = to_string(test_name) 18 | start_supervised!({VCNL4040Sim, bus_name: i2c_bus, address: @i2c_address}) 19 | 20 | rendered = I2CServer.render(i2c_bus, @i2c_address) 21 | 22 | assert rendered == 23 | "Ambient light sensor output\n\nProximity: 0\nAmbient Light: 0\nWhite Light: 0\n" 24 | end 25 | 26 | test "supports VCNL4040 package", %{test: test_name} do 27 | i2c_bus = to_string(test_name) 28 | start_supervised!({VCNL4040Sim, bus_name: i2c_bus, address: @i2c_address}) 29 | 30 | VCNL4040Sim.set_proximity(i2c_bus, @i2c_address, 10) 31 | VCNL4040Sim.set_ambient_light(i2c_bus, @i2c_address, 50) 32 | VCNL4040Sim.set_white_light(i2c_bus, @i2c_address, 40) 33 | 34 | assert {:ok, <<10::little-16>>} = I2CServer.write_read(i2c_bus, @i2c_address, <<@ps_data>>, 2) 35 | 36 | assert {:ok, <<50::little-16>>} = 37 | I2CServer.write_read(i2c_bus, @i2c_address, <<@als_data>>, 2) 38 | 39 | assert {:ok, <<40::little-16>>} = I2CServer.write_read(i2c_bus, @i2c_address, <<@wl_data>>, 2) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /test/circuits_sim/device/veml7700_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | defmodule CircuitsSim.Device.VEML7700Test do 6 | use ExUnit.Case 7 | 8 | alias CircuitsSim.I2C.I2CServer 9 | alias CircuitsSim.Device.VEML7700, as: VEML7700Sim 10 | 11 | @i2c_address 0x48 12 | @cmd_config 0x00 13 | @cmd_light 0x04 14 | 15 | setup context do 16 | i2c_bus = to_string(context.test) 17 | start_supervised!({VEML7700Sim, bus_name: i2c_bus, address: @i2c_address}) 18 | 19 | [i2c_bus: i2c_bus] 20 | end 21 | 22 | test "setting VEML7700 state", %{i2c_bus: i2c_bus} do 23 | VEML7700Sim.set_state(i2c_bus, @i2c_address, als_output: 123) 24 | assert I2CServer.render(i2c_bus, @i2c_address) == "Ambient light sensor raw output: 123" 25 | end 26 | 27 | test "reads and writes registers", %{i2c_bus: i2c_bus} do 28 | VEML7700Sim.set_state(i2c_bus, @i2c_address, als_config: 0, als_output: 440) 29 | 30 | # read ambient light sensor settings 31 | assert {:ok, <<0, 0>>} = I2CServer.write_read(i2c_bus, @i2c_address, <<@cmd_config>>, 2) 32 | 33 | # write ambient light sensor settings 34 | config = 0b0001100000000000 35 | assert :ok = I2CServer.write(i2c_bus, @i2c_address, <<@cmd_config, config::little-16>>) 36 | 37 | # read ambient light sensor settings 38 | assert {:ok, <<0, 24>>} = I2CServer.write_read(i2c_bus, @i2c_address, <<@cmd_config>>, 2) 39 | 40 | # read ambient light sensor output data 41 | assert {:ok, <<440::little-16>>} = 42 | I2CServer.write_read(i2c_bus, @i2c_address, <<@cmd_light>>, 2) 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /test/circuits_sim_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # SPDX-FileCopyrightText: 2023 Masatoshi Nishiguchi 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule CircuitsSimTest do 7 | use ExUnit.Case 8 | doctest CircuitsSim 9 | 10 | test "info/0 does not crash" do 11 | CircuitsSim.info() 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2023 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | ExUnit.start() 6 | --------------------------------------------------------------------------------