Compare commits

...

28 Commits

Author SHA1 Message Date
Simon ed30c8de24 Fix chart precision
continuous-integration/drone/push Build is passing Details
2021-10-06 02:13:14 +01:00
Simon 76e35c7a63 fix graph gridlines
continuous-integration/drone/push Build is passing Details
2021-10-06 02:01:41 +01:00
Simon 868291c135 Remove Privacy page, clean up some css, add jacknet login link
continuous-integration/drone/push Build is passing Details
2021-10-06 00:45:38 +01:00
Simon d7c38191ce Add device page filter
continuous-integration/drone/push Build is passing Details
2021-10-05 23:43:23 +01:00
Simon 26017568f0 Cache api device keys
continuous-integration/drone/push Build is passing Details
2021-10-04 00:56:24 +01:00
Simon 04028b41e7 Remove maintain aspect ratio
continuous-integration/drone/push Build is passing Details
2021-10-03 16:18:05 +01:00
Simon 51b0324e13 Update graph formating
continuous-integration/drone/push Build is passing Details
2021-10-03 15:09:13 +01:00
Simon 6c8fdf875f Update nginx
continuous-integration/drone/push Build is passing Details
2021-10-03 03:52:45 +01:00
Simon 55486aaedd Im in? 2021-10-03 03:48:30 +01:00
Simon bacb791ba9 :`(
continuous-integration/drone/push Build is passing Details
2021-10-03 03:11:40 +01:00
Simon 2d52da61a3 Another attempt
continuous-integration/drone/push Build is passing Details
2021-10-03 03:05:31 +01:00
Simon b7f07c36b9 More attempting to read forward headers
continuous-integration/drone/push Build is passing Details
2021-10-03 02:55:25 +01:00
Simon afbcf4ae11 Attempt to use ForwardedHeadersOptions
continuous-integration/drone/push Build is passing Details
2021-10-03 02:42:03 +01:00
Simon a9e1baf7c3 Update injection of values to frontend
continuous-integration/drone/push Build is passing Details
2021-10-03 02:08:31 +01:00
Simon 90346cefda Update read database path
continuous-integration/drone/push Build is passing Details
2021-10-03 00:13:51 +01:00
Simon 3e5bf1d23d Read mongodb path from env
continuous-integration/drone/push Build is failing Details
2021-10-03 00:08:41 +01:00
Simon 9bb6c12ef9 update naming issue
continuous-integration/drone/push Build is passing Details
2021-10-02 03:45:15 +01:00
Simon 42ad8129b5 Collect all firmware
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2021-10-02 03:41:39 +01:00
Simon 7c1ad27492 Update branch tag issues
continuous-integration/drone/tag Build is passing Details
2021-10-02 03:32:29 +01:00
Simon 0103bb4522 Require tags for release
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2021-10-02 03:20:25 +01:00
Simon f68a645713 Release from master
continuous-integration/drone/push Build is failing Details
2021-10-02 03:17:12 +01:00
Simon 04164423b6 Move BME280 library
continuous-integration/drone/push Build is passing Details
2021-10-02 03:08:39 +01:00
Simon 4561c334b6 Change reference
continuous-integration/drone/push Build is failing Details
2021-10-02 03:02:16 +01:00
Simon e2eb2c841c Add platformio build step
continuous-integration/drone/push Build encountered an error Details
2021-10-02 03:01:01 +01:00
Simon 07861a01e4 change upload context
continuous-integration/drone/push Build is passing Details
2021-10-02 02:52:48 +01:00
Simon 5ebfa470fe update drone.io
continuous-integration/drone/push Build is failing Details
2021-10-02 02:49:44 +01:00
Simon b78f259189 Update registry settings
continuous-integration/drone/push Build is passing Details
2021-10-02 02:48:19 +01:00
Simon 31395d7fa3 Merge remote-tracking branch 'home/develop' 2021-10-02 02:47:56 +01:00
46 changed files with 3708 additions and 110 deletions

View File

@ -12,7 +12,12 @@ steps:
- cd Api
- go build
# Platformio esp firmware
# - name: build_esp
- name: build_esp
image: python:slim
commands:
- pip install -U platformio
- cd ESP-Temp-Humidity
- pio run
# C# frontend
# upload docker
- name: upload_frontend
@ -20,9 +25,10 @@ steps:
when:
branch:
- master
settings:
settings:
context: ManagementPage
dockerfile: ManagementPage/ManagementPage/Dockerfile
repo: "registry.jacknet.io/51m0n/environment-api"
repo: registry.jacknet.io/51m0n/environment-frontend
username: simon
password:
from_secret: docker_password
@ -39,11 +45,25 @@ steps:
settings:
context: Api
dockerfile: Api/Dockerfile
repo: "registry.jacknet.io/51m0n/environment-api"
repo: registry.jacknet.io/51m0n/environment-api
username: simon
password:
from_secret: docker_password
registry: registry.jacknet.io
auto_tag: true
# upload firmware blob
# - name: upload_esp
- name: upload_esp
image: plugins/gitea-release
depends_on:
- build_esp
# This step is only run when a branch is tagged in Gitea.
when:
event:
- tag
settings:
base_url: https://git.jacknet.io
api_key:
from_secret: gitea_token
files: ESP-Temp-Humidity\.pio\build\esp07\firmware.*
checksum:
- sha1

View File

@ -3,6 +3,7 @@ module 51m0n.com/EnvironmentManagerAPI/v2
go 1.15
require (
github.com/coocood/freecache v1.1.1
github.com/gin-gonic/gin v1.7.4
go.mongodb.org/mongo-driver v1.7.2
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9

View File

@ -1,4 +1,9 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/coocood/freecache v1.1.1 h1:uukNF7QKCZEdZ9gAV7WQzvh0SbjwdMF6m3x3rxEkaPc=
github.com/coocood/freecache v1.1.1/go.mod h1:OKrEjkGVoxZhyWAJoeFi5BMLUJm2Tit0kpGkIr7NGYY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
@ -80,6 +85,7 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@ -109,8 +115,11 @@ golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaE
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -125,8 +134,13 @@ golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

View File

@ -3,9 +3,12 @@ package src
import (
"context"
"fmt"
"os"
"encoding/base64"
"encoding/binary"
"github.com/coocood/freecache"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
@ -13,15 +16,21 @@ import (
"golang.org/x/crypto/blake2s"
)
const uri = "mongodb://192.168.0.159:27017"
const salt = "ENVIRONMENT"
// 30m
const timeout = 1800
// 10m
const cacheSize = 10 * 1024 * 1024
var dbCollection *mongo.Collection
var dbDevices *mongo.Collection
var mongoClient *mongo.Client
var cache *freecache.Cache
func DbConnect() {
mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(getMongoURI()))
if err != nil {
panic(err)
@ -33,21 +42,36 @@ func DbConnect() {
db := mongoClient.Database("Environment")
dbCollection = db.Collection("Main")
dbDevices = db.Collection("Devices")
cache = freecache.NewCache(cacheSize)
}
func GetDeviceKey(api uint64) ([]byte, error) {
apiSigned := int64(api)
filter := bson.D{{"ApiID", apiSigned}}
var result bson.M
err := dbDevices.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
return nil, err
}
cacheKey := Uint64ToBytes(api)
// Check the cache for the user
val, err := cache.Get(cacheKey)
if err == nil {
return val, err
} else {
apiSigned := int64(api)
filter := bson.D{{"ApiID", apiSigned}}
var result bson.M
err := dbDevices.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
return nil, err
}
key, err := DeriveKey(result["Passcode"].(string))
fmt.Printf(base64.StdEncoding.EncodeToString(key))
// We should cache this!
return key, err
key, err := DeriveKey(result["Passcode"].(string))
fmt.Printf(base64.StdEncoding.EncodeToString(key))
// We should cache this!
_ = cache.Set(cacheKey, key, timeout)
return key, err
}
}
func Uint64ToBytes(num uint64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, num)
return buf
}
func DeriveKey(passcode string) ([]byte, error) {
@ -70,3 +94,13 @@ func DbDisconnect() {
panic(err)
}
}
func getMongoURI() string {
dbPath := os.Getenv("GIN_DB_PATH")
if dbPath == "" {
dbPath = "mongodb://192.168.0.159:27017"
}
return dbPath
}

View File

@ -0,0 +1,675 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at finitespaceghb2@junk.yoglenn.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@ -0,0 +1,5 @@
1. Fork the project.
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request.

View File

@ -0,0 +1,11 @@
First off, did you read the manual? Did it answer your question?
Second, did you look at the examples? Did they answer your question?
No, alright, please discribe the problem below.
### Expected behavior
### Actual behavior
### Steps to reporduce the behavior

View File

@ -0,0 +1,9 @@
### Related issue # and issue behavior
### Description of changes/fixes
### @mention a person to review
### Steps to test
### Any outstanding TODOs or known issues

View File

@ -0,0 +1,389 @@
# BME280
Provides an Arduino library for reading and interpreting Bosch BME280 data over I2C, SPI or Sw SPI. Additional environment calculation functions are provided. ESP and BRZO are now supported.
## Table of Contents
1. [BME280](#bme280)
2. [Table of Contents](#table-of-contents)
3. [Summary](#summary)
4. [Installation](#installation)
5. [Usage](#usage)
6. [Enumerations](#enumerations)
7. [Settings](#settings)
- [BME280I2C::Settings](#settings)
- [BME280Spi::Settings](#settings)
- [BME280SpiSw::Settings](#settings)
8. [Methods](#methods)
- [BME280I2C(const BME280I2C::Settings& settings)](#methods)
- [BME280Spi(const BME280Spi::Settings& settings)](#methods)
- [BME280SpiSw(const BME280SpiSw::Settings& settings)](#methods)
- [bool begin()](#methods)
- [void setSettings(const Settings& settings)](#methods)
- [const Settings& getSettings() const](#methods)
- [float temp(TempUnit unit)](#methods)
- [float pres(PresUnit unit)](#methods)
- [float hum()](#methods)
- [void read(float& pressure, float& temp, float& humidity, TempUnit tempUnit, PresUnit presUnit)](#methods)
- [ChipModel chipModel()](#methods)
9. [Environment Calculations](#environment-calculations)
- [float Altitude(float pressure, bool metric = true, float seaLevelPressure = 101325)](#environment-calculations)
- [float AbsoluteHumidity(float temperature, float humidity, TempUnit tempUnit = TempUnit_Celsius)](#environment-calculations)
- [float EquivalentSeaLevelPressure(float altitude, float temp, float pres)](#environment-calculations)
- [float DewPoint(float temp, float hum, TempUnit tempunit = TempUnit_Celsius)](#environment-calculations)
- [int HeatIndex(float temperature, float humidity, TempUnit tempunit = TempUnit_Celsius)](#environment-calculations)
10. [Contributing](#contributing)
11. [History](#history)
12. [Credits](#credits)
13. [License](#license)
<snippet>
<content>
## Summary
Reads temperature, humidity, and pressure. Calculates altitude, equivalent sea level pressure and dew point. Provides functions for english and metric. Also reads pressure in Pa, hPa, inHg, atm, bar, torr, N/m^2 and psi.
## Installation
To use this library download the zip file, decompress it to a folder named BME280. Move the folder to {Arduino Path}/libraries.
## Usage
Include the library at the top of your Arduino script. `#include <BME280>`
Create a global or local variable. `BME280 bme`
In your start up call `bme.begin()`.
Read the temperature, humidity, pressure, altitude and/or dew point.
`float pres, temp, hum`
`bme.read(pres, temp, hum)`
or
`temp = bme.temp()`
`hum = bme.hum()`
`pres = bme.pres()`
## Enumerations
#### TempUnit Enum
* TempUnit_Celsius
* TempUnit_Fahrenheit
#### PresUnit Enum
* PresUnit_Pa
* PresUnit_hPa
* PresUnit_inHg
* PresUnit_atm
* PresUnit_bar
* PresUnit_torr
* PresUnit_psi
#### OSR Enum
* OSR_Off
* OSR_X1
* OSR_X2
* OSR_X4
* OSR_X8
* OSR_X16
#### Mode Enum
* Mode_Sleep
* Mode_Forced
* Mode_Normal
#### StandbyTime Enum
* StandbyTime_500us
* StandbyTime_62500us
* StandbyTime_125ms
* StandbyTime_250ms
* StandbyTime_50ms
* StandbyTime_1000ms
* StandbyTime_10ms
* StandbyTime_20ms
#### Filter Enum
* Filter_Off
* Filter_1
* Filter_2
* Filter_4
* Filter_8
* Filter_16
#### ChipModel Enum
* ChipModel_Unknown
* ChipModel_BME280
* ChipModel_BMP280
## Settings
#### BME280::Settings Struct
```
* Temperature Oversampling Rate (tempOSR): OSR Enum, default = OSR_X1
* Humidity Oversampling Rate (humOSR): OSR Enum, default = OSR_X1
* Pressure Oversampling Rate (presOSR): OSR Enum, default = OSR_X1
* Mode (mode): Mode Enum, default = Mode_Forced
* Standby Time (standbyTime): StandbyTime Enum, default = StandbyTime_1000ms
* Filter (filter): Filter Enum, default = Filter_16
* SPI Enable: SpiEnable Enum, default = false
values: true = enable, false = disable
```
#### BME280I2C::Settings Struct
* Includes all fields in BME280 settings.
```
* BME 280 Address (bme280Addr): uint8_t, default = 0x76
```
#### BME280Spi::Settings Struct
* Includes all fields in BME280 settings.
```
* SPI Chip Select Pin (spiCsPin): uint8_t
values: Any pin 0-31
```
#### BME280Spi::Settings Struct
* Includes all fields in BME280 settings.
```
* SPI Chip Select Pin (spiCsPin): uint8_t
values: Any pin 0-31
* SPI Master Out Slave In Pin (spiMosiPin): uint8_t
values: Any pin 0-31
* SPI Master In Slave Out Pin (spiMisoPin): uint8_t
values: Any pin 0-31
* SPI Serial Clock Pin (spiSckPin): uint8_t
values: Any pin 0-31
```
## Methods
#### BME280I2C(const BME280I2C::Settings& settings)
Constructor used to create the I2C Bme class. All parameters have default values.
#### BME280Spi(const BME280Spi::Settings& settings)
Constructor used to create the Spi Bme class. All parameters have default values except chip select.
#### BME280SpiSw(const BME280SpiSw::Settings& settings)
Constructor used to create the software Spi Bme class. All parameters have default values except chip select, mosi, miso and sck.
#### bool begin()
Method used at start up to initialize the class. Starts the I2C or SPI interface. Can be called again to re-initialize the mode settings.
```
* return: bool, true = success, false = failure (no device found)
```
#### void setSettings(const Settings& settings)
Method to set the sensor settings.
#### const Settings& getSettings() const
Method to get the sensor settings.
#### float temp(TempUnit unit)
Read the temperature from the BME280 and return a float.
```
return: float = temperature
* unit: tempUnit, default = TempUnit_Celsius
```
#### float pres(PresUnit unit)
Read the pressure from the BME280 and return a float with the specified unit.
```
return: float = pressure
* presUnit: uint8_t, default = PresUnit_hPa
```
#### float hum()
Read the humidity from the BME280 and return a percentage as a float.
```
* return: float = percent relative humidity
```
#### void read(float& pressure, float& temp, float& humidity, TempUnit tempUnit, PresUnit presUnit)
Read the data from the BME280 with the specified units.
```
return: None, however, pressure, temp and humidity are changed.
* Pressure: float, reference
values: reference to storage float for pressure
* Temperature: float, reference
values: reference to storage float for temperature
* Humidity: float, reference
values: reference to storage float for humidity
* tempUnit: tempUnit, default = TempUnit_Celsius
* presUnit: uint8_t, default = PresUnit_hPa
```
#### ChipModel chipModel()
```
* return: [ChipModel](#chipmodel-enum) enum
```
## Environment Calculations
#### float Altitude(float pressure, AltitudeUnit = AltitudeUnit_Meters, float seaLevelPressure = 1013.25, outsideTemp = 15.0, TempUnit = TempUnit_Celsius)
Calculate the altitude based on the pressure with the specified units.
```
Return: float altitude
* Pressure: float
values: unit independent
* AltitudeUnit: default = AltitudeUnit_Meters
values: AltitudeUnit_Meters, AltitudeUnit_Feet
* Sea Level Pressure: float, default = 1013.25
values: unit independent
* outsideTemp: float, default = 15.0
values: any float related to TempUnit
* TempUnit: default = TempUnit_Celsius
values: TempUnit_Celsius, TempUnit_Fahrenheit
Note: The formula evaluates the height difference based on difference of pressure.
- May be used to evaluate altitude over MSL. (default set)
(default referencePressure, default outsideTemp parameters ~ ISA standard)
The altitude is derived from QNH, used in aviation.
- May be used to evaluate height over MSL
(referencePressure should be equal to QFF read in meteorologic synoptic maps,
outsideTemp should be equal to local temperature)
- May be used to evaluate the height difference between two points
(referencePressure should be set to the pressure on the lower point.)
```
#### float EquivalentSeaLevelPressure(float altitude, float temp, float pres, AltitudeUnit altUnit, TempUnit tempUnit )
Convert current pressure to equivalent sea-level pressure.
```
Return: float equivalent pressure at sea level.
* altitude: float
values: meters
* temp: float
values: celsius
* pres: float
values: unit independent
* AltitudeUnit: default = AltitudeUnit_Meters
values: AltitudeUnit_Meters, AltitudeUnit_Feet
* TempUnit: default = TempUnit_Celsius
values: TempUnit_Celsius, TempUnit_Fahrenheit
Note: To get correct EquivalentSeaLevel pressure (QNH or QFF) the altitude value should be independent
on measured pressure. It is necessary to use fixed altitude point e.g. the altitude of barometer
read in map.
```
#### float DewPoint(float temp, float hum, TempUnit = TempUnit_Celsius)
Calculate the dew point based on the temperature and humidity with the specified units.
```
return: float dew point
* Temperature: float
values: any float related to TempUnit
* Humidity: float, unit = % relative humidity
values: any float
* TempUnit: TempUnit, default = TempUnit_Celsius
values: TempUnit_Celsius = return degrees Celsius, TempUnit_Fahrenheit = return degrees Fahrenheit
```
#### float AbsoluteHumidity(float temperature, float humidity, TempUnit = TempUnit_Celsius)
Calculate the absolute humidity based on the temperature and humidity with the specified units.
```
return: float absolute humidity
* Temperature: float
values: any float related to TempUnit
* Humidity: float, unit = % relative humidity
values: any float
* TempUnit: TempUnit, default = TempUnit_Celsius
values: TempUnit_Celsius = return degrees Celsius, TempUnit_Fahrenheit = return degrees Fahrenheit
```
#### float HeatIndex(float temperature, float humidity, TempUnit tempUnit = TempUnit_Celsius)
Calculate the heat index based on the temperature and humidity with the specified units.
The U.S. NWS algorithm is used.
```
return: float heat index in TempUnit
* Temperature: float
values: any float related to TempUnit
* Humidity: float, unit = % relative humidity
values: any float
* TempUnit: TempUnit, default = TempUnit_Celsius
values: TempUnit_Celsius = return degrees Celsius, TempUnit_Fahrenheit = return degrees Fahrenheit
```
## Contributing
1. Fork the project.
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request.
## History
- Jan 1, 2016 - Version 1.0.0 released
- Sep 19, 2016 - Version 2.0.0 released (Restructure for I2C and SPI)
- Nov 21, 2016 - Version 2.0.1 released (Set mode support)
- Dec 19, 2016 - Version 2.1.0 released (Support for SPI)
- Dec 21, 2016 - Version 2.1.1 released (Bugs)
- Feb 17, 2017 - Version 2.1.2 released (Docs)
- Sept 9, 2017 - Version 2.1.3 released (Formatting, reorg)
- Sept 13, 2017 - Version 2.1.4 released (Examples update, bug fixes)
- Oct 7, 2017 - Version 2.2.0 released (Enums, begin restructure)
- Oct 10, 2017 - Version 2.2.1 released (Bug fixes)
- Nov 21, 2017 - Version 2.3.0 released (Examples updates, env calc fixes, bugs)
- Brief intermission
- Dec xx, 2018. - Version 3.0.0 pending (A lot)
## Credits
Written by Tyler Glenn, 2016.
Special thanks to Mike Glenn for editing and reviewing the code.
## License
GNU GPL, see License.txt
</content>
</snippet>

View File

@ -0,0 +1,12 @@
BME280I2C KEYWORD1
BME280Spi KEYWORD1
begin KEYWORD2
temp KEYWORD2
pres KEYWORD2
hum KEYWORD2
read KEYWORD2
Altitude KEYWORD2
EquivalentSeaLevelPressure KEYWORD2
DewPoint KEYWORD2
HeatIndex KEYWORD2
AbsoluteHumidity KEYWORD2

After

Width:  |  Height:  |  Size: 225 B

View File

@ -0,0 +1,9 @@
name=BME280
version=3.0.0
author=Tyler Glenn <finitespaceghb2@junk.yoglenn.com>
maintainer=Tyler Glenn <finitespaceghb2@junk.yoglenn.com>
sentence=Provides a library for reading and interpreting Bosch BME280 environmental sensor data over I2C, SPI or Sw SPI.
paragraph=Reads temperature, humidity, and pressure. Includes environment calculations. Provides functions for english and metric. Also reads pressure in Pa, hPa, inHg, atm, bar, torr, N/m^2 and psi. ESP and BRZO I2C support.
category=Sensors
url=https://www.github.com/finitespace/BME280
architectures=*

View File

@ -0,0 +1,431 @@
/*
BME280.cpp
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 30 2015.
Last Updated: Oct 07 2017.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the Bme280 environmental sensor,
calibration code based on algorithms providedBosch, some unit conversations courtesy
of www.endmemo.com, altitude equation courtesy of NOAA, and dew point equation
courtesy of Brian McNoldy at http://andrew.rsmas.miami.edu.
*/
#include <Wire.h>
#include "BME280.h"
/****************************************************************/
BME280::BME280
(
const Settings& settings
):m_settings(settings),
m_initialized(false)
{
}
/****************************************************************/
bool BME280::Initialize()
{
bool success(true);
success &= ReadChipID();
if(success)
{
success &= ReadTrim();
if(m_settings.filter != Filter_Off)
{
InitializeFilter();
}
WriteSettings();
}
m_initialized = success;
return m_initialized;
}
/****************************************************************/
void BME280::InitializeFilter()
{
// Force an unfiltered measurement to populate the filter buffer.
// This fixes a bug that causes the first read to always be 28.82 °C 81732.34 hPa.
Filter filter = m_settings.filter;
m_settings.filter = Filter_Off;
WriteSettings();
float dummy;
read(dummy, dummy, dummy);
m_settings.filter = filter;
}
/****************************************************************/
bool BME280::ReadChipID()
{
uint8_t id[1];
ReadRegister(ID_ADDR, &id[0], 1);
switch(id[0])
{
case ChipModel_BME280:
m_chip_model = ChipModel_BME280;
break;
case ChipModel_BMP280:
m_chip_model = ChipModel_BMP280;
break;
default:
m_chip_model = ChipModel_UNKNOWN;
return false;
}
return true;
}
/****************************************************************/
void BME280::WriteSettings()
{
uint8_t ctrlHum, ctrlMeas, config;
CalculateRegisters(ctrlHum, ctrlMeas, config);
WriteRegister(CTRL_HUM_ADDR, ctrlHum);
WriteRegister(CTRL_MEAS_ADDR, ctrlMeas);
WriteRegister(CONFIG_ADDR, config);
}
/****************************************************************/
void BME280::setSettings
(
const Settings& settings
)
{
m_settings = settings;
WriteSettings();
}
/****************************************************************/
const BME280::Settings& BME280::getSettings() const
{
return m_settings;
}
/****************************************************************/
bool BME280::begin
(
)
{
bool success = Initialize();
success &= m_initialized;
return success;
}
/****************************************************************/
void BME280::CalculateRegisters
(
uint8_t& ctrlHum,
uint8_t& ctrlMeas,
uint8_t& config
)
{
// ctrl_hum register. (ctrl_hum[2:0] = Humidity oversampling rate.)
ctrlHum = (uint8_t)m_settings.humOSR;
// ctrl_meas register. (ctrl_meas[7:5] = temperature oversampling rate, ctrl_meas[4:2] = pressure oversampling rate, ctrl_meas[1:0] = mode.)
ctrlMeas = ((uint8_t)m_settings.tempOSR << 5) | ((uint8_t)m_settings.presOSR << 2) | (uint8_t)m_settings.mode;
// config register. (config[7:5] = standby time, config[4:2] = filter, ctrl_meas[0] = spi enable.)
config = ((uint8_t)m_settings.standbyTime << 5) | ((uint8_t)m_settings.filter << 2) | (uint8_t)m_settings.spiEnable;
}
/****************************************************************/
bool BME280::ReadTrim()
{
uint8_t ord(0);
bool success = true;
// Temp. Dig
success &= ReadRegister(TEMP_DIG_ADDR, &m_dig[ord], TEMP_DIG_LENGTH);
ord += TEMP_DIG_LENGTH;
// Pressure Dig
success &= ReadRegister(PRESS_DIG_ADDR, &m_dig[ord], PRESS_DIG_LENGTH);
ord += PRESS_DIG_LENGTH;
// Humidity Dig 1
success &= ReadRegister(HUM_DIG_ADDR1, &m_dig[ord], HUM_DIG_ADDR1_LENGTH);
ord += HUM_DIG_ADDR1_LENGTH;
// Humidity Dig 2
success &= ReadRegister(HUM_DIG_ADDR2, &m_dig[ord], HUM_DIG_ADDR2_LENGTH);
ord += HUM_DIG_ADDR2_LENGTH;
#ifdef DEBUG_ON
Serial.print("Dig: ");
for(int i = 0; i < 32; ++i)
{
Serial.print(m_dig[i], HEX);
Serial.print(" ");
}
Serial.println();
#endif
return success && ord == DIG_LENGTH;
}
/****************************************************************/
bool BME280::ReadData
(
int32_t data[SENSOR_DATA_LENGTH]
)
{
bool success;
uint8_t buffer[SENSOR_DATA_LENGTH];
// For forced mode we need to write the mode to BME280 register before reading
if (m_settings.mode == Mode_Forced)
{
WriteSettings();
}
// Registers are in order. So we can start at the pressure register and read 8 bytes.
success = ReadRegister(PRESS_ADDR, buffer, SENSOR_DATA_LENGTH);
for(int i = 0; i < SENSOR_DATA_LENGTH; ++i)
{
data[i] = static_cast<int32_t>(buffer[i]);
}
#ifdef DEBUG_ON
Serial.print("Data: ");
for(int i = 0; i < 8; ++i)
{
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.println();
#endif
return success;
}
/****************************************************************/
float BME280::CalculateTemperature
(
int32_t raw,
int32_t& t_fine,
TempUnit unit
)
{
// Code based on calibration algorthim provided by Bosch.
int32_t var1, var2, final;
uint16_t dig_T1 = (m_dig[1] << 8) | m_dig[0];
int16_t dig_T2 = (m_dig[3] << 8) | m_dig[2];
int16_t dig_T3 = (m_dig[5] << 8) | m_dig[4];
var1 = ((((raw >> 3) - ((int32_t)dig_T1 << 1))) * ((int32_t)dig_T2)) >> 11;
var2 = (((((raw >> 4) - ((int32_t)dig_T1)) * ((raw >> 4) - ((int32_t)dig_T1))) >> 12) * ((int32_t)dig_T3)) >> 14;
t_fine = var1 + var2;
final = (t_fine * 5 + 128) >> 8;
return unit == TempUnit_Celsius ? final/100.0 : final/100.0*9.0/5.0 + 32.0;
}
/****************************************************************/
float BME280::CalculateHumidity
(
int32_t raw,
int32_t t_fine
)
{
// Code based on calibration algorthim provided by Bosch.
int32_t var1;
uint8_t dig_H1 = m_dig[24];
int16_t dig_H2 = (m_dig[26] << 8) | m_dig[25];
uint8_t dig_H3 = m_dig[27];
int16_t dig_H4 = (m_dig[28] << 4) | (0x0F & m_dig[29]);
int16_t dig_H5 = (m_dig[30] << 4) | ((m_dig[29] >> 4) & 0x0F);
int8_t dig_H6 = m_dig[31];
var1 = (t_fine - ((int32_t)76800));
var1 = (((((raw << 14) - (((int32_t)dig_H4) << 20) - (((int32_t)dig_H5) * var1)) +
((int32_t)16384)) >> 15) * (((((((var1 * ((int32_t)dig_H6)) >> 10) * (((var1 *
((int32_t)dig_H3)) >> 11) + ((int32_t)32768))) >> 10) + ((int32_t)2097152)) *
((int32_t)dig_H2) + 8192) >> 14));
var1 = (var1 - (((((var1 >> 15) * (var1 >> 15)) >> 7) * ((int32_t)dig_H1)) >> 4));
var1 = (var1 < 0 ? 0 : var1);
var1 = (var1 > 419430400 ? 419430400 : var1);
return ((uint32_t)(var1 >> 12))/1024.0;
}
/****************************************************************/
float BME280::CalculatePressure
(
int32_t raw,
int32_t t_fine,
PresUnit unit
)
{
// Code based on calibration algorthim provided by Bosch.
int64_t var1, var2, pressure;
float final;
uint16_t dig_P1 = (m_dig[7] << 8) | m_dig[6];
int16_t dig_P2 = (m_dig[9] << 8) | m_dig[8];
int16_t dig_P3 = (m_dig[11] << 8) | m_dig[10];
int16_t dig_P4 = (m_dig[13] << 8) | m_dig[12];
int16_t dig_P5 = (m_dig[15] << 8) | m_dig[14];
int16_t dig_P6 = (m_dig[17] << 8) | m_dig[16];
int16_t dig_P7 = (m_dig[19] << 8) | m_dig[18];
int16_t dig_P8 = (m_dig[21] << 8) | m_dig[20];
int16_t dig_P9 = (m_dig[23] << 8) | m_dig[22];
var1 = (int64_t)t_fine - 128000;
var2 = var1 * var1 * (int64_t)dig_P6;
var2 = var2 + ((var1 * (int64_t)dig_P5) << 17);
var2 = var2 + (((int64_t)dig_P4) << 35);
var1 = ((var1 * var1 * (int64_t)dig_P3) >> 8) + ((var1 * (int64_t)dig_P2) << 12);
var1 = (((((int64_t)1) << 47) + var1)) * ((int64_t)dig_P1) >> 33;
if (var1 == 0) { return NAN; } // Don't divide by zero.
pressure = 1048576 - raw;
pressure = (((pressure << 31) - var2) * 3125)/var1;
var1 = (((int64_t)dig_P9) * (pressure >> 13) * (pressure >> 13)) >> 25;
var2 = (((int64_t)dig_P8) * pressure) >> 19;
pressure = ((pressure + var1 + var2) >> 8) + (((int64_t)dig_P7) << 4);
final = ((uint32_t)pressure)/256.0;
// Conversion units courtesy of www.endmemo.com.
switch(unit){
case PresUnit_hPa: /* hPa */
final /= 100.0;
break;
case PresUnit_inHg: /* inHg */
final /= 3386.3752577878; /* final pa * 1inHg/3386.3752577878Pa */
break;
case PresUnit_atm: /* atm */
final /= 101324.99766353; /* final pa * 1 atm/101324.99766353Pa */
break;
case PresUnit_bar: /* bar */
final /= 100000.0; /* final pa * 1 bar/100kPa */
break;
case PresUnit_torr: /* torr */
final /= 133.32236534674; /* final pa * 1 torr/133.32236534674Pa */
break;
case PresUnit_psi: /* psi */
final /= 6894.744825494; /* final pa * 1psi/6894.744825494Pa */
break;
default: /* Pa (case: 0) */
break;
}
return final;
}
/****************************************************************/
float BME280::temp
(
TempUnit unit
)
{
int32_t data[8];
int32_t t_fine;
if(!ReadData(data)){ return NAN; }
uint32_t rawTemp = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
return CalculateTemperature(rawTemp, t_fine, unit);
}
/****************************************************************/
float BME280::pres
(
PresUnit unit
)
{
int32_t data[8];
int32_t t_fine;
if(!ReadData(data)){ return NAN; }
uint32_t rawTemp = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
uint32_t rawPressure = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
CalculateTemperature(rawTemp, t_fine);
return CalculatePressure(rawPressure, t_fine, unit);
}
/****************************************************************/
float BME280::hum()
{
int32_t data[8];
int32_t t_fine;
if(!ReadData(data)){ return NAN; }
uint32_t rawTemp = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
uint32_t rawHumidity = (data[6] << 8) | data[7];
CalculateTemperature(rawTemp, t_fine);
return CalculateHumidity(rawHumidity, t_fine);
}
/****************************************************************/
void BME280::read
(
float& pressure,
float& temp,
float& humidity,
TempUnit tempUnit,
PresUnit presUnit
)
{
int32_t data[8];
int32_t t_fine;
if(!ReadData(data)){
pressure = temp = humidity = NAN;
return;
}
uint32_t rawPressure = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
uint32_t rawTemp = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
uint32_t rawHumidity = (data[6] << 8) | data[7];
temp = CalculateTemperature(rawTemp, t_fine, tempUnit);
pressure = CalculatePressure(rawPressure, t_fine, presUnit);
humidity = CalculateHumidity(rawHumidity, t_fine);
}
/****************************************************************/
BME280::ChipModel BME280::chipModel
(
)
{
return m_chip_model;
}

View File

@ -0,0 +1,344 @@
/*
BME280.h
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 30 2015.
Last Updated: Oct 07 2017.
This code is licensed under the GNU LGPL and is open for ditrbution
and copying in accordance with the license.
This header must be included in any derived code or copies of the code.
*/
#ifndef TG_BME_280_H
#define TG_BME_280_H
#include "Arduino.h"
//////////////////////////////////////////////////////////////////
/// BME280 - Driver class for Bosch Bme280 sensor
///
/// Based on the data sheet provided by Bosch for
/// the Bme280 environmental sensor.
///
class BME280
{
public:
/*****************************************************************/
/* ENUMERATIONS */
/*****************************************************************/
enum TempUnit
{
TempUnit_Celsius,
TempUnit_Fahrenheit
};
enum PresUnit
{
PresUnit_Pa,
PresUnit_hPa,
PresUnit_inHg,
PresUnit_atm,
PresUnit_bar,
PresUnit_torr,
PresUnit_psi
};
enum OSR
{
OSR_Off = 0,
OSR_X1 = 1,
OSR_X2 = 2,
OSR_X4 = 3,
OSR_X8 = 4,
OSR_X16 = 5
};
enum Mode
{
Mode_Sleep = 0,
Mode_Forced = 1,
Mode_Normal = 3
};
enum StandbyTime
{
StandbyTime_500us = 0,
StandbyTime_62500us = 1,
StandbyTime_125ms = 2,
StandbyTime_250ms = 3,
StandbyTime_50ms = 4,
StandbyTime_1000ms = 5,
StandbyTime_10ms = 6,
StandbyTime_20ms = 7
};
enum Filter
{
Filter_Off = 0,
Filter_2 = 1,
Filter_4 = 2,
Filter_8 = 3,
Filter_16 = 4
};
enum SpiEnable
{
SpiEnable_False = 0,
SpiEnable_True = 1
};
enum ChipModel
{
ChipModel_UNKNOWN = 0,
ChipModel_BMP280 = 0x58,
ChipModel_BME280 = 0x60
};
/*****************************************************************/
/* STRUCTURES */
/*****************************************************************/
struct Settings
{
Settings(
OSR _tosr = OSR_X1,
OSR _hosr = OSR_X1,
OSR _posr = OSR_X1,
Mode _mode = Mode_Forced,
StandbyTime _st = StandbyTime_1000ms,
Filter _filter = Filter_Off,
SpiEnable _se = SpiEnable_False
): tempOSR(_tosr),
humOSR(_hosr),
presOSR(_posr),
mode(_mode),
standbyTime(_st),
filter(_filter),
spiEnable(_se) {}
OSR tempOSR;
OSR humOSR;
OSR presOSR;
Mode mode;
StandbyTime standbyTime;
Filter filter;
SpiEnable spiEnable;
};
/*****************************************************************/
/* INIT FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
/// Constructor used to create the class.
/// All parameters have default values.
BME280(
const Settings& settings);
/////////////////////////////////////////////////////////////////
/// Method used to initialize the class.
bool begin();
/*****************************************************************/
/* ENVIRONMENTAL FUNCTIONS */
/*****************************************************************/
//////////////////////////////////////////////////
/// Read the temperature from the BME280 and return a float.
float temp(
TempUnit unit = TempUnit_Celsius);
/////////////////////////////////////////////////////////////////
/// Read the pressure from the BME280 and return a float with the
/// specified unit.
float pres(
PresUnit unit = PresUnit_hPa);
/////////////////////////////////////////////////////////////////
/// Read the humidity from the BME280 and return a percentage
/// as a float.
float hum();
/////////////////////////////////////////////////////////////////
/// Read the data from the BME280 in the specified unit.
void read(
float& pressure,
float& temperature,
float& humidity,
TempUnit tempUnit = TempUnit_Celsius,
PresUnit presUnit = PresUnit_hPa);
/*****************************************************************/
/* ACCESSOR FUNCTIONS */
/*****************************************************************/
////////////////////////////////////////////////////////////////
/// Method used to return ChipModel.
ChipModel chipModel();
protected:
/*****************************************************************/
/* CONSTRUCTOR INIT FUNCTIONS */
/*****************************************************************/
///////////////////////////////////////////////////////////////
/// Write configuration to BME280, return true if successful.
/// Must be called from any child classes.
virtual bool Initialize();
///////////////////////////////////////////////////////////////
/// Force a unfiltered measurement to populate the filter
/// buffer.
void InitializeFilter();
/*****************************************************************/
/* ACCESSOR FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
virtual void setSettings(
const Settings& settings);
/////////////////////////////////////////////////////////////////
virtual const Settings& getSettings() const;
private:
/*****************************************************************/
/* CONSTANTS */
/*****************************************************************/
static const uint8_t CTRL_HUM_ADDR = 0xF2;
static const uint8_t CTRL_MEAS_ADDR = 0xF4;
static const uint8_t CONFIG_ADDR = 0xF5;
static const uint8_t PRESS_ADDR = 0xF7;
static const uint8_t TEMP_ADDR = 0xFA;
static const uint8_t HUM_ADDR = 0xFD;
static const uint8_t TEMP_DIG_ADDR = 0x88;
static const uint8_t PRESS_DIG_ADDR = 0x8E;
static const uint8_t HUM_DIG_ADDR1 = 0xA1;
static const uint8_t HUM_DIG_ADDR2 = 0xE1;
static const uint8_t ID_ADDR = 0xD0;
static const uint8_t TEMP_DIG_LENGTH = 6;
static const uint8_t PRESS_DIG_LENGTH = 18;
static const uint8_t HUM_DIG_ADDR1_LENGTH = 1;
static const uint8_t HUM_DIG_ADDR2_LENGTH = 7;
static const uint8_t DIG_LENGTH = 32;
static const uint8_t SENSOR_DATA_LENGTH = 8;
/*****************************************************************/
/* VARIABLES */
/*****************************************************************/
Settings m_settings;
uint8_t m_dig[32];
ChipModel m_chip_model;
bool m_initialized;
/*****************************************************************/
/* ABSTRACT FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
/// Write values to BME280 registers.
virtual bool WriteRegister(
uint8_t addr,
uint8_t data)=0;
/////////////////////////////////////////////////////////////////
/// Read values from BME280 registers.
virtual bool ReadRegister(
uint8_t addr,
uint8_t data[],
uint8_t length)=0;
/*****************************************************************/
/* WORKER FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
/// Calculates registers based on settings.
void CalculateRegisters(
uint8_t& ctrlHum,
uint8_t& ctrlMeas,
uint8_t& config);
/////////////////////////////////////////////////////////////////
/// Write the settings to the chip.
void WriteSettings();
/////////////////////////////////////////////////////////////////
/// Read the the chip id data from the BME280, return true if
/// successful and the id matches a known value.
bool ReadChipID();
/////////////////////////////////////////////////////////////////
/// Read the the trim data from the BME280, return true if
/// successful.
bool ReadTrim();
/////////////////////////////////////////////////////////////////
/// Read the raw data from the BME280 into an array and return
/// true if successful.
bool ReadData(
int32_t data[8]);
/////////////////////////////////////////////////////////////////
/// Calculate the temperature from the BME280 raw data and
/// BME280 trim, return a float.
float CalculateTemperature(
int32_t raw,
int32_t& t_fine,
TempUnit unit = TempUnit_Celsius);
/////////////////////////////////////////////////////////////////
/// Calculate the humidity from the BME280 raw data and BME280
/// trim, return a float.
float CalculateHumidity(
int32_t raw,
int32_t t_fine);
/////////////////////////////////////////////////////////////////
/// Calculate the pressure from the BME280 raw data and BME280
/// trim, return a float.
float CalculatePressure(
int32_t raw,
int32_t t_fine,
PresUnit unit = PresUnit_hPa);
};
#endif // TG_BME_280_H

View File

@ -0,0 +1,102 @@
/*
BME280I2CI2C.cpp
This code records data from the BME280I2C sensor and provides an API.
This file is part of the Arduino BME280I2C library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 30 2015.
Last Updated: Jan 1 2016. - Happy New year!
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the BME280I2C environmental sensor,
calibration code based on algorithms providedBosch, some unit conversations courtesy
of www.endmemo.com, altitude equation courtesy of NOAA, and dew point equation
courtesy of Brian McNoldy at http://andrew.rsmas.miami.edu.
*/
#include <Wire.h>
#include "BME280I2C.h"
/****************************************************************/
BME280I2C::BME280I2C
(
const Settings& settings
):BME280(settings),
m_settings(settings)
{
}
/****************************************************************/
void BME280I2C::setSettings
(
const Settings& settings
)
{
m_settings = settings;
BME280::setSettings(settings);
}
/****************************************************************/
const BME280I2C::Settings& BME280I2C::getSettings() const
{
return m_settings;
}
/****************************************************************/
bool BME280I2C::WriteRegister
(
uint8_t addr,
uint8_t data
)
{
Wire.beginTransmission(m_settings.bme280Addr);
Wire.write(addr);
Wire.write(data);
Wire.endTransmission();
return true; // TODO: Check return values from wire calls.
}
/****************************************************************/
bool BME280I2C::ReadRegister
(
uint8_t addr,
uint8_t data[],
uint8_t length
)
{
uint8_t ord(0);
Wire.beginTransmission(m_settings.bme280Addr);
Wire.write(addr);
Wire.endTransmission();
Wire.requestFrom(static_cast<uint8_t>(m_settings.bme280Addr), length);
while(Wire.available())
{
data[ord++] = Wire.read();
}
return ord == length;
}

View File

@ -0,0 +1,105 @@
/*
BME280I2C.h
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Sep 19 2016.
Last Updated: Oct 07 2017.
This code is licensed under the GNU LGPL and is open for ditrbution
and copying in accordance with the license.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the Bme280 environmental sensor.
*/
#ifndef TG_BME_280_I2C_H
#define TG_BME_280_I2C_H
#include "BME280.h"
//////////////////////////////////////////////////////////////////
/// BME280I2C - I2C Implementation of BME280.
class BME280I2C: public BME280
{
public:
enum I2CAddr
{
I2CAddr_0x76 = 0x76,
I2CAddr_0x77 = 0x77
};
struct Settings : public BME280::Settings
{
Settings(
OSR _tosr = OSR_X1,
OSR _hosr = OSR_X1,
OSR _posr = OSR_X1,
Mode _mode = Mode_Forced,
StandbyTime _st = StandbyTime_1000ms,
Filter _filter = Filter_16,
SpiEnable _se = SpiEnable_False,
I2CAddr _addr = I2CAddr_0x76
): BME280::Settings(_tosr, _hosr, _posr, _mode, _st, _filter, _se),
bme280Addr(_addr) {}
I2CAddr bme280Addr;
};
///////////////////////////////////////////////////////////////
/// Constructor used to create the class. All parameters have
/// default values.
BME280I2C(
const Settings& settings = Settings());
/*****************************************************************/
/* ACCESSOR FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
virtual void setSettings(
const Settings& settings);
/////////////////////////////////////////////////////////////////
const Settings& getSettings() const;
protected:
private:
Settings m_settings;
//////////////////////////////////////////////////////////////////
/// Write values to BME280 registers.
virtual bool WriteRegister(
uint8_t addr,
uint8_t data);
/////////////////////////////////////////////////////////////////
/// Read values from BME280 registers.
virtual bool ReadRegister(
uint8_t addr,
uint8_t data[],
uint8_t length);
};
#endif // TG_BME_280_I2C_H

View File

@ -0,0 +1,97 @@
/*
BME280I2C_BRZO.cpp
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
Forked by Alex Shavlovsky
to support https://github.com/pasko-zh/brzo_i2c library on ESP8266.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 30 2015.
Last Updated: Oct 07 2017.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the BME280I2C_BRZO environmental sensor,
calibration code based on algorithms providedBosch, some unit conversations courtesy
of www.endmemo.com, altitude equation courtesy of NOAA, and dew point equation
courtesy of Brian McNoldy at http://andrew.rsmas.miami.edu.
*/
#include "BME280I2C_BRZO.h"
#ifdef USING_BRZO
#include "brzo_i2c.h"
/****************************************************************/
BME280I2C_BRZO::BME280I2C_BRZO
(
const Settings& settings
):BME280I2C(settings),
m_settings(settings)
{
}
/****************************************************************/
void BME280I2C_BRZO::setSettings
(
const Settings& settings
)
{
m_settings = settings;
BME280::setSettings(settings);
}
/****************************************************************/
const BME280I2C_BRZO::Settings& BME280I2C_BRZO::getSettings() const
{
return m_settings;
}
/****************************************************************/
bool BME280I2C_BRZO::WriteRegister
(
uint8_t addr,
uint8_t data
)
{
uint8_t bf[2];
bf[0] = addr;
bf[1] = data;
brzo_i2c_start_transaction(m_settings.bme280Addr, m_settings.i2cClockRate);
brzo_i2c_write(bf, 2, false);
return (brzo_i2c_end_transaction()==0);
}
/****************************************************************/
bool BME280I2C_BRZO::ReadRegister
(
uint8_t addr,
uint8_t data[],
uint8_t length
)
{
brzo_i2c_start_transaction(m_settings.bme280Addr, m_settings.i2cClockRate);
brzo_i2c_write(&addr, 1, true);
brzo_i2c_read(data, length, false);
brzo_i2c_end_transaction();
return (brzo_i2c_end_transaction()==0);
}
#endif

View File

@ -0,0 +1,101 @@
/*
BME280I2C_BRZO.h
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
Forked by Alex Shavlovsky
to support https://github.com/pasko-zh/brzo_i2c library on ESP8266.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Sep 19 2016.
Last Updated: Oct 07 2017.
This code is licensed under the GNU LGPL and is open for ditrbution
and copying in accordance with the license.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the Bme280 environmental sensor.
*/
#ifndef BME280I2C_BRZO_H
#define BME280I2C_BRZO_H
#include "BME280I2C.h"
//////////////////////////////////////////////////////////////////
/// BME280I2C_BRZO - I2C Implementation of BME280.
class BME280I2C_BRZO : public BME280I2C
{
public:
struct Settings : public BME280I2C::Settings
{
Settings(
OSR _tosr = OSR_X1,
OSR _hosr = OSR_X1,
OSR _posr = OSR_X1,
Mode _mode = Mode_Forced,
StandbyTime _st = StandbyTime_1000ms,
Filter _filter = Filter_Off,
SpiEnable _se = SpiEnable_False,
uint16_t _cr = 400
): BME280I2C::Settings(_tosr, _hosr, _posr, _mode, _st, _filter, _se),
i2cClockRate(_cr) {}
uint16_t i2cClockRate;
};
///////////////////////////////////////////////////////////////
/// Constructor used to create the class. All parameters have
/// default values.
BME280I2C_BRZO(
const Settings& settings = Settings());
/*****************************************************************/
/* ACCESSOR FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
virtual void setSettings(
const Settings& settings);
/////////////////////////////////////////////////////////////////
const Settings& getSettings() const;
protected:
private:
Settings m_settings;
//////////////////////////////////////////////////////////////////
/// Write values to BME280 registers.
virtual bool WriteRegister(
uint8_t addr,
uint8_t data);
/////////////////////////////////////////////////////////////////
/// Read values from BME280 registers.
virtual bool ReadRegister(
uint8_t addr,
uint8_t data[],
uint8_t length);
};
#endif // BME280I2C_BRZO_H

View File

@ -0,0 +1,134 @@
/*
BME280Spi.cpp
This code records data from the BME280Spi sensor and provides an API.
This file is part of the Arduino BME280Spi library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 18 2016. - Happy Holidays!
Last Updated: Oct 07 2017.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the BME280Spi environmental sensor,
calibration code based on algorithms providedBosch, some unit conversations courtesy
of www.endmemo.com, altitude equation courtesy of NOAA, and dew point equation
courtesy of Brian McNoldy at http://andrew.rsmas.miami.edu.
*/
#include "Arduino.h"
#include "BME280Spi.h"
#include <SPI.h>
/****************************************************************/
BME280Spi::BME280Spi
(
const Settings& settings
)
:BME280(settings),
m_settings(settings)
{
}
/****************************************************************/
bool BME280Spi::Initialize()
{
pinMode(m_settings.spiCsPin, OUTPUT);
digitalWrite(m_settings.spiCsPin, HIGH);
return BME280::Initialize();
}
/****************************************************************/
void BME280Spi::setSettings
(
const Settings& settings
)
{
m_settings = settings;
BME280::setSettings(settings);
}
/****************************************************************/
const BME280Spi::Settings& BME280Spi::getSettings() const
{
return m_settings;
}
/****************************************************************/
bool BME280Spi::ReadRegister
(
uint8_t addr,
uint8_t data[],
uint8_t len
)
{
SPI.beginTransaction(SPISettings(500000,MSBFIRST,SPI_MODE0));
// bme280 uses the msb to select read and write
// combine the addr with the read/write bit
uint8_t readAddr = addr | BME280_SPI_READ;
//select the device
digitalWrite(m_settings.spiCsPin, LOW);
// transfer the addr
SPI.transfer(readAddr);
// read the data
for(int i = 0; i < len; ++i)
{
// transfer 0x00 to get the data
data[i] = SPI.transfer(0);
}
// de-select the device
digitalWrite(m_settings.spiCsPin, HIGH);
SPI.endTransaction();
return true;
}
/****************************************************************/
bool BME280Spi::WriteRegister
(
uint8_t addr,
uint8_t data
)
{
SPI.beginTransaction(SPISettings(500000,MSBFIRST,SPI_MODE0));
// bme280 uses the msb to select read and write
// combine the addr with the read/write bit
uint8_t writeAddr = addr & ~0x80;
// select the device
digitalWrite(m_settings.spiCsPin, LOW);
// transfer the addr and then the data to spi device
SPI.transfer(writeAddr);
SPI.transfer(data);
// de-select the device
digitalWrite(m_settings.spiCsPin, HIGH);
SPI.endTransaction();
return true;
}

View File

@ -0,0 +1,104 @@
/*
BME280Spi.h
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 18 2016. - Happy Holidays!
Last Updated: Oct 07 2017.
This code is licensed under the GNU LGPL and is open for ditrbution
and copying in accordance with the license.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the Bme280 environmental sensor.
*/
#ifndef TG_BME_280_SPI_H
#define TG_BME_280_SPI_H
#include "BME280.h"
class BME280Spi: public BME280
{
public:
struct Settings : public BME280::Settings
{
Settings(
uint8_t _cspin,
OSR _tosr = OSR_X1,
OSR _hosr = OSR_X1,
OSR _posr = OSR_X1,
Mode _mode = Mode_Forced,
StandbyTime _st = StandbyTime_1000ms,
Filter _filter = Filter_Off,
SpiEnable _se = SpiEnable_False
): BME280::Settings(_tosr, _hosr, _posr, _mode, _st, _filter, _se),
spiCsPin(_cspin) {}
uint8_t spiCsPin;
};
////////////////////////////////////////////////////////////////
/// Constructor used to create the class. All parameters have
/// default values.
BME280Spi(
const Settings& settings);
/*****************************************************************/
/* ACCESSOR FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
virtual void setSettings(
const Settings& settings);
/////////////////////////////////////////////////////////////////
const Settings& getSettings() const;
protected:
////////////////////////////////////////////////////////////////
/// Method used at start up to initialize the class. Starts the
/// I2C interface.
virtual bool Initialize();
private:
static const uint8_t BME280_SPI_WRITE = 0x7F;
static const uint8_t BME280_SPI_READ = 0x80;
Settings m_settings;
////////////////////////////////////////////////////////////////
/// Read the data from the BME280 addr into an array and
/// return true if successful.
virtual bool ReadRegister(
uint8_t addr,
uint8_t array[],
uint8_t len);
////////////////////////////////////////////////////////////////
/// Write values to BME280 registers.
virtual bool WriteRegister(
uint8_t addr,
uint8_t data);
};
#endif // TG_BME_280_SPI_H

View File

@ -0,0 +1,152 @@
/*
BME280SpiSw.cpp
This code records data from the BME280SpiSw sensor and provides an API.
This file is part of the Arduino BME280SpiSw library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 18 2016. - Happy Holidays!
Last Updated: Dec 18 2016. - Happy Holidays!
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the BME280SpiSw environmental sensor,
calibration code based on algorithms providedBosch, some unit conversations courtesy
of www.endmemo.com, altitude equation courtesy of NOAA, and dew point equation
courtesy of Brian McNoldy at http://andrew.rsmas.miami.edu.
*/
#include "Arduino.h"
#include "BME280SpiSw.h"
/****************************************************************/
BME280SpiSw::BME280SpiSw
(
const Settings& settings
)
:BME280(settings),
m_settings(settings)
{
}
/****************************************************************/
bool BME280SpiSw::Initialize(){
digitalWrite(m_settings.spiCsPin, HIGH);
pinMode(m_settings.spiCsPin, OUTPUT);
pinMode(m_settings.spiSckPin, OUTPUT);
pinMode(m_settings.spiMosiPin, OUTPUT);
pinMode(m_settings.spiMisoPin, INPUT);
return BME280::Initialize();
}
/****************************************************************/
void BME280SpiSw::setSettings
(
const Settings& settings
)
{
m_settings = settings;
BME280::setSettings(settings);
}
/****************************************************************/
const BME280SpiSw::Settings& BME280SpiSw::getSettings() const
{
return m_settings;
}
/****************************************************************/
uint8_t BME280SpiSw::SpiTransferSw
(
uint8_t data
)
{
uint8_t resp = 0;
for (int bit = 7; bit >= 0; --bit) {
resp <<= 1;
digitalWrite(m_settings.spiSckPin, LOW);
digitalWrite(m_settings.spiMosiPin, data & (1 << bit));
digitalWrite(m_settings.spiSckPin, HIGH);
resp |= digitalRead(m_settings.spiMisoPin);
}
return resp;
}
/****************************************************************/
bool BME280SpiSw::ReadRegister
(
uint8_t addr,
uint8_t data[],
uint8_t length
)
{
// bme280 uses the msb to select read and write
// combine the addr with the read/write bit
uint8_t readAddr = addr | BME280_SPI_READ;
//select the device
digitalWrite(m_settings.spiCsPin, LOW);
// transfer the addr
SpiTransferSw(readAddr);
// read the data
for(int i = 0; i < length; ++i)
{
// transfer 0x00 to get the data
data[i] = SpiTransferSw(0);
}
// de-select the device
digitalWrite(m_settings.spiCsPin, HIGH);
return true;
}
/****************************************************************/
bool BME280SpiSw::WriteRegister
(
uint8_t addr,
uint8_t data
)
{
// bme280 uses the msb to select read and write
// combine the addr with the read/write bit
uint8_t writeAddr = addr & ~0x80;
// select the device
digitalWrite(m_settings.spiCsPin, LOW);
// transfer the addr and then the data to spi device
SpiTransferSw(writeAddr);
SpiTransferSw(data);
// de-select the device
digitalWrite(m_settings.spiCsPin, HIGH);
return true;
}

View File

@ -0,0 +1,115 @@
/*
BME280SpiSw.h
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 18 2016. - Happy Holidays!
Last Updated: Oct 07 2017.
This code is licensed under the GNU LGPL and is open for ditrbution
and copying in accordance with the license.
This header must be included in any derived code or copies of the code.
Based on the data sheet provided by Bosch for the Bme280 environmental sensor.
*/
#ifndef TG_BME_280_SPI_H
#define TG_BME_280_SPI_H
#include "BME280.h"
class BME280SpiSw: public BME280{
public:
struct Settings : public BME280::Settings
{
Settings(
uint8_t _cs,
uint8_t _mosi,
uint8_t _miso,
uint8_t _sck,
OSR _tosr = OSR_X1,
OSR _hosr = OSR_X1,
OSR _posr = OSR_X1,
Mode _mode = Mode_Forced,
StandbyTime _st = StandbyTime_1000ms,
Filter _filter = Filter_Off,
SpiEnable _se = SpiEnable_False
): BME280::Settings(_tosr, _hosr, _posr, _mode, _st, _filter, _se),
spiCsPin(_cs),
spiMosiPin(_mosi),
spiMisoPin(_miso),
spiSckPin(_sck) {}
uint8_t spiCsPin;
uint8_t spiMosiPin;
uint8_t spiMisoPin;
uint8_t spiSckPin;
};
////////////////////////////////////////////////////////////////
/// Constructor for software spi
BME280SpiSw(
const Settings& settings);
/*****************************************************************/
/* ACCESSOR FUNCTIONS */
/*****************************************************************/
/////////////////////////////////////////////////////////////////
virtual void setSettings(
const Settings& settings);
/////////////////////////////////////////////////////////////////
const Settings& getSettings() const;
protected:
////////////////////////////////////////////////////////////////
/// Method used at start up to initialize the class. Starts the
/// software SPI interface.
virtual bool Initialize();
private:
static const uint8_t BME280_SPI_WRITE = 0x7F;
static const uint8_t BME280_SPI_READ = 0x80;
Settings m_settings;
////////////////////////////////////////////////////////////////
/// Does a sw spi transfer.
uint8_t SpiTransferSw(
uint8_t data);
////////////////////////////////////////////////////////////////
/// Read the data from the BME280 addr into an array and return
/// true if successful.
virtual bool ReadRegister(
uint8_t addr,
uint8_t data[],
uint8_t length);
////////////////////////////////////////////////////////////////
/// Write values to BME280 registers.
virtual bool WriteRegister(
uint8_t addr,
uint8_t data);
};
#endif // TG_BME_280_SPI_H

View File

@ -0,0 +1,217 @@
/*
EnvironmentCalculations.cpp
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Dec 30 2015.
Last Updated: Dec 23 2017.
This header must be included in any derived code or copies of the code.
*/
#include "EnvironmentCalculations.h"
#include <Arduino.h>
#include <math.h>
#define hi_coeff1 -42.379
#define hi_coeff2 2.04901523
#define hi_coeff3 10.14333127
#define hi_coeff4 -0.22475541
#define hi_coeff5 -0.00683783
#define hi_coeff6 -0.05481717
#define hi_coeff7 0.00122874
#define hi_coeff8 0.00085282
#define hi_coeff9 -0.00000199
/****************************************************************/
float EnvironmentCalculations::Altitude
(
float pressure,
AltitudeUnit altUnit,
float referencePressure,
float outdoorTemp,
TempUnit tempUnit
)
{
// Equation inverse to EquivalentSeaLevelPressure calculation.
float altitude = NAN;
if (!isnan(pressure) && !isnan(referencePressure) && !isnan(outdoorTemp))
{
if(tempUnit != TempUnit_Celsius)
outdoorTemp = (outdoorTemp - 32.0) * (5.0 / 9.0); /*conversion to [°C]*/
altitude = pow(referencePressure / pressure, 0.190234) - 1;
altitude *= ((outdoorTemp + 273.15) / 0.0065);
if(altUnit != AltitudeUnit_Meters) altitude *= 3.28084;
}
return altitude;
}
/****************************************************************/
float EnvironmentCalculations::AbsoluteHumidity
(
float temperature,
float humidity,
TempUnit tempUnit
)
{
//taken from https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
//precision is about 0.1°C in range -30 to 35°C
//August-Roche-Magnus 6.1094 exp(17.625 x T)/(T + 243.04)
//Buck (1981) 6.1121 exp(17.502 x T)/(T + 240.97)
//reference https://www.eas.ualberta.ca/jdwilson/EAS372_13/Vomel_CIRES_satvpformulae.html
float temp = NAN;
const float mw = 18.01534; // molar mass of water g/mol
const float r = 8.31447215; // Universal gas constant J/mol/K
if (isnan(temperature) || isnan(humidity) )
{
return NAN;
}
if(tempUnit != TempUnit_Celsius)
{
temperature = (temperature - 32.0) * (5.0 / 9.0); /*conversion to [°C]*/
}
temp = pow(2.718281828, (17.67 * temperature) / (temperature + 243.5));
//return (6.112 * temp * humidity * 2.1674) / (273.15 + temperature); //simplified version
return (6.112 * temp * humidity * mw) / ((273.15 + temperature) * r); //long version
}
/****************************************************************/
//FYI: https://ehp.niehs.nih.gov/1206273/ in detail this flow graph: https://ehp.niehs.nih.gov/wp-content/uploads/2013/10/ehp.1206273.g003.png
float EnvironmentCalculations::HeatIndex
(
float temperature,
float humidity,
TempUnit tempUnit
)
{
float heatIndex(NAN);
if ( isnan(temperature) || isnan(humidity) )
{
return heatIndex;
}
if (tempUnit == TempUnit_Celsius)
{
temperature = (temperature * (9.0 / 5.0) + 32.0); /*conversion to [°F]*/
}
// Using both Rothfusz and Steadman's equations
// http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
if (temperature <= 40)
{
heatIndex = temperature; //first red block
}
else
{
heatIndex = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (humidity * 0.094)); //calculate A -- from the official site, not the flow graph
if (heatIndex >= 79)
{
/*
* calculate B
* the following calculation is optimized. Simply spoken, reduzed cpu-operations to minimize used ram and runtime.
* Check the correctness with the following link:
* http://www.wolframalpha.com/input/?source=nav&i=b%3D+x1+%2B+x2*T+%2B+x3*H+%2B+x4*T*H+%2B+x5*T*T+%2B+x6*H*H+%2B+x7*T*T*H+%2B+x8*T*H*H+%2B+x9*T*T*H*H
*/
heatIndex = hi_coeff1
+ (hi_coeff2 + hi_coeff4 * humidity + temperature * (hi_coeff5 + hi_coeff7 * humidity)) * temperature
+ (hi_coeff3 + humidity * (hi_coeff6 + temperature * (hi_coeff8 + hi_coeff9 * temperature))) * humidity;
//third red block
if ((humidity < 13) && (temperature >= 80.0) && (temperature <= 112.0))
{
heatIndex -= ((13.0 - humidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882);
} //fourth red block
else if ((humidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0))
{
heatIndex += (0.02 * (humidity - 85.0) * (87.0 - temperature));
}
}
}
if (tempUnit == TempUnit_Celsius)
{
return (heatIndex - 32.0) * (5.0 / 9.0); /*conversion back to [°C]*/
}
else
{
return heatIndex; //fifth red block
}
}
/****************************************************************/
float EnvironmentCalculations::EquivalentSeaLevelPressure
(
float altitude,
float temp,
float pres,
AltitudeUnit altUnit,
TempUnit tempUnit
)
{
float seaPress = NAN;
if(!isnan(altitude) && !isnan(temp) && !isnan(pres))
{
if(tempUnit != TempUnit_Celsius)
temp = (temp - 32.0) * (5.0 / 9.0); /*conversion to [°C]*/
if(altUnit != AltitudeUnit_Meters)
altitude *= 0.3048; /*conversion to meters*/
seaPress = (pres / pow(1 - ((0.0065 *altitude) / (temp + (0.0065 *altitude) + 273.15)), 5.257));
}
return seaPress;
}
/****************************************************************/
float EnvironmentCalculations::DewPoint
(
float temp,
float hum,
TempUnit tempUnit
)
{
// Equations courtesy of Brian McNoldy from http://andrew.rsmas.miami.edu;
float dewPoint = NAN;
if(!isnan(temp) && !isnan(hum))
{
if (tempUnit == TempUnit_Celsius)
{
dewPoint = 243.04 * (log(hum/100.0) + ((17.625 * temp)/(243.04 + temp)))
/(17.625 - log(hum/100.0) - ((17.625 * temp)/(243.04 + temp)));
}
else
{
float ctemp = (temp - 32.0) * 5.0/9.0;
dewPoint = 243.04 * (log(hum/100.0) + ((17.625 * ctemp)/(243.04 + ctemp)))
/(17.625 - log(hum/100.0) - ((17.625 * ctemp)/(243.04 + ctemp)));
dewPoint = dewPoint * 9.0/5.0 + 32.0;
}
}
return dewPoint;
}

View File

@ -0,0 +1,129 @@
/*
EnvironmentCalculations.h
This code records data from the BME280 sensor and provides an API.
This file is part of the Arduino BME280 library.
Copyright (C) 2016 Tyler Glenn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written: Oct 7 2017.
Last Updated: Dec 11 2017.
This code is licensed under the GNU LGPL and is open for distrbution
and copying in accordance with the license.
This header must be included in any derived code or copies of the code.
*/
#ifndef TG_ENVIRONMENT_CALCULATIONS_H
#define TG_ENVIRONMENT_CALCULATIONS_H
namespace EnvironmentCalculations
{
/////////////////////////////////////////////////////////////////
/// Temperature unit enumeration.
enum TempUnit
{
TempUnit_Celsius,
TempUnit_Fahrenheit
};
/////////////////////////////////////////////////////////////////
/// Altitude unit enumeration.
enum AltitudeUnit
{
AltitudeUnit_Meters,
AltitudeUnit_Feet
};
/////////////////////////////////////////////////////////////////
/// Calculate the altitude based on the pressure and temperature
/// in temptUnit.
/// @param pressure at the station in any units.
/// @param altUnit meters or feet. default=AltitudeUnit_Meters
/// @param referencePressure (usually pressure on MSL)
/// in the same units as pressure. default=1013.25hPa (ISA)
/// @param outdoorTemp temperature at the station in tempUnit
/// default=15°C (ISA)
/// @param temptUnit in °C or °F. default=TempUnit_Celsius
/// @return Calculated Altitude in altUnit.
float Altitude(
float pressure,
AltitudeUnit altUnit = AltitudeUnit_Meters,
float referencePressure = 1013.25, // [hPa] ....ISA value
float outdoorTemp = 15, // [°C] .... ISA value
TempUnit tempUnit = TempUnit_Celsius);
/////////////////////////////////////////////////////////////////
/// Calculate the heatindex based on the humidity and temperature
/// in tempUnit.
/// The formula based on the Heat Index Equation of the US National Weather Service
/// http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
/// @param temperature in tempUnit
/// @param humidity in percentage
/// @param temptUnit in °C or °F. default=TempUnit_Celsius
/// @return Calculated heatindex as float in TempUnit
float HeatIndex(
float temperature,
float humidity,
TempUnit tempUnit = TempUnit_Celsius);
/////////////////////////////////////////////////////////////////
/// Calculate the absolute humidity based on the relative humidity and temperature
/// in tempUnit.
/// the formula does work for values between -30°C and 35°C with 0.1°C precision
/// @param temperature in tempUnit
/// @param humidity in percentage
/// @param tempUnit in °C. default=TempUnit_Celsius
/// @return Calculated absolute humidity in grams/m³
float AbsoluteHumidity
(
float temperature,
float humidity,
TempUnit tempUnit
);
/////////////////////////////////////////////////////////////////
/// Convert current pressure to equivalent sea-level pressure.
/// @param altitude in altUnit.
/// @param temp in tempUnit.
/// @param pressure at the station in any units.
/// @param altUnit meters or feet. default=AltitudeUnit_Meters
/// @param tempUnit in °C or °F. default=TempUnit_Celsius
/// @return Equivalent pressure at sea level. The input pressure
/// unit will determine the output
/// pressure unit.
float EquivalentSeaLevelPressure(
float altitude,
float temp,
float pres,
AltitudeUnit altUnit = AltitudeUnit_Meters,
TempUnit tempUnit = TempUnit_Celsius);
/////////////////////////////////////////////////////////////////
/// Calculate the dew point based on the temperature in tempUnit
/// and humidity.
/// @param temp in tempUnit.
/// @param hum in %.
/// @param temptUnit in °C or °F. default=TempUnit_Celsius
float DewPoint(
float temp,
float hum,
TempUnit tempUnit = TempUnit_Celsius);
}
#endif // TG_ENVIRONMENT_CALCULATIONS_H

View File

@ -14,5 +14,4 @@ board = d1
framework = arduino
lib_deps =
olikraus/U8g2@^2.28.8
finitespace/BME280@^3.0.0
rweather/Crypto@^0.2.0

5
EnvTest/go.mod Normal file
View File

@ -0,0 +1,5 @@
module 51m0n.com/EnvironmentManagerTest/v2
go 1.15
require golang.org/x/crypto v0.0.0-20210921155107-089bfa567519

9
EnvTest/go.sum Normal file
View File

@ -0,0 +1,9 @@
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

73
EnvTest/main.go Normal file
View File

@ -0,0 +1,73 @@
package main
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"net/http"
"golang.org/x/crypto/blake2s"
"golang.org/x/crypto/chacha20poly1305"
)
type EnvironmentData struct {
Temp float64 `json:"t" binding:"required"`
Humidity float64 `json:"h" binding:"required"`
}
const passcode = "pass2"
const salt = "ENVIRONMENT"
func main() {
data := EnvironmentData{Temp: 25, Humidity: 40}
b, err := json.Marshal(data)
if err != nil {
panic(err)
}
pass, err := DeriveKey(passcode)
if err != nil {
panic(err)
}
aead, err := chacha20poly1305.New([]byte(pass))
if err != nil {
panic(err)
}
iv := make([]byte, chacha20poly1305.NonceSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
cypher := aead.Seal(nil, iv, b, nil)
cypher = append(iv, cypher...)
request, err := http.NewRequest(http.MethodPut, "http://localhost:8080/data/authed/7701238505945920037", bytes.NewReader(cypher))
if err == nil {
resp, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("Sent, code: %s", resp.Status)
} else {
panic(err)
}
}
func DeriveKey(passcode string) ([]byte, error) {
hash, err := blake2s.New256(nil)
if err != nil {
return nil, err
}
hash.Write([]byte(salt))
hash.Write([]byte(passcode))
fmt.Printf("SALT %s PASS %s\n", salt, passcode)
return hash.Sum(nil), nil
}

View File

@ -11,7 +11,7 @@ namespace ManagementPage.Database
private const string _accountsCollectionName = "Accounts";
private const string _deviceCollectionName = "Devices";
private const string _databaseName = "Environment";
private const string _uri = "mongodb://192.168.0.159:27017";
private readonly string _uri;
private readonly IMongoDatabase _database;
private readonly MongoClient _client;
@ -20,8 +20,9 @@ namespace ManagementPage.Database
public IMongoCollection<DeviceData> DeviceCollection { get; private set; }
public MongoDbClient()
public MongoDbClient(IConfiguration configRoot)
{
_uri = configRoot["mongodb:uri"];
_client = new MongoClient(_uri);
_database = _client.GetDatabase(_databaseName);
BsonClassMap.RegisterClassMap<EnvironmentData>(cm =>

View File

@ -6,6 +6,9 @@
<RazorPage_SelectedScaffolderID>RazorPageScaffolder</RazorPage_SelectedScaffolderID>
<RazorPage_SelectedScaffolderCategoryPath>root/Common/RazorPage</RazorPage_SelectedScaffolderCategoryPath>
<NameOfLastUsedPublishProfile>P:\EnvironmentManagement\ManagementPage\ManagementPage\Properties\PublishProfiles\registry.jacknet.io.pubxml</NameOfLastUsedPublishProfile>
<ActiveDebugProfile>Docker</ActiveDebugProfile>
<ActiveDebugProfile>ManagementPage</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -8,10 +8,10 @@
<h2>@Model.device.Name</h2>
<h4>Current Conditions</h4>
<div>
Temp: @Model.data.LastOrDefault()?.Temperature.ToString("N1")
Temp: @Model.data.FirstOrDefault()?.Temperature.ToString("N1")°C
</div>
<div>
Humidity: @Model.data.LastOrDefault()?.Humidity.ToString("N1")
Humidity: @Model.data.FirstOrDefault()?.Humidity.ToString("N1")%
</div>
</div>
<div >
@ -19,6 +19,8 @@
</div>
<script src="~/lib/chart.js/dist/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.js" integrity="sha256-8AdWdyRXkrETyAGla9NmgkYVlqw4MOHR6sJJmtFGAYQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0/dist/chartjs-adapter-moment.min.js" integrity="sha256-sFB24K2xU2EOgWAtb3ySAGjhMqcUvUJGmwjDcTQa04k=" crossorigin="anonymous"></script>
<script src="~/js/temperature_chart.js" asp-append-version="true"></script>
<script>
var ctx = document.getElementById('tempChart');

View File

@ -25,11 +25,12 @@ namespace ManagementPage.Pages
humidity = new List<DataSet>();
temperature = new List<DataSet>();
_dbClient = dbClient;
device = new DeviceData("","",0);
}
public async Task<IActionResult> OnGetAsync()
{
var deviceId = 0l ;
var deviceId = 0L;
try
{
var idString = (string?)RouteData.Values.Where(k => k.Key == "id")?.First().Value;

View File

@ -3,7 +3,7 @@
@{
ViewData["Title"] = "Error";
}
<div style="font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif">
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@ -13,14 +13,3 @@
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -6,5 +6,21 @@
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<div class="container-fluid">
@if (User.Identity == null || !User.Identity.IsAuthenticated)
{
<h2>Please log in</h2>
<a asp-page="/UserHome" style="display: inline-block;">
<span style="white-space: nowrap;display: flex;">
Login with
<img style="no-repeat;width: 6em;background-size: contain;background-position: center;margin-left: 10px;" src="~/static/JackNet-auth-logo-orange.svg"></img>
</span>
</a>
}
else
{
<p>You're already logged in, please use the <a asp-area="" asp-page="/UserHome">User</a> tab to see your devices.</p>
}
</div>

View File

@ -1,8 +0,0 @@
@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -1,19 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ManagementPage.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}

View File

@ -23,16 +23,16 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/UserHome">User</a>
</li>
@if (User.Identity != null && User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/UserHome">User</a>
</li>
}
</ul>
@if (User.Identity != null && User.Identity.IsAuthenticated)
{
<ul class="navbar-nav flex-grow-1">
<ul class="navbar-nav flex-grow-1" style="justify-content: right">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/logout">Logout</a>
</li>
@ -50,7 +50,7 @@
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2021 - ManagementPage - <a asp-area="" asp-page="/Privacy">Privacy</a>
&copy; 2021 - 51m0n</a>
</div>
</footer>

View File

@ -6,31 +6,34 @@
<h3>Hi @Model.name</h3>
<hr></hr>
<div class="card-deck row row-cols-1 row-cols-md-3 g-4">
@foreach (var item in @Model.data)
{
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">@item.Name</h5>
<p class="card-text">
<h4>Current conditions:</h4>
<div>Temperature @Model.currentEnvironment[@item.ApiID].Temperature</div>
<div>Humidity @Model.currentEnvironment[@item.ApiID].Humidity</div>
</p>
<a class="btn btn-primary" asp-area="" asp-page="/DevicePage" asp-route-id="@((UInt64)item.ApiID)">Details</a>
<div class="container-fluid">
<div class="card-deck row row-cols-1 row-cols-md-3 g-4">
@foreach (var item in @Model.data)
{
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">@item.Name</h5>
<p class="card-text">
<h4>Current conditions:</h4>
<div>Temperature @Model.currentEnvironment[@item.ApiID].Temperature</div>
<div>Humidity @Model.currentEnvironment[@item.ApiID].Humidity</div>
</p>
<a class="btn btn-primary" asp-area="" asp-page="/DevicePage" asp-route-id="@((UInt64)item.ApiID)">Details</a>
</div>
</div>
</div>
}
}
<div class="card text-center" style="width: 18rem;">
<div class="card-body ">
<h5 class="card-title">New Item</h5>
<p class="card-text">Register a new device</p>
<button type="button" class="btn btn-primary oi oi-plus" data-bs-toggle="modal" data-bs-target="#devicemodal"></button>
<div class="card text-center" style="width: 18rem;">
<div class="card-body d-flex flex-column">
<h5 class="card-title">New Item</h5>
<p class="card-text">Register a new device</p>
<div class="mt-auto">
<button type="button" class="btn btn-primary oi oi-plus" data-bs-toggle="modal" data-bs-target="#devicemodal"></button>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="devicemodal" tabindex="-1" aria-labelledby="deviceModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">

View File

@ -44,9 +44,9 @@ namespace ManagementPage.Pages
var id = await binder.GetLocalAccount(User.FindFirstValue(ClaimTypes.NameIdentifier));
name = User.FindFirstValue(ClaimTypes.GivenName);
using var cursor = await _dbClient.DeviceCollection.FindAsync(new BsonDocument());
data = cursor.ToList();
data.Clear();
data.AddRange(_dbClient.DeviceCollection.AsQueryable().Where(s => id.Devices.Contains(s._id)).ToArray());
foreach (var item in data)
{
@ -63,7 +63,7 @@ namespace ManagementPage.Pages
{
return Page();
}
var id = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(),4);
var id = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 4);
var device = new DeviceData(NewDevice.Name, NewDevice.Passcode, id);
device._id = ObjectId.GenerateNewId();
await _dbClient.DeviceCollection.InsertOneAsync(device);

View File

@ -4,10 +4,19 @@ using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using System.Collections;
var builder = WebApplication.CreateBuilder(args);
var Configuration = builder.Configuration;
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllers();
@ -24,7 +33,6 @@ builder.Services.AddAuthentication(options => {
options.ClientSecret = Configuration["oidc:clientsecret"];
options.Authority = @"https://auth.jacknet.io/auth/realms/JackNet";
//options.Authority = String.Format("https://{0}.onelogin.com/oidc/2", Configuration["oidc:region"]);
options.ResponseType = "code";
options.GetClaimsFromUserInfoEndpoint = true;
}
@ -32,6 +40,8 @@ builder.Services.AddAuthentication(options => {
var app = builder.Build();
app.UseForwardedHeaders();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
@ -40,7 +50,6 @@ if (!app.Environment.IsDevelopment())
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
@ -49,12 +58,6 @@ app.UseRouting();
app.UseAuthorization();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
RequireHeaderSymmetry = false,
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.MapRazorPages();
app.Run();

View File

@ -14,7 +14,7 @@
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://environment.51m0n.com;http://+:80",
"applicationUrl": "https://localhost:443;http://+:80",
"dotnetRunMessages": true
},
"IIS Express": {

View File

@ -6,6 +6,9 @@
"Microsoft.AspNetCore": "Warning"
}
},
"mongodb": {
"uri": "mongodb://192.168.0.159:27017"
},
"oidc": {
"region": "openid-connect",
"clientid": "51m0n-temperature",

View File

@ -24,7 +24,65 @@ function CreateChart(ctx, temp, humidity) {
const config = {
type: 'line',
data: data,
options: { maintainAspectRatio: true }
options: {
maintainAspectRatio: true,
scales: {
y: {
title: {
display: true,
text: "Temperature",
},
ticks: {
callback: function (value, index, values) {
return value + '°C';
},
precision: 1,
}
},
humid: {
title: {
display: true,
text: "Humidity",
},
position: "right",
ticks: {
callback: function (value, index, values) {
return value + '%';
},
precision: 0,
},
grid: {
drawOnChartArea: false,
},
},
x: {
title: {
display: true,
text: "Time",
},
type: 'time',
time: {
unit: 'minute',
displayFormats: {
minute: "D MMM HH:mm"
},
},
ticks: {
autoSkip: true,
maxTicksLimit: 25
}
}
},
plugins: {
legend: {
labels: {
font: {
family: "'Quicksand', serif"
}
}
}
}
}
};
return tempChart = new Chart(ctx, config);

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -2,13 +2,34 @@ version: "3.4"
services:
frontend:
image: registry.jacknet.io/51m0n/environment-frontend:latest
depends_on:
- database
environment:
- ASPNETCORE_oidc_region=openid-connect
- ASPNETCORE_oidc_clientid=51m0n-temperature
- ASPNETCORE_oidc_clientsecret=
- ASPNETCORE_mongodb_uri=mongodb://database:27017/
database:
image: mongodb:latest
image: mongo:latest
volumes:
- "db-data:/data/db"
apiserver:
image: registry.jacknet.io/51m0n/environment-api:latest
environment:
- GIN_DB_PATH=mongodb://database:27017/
depends_on:
- database
proxy:
image: nginx:latest
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
ports:
- "9030:9000"
depends_on:
- apiserver
- frontend
volumes:
db-data:

79
env_page_nginx.conf Normal file
View File

@ -0,0 +1,79 @@
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
# include /etc/nginx/conf.d/*.conf;
server {
listen 9000;
listen [::]:9000;
server_name localhost;
# To allow special characters in headers
ignore_invalid_headers off;
# Allow any size file to be uploaded.
# Set to a value such as 1000m; to restrict file size to a specific value
client_max_body_size 1m;
# To disable buffering
proxy_buffering off;
location /api/ {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 300;
# Default is HTTP/1, keepalive is only enabled in HTTP/1.1
proxy_http_version 1.1;
proxy_set_header Connection "";
chunked_transfer_encoding off;
proxy_pass http://apiserver:8080/;
}
location / {
# Do preserve this
proxy_set_header Host $http_host;
# again dont overwrite this
#proxy_set_header X-Real-IP $remote_addr;
# this just seems to append another ip ie <host>, <proxy>
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Preserve the scheme as https if behind another proxy
#proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 300;
# Default is HTTP/1, keepalive is only enabled in HTTP/1.1
proxy_http_version 1.1;
proxy_set_header Connection "";
chunked_transfer_encoding off;
proxy_pass http://frontend;
}
}
}