Merge remote-tracking branch 'upstream/development' into development

This commit is contained in:
Tortone Gennaro 2018-03-01 08:44:12 +01:00
commit fd2171ad9b
95 changed files with 9040 additions and 6465 deletions

6
.gitignore vendored
View File

@ -1,3 +1,9 @@
## OS specific ########
.DS_Store
.fuse_hidden*
## Project files ######
.pioenvs
.piolibdeps
.clang_complete

View File

@ -1,7 +1,7 @@
## Sonoff-Tasmota
Provide ESP8266 based Sonoff by [iTead Studio](https://www.itead.cc/) and ElectroDragon IoT Relay with Serial, Web and MQTT control allowing 'Over the Air' or OTA firmware updates using Arduino IDE.
Current version is **5.11.1h** - See [sonoff/_releasenotes.ino](https://github.com/arendst/Sonoff-Tasmota/blob/development/sonoff/_releasenotes.ino) for change information.
Current version is **5.12.0d** - See [sonoff/_releasenotes.ino](https://github.com/arendst/Sonoff-Tasmota/blob/development/sonoff/_releasenotes.ino) for change information.
### ATTENTION All versions
@ -43,6 +43,7 @@ The following devices are supported:
- [iTead Sonoff 4CH Pro](https://www.itead.cc/smart-home/sonoff-4ch-pro.html)
- [iTead S20 Smart Socket](https://www.itead.cc/smart-socket.html)
- [Sonoff S22 Smart Socket](https://github.com/arendst/Sonoff-Tasmota/issues/627)
- [iTead Sonoff S31 Smart Socket with Energy Monitoring](https://www.itead.cc/sonoff-s31.html)
- [iTead Slampher](https://www.itead.cc/slampher.html)
- [iTead Sonoff Touch](https://www.itead.cc/sonoff-touch.html)
- [iTead Sonoff T1](https://www.itead.cc/sonoff-t1.html)
@ -61,7 +62,7 @@ The following devices are supported:
- AriLux AL-LC01, AL-LC06 and AL-LC11 PWM LED controller
- [Supla device - Espablo-inCan mod. for electrical Installation box](https://forum.supla.org/viewtopic.php?f=33&t=2188)
- [Luani HVIO board](https://luani.de/projekte/esp8266-hvio/)
- Wemos D1 mini and NodeMcu
- Wemos D1 mini, NodeMcu and Ledunia
### License

File diff suppressed because it is too large Load Diff

View File

@ -1,131 +0,0 @@
# ESP8266 platform
# ------------------------------
# For more info:
# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification
name=ESP8266 Modules
version=2.4.0
compiler.warning_flags=-w
compiler.warning_flags.none=-w
compiler.warning_flags.default=
compiler.warning_flags.more=-Wall
compiler.warning_flags.all=-Wall -Wextra
build.lwip_lib=-llwip_gcc
build.lwip_flags=-DLWIP_OPEN_SRC
compiler.path={runtime.tools.xtensa-lx106-elf-gcc.path}/bin/
compiler.sdk.path={runtime.platform.path}/tools/sdk
compiler.libc.path={runtime.platform.path}/tools/sdk/libc/xtensa-lx106-elf
compiler.cpreprocessor.flags=-D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-I{compiler.sdk.path}/include" "-I{compiler.sdk.path}/lwip/include" "-I{compiler.libc.path}/include" "-I{build.path}/core"
compiler.c.cmd=xtensa-lx106-elf-gcc
compiler.c.flags=-c {compiler.warning_flags} -Os -g -Wpointer-arith -Wno-implicit-function-declaration -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -falign-functions=4 -MMD -std=gnu99 -ffunction-sections -fdata-sections
compiler.S.cmd=xtensa-lx106-elf-gcc
compiler.S.flags=-c -g -x assembler-with-cpp -MMD -mlongcalls
compiler.c.elf.flags=-g {compiler.warning_flags} -Os -nostdlib -Wl,--no-check-sections -u call_user_start -u _printf_float -u _scanf_float -Wl,-static "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" "-L{compiler.libc.path}/lib" "-T{build.flash_ld}" -Wl,--gc-sections -Wl,-wrap,system_restart_local -Wl,-wrap,spi_flash_read
compiler.c.elf.cmd=xtensa-lx106-elf-gcc
compiler.c.elf.libs=-lhal -lphy -lpp -lnet80211 {build.lwip_lib} -lwpa -lcrypto -lmain -lwps -laxtls -lespnow -lsmartconfig -lmesh -lwpa2 -lstdc++ -lm -lc -lgcc
compiler.cpp.cmd=xtensa-lx106-elf-g++
compiler.cpp.flags=-c {compiler.warning_flags} -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections
compiler.as.cmd=xtensa-lx106-elf-as
compiler.ar.cmd=xtensa-lx106-elf-ar
compiler.ar.flags=cru
compiler.elf2hex.cmd=esptool
compiler.elf2hex.flags=
compiler.size.cmd=xtensa-lx106-elf-size
compiler.esptool.cmd=esptool
compiler.esptool.cmd.windows=esptool.exe
# This can be overriden in boards.txt
build.extra_flags=-DESP8266
# These can be overridden in platform.local.txt
compiler.c.extra_flags=
compiler.c.elf.extra_flags=
compiler.S.extra_flags=
compiler.cpp.extra_flags=
compiler.ar.extra_flags=
compiler.objcopy.eep.extra_flags=
compiler.elf2hex.extra_flags=
## generate file with git version number
## needs bash, git, and echo
## windows-compatible version may be added later
## Compile c files
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.c.flags} -DF_CPU={build.f_cpu} {build.lwip_flags} {build.debug_port} {build.debug_level} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Compile c++ files
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} -DF_CPU={build.f_cpu} {build.lwip_flags} {build.debug_port} {build.debug_level} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Compile S files
recipe.S.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.S.flags} -DF_CPU={build.f_cpu} {build.lwip_flags} {build.debug_port} {build.debug_level} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Create archives
recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/arduino.ar" "{object_file}"
## Combine gc-sections, archives, and objects
recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" -Wl,--start-group {object_files} "{build.path}/arduino.ar" {compiler.c.elf.libs} -Wl,--end-group "-L{build.path}"
## Create eeprom
recipe.objcopy.eep.pattern=
## Create hex
#recipe.objcopy.hex.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.hex"
recipe.objcopy.hex.pattern="{runtime.tools.esptool.path}/{compiler.esptool.cmd}" -eo "{runtime.platform.path}/bootloaders/eboot/eboot.elf" -bo "{build.path}/{build.project_name}.bin" -bm {build.flash_mode} -bf {build.flash_freq} -bz {build.flash_size} -bs .text -bp 4096 -ec -eo "{build.path}/{build.project_name}.elf" -bs .irom0.text -bs .text -bs .data -bs .rodata -bc -ec
## Save hex
recipe.output.tmp_file={build.project_name}.bin
recipe.output.save_file={build.project_name}.{build.variant}.bin
## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.irom0\.text|\.text|\.data|\.rodata|)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.rodata|\.bss)\s+([0-9]+).*
#recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*
# ------------------------------
tools.esptool.cmd=esptool
tools.esptool.cmd.windows=esptool.exe
tools.esptool.path={runtime.tools.esptool.path}
tools.esptool.network_cmd=python
tools.esptool.network_cmd.windows=python.exe
tools.esptool.upload.protocol=esp
tools.esptool.upload.params.verbose=-vv
tools.esptool.upload.params.quiet=
tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"
tools.esptool.upload.network_pattern="{network_cmd}" "{runtime.platform.path}/tools/espota.py" -i "{serial.port}" -p "{network.port}" "--auth={network.password}" -f "{build.path}/{build.project_name}.bin"
tools.mkspiffs.cmd=mkspiffs
tools.mkspiffs.cmd.windows=mkspiffs.exe
tools.mkspiffs.path={runtime.tools.mkspiffs.path}
tools.espupload.cmd=python
tools.espupload.cmd.windows=python.exe
tools.espupload.path={runtime.platform.path}/tools
tools.espupload.upload.protocol=espupload
tools.espupload.upload.params.verbose=
tools.espupload.upload.params.quiet=
tools.espupload.upload.pattern="{cmd}" "{path}/espupload.py" -f "{build.path}/{build.project_name}.bin"

File diff suppressed because it is too large Load Diff

View File

@ -1,131 +0,0 @@
# ESP8266 platform
# ------------------------------
# For more info:
# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification
name=ESP8266 Modules
version=2.4.0
compiler.warning_flags=-w
compiler.warning_flags.none=-w
compiler.warning_flags.default=
compiler.warning_flags.more=-Wall
compiler.warning_flags.all=-Wall -Wextra
build.lwip_lib=-llwip_gcc
build.lwip_flags=-DLWIP_OPEN_SRC
compiler.path={runtime.tools.xtensa-lx106-elf-gcc.path}/bin/
compiler.sdk.path={runtime.platform.path}/tools/sdk
compiler.libc.path={runtime.platform.path}/tools/sdk/libc/xtensa-lx106-elf
compiler.cpreprocessor.flags=-D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-I{compiler.sdk.path}/include" "-I{compiler.sdk.path}/lwip/include" "-I{compiler.libc.path}/include" "-I{build.path}/core"
compiler.c.cmd=xtensa-lx106-elf-gcc
compiler.c.flags=-c {compiler.warning_flags} -Os -g -Wpointer-arith -Wno-implicit-function-declaration -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -falign-functions=4 -MMD -std=gnu99 -ffunction-sections -fdata-sections
compiler.S.cmd=xtensa-lx106-elf-gcc
compiler.S.flags=-c -g -x assembler-with-cpp -MMD -mlongcalls
compiler.c.elf.flags=-g {compiler.warning_flags} -Os -nostdlib -Wl,--no-check-sections -u call_user_start -u _printf_float -u _scanf_float -Wl,-static "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" "-L{compiler.libc.path}/lib" "-T{build.flash_ld}" -Wl,--gc-sections -Wl,-wrap,system_restart_local -Wl,-wrap,spi_flash_read
compiler.c.elf.cmd=xtensa-lx106-elf-gcc
compiler.c.elf.libs=-lhal -lphy -lpp -lnet80211 {build.lwip_lib} -lwpa -lcrypto -lmain -lwps -laxtls -lespnow -lsmartconfig -lairkiss -lmesh -lwpa2 -lstdc++ -lm -lc -lgcc
compiler.cpp.cmd=xtensa-lx106-elf-g++
compiler.cpp.flags=-c {compiler.warning_flags} -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections
compiler.as.cmd=xtensa-lx106-elf-as
compiler.ar.cmd=xtensa-lx106-elf-ar
compiler.ar.flags=cru
compiler.elf2hex.cmd=esptool
compiler.elf2hex.flags=
compiler.size.cmd=xtensa-lx106-elf-size
compiler.esptool.cmd=esptool
compiler.esptool.cmd.windows=esptool.exe
# This can be overriden in boards.txt
build.extra_flags=-DESP8266
# These can be overridden in platform.local.txt
compiler.c.extra_flags=
compiler.c.elf.extra_flags=
compiler.S.extra_flags=
compiler.cpp.extra_flags=
compiler.ar.extra_flags=
compiler.objcopy.eep.extra_flags=
compiler.elf2hex.extra_flags=
## generate file with git version number
## needs bash, git, and echo
## windows-compatible version may be added later
## Compile c files
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.c.flags} -DF_CPU={build.f_cpu} {build.lwip_flags} {build.debug_port} {build.debug_level} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Compile c++ files
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} -DF_CPU={build.f_cpu} {build.lwip_flags} {build.debug_port} {build.debug_level} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Compile S files
recipe.S.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.S.flags} -DF_CPU={build.f_cpu} {build.lwip_flags} {build.debug_port} {build.debug_level} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BOARD="{build.board}" {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Create archives
recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/arduino.ar" "{object_file}"
## Combine gc-sections, archives, and objects
recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" -Wl,--start-group {object_files} "{build.path}/arduino.ar" {compiler.c.elf.libs} -Wl,--end-group "-L{build.path}"
## Create eeprom
recipe.objcopy.eep.pattern=
## Create hex
#recipe.objcopy.hex.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.hex"
recipe.objcopy.hex.pattern="{runtime.tools.esptool.path}/{compiler.esptool.cmd}" -eo "{runtime.platform.path}/bootloaders/eboot/eboot.elf" -bo "{build.path}/{build.project_name}.bin" -bm {build.flash_mode} -bf {build.flash_freq} -bz {build.flash_size} -bs .text -bp 4096 -ec -eo "{build.path}/{build.project_name}.elf" -bs .irom0.text -bs .text -bs .data -bs .rodata -bc -ec
## Save hex
recipe.output.tmp_file={build.project_name}.bin
recipe.output.save_file={build.project_name}.{build.variant}.bin
## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.irom0\.text|\.text|\.data|\.rodata|)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.rodata|\.bss)\s+([0-9]+).*
#recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*
# ------------------------------
tools.esptool.cmd=esptool
tools.esptool.cmd.windows=esptool.exe
tools.esptool.path={runtime.tools.esptool.path}
tools.esptool.network_cmd=python
tools.esptool.network_cmd.windows=python.exe
tools.esptool.upload.protocol=esp
tools.esptool.upload.params.verbose=-vv
tools.esptool.upload.params.quiet=
tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"
tools.esptool.upload.network_pattern="{network_cmd}" "{runtime.platform.path}/tools/espota.py" -i "{serial.port}" -p "{network.port}" "--auth={network.password}" -f "{build.path}/{build.project_name}.bin"
tools.mkspiffs.cmd=mkspiffs
tools.mkspiffs.cmd.windows=mkspiffs.exe
tools.mkspiffs.path={runtime.tools.mkspiffs.path}
tools.espupload.cmd=python
tools.espupload.cmd.windows=python.exe
tools.espupload.path={runtime.platform.path}/tools
tools.espupload.upload.protocol=espupload
tools.espupload.upload.params.verbose=
tools.espupload.upload.params.quiet=
tools.espupload.upload.pattern="{cmd}" "{path}/espupload.py" -f "{build.path}/{build.project_name}.bin"

674
lib/Joba_Tsl2561/COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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:
<program> Copyright (C) <year> <name of author>
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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

20
lib/Joba_Tsl2561/README Normal file
View File

@ -0,0 +1,20 @@
This is a library for the TSL2561 digital luminosity sensors from Ams (Taos).
Design goals:
* It is modularized so you can use only what you need if space/ram is constrained.
* It does not swallow error codes so you can react on them.
* It doesn't use floats as they are overkill for most IoT stuff.
Datasheet used:
http://ams.com/eng/Products/Light-Sensors/Ambient-Light-Sensors/TSL2561/TSL2560-TSL2561-Datasheet
http://ams.com/eng/content/download/250094/975485/file/TSL2560-61_DS000110_2-00.pdf
http://ams.com/eng/content/view/download/145438
http://ams.com/eng/content/view/download/181895
To use the library, just place the folder in your projects lib folder.
For usage, see the examples folder.
The library has 3 classes:
Tsl2561 All register access as described in the datasheet, except for interrupts
Tsl2561Util Convenience functions like lux calculation or automatic gain
Tsl2561Int TODO, Interrupt related stuff (not needed if int pin unconnected)

View File

@ -0,0 +1,65 @@
/*
Autogain tests for Tsl2561Util namespace.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561Util.h>
Tsl2561 Tsl(Wire);
uint8_t id;
void setup() {
Serial.begin(115200);
Wire.begin();
while( !Tsl.begin() )
; // wait until chip detected or wdt reset
Serial.println("\nStarting Tsl2561Util autogain loop");
Tsl.on();
Tsl.id(id);
}
void loop() {
uint16_t scaledFull = ~0, scaledIr = ~0;
uint32_t full = ~0, ir = ~0, milliLux = ~0;
bool gain = false;
Tsl2561::exposure_t exposure = Tsl2561::EXP_OFF;
if( Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr) ) {
if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) {
if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) {
Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, full: %5u, ir: %5u, gain: %d, exp: %d, lux: %5u.%03u\n",
Tsl.address(), id, scaledFull, scaledIr, full, ir, gain, exposure, milliLux/1000, milliLux%1000);
}
else {
Serial.printf("Tsl2561Util::milliLux(full=%u, ir=%u) error\n", full, ir);
}
}
else {
Serial.printf("Tsl2561Util::normalizedLuminosity(gain=%u, exposure=%u, sfull=%u, sir=%u, full=%u, ir=%u) error\n",
gain, exposure, scaledFull, scaledIr, full, ir);
}
}
else {
Serial.printf("Tsl2561Util::autoGain(gain=%u, exposure=%u, sfull=%u, sir=%u) error\n",
gain, exposure, scaledFull, scaledIr);
}
delay(1000);
}

View File

@ -0,0 +1,56 @@
/*
Simple tests for Tsl2561 class. No error checking is done.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561.h>
Tsl2561 Tsl(Wire);
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561 simple loop");
}
void loop() {
Tsl.begin();
if( Tsl.available() ) {
Tsl.on();
Tsl.setSensitivity(true, Tsl2561::EXP_14);
delay(16);
uint8_t id;
uint16_t full, ir;
Tsl.id(id);
Tsl.fullLuminosity(full);
Tsl.irLuminosity(ir);
Serial.printf("Tsl2561 at 0x%02x(id=0x%02x) luminosity is %5u (full) and %5u (ir)\n", Tsl.address(), id, full, ir);
Tsl.off();
}
else {
Serial.println("No Tsl2561 found. Check wiring.");
}
delay(5000);
}

View File

@ -0,0 +1,163 @@
/*
Tests for the Tsl2561 class.
It shows how to use every available method.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561.h>
Tsl2561 Tsl(Wire);
void showError( Tsl2561 &tsl ) {
Tsl2561::status_t status = tsl.status();
Serial.printf("Error was %u: ", status);
switch( status ) {
case Tsl2561::ERR_OK: Serial.println("None"); break;
case Tsl2561::ERR_RW: Serial.println("Read/Write"); break;
case Tsl2561::ERR_BUSY: Serial.println("Busy"); break;
case Tsl2561::ERR_GONE: Serial.println("Gone"); break;
case Tsl2561::ERR_GENERAL: Serial.println("General"); break;
default: Serial.println("Unknown"); break;
}
}
void testSensitivity( Tsl2561 &tsl, bool newGain, Tsl2561::exposure_t newExp ) {
if( tsl.on() ) {
uint32_t start = millis();
Serial.printf("Chip powered on at %u\n", start);
bool chipGain;
Tsl2561::exposure_t chipExp;
bool change = true;
if( tsl.getSensitivity(chipGain, chipExp) ) {
if( chipGain == newGain && chipExp == newExp ) {
change = false;
}
}
else {
Serial.print("getSensitivity failed. ");
showError(tsl);
}
bool check = true;
if( change ) {
if( tsl.setSensitivity(newGain, newExp) ) {
Serial.printf("New gain = %d, exposure = 0x%02x\n", newGain, newExp);
}
else {
check = false;
Serial.print("setSensitivity failed. ");
showError(tsl);
}
}
if( check ) {
uint16_t ir, full = 0;
while( !full && millis() - start < 1000 ) {
if( !tsl.fullLuminosity(full) ) {
Serial.print("Check full luminosity failed. ");
showError(tsl);
}
if( full ) {
if( !tsl.irLuminosity(ir) ) {
Serial.print("Check ir luminosity failed. ");
showError(tsl);
}
}
else {
delay(10);
}
}
if( !full ) {
Serial.println("No luminosity reading after 1s. Too dark?");
}
else {
Serial.printf("Got luminosity after %d ms. Full spectrum is %d and IR only is %d\n", millis() - start, full, ir);
}
}
if( !tsl.off() ) {
Serial.print("Power off failed. ");
showError(tsl);
}
}
else {
Serial.print("Power on failed. ");
showError(tsl);
}
}
bool testPackage( Tsl2561 &tsl ) {
uint8_t id;
if( tsl.id(id) ) {
Serial.printf("Chip has type %02x and revision %x\n", Tsl2561::type(id), Tsl2561::revision(id) );
if( Tsl2561::packageT_FN_CL(id) ) {
Serial.println("Chip is a T, FN or CL type package");
}
else if( Tsl2561::packageCS(id) ) {
Serial.println("Chip is a CS type package");
}
else {
Serial.println("Chip is an unknown package");
}
return true;
}
else {
Serial.print("Get Chip ID failed. ");
showError(tsl);
}
return false;
}
void test( Tsl2561 &tsl ) {
bool ok = tsl.available();
Serial.printf("\nTesting Tsl2561 at address %02x: %sfound\n", tsl.address(), ok ? "" : "NOT ");
if( ok ) {
if( testPackage(tsl) ) {
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_402);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_402);
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_101);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_101);
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_14);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_14);
}
}
else {
showError(tsl);
}
}
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561 testing loop");
}
void loop() {
Tsl.begin(Tsl2561::ADDR_GND);
test(Tsl);
Tsl.begin(Tsl2561::ADDR_FLOAT);
test(Tsl);
Tsl.begin(Tsl2561::ADDR_VDD);
test(Tsl);
Serial.println("\nNext test in 5s\n");
delay(5000);
}

View File

@ -0,0 +1,87 @@
/*
Simple tests for Tsl2561Util namespace.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561Util.h>
Tsl2561::address_t addr[] = { Tsl2561::ADDR_GND, Tsl2561::ADDR_FLOAT, Tsl2561::ADDR_VDD };
Tsl2561 Tsl(Wire);
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561Util loop");
}
void loop() {
bool found = false;
for( uint8_t i = 0; i < sizeof(addr)/sizeof(addr[0]); i++ ) {
if( Tsl.begin(addr[i]) ) {
found = true;
Serial.println();
uint16_t scaledFull = 0, scaledIr;
uint32_t full, ir, milliLux;
uint8_t id;
bool gain;
Tsl2561::exposure_t exposure;
for( uint8_t g=0; g<2; g++ ) {
gain = g;
for( uint8_t e=0; e<3; e++ ) {
exposure = (Tsl2561::exposure_t)e;
Tsl.on();
Tsl.setSensitivity(gain, exposure);
Tsl2561Util::waitNext(exposure);
Tsl.id(id);
Tsl.getSensitivity(gain, exposure);
Tsl.fullLuminosity(scaledFull);
Tsl.irLuminosity(scaledIr);
Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, gain: %d, exp: %d", addr[i], id, scaledFull, scaledIr, gain, exposure);
if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) {
if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) {
Serial.printf(", full: %5u, ir: %5u, lux: %5u.%03u\n", full, ir, milliLux/1000, milliLux%1000);
}
else {
Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::milliLux() error\n", full, ir);
}
}
else {
Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::normalizedLuminosity() error\n", full, ir);
}
Tsl.off();
}
}
}
}
if( !found ) {
Serial.println("No Tsl2561 found. Check wiring.");
}
delay(5000);
}

View File

@ -0,0 +1,13 @@
{
"name": "Joba_Tsl2561",
"version": "2.0.1",
"keywords": "twowire, i2c, bus, sensor, luminosity, illuminance, lux",
"description": "Arduino Library for ams (taos) luminance chip Tsl2561 with autogain",
"repository":
{
"type": "git",
"url": "https://github.com/joba-1/Joba_Tsl2561.git"
},
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=Joba Tsl2561 Library
version=2.0.1
author=joba-1
maintainer=joba-1 <joban123.psn@gmail.com>
sentence=IoT library for using the Tsl2561 luminosity sensor
paragraph=Luminosity measurement in lux with autogain
category=Sensors
url=https://github.com/joba-1/Joba_Tsl2561
architectures=*

View File

@ -0,0 +1,134 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Tsl2561.h"
Tsl2561::Tsl2561( TwoWire &wire ) : _addr(ADDR_NONE), _wire(wire), _status(ERR_OK) {
}
bool Tsl2561::available() {
_wire.beginTransmission(_addr);
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::begin( address_t addr ) {
_addr = addr;
return available();
}
bool Tsl2561::begin() {
static address_t addr[] = { ADDR_GND, ADDR_FLOAT, ADDR_VDD };
for( uint8_t i=0; i<sizeof(addr)/sizeof(addr[0]); i++ ) {
if( begin(addr[i]) ) {
return true;
}
}
_addr = ADDR_NONE;
return false;
}
bool Tsl2561::readByte( register_t reg, uint8_t &val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
if( _wire.endTransmission(false) == ERR_OK ) {
if( _wire.requestFrom(_addr, 1) ) {
val = static_cast<uint8_t>(_wire.read());
}
}
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::readWord( register_t reg, uint16_t &val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
if( _wire.endTransmission(false) == ERR_OK ) {
if( _wire.requestFrom(_addr, 2) ) {
val = (uint16_t)_wire.read() & 0xff;
val |= ((uint16_t)_wire.read() & 0xff) << 8;
}
}
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::writeByte( register_t reg, uint8_t val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
_wire.write(val);
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
Tsl2561::status_t Tsl2561::status() const {
return _status;
}
Tsl2561::address_t Tsl2561::address() const {
return _addr;
}
bool Tsl2561::id( uint8_t &id ) {
return readByte(REG_ID, id);
}
uint8_t Tsl2561::type( uint8_t id ) {
return id & PKG_ID;
}
uint8_t Tsl2561::revision( uint8_t id ) {
return id & PKG_REV;
}
bool Tsl2561::packageCS( uint8_t id ) {
return type(id) == PKG_CS;
}
bool Tsl2561::packageT_FN_CL( uint8_t id ) {
return type(id) == PKG_T_FN_CL;
}
bool Tsl2561::on() {
return writeByte(REG_CONTROL, POWER_ON);
}
bool Tsl2561::off() {
return writeByte(REG_CONTROL, POWER_OFF);
}
bool Tsl2561::setSensitivity( bool gain, exposure_t exposure ) {
return writeByte(REG_TIMING, (gain ? GAIN_ON : GAIN_OFF) | exposure);
}
bool Tsl2561::getSensitivity( bool &gain, exposure_t &exposure )
{
uint8_t val;
if( readByte(REG_TIMING, val) ) {
gain = val & GAIN_ON;
exposure = static_cast<exposure_t>(val & EXP_ON);
}
return _status == ERR_OK;
}
bool Tsl2561::fullLuminosity( uint16_t &luminosity ) {
return readWord(REG_DATA0LOW, luminosity);
}
bool Tsl2561::irLuminosity( uint16_t &luminosity ) {
return readWord(REG_DATA1LOW, luminosity);
}

View File

@ -0,0 +1,133 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Tsl2561_H
#define Tsl2561_H
#include <Arduino.h>
#include <Wire.h>
class Tsl2561 {
public:
typedef enum {
ADDR_NONE = 0b0000000,
ADDR_GND = 0b0101001,
ADDR_FLOAT = 0b0111001,
ADDR_VDD = 0b1001001
} address_t;
typedef enum {
REG_CONTROL, // Control of basic functions
REG_TIMING, // Integration time/gain control
REG_THRESHLOWLOW, // Low byte of low interrupt threshold
REG_THRESHLOWHIGH, // High byte of low interrupt threshold
REG_THRESHHIGHLOW, // Low byte of high interrupt threshold
REG_THRESHHIGHHIGH, // High byte of high interrupt threshold
REG_INTERRUPT, // Interrupt control
REG_RESERVED1,
REG_CRC, // Factory test - not a user register
REG_RESERVED2,
REG_ID, // Part number/Rev ID
REG_RESERVED3,
REG_DATA0LOW, // Low byte of ADC channel 0
REG_DATA0HIGH, // High byte of ADC channel 0
REG_DATA1LOW, // Low byte of ADC channel 1
REG_DATA1HIGH // High byte of ADC channel 1
} register_t;
enum {
CONTROL_CMD = 0b10000000,
CONTROL_CLEAR = 0b01000000,
CONTROL_WORD = 0b00100000, // SPI only?
CONTROL_BLOCK = 0b00010000, // SPI only?
CONTROL_ADDRESS = 0b00001111
};
enum {
POWER_OFF,
POWER_ON = 0b11,
};
enum {
GAIN_OFF,
GAIN_ON = 0b00010000
};
typedef enum {
EXP_ON = 0b00001011,
EXP_OFF = 0b00000011,
EXP_14 = 0b00000000,
EXP_101 = 0b00000001,
EXP_402 = 0b00000010
} exposure_t;
enum {
PKG_ID = 0b11110000,
PKG_REV = 0b00001111,
PKG_CS = 0b00010000,
PKG_T_FN_CL = 0b01010000
};
typedef enum {
ERR_OK = 0,
ERR_GENERAL = 1,
ERR_GONE = 2,
ERR_RW = 3,
ERR_BUSY = 4
} status_t;
Tsl2561( TwoWire &wire );
bool begin( address_t addr );
bool begin();
bool available();
status_t status() const;
address_t address() const;
bool id( uint8_t &id );
static uint8_t type( uint8_t id );
static uint8_t revision( uint8_t id );
static bool packageCS( uint8_t id );
static bool packageT_FN_CL( uint8_t id );
bool on();
bool off();
bool setSensitivity( bool gain, exposure_t exposure );
bool getSensitivity( bool &gain, exposure_t &exposure );
bool fullLuminosity( uint16_t &luminosity );
bool irLuminosity( uint16_t &luminosity );
protected:
bool readByte( register_t reg, uint8_t &val );
bool readWord( register_t reg, uint16_t &val );
bool writeByte( register_t reg, uint8_t val );
private:
Tsl2561();
Tsl2561( Tsl2561 & );
address_t _addr;
TwoWire &_wire;
status_t _status;
};
#endif

View File

@ -0,0 +1,193 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Tsl2561Util.h"
namespace Tsl2561Util {
// Tsl2561Util::normalizedLuminosity returncode false can mean:
// - saturation: full and/or ir have value ~0 (aka -1)
// - manual exposure time: full and ir are corrected only for gain
// If true, full and ir have values as if exposure was 402 and gain 16.
bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir ) {
uint16_t scaledFull = (uint16_t)full;
uint16_t scaledIr = (uint16_t)ir;
if( scaledFull ) {
if( ! gain ) {
full <<= 4;
ir <<= 4;
}
switch( exposure ) {
case Tsl2561::EXP_14:
full = (scaledFull >= 5047/4*3) ? ~0 : ((full + 5) * 322) / 11;
ir = (scaledIr >= 5047/4*3) ? ~0 : ((ir + 5) * 322) / 11;
break;
case Tsl2561::EXP_101:
full = (scaledFull >= 37177/4*3) ? ~0 : ((full + 40) * 322) / 81;
ir = (scaledIr >= 37177/4*3) ? ~0 : ((ir + 40) * 322) / 81;
break;
case Tsl2561::EXP_402:
if( scaledFull >= 65535/4*3 ) full = ~0;
if( scaledIr >= 65535/4*3 ) ir = ~0;
break;
default:
return false;
}
return full != ~0U && ir != ~0U;
}
return false;
}
// Return upper saturation limit upto which chip returns accurate data
uint16_t getLimit( Tsl2561::exposure_t exposure ) {
switch( exposure ) {
case Tsl2561::EXP_14: return 5047/4*3;
case Tsl2561::EXP_101: return 37177/4*3;
default: return 65535/4*3;
}
}
// Wait for one measurement interval plus some empirically tested extra millis
void waitNext( Tsl2561::exposure_t exposure ) {
switch( exposure ) {
case Tsl2561::EXP_14: delay(16); break;
case Tsl2561::EXP_101: delay(103); break;
default: delay(408); break;
}
}
// Wait for next sample, read luminosity and adjust sensitivity, if needed and possible
bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir ) {
static const struct {
bool gain;
Tsl2561::exposure_t exposure;
} sensitivity[] = {
{ false, Tsl2561::EXP_14, }, // min
{ false, Tsl2561::EXP_101 },
{ true, Tsl2561::EXP_14 },
{ false, Tsl2561::EXP_402 },
{ true, Tsl2561::EXP_101 },
{ true, Tsl2561::EXP_402 } // max
};
// get current sensitivity
if( !tsl.getSensitivity(gain, exposure) ) {
return false;
}
// find index of current sensitivity
uint8_t curr = 0;
while( curr < sizeof(sensitivity)/sizeof(sensitivity[0]) ) {
if( sensitivity[curr].gain == gain && sensitivity[curr].exposure == exposure ) {
break;
}
curr++;
}
if( curr == sizeof(sensitivity)/sizeof(sensitivity[0]) ) {
return false; // should not happen...
}
// in a loop wait for next sample, get values and adjust sensitivity if needed
while( true ) {
waitNext(exposure);
if( !tsl.fullLuminosity(full) || !tsl.irLuminosity(ir) ) {
return false;
}
uint16_t limit = getLimit(exposure);
if( full >= 1000 && full <= limit ) {
return true; // new value within limits
}
if( (full < 1000 && ++curr < sizeof(sensitivity)/sizeof(sensitivity[0]))
|| (full > limit && curr-- > 0) ) {
if( !tsl.setSensitivity(sensitivity[curr].gain, sensitivity[curr].exposure) ) {
return false;
}
gain = sensitivity[curr].gain;
exposure = sensitivity[curr].exposure;
}
else {
return true; // saturated, but best we can do
}
}
}
// Measurement is up to 20% too high for temperatures above 25°C. Compensate for that.
bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir ) {
// assume linear gradient 0% at 25°C to +20% at 70°C
if( centiCelsius >= -3000 && centiCelsius <= 7000 ) {
full -= (full * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500));
ir -= (ir * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500));
return true;
}
return false;
}
// Calculate lux from raw luminosity values
bool milliLux( uint32_t full, uint32_t ir, uint32_t &mLux, bool csType ) {
if( !full ) {
mLux = 0;
return true;
}
uint32_t milliRatio = ir * 1000 / full;
if( csType ) {
if( milliRatio < 130 ) { mLux = 1000 * full - 840 * ir; }
else if ( milliRatio < 260 ) { mLux = 1080 * full - 1380 * ir; }
else if ( milliRatio < 390 ) { mLux = 1160 * full - 1690 * ir; }
else if ( milliRatio < 520 ) { mLux = 1260 * full - 1940 * ir; }
else if ( milliRatio < 650 ) { mLux = 730 * full - 930 * ir; }
else if ( milliRatio < 800 ) { mLux = 500 * full - 575 * ir; }
else if ( milliRatio < 1300 ) { mLux = 110 * full - 85 * ir; }
else {
mLux = 0;
return false;
}
mLux /= 400 * 16 / 200; // 32 = counts/lux (cpl)
}
else {
if( milliRatio < 125 ) { mLux = 1000 * full - 895 * ir; }
else if ( milliRatio < 250 ) { mLux = 1070 * full - 1045 * ir; }
else if ( milliRatio < 375 ) { mLux = 1150 * full - 1790 * ir; }
else if ( milliRatio < 500 ) { mLux = 1260 * full - 2050 * ir; }
else if ( milliRatio < 610 ) { mLux = 740 * full - 1020 * ir; }
else if ( milliRatio < 800 ) { mLux = 420 * full - 500 * ir; }
else if ( milliRatio < 1300 ) { mLux = 48 * full - 37 * ir; }
else {
mLux = 0;
return false;
}
mLux /= 400 * 16 / 193; // 33 = counts/lux (cpl)
}
return true;
}
} // namespace Tsl2561Util

View File

@ -0,0 +1,48 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Tsl2561Util_H
#define Tsl2561Util_H
#include <Tsl2561.h>
namespace Tsl2561Util {
// delay until next sample is available
void waitNext( Tsl2561::exposure_t exposure );
// get saturation limit for given exposure time
uint16_t getLimit( Tsl2561::exposure_t exposure );
// in a loop wait for a sample, get it, check if within thresholds,
// until luminosity is either valid or at upper or lower saturation limit
bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir );
// adjust luminosity as if measured with maximum exposure time and maximum gain
bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir );
// adjust luminosity according to sensor temperature (max +/-20% from 25°C)
bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir );
// calculate lux from normalized (and optionally temperature adjusted) luminosity
bool milliLux( uint32_t full, uint32_t ir, uint32_t &milliLux, bool csType = false );
};
#endif

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,45 @@
# Mutichannel_Gas_Sensor
This Arduino library is used for driving "Xadow - Mutichannel Gas Sensor" and "Grove - Mutichanel Gas Sensor"
## Usage:
mutichannelGasSensor.begin(0x04);
mutichannelGasSensor.powerOn();
then read the concentration of the specific gas you want to measure:
mutichannelGasSensor.measure_NH3();
mutichannelGasSensor.measure_CO();
mutichannelGasSensor.measure_NO2();
mutichannelGasSensor.measure_C3H8();
mutichannelGasSensor.measure_C4H10();
mutichannelGasSensor.measure_CH4();
mutichannelGasSensor.measure_H2();
mutichannelGasSensor.measure_C2H5OH();
For details please move to [wiki page](http://www.seeedstudio.com/wiki/Grove_-_Multichannel_Gas_Sensor).
----
This software is written by Jacky Zhang (![](http://www.seeedstudio.com/wiki/images/8/8f/Email_addr_of_jacky_zhang.png)) from [Seeed Technology Inc.](http://www.seeed.cc) and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check License.txt/LICENSE for the details of MIT license.<br>
Contributing to this software is warmly welcomed. You can do this basically by<br>
[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then [pulling requests](https://help.github.com/articles/using-pull-requests) (follow the links above<br>
for operating guide). Adding change log and your contact into file header is encouraged.<br>
Thanks for your contribution.
Seeed is a hardware innovation platform for makers to grow inspirations into differentiating products. By working closely with technology providers of all scale, Seeed provides accessible technologies with quality, speed and supply chain knowledge. When prototypes are ready to iterate, Seeed helps productize 1 to 1,000 pcs using in-house engineering, supply chain management and agile manufacture forces. Seeed also team up with incubators, Chinese tech ecosystem, investors and distribution channels to portal Maker startups beyond.
[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Mutichannel_Gas_Sensor)](https://github.com/igrigorik/ga-beacon)

View File

@ -0,0 +1,20 @@
// Get firmware version of Grove Multichannel Gas Sensor
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR);
unsigned char version = gas.getVersion();
Serial.print("Version = ");
Serial.println(version);
}
void loop()
{
// nothing to do
}

View File

@ -0,0 +1,25 @@
// change i2c address
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR_OLD 0x04 // default to 0x04
#define SENSOR_ADDR_NEW 0x19 // change i2c address to 0x19
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR_OLD); //
gas.change_i2c_address(SENSOR_ADDR_NEW);
Serial.print("I2C ADDRESS SET TO 0X");;
Serial.println(SENSOR_ADDR_NEW, HEX);
}
void loop()
{
}
// END FILE

View File

@ -0,0 +1,57 @@
// get RAW data from the sensor
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR); //
}
void loop()
{
float R0_NH3, R0_CO, R0_NO2;
float Rs_NH3, Rs_CO, Rs_NO2;
float ratio_NH3, ratio_CO, ratio_NO2;
R0_NH3 = gas.getR0(0);
R0_CO = gas.getR0(1);
R0_NO2 = gas.getR0(2);
Rs_NH3 = gas.getRs(0);
Rs_CO = gas.getRs(1);
Rs_NO2 = gas.getRs(2);
ratio_NH3 = Rs_NH3/R0_NH3;
ratio_CO = Rs_CO/R0_CO;
ratio_NO2 = Rs_NH3/R0_NO2;
Serial.println("R0:");
Serial.print(R0_NH3);
Serial.print('\t');
Serial.print(R0_CO);
Serial.print('\t');
Serial.println(R0_NO2);
Serial.println("Rs:");
Serial.print(Rs_NH3);
Serial.print('\t');
Serial.print(Rs_CO);
Serial.print('\t');
Serial.println(Rs_NO2);
Serial.println("ratio:");
Serial.print(ratio_NH3);
Serial.print('\t');
Serial.print(ratio_CO);
Serial.print('\t');
Serial.println(ratio_NO2);
Serial.println("------------------------");
delay(1000);
}

View File

@ -0,0 +1,81 @@
/*
This is a demo to test gas library
This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas
There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master.
the data is raw ADC value, algorithm should be realized on master.
please feel free to write email to me if there is any question
Jacky Zhang, Embedded Software Engineer
qi.zhang@seeed.cc
17,mar,2015
*/
#include <Wire.h>
#include "MutichannelGasSensor.h"
void setup()
{
Serial.begin(115200); // start serial for output
Serial.println("power on!");
gas.begin(0x04);//the default I2C address of the slave is 0x04
gas.powerOn();
Serial.print("Firmware Version = ");
Serial.println(gas.getVersion());
}
void loop()
{
float c;
c = gas.measure_NH3();
Serial.print("The concentration of NH3 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CO();
Serial.print("The concentration of CO is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_NO2();
Serial.print("The concentration of NO2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C3H8();
Serial.print("The concentration of C3H8 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C4H10();
Serial.print("The concentration of C4H10 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CH4();
Serial.print("The concentration of CH4 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_H2();
Serial.print("The concentration of H2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C2H5OH();
Serial.print("The concentration of C2H5OH is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
delay(1000);
Serial.println("...");
}

View File

@ -0,0 +1,89 @@
/*
This is a demo to test gas library
This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas
There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master.
the data is raw ADC value, algorithm should be realized on master.
please feel free to write email to me if there is any question
Jacky Zhang, Embedded Software Engineer
qi.zhang@seeed.cc
17,mar,2015
*/
#include "xadow.h"
#include <Wire.h>
#include "MutichannelGasSensor.h"
void setup()
{
Xadow.init();
Serial.begin(9600); // start serial for output
Serial.println("power on!");
gas.begin(0x04);//the default I2C address of the slave is 0x04
//gas.changeI2cAddr(0x10);
//gas.doCalibrate();
gas.powerOn();
}
void loop()
{
float c;
c = gas.measure_NH3();
Serial.print("The concentration of NH3 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CO();
Serial.print("The concentration of CO is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_NO2();
Serial.print("The concentration of NO2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C3H8();
Serial.print("The concentration of C3H8 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C4H10();
Serial.print("The concentration of C4H10 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CH4();
Serial.print("The concentration of CH4 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_H2();
Serial.print("The concentration of H2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C2H5OH();
Serial.print("The concentration of C2H5OH is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
Xadow.greenLed(LEDON);
delay(500);
Xadow.greenLed(LEDOFF);
delay(500);
Serial.println("...");
}

View File

@ -0,0 +1,513 @@
// Atmega chip programmer
// Author: Nick Gammon
// Date: 22nd May 2012
// Version: 1.17
// Version 1.1: Reset foundSig to -1 each time around the loop.
// Version 1.2: Put hex bootloader data into separate files
// Version 1.3: Added verify, and MD5 sums
// Version 1.4: Added signatures for ATmeag8U2/16U2/32U2 (7 May 2012)
// Version 1.5: Added signature for ATmega1284P (8 May 2012)
// Version 1.6: Allow sketches to read bootloader area (lockbyte: 0x2F)
// Version 1.7: Added choice of bootloaders for the Atmega328P (8 MHz or 16 MHz)
// Version 1.8: Output an 8 MHz clock on pin 9
// Version 1.9: Added support for Atmega1284P, and fixed some bugs
// Version 1.10: Corrected flash size for Atmega1284P.
// Version 1.11: Added support for Atmega1280. Removed MD5SUM stuff to make room.
// Version 1.12: Added signatures for ATtiny2313A, ATtiny4313, ATtiny13
// Version 1.13: Added signature for Atmega8A
// Version 1.14: Added bootloader for Atmega8
// Version 1.15: Removed extraneous 0xFF from some files
// Version 1.16: Added signature for Atmega328
// Version 1.17: Allowed for running on the Leonardo, Micro, etc.
/*
Copyright 2012 Nick Gammon.
PERMISSION TO DISTRIBUTE
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
LIMITATION OF LIABILITY
The software is provided "as is", without warranty of any kind, express or implied,
including but not limited to the warranties of merchantability, fitness for a particular
purpose and noninfringement. In no event shall the authors or copyright holders be liable
for any claim, damages or other liability, whether in an action of contract,
tort or otherwise, arising from, out of or in connection with the software
or the use or other dealings in the software.
*/
#include <SPI.h>
#include <avr/pgmspace.h>
const unsigned long BAUD_RATE = 115200;
const byte CLOCKOUT = 9;
const byte RESET = 10; // --> goes to reset on the target board
#if ARDUINO < 100
const byte SCK = 13; // SPI clock
#endif
// number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))
// programming commands to send via SPI to the chip
enum {
progamEnable = 0xAC,
// writes are preceded by progamEnable
chipErase = 0x80,
writeLockByte = 0xE0,
writeLowFuseByte = 0xA0,
writeHighFuseByte = 0xA8,
writeExtendedFuseByte = 0xA4,
pollReady = 0xF0,
programAcknowledge = 0x53,
readSignatureByte = 0x30,
readCalibrationByte = 0x38,
readLowFuseByte = 0x50, readLowFuseByteArg2 = 0x00,
readExtendedFuseByte = 0x50, readExtendedFuseByteArg2 = 0x08,
readHighFuseByte = 0x58, readHighFuseByteArg2 = 0x08,
readLockByte = 0x58, readLockByteArg2 = 0x00,
readProgramMemory = 0x20,
writeProgramMemory = 0x4C,
loadExtendedAddressByte = 0x4D,
loadProgramMemory = 0x40,
}; // end of enum
// structure to hold signature and other relevant data about each chip
typedef struct {
byte sig [3];
char * desc;
unsigned long flashSize;
unsigned int baseBootSize;
const byte * bootloader;
unsigned long loaderStart; // bytes
unsigned int loaderLength; // bytes
unsigned long pageSize; // bytes
byte lowFuse, highFuse, extFuse, lockByte;
} signatureType;
const unsigned long kb = 1024;
// hex bootloader data
#include "bootloader_atmega168.h"
// see Atmega328 datasheet page 298
signatureType signatures [] =
{
// signature description flash size bootloader size
// Attiny84 family
{ { 0x1E, 0x91, 0x0B }, "ATtiny24", 2 * kb, 0 },
{ { 0x1E, 0x92, 0x07 }, "ATtiny44", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0C }, "ATtiny84", 8 * kb, 0 },
// Attiny85 family
{ { 0x1E, 0x91, 0x08 }, "ATtiny25", 2 * kb, 0 },
{ { 0x1E, 0x92, 0x06 }, "ATtiny45", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0B }, "ATtiny85", 8 * kb, 0 },
// Atmega328 family
{ { 0x1E, 0x92, 0x0A }, "ATmega48PA", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0F }, "ATmega88PA", 8 * kb, 256 },
{ { 0x1E, 0x94, 0x0B }, "ATmega168PA", 16 * kb, 256,
atmega168_optiboot, // loader image
//0x3E00, // start address
0x0,
sizeof atmega168_optiboot,
128, // page size (for committing)
0xC6, // fuse low byte: external full-swing crystal
0xde, // fuse high byte: SPI enable, brown-out detection at 2.7V
0xf8, // fuse extended byte: boot into bootloader, 512 byte bootloader
0xcf }, // lock bits: SPM is not allowed to write to the Boot Loader section.
}; // end of signatures
// if signature found in above table, this is its index
int foundSig = -1;
byte lastAddressMSB = 0;
// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
// processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
{
SPI.transfer (b1);
SPI.transfer (b2);
SPI.transfer (b3);
return SPI.transfer (b4);
} // end of program
// read a byte from flash memory
byte readFlash (unsigned long addr)
{
byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted
addr >>= 1; // turn into word address
// set the extended (most significant) address byte if necessary
byte MSB = (addr >> 16) & 0xFF;
if (MSB != lastAddressMSB)
{
program (loadExtendedAddressByte, 0, MSB);
lastAddressMSB = MSB;
} // end if different MSB
return program (readProgramMemory | high, highByte (addr), lowByte (addr));
} // end of readFlash
// write a byte to the flash memory buffer (ready for committing)
byte writeFlash (unsigned long addr, const byte data)
{
byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted
addr >>= 1; // turn into word address
program (loadProgramMemory | high, 0, lowByte (addr), data);
} // end of writeFlash
// show a byte in hex with leading zero and optional newline
void showHex (const byte b, const boolean newline = false, const boolean show0x = true)
{
if (show0x)
Serial.print (F("0x"));
// try to avoid using sprintf
char buf [4] = { ((b >> 4) & 0x0F) | '0', (b & 0x0F) | '0', ' ' , 0 };
if (buf [0] > '9')
buf [0] += 7;
if (buf [1] > '9')
buf [1] += 7;
Serial.print (buf);
if (newline)
Serial.println ();
} // end of showHex
// convert a boolean to Yes/No
void showYesNo (const boolean b, const boolean newline = false)
{
if (b)
Serial.print (F("Yes"));
else
Serial.print (F("No"));
if (newline)
Serial.println ();
} // end of showYesNo
// poll the target device until it is ready to be programmed
void pollUntilReady ()
{
while ((program (pollReady) & 1) == 1)
{} // wait till ready
} // end of pollUntilReady
// commit page
void commitPage (unsigned long addr)
{
//Serial.print (F("Committing page starting at 0x"));
//Serial.println (addr, HEX);
addr >>= 1; // turn into word address
// set the extended (most significant) address byte if necessary
byte MSB = (addr >> 16) & 0xFF;
if (MSB != lastAddressMSB)
{
program (loadExtendedAddressByte, 0, MSB);
lastAddressMSB = MSB;
} // end if different MSB
program (writeProgramMemory, highByte (addr), lowByte (addr));
pollUntilReady ();
} // end of commitPage
// write specified value to specified fuse/lock byte
void writeFuse (const byte newValue, const byte instruction)
{
if (newValue == 0)
return; // ignore
program (progamEnable, instruction, 0, newValue);
pollUntilReady ();
} // end of writeFuse
void getFuseBytes ()
{
Serial.print (F("LFuse = "));
showHex (program (readLowFuseByte, readLowFuseByteArg2), true);
Serial.print (F("HFuse = "));
showHex (program (readHighFuseByte, readHighFuseByteArg2), true);
Serial.print (F("EFuse = "));
showHex (program (readExtendedFuseByte, readExtendedFuseByteArg2), true);
Serial.print (F("Lock byte = "));
showHex (program (readLockByte, readLockByteArg2), true);
Serial.print ("Clock calibration = ");
showHex (program (readCalibrationByte), true);
} // end of getFuseBytes
// burn the bootloader to the target device
void writeBootloader ()
{
if (signatures [foundSig].bootloader == 0)
{
Serial.println (F("No bootloader support for this device."));
return;
} // end if
int i;
byte lFuse = program (readLowFuseByte, readLowFuseByteArg2);
byte newlFuse = signatures [foundSig].lowFuse;
byte newhFuse = signatures [foundSig].highFuse;
byte newextFuse = signatures [foundSig].extFuse;
byte newlockByte = signatures [foundSig].lockByte;
unsigned long addr = signatures [foundSig].loaderStart;
unsigned int len = signatures [foundSig].loaderLength;
unsigned long pagesize = signatures [foundSig].pageSize;
unsigned long pagemask = ~(pagesize - 1);
const byte * bootloader = signatures [foundSig].bootloader;
Serial.print (F("Bootloader address = 0x"));
Serial.println (addr, HEX);
Serial.print (F("Bootloader length = "));
Serial.print (len);
Serial.println (F(" bytes."));
byte subcommand = 'U';
// Atmega328P or Atmega328
if (signatures [foundSig].sig [0] == 0x1E &&
signatures [foundSig].sig [1] == 0x95 &&
(signatures [foundSig].sig [2] == 0x0F || signatures [foundSig].sig [2] == 0x14)
)
{
Serial.println (F("Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ..."));
do
{
subcommand = toupper (Serial.read ());
} while (subcommand != 'L' && subcommand != 'U');
if (subcommand == 'L') // use internal 8 MHz clock
{
Serial.println (F("Using Lilypad 8 MHz loader."));
bootloader = atmega168_optiboot;
newlFuse = 0xE2; // internal 8 MHz oscillator
newhFuse = 0xDA; // 2048 byte bootloader, SPI enabled
addr = 0x7800;
len = sizeof atmega168_optiboot;
} // end of using the 8 MHz clock
else
Serial.println (F("Using Uno Optiboot 16 MHz loader."));
} // end of being Atmega328P
unsigned long oldPage = addr & pagemask;
Serial.println (F("Type 'V' to verify, or 'G' to program the chip with the bootloader ..."));
char command;
do
{
command = toupper (Serial.read ());
} while (command != 'G' && command != 'V');
if (command == 'G')
{
Serial.println (F("Erasing chip ..."));
program (progamEnable, chipErase); // erase it
pollUntilReady ();
Serial.println (F("Writing bootloader ..."));
for (i = 0; i < len; i += 2)
{
unsigned long thisPage = (addr + i) & pagemask;
// page changed? commit old one
if (thisPage != oldPage)
{
commitPage (oldPage);
oldPage = thisPage;
}
unsigned char c1 = pgm_read_byte(bootloader + i);
unsigned char c2 = pgm_read_byte(bootloader + i+1);
writeFlash (addr + i, c1);
writeFlash (addr + i + 1, c2);
} // end while doing each word
Serial.println();
// commit final page
commitPage (oldPage);
Serial.println ("Written.");
} // end if programming
Serial.println (F("Verifying ..."));
// count errors
unsigned int errors = 0;
// check each byte
for (i = 0; i < signatures [foundSig].loaderLength; i++)
{
//if(i==0)Serial.print(" ");
byte found = readFlash (addr + i);
byte expected = pgm_read_byte(bootloader + i);
if (found != expected)
{
if (errors <= 100)
{
Serial.print (F("Verification error at address "));
Serial.print (addr + i, HEX);
Serial.print (F(". Got: "));
showHex (found);
Serial.print (F(" Expected: "));
showHex (expected, true);
} // end of haven't shown 100 errors yet
errors++;
} // end if error
} // end of for
Serial.println("\r\n");
if (errors == 0)
Serial.println (F("No errors found."));
else
{
Serial.print (errors, DEC);
Serial.println (F(" verification error(s)."));
if (errors > 100)
Serial.println (F("First 100 shown."));
return; // don't change fuses if errors
} // end if
if (command == 'G')
{
Serial.println (F("Writing fuses ..."));
writeFuse (newlFuse, writeLowFuseByte);
writeFuse (newhFuse, writeHighFuseByte);
writeFuse (newextFuse, writeExtendedFuseByte);
writeFuse (newlockByte, writeLockByte);
// confirm them
getFuseBytes ();
} // end if programming
Serial.println (F("Done."));
} // end of writeBootloader
void startProgramming ()
{
byte confirm;
pinMode (RESET, OUTPUT);
pinMode (SCK, OUTPUT);
// we are in sync if we get back programAcknowledge on the third byte
do
{
delay (100);
// ensure SCK low
digitalWrite (SCK, LOW);
// then pulse reset, see page 309 of datasheet
digitalWrite (RESET, HIGH);
delay (1); // pulse for at least 2 clock cycles
digitalWrite (RESET, LOW);
delay (25); // wait at least 20 mS
SPI.transfer (progamEnable);
SPI.transfer (programAcknowledge);
confirm = SPI.transfer (0);
SPI.transfer (0);
} while (confirm != programAcknowledge);
Serial.println (F("Entered programming mode OK."));
} // end of startProgramming
void getSignature ()
{
foundSig = -1;
lastAddressMSB = 0;
byte sig [3];
Serial.print (F("Signature = "));
for (byte i = 0; i < 3; i++)
{
sig [i] = program (readSignatureByte, 0, i);
showHex (sig [i]);
} // end for each signature byte
Serial.println ();
for (int j = 0; j < NUMITEMS (signatures); j++)
{
if (memcmp (sig, signatures [j].sig, sizeof sig) == 0)
{
foundSig = j;
Serial.print (F("Processor = "));
Serial.println (signatures [j].desc);
Serial.print (F("Flash memory size = "));
Serial.print (signatures [j].flashSize, DEC);
Serial.println (F(" bytes."));
return;
} // end of signature found
} // end of for each signature
Serial.println (F("Unrecogized signature."));
} // end of getSignature
void setup ()
{
Serial.begin (BAUD_RATE);
while (!Serial) ; // for Leonardo, Micro etc.
Serial.println ();
Serial.println (F("Atmega chip programmer."));
Serial.println (F("Written by Nick Gammon."));
digitalWrite (RESET, HIGH); // ensure SS stays high for now
SPI.begin ();
// slow down SPI for benefit of slower processors like the Attiny
SPI.setClockDivider (SPI_CLOCK_DIV64);
pinMode (CLOCKOUT, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0); // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10); // CTC, no prescaling
OCR1A = 0; // output every cycle
} // end of setup
void loop ()
{
startProgramming ();
getSignature ();
getFuseBytes ();
// if we found a signature try to write a bootloader
if (foundSig != -1)
writeBootloader ();
// release reset
digitalWrite (RESET, HIGH);
Serial.println (F("Type 'C' when ready to continue with another chip ..."));
while (toupper (Serial.read ()) != 'C')
{}
} // end of loop

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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.

View File

@ -0,0 +1,35 @@
// Calibration code for Grove - Multichannel Gas Sensor
// Note that it need 10 minutes pre-heat before calibration
// This code is writen by Loovee@2016-5-18
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
#define PRE_HEAT_TIME 0 // pre-heat time, 10-30 minutes is recommended
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR); //
Serial.println("power on, and pre-heat");
for(int i=60*PRE_HEAT_TIME; i>=0; i--)
{
Serial.print(i/60);
Serial.print(":");
Serial.println(i%60);
delay(1000);
}
Serial.println("Begin to calibrate...");
gas.doCalibrate();
Serial.println("Calibration ok");
gas.display_eeprom();
}
void loop()
{
}

View File

@ -0,0 +1,36 @@
// factory setting
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
Serial.println("Please input something to continue");
while(!Serial.available());
gas.begin(SENSOR_ADDR); //
Serial.println("FACTORY SETTING OK");
float R0_NH3, R0_CO, R0_NO2;
R0_NH3 = gas.getR0(0);
R0_CO = gas.getR0(1);
R0_NO2 = gas.getR0(2);
Serial.print("R0_NH3 = ");
Serial.println(R0_NH3);
Serial.print("R0_CO = ");
Serial.println(R0_CO);
Serial.print("R0_NO2 = ");
Serial.println(R0_NO2);
}
void loop()
{
}

View File

@ -0,0 +1,272 @@
/*firmware of multichannel gas sensor v2.0*3
write by loovee
2016-11-6
Factory adc value of 3 channels:
NH3 = 860
CO = 950
NO2 = 155
Default address is 0x04
*/
#include <Wire.h>
#include <EEPROM.h>
#define DEFAULT_I2C_ADDR 0x04
#define DBG 1
// EEPROM ADDRESS
#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set
#define ADDR_FACTORY_ADC_NH3 2
#define ADDR_FACTORY_ADC_CO 4
#define ADDR_FACTORY_ADC_NO2 6
#define ADDR_USER_ADC_HN3 8
#define ADDR_USER_ADC_CO 10
#define ADDR_USER_ADC_NO2 12
#define ADDR_IF_CALI 14 // IF USER HAD CALI
#define ADDR_I2C_ADDRESS 20
// I2C COMMAND
#define CMD_ADC_RES0 1 // NH3
#define CMD_ADC_RES1 2 // CO
#define CMD_ADC_RES2 3 // NO2
#define CMD_ADC_RESALL 4 // ALL CHANNEL
#define CMD_CHANGE_I2C 5 // CHANGE I2C
#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT
#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE
#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE
#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE
#define CMD_CONTROL_LED 10
#define CMD_CONTROL_PWR 11
// EEPROM READ AND WRITE - UNSIGNED INT
void eeprom_write(int addr, unsigned int value)
{
EEPROM.write(addr, value>>8);
EEPROM.write(addr+1, value&0xff);
}
unsigned int eeprom_read(int addr)
{
unsigned int r = EEPROM.read(addr);
r <<= 8;
r+= EEPROM.read(addr+1);
return r;
}
const int pin_pwr = 8;
const int pin_led = 9;
const int pin_NH3 = A0; // RES0
const int pin_CO = A1; // RES1
const int pin_NO2 = A2; // RES2
unsigned char i2c_address = 0;
#define LED_ON() digitalWrite(pin_led, LOW)
#define LED_OFF() digitalWrite(pin_led, HIGH)
void factory_init()
{
#if DBG
Serial.print("FACTORY: ");
#endif
if(1126 != eeprom_read(ADDR_IS_SET)) // IF FACTORY SET
{
#if DBG
Serial.println("YES");
#endif
eeprom_write(ADDR_IS_SET, 1126);
eeprom_write(ADDR_FACTORY_ADC_NH3, 860);
eeprom_write(ADDR_FACTORY_ADC_CO, 950);
eeprom_write(ADDR_FACTORY_ADC_NO2, 155);
eeprom_write(ADDR_USER_ADC_HN3, 860);
eeprom_write(ADDR_USER_ADC_CO, 950);
eeprom_write(ADDR_USER_ADC_NO2, 155);
eeprom_write(ADDR_IF_CALI, 0);
eeprom_write(ADDR_I2C_ADDRESS, DEFAULT_I2C_ADDR);
}
#if DBG
else Serial.println("NO");
#endif
}
int getAnalog(int pin)
{
long sum = 0;
for(int i=0; i<64; i++)
{
sum += analogRead(pin);
}
return sum>>6;
}
unsigned int ADC_RES0 = 0;
unsigned int ADC_RES1 = 0;
unsigned int ADC_RES2 = 0;
unsigned char raw_adc[6];
void updateValue()
{
static unsigned long timer_s = millis();
if(millis()-timer_s < 1000)return;
timer_s = millis();
ADC_RES0 = getAnalog(pin_NH3);
ADC_RES1 = getAnalog(pin_CO);
ADC_RES2 = getAnalog(pin_NO2);
raw_adc[0] = ADC_RES0>>8;
raw_adc[1] = ADC_RES0;
raw_adc[2] = ADC_RES1>>8;
raw_adc[3] = ADC_RES1;
raw_adc[4] = ADC_RES2>>8;
raw_adc[5] = ADC_RES2;
}
void setup()
{
#if DBG
Serial.begin(115200);
#endif
pinMode(pin_pwr, OUTPUT);
digitalWrite(pin_pwr, HIGH);
pinMode(pin_led, OUTPUT);
factory_init();
i2c_address = eeprom_read(ADDR_I2C_ADDRESS);
#if DBG
Serial.print("i2d address = 0x");
Serial.println(i2c_address, HEX);
#endif
for(int i=0; i<5; i++)
{
digitalWrite(pin_led, LOW);
delay(100);
digitalWrite(pin_led, HIGH);
delay(100);
}
Wire.begin(i2c_address); // join i2c bus with address
Wire.onReceive(receiveCallback); // register receive callback
Wire.onRequest(requestCallback); // register request callback
}
void loop()
{
updateValue();
}
unsigned char recvCmd = 0;
unsigned char recvDta = 0;
unsigned char recvDtaStr[10];
void receiveCallback(int dtaCount)
{
if(dtaCount == 1)
{
recvCmd = Wire.read();
}
else if(dtaCount == 2) // set i2c address
{
recvCmd = Wire.read();
recvDta = Wire.read();
if(CMD_CHANGE_I2C == recvCmd)
{
i2c_address = recvDta;
eeprom_write(ADDR_I2C_ADDRESS, i2c_address);
Wire.begin(i2c_address);
}
else if(CMD_CONTROL_LED == recvCmd)
{
if(0 == recvDta)LED_OFF();
else if(1 == recvDta)LED_ON();
}
else if(CMD_CONTROL_PWR == recvCmd)
{
if(0 == recvDta)digitalWrite(pin_pwr, LOW);
else if(1 == recvDta)digitalWrite(pin_pwr, HIGH);
}
}
else if(dtaCount == 7) // set ADC value
{
recvCmd = Wire.read();
unsigned int dta[3];
for(int i=0; i<3; i++)
{
dta[i] = Wire.read();
dta[i] <<= 8;
dta[i] += Wire.read();
}
if(recvCmd == CMD_SET_R0_ADC)
{
eeprom_write(ADDR_USER_ADC_HN3, dta[0]);
eeprom_write(ADDR_USER_ADC_CO, dta[1]);
eeprom_write(ADDR_USER_ADC_NO2, dta[2]);
}
}
}
unsigned char rcDta[10];
void requestCallback()
{
switch(recvCmd)
{
case CMD_ADC_RES0: // NH3
Wire.write(&raw_adc[0], 2); // HIGH FIRST
break;
case CMD_ADC_RES1: // CO
Wire.write(&raw_adc[2], 2); // HIGH FIRST
break;
case CMD_ADC_RES2: // NO2
Wire.write(&raw_adc[4], 2); // HIGH FIRST
break;
case CMD_ADC_RESALL:
Wire.write(raw_adc, 6);
break;
case CMD_READ_EEPROM:
rcDta[0] = EEPROM.read(recvDta);
rcDta[1] = EEPROM.read(recvDta+1);
Wire.write(rcDta, 2);
break;
case CMD_GET_R0_ADC:
rcDta[0] = EEPROM.read(ADDR_USER_ADC_HN3);
rcDta[1] = EEPROM.read(ADDR_USER_ADC_HN3+1);
rcDta[2] = EEPROM.read(ADDR_USER_ADC_CO);
rcDta[3] = EEPROM.read(ADDR_USER_ADC_CO+1);
rcDta[4] = EEPROM.read(ADDR_USER_ADC_NO2);
rcDta[5] = EEPROM.read(ADDR_USER_ADC_NO2+1);
Wire.write(rcDta, 6);
break;
case CMD_GET_R0_ADC_FACTORY:
rcDta[0] = EEPROM.read(ADDR_FACTORY_ADC_NH3);
rcDta[1] = EEPROM.read(ADDR_FACTORY_ADC_NH3+1);
rcDta[2] = EEPROM.read(ADDR_FACTORY_ADC_CO);
rcDta[3] = EEPROM.read(ADDR_FACTORY_ADC_CO+1);
rcDta[4] = EEPROM.read(ADDR_FACTORY_ADC_NO2);
rcDta[5] = EEPROM.read(ADDR_FACTORY_ADC_NO2+1);
Wire.write(rcDta, 6);
break;
default:;
}
}
// END FILE

View File

@ -0,0 +1,14 @@
{
"name": "Mutichannel_Gas_Sensor",
"keywords": "Gas Sensor",
"description": "Grove - Multichannel Gas Sensor",
"homepage": "http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/",
"repository":
{
"type": "git",
"url": "https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git"
},
"version": "0.0.1",
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=Grove - Multichannel Gas Sensor
version=0.0.1
author=WEMOS.CC <support@wemos.cc>
maintainer=WEMOS.CC
sentence=Library for the <a href="http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/"> Grove - Multichannel Gas Sensor</a>.
paragraph=Library for the Grove - Multichannel Gas Sensor.
category=Device Control
url=https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git
architectures=*

View File

@ -0,0 +1,729 @@
/*
MutichannelGasSensor.cpp
2015 Copyright (c) Seeed Technology Inc. All right reserved.
Author: Jacky Zhang
2015-3-17
http://www.seeed.cc/
modi by Jack, 2015-8
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <math.h>
#include <Wire.h>
#include <Arduino.h>
#include "MutichannelGasSensor.h"
/*********************************************************************************************************
** Function name: begin
** Descriptions: initialize I2C
*********************************************************************************************************/
void MutichannelGasSensor::begin(int address)
{
__version = 1; // version 1/2
r0_inited = false;
Wire.begin();
i2cAddress = address;
__send_error = false;
__version = getVersion();
}
bool MutichannelGasSensor::isError()
{
return __send_error;
}
unsigned char MutichannelGasSensor::getVersion()
{
if(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET) == 1126) // get version
{
__version = 2;
return __version;
}
if (!__send_error) {
__version = 1;
}
else {
__version = -1;
}
return __version;
}
void MutichannelGasSensor::begin()
{
begin(DEFAULT_I2C_ADDR);
}
/*********************************************************************************************************
** Function name: sendI2C
** Descriptions: send one byte to I2C Wire
*********************************************************************************************************/
void MutichannelGasSensor::sendI2C(unsigned char dta)
{
__send_error = false;
Wire.beginTransmission(i2cAddress); // transmit to device #4
Wire.write(dta); // sends one byte
if (Wire.endTransmission()) { // stop transmitting
__send_error = true;
}
}
unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg)
{
int trys = 0;
START:
__send_error = false;
Wire.beginTransmission(i2cAddress);
Wire.write(addr_reg);
if (Wire.endTransmission()) { // stop transmitting
trys++;
__send_error = true;
if (trys > 3) {
return 0;
}
}
Wire.requestFrom(i2cAddress, (uint8_t)2);
unsigned int dta = 0;
unsigned char raw[10];
int cnt = 0;
while(Wire.available())
{
raw[cnt++] = Wire.read();
}
if(cnt == 0)goto START;
dta = raw[0];
dta <<= 8;
dta += raw[1];
switch(addr_reg)
{
case CH_VALUE_NH3:
if(dta > 0)
{
adcValueR0_NH3_Buf = dta;
}
else
{
dta = adcValueR0_NH3_Buf;
}
break;
case CH_VALUE_CO:
if(dta > 0)
{
adcValueR0_CO_Buf = dta;
}
else
{
dta = adcValueR0_CO_Buf;
}
break;
case CH_VALUE_NO2:
if(dta > 0)
{
adcValueR0_NO2_Buf = dta;
}
else
{
dta = adcValueR0_NO2_Buf;
}
break;
default:;
}
return dta;
}
unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg, unsigned char __dta)
{
int trys = 0;
START:
__send_error = false;
Wire.beginTransmission(i2cAddress);
Wire.write(addr_reg);
Wire.write(__dta);
if (Wire.endTransmission()) { // stop transmitting
trys++;
__send_error = true;
if (trys > 3) {
return 0;
}
}
Wire.requestFrom(i2cAddress, (uint8_t)2);
unsigned int dta = 0;
unsigned char raw[10];
int cnt = 0;
while(Wire.available())
{
raw[cnt++] = Wire.read();
}
if(cnt == 0)goto START;
dta = raw[0];
dta <<= 8;
dta += raw[1];
return dta;
}
void MutichannelGasSensor::write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len)
{
__send_error = false;
Wire.beginTransmission(addr);
for(int i=0; i<dta_len; i++)
{
Wire.write(dta[i]);
}
if (Wire.endTransmission()) {
__send_error = true;
}
}
/*********************************************************************************************************
** Function name: readData
** Descriptions: read 4 bytes from I2C slave
*********************************************************************************************************/
int16_t MutichannelGasSensor::readData(uint8_t cmd)
{
uint16_t timeout = 0;
uint8_t buffer[4];
uint8_t checksum = 0;
int16_t rtnData = 0;
//send command
sendI2C(cmd);
//wait for a while
delay(2);
//get response
Wire.requestFrom(i2cAddress, (uint8_t)4); // request 4 bytes from slave device
while(Wire.available() == 0)
{
if(timeout++ > 100)
return -2;//time out
delay(2);
}
if(Wire.available() != 4)
return -3;//rtnData length wrong
buffer[0] = Wire.read();
buffer[1] = Wire.read();
buffer[2] = Wire.read();
buffer[3] = Wire.read();
checksum = (uint8_t)(buffer[0] + buffer[1] + buffer[2]);
if(checksum != buffer[3])
return -4;//checksum wrong
rtnData = ((buffer[1] << 8) + buffer[2]);
return rtnData;//successful
}
/*********************************************************************************************************
** Function name: readR0
** Descriptions: read R0 stored in slave MCU
*********************************************************************************************************/
int16_t MutichannelGasSensor::readR0(void)
{
int16_t rtnData = 0;
rtnData = readData(0x11);
if(rtnData > 0)
res0[0] = rtnData;
else
return rtnData; //unsuccessful
rtnData = readData(0x12);
if(rtnData > 0)
res0[1] = rtnData;
else
return rtnData; //unsuccessful
rtnData = readData(0x13);
if(rtnData > 0)
res0[2] = rtnData;
else
return rtnData; //unsuccessful
return 1;//successful
}
/*********************************************************************************************************
** Function name: readR
** Descriptions: read resistance value of each channel from slave MCU
*********************************************************************************************************/
int16_t MutichannelGasSensor::readR(void)
{
int16_t rtnData = 0;
rtnData = readData(0x01);
if(rtnData >= 0)
res[0] = rtnData;
else
return rtnData;//unsuccessful
rtnData = readData(0x02);
if(rtnData >= 0)
res[1] = rtnData;
else
return rtnData;//unsuccessful
rtnData = readData(0x03);
if(rtnData >= 0)
res[2] = rtnData;
else
return rtnData;//unsuccessful
return 0;//successful
}
/*********************************************************************************************************
** Function name: readR
** Descriptions: calculate gas concentration of each channel from slave MCU
** Parameters:
gas - gas type
** Returns:
float value - concentration of the gas
*********************************************************************************************************/
float MutichannelGasSensor::calcGas(int gas)
{
float ratio0, ratio1, ratio2;
if(1 == __version)
{
if(!r0_inited)
{
if(readR0() >= 0) r0_inited = true;
else return -1.0f;
}
if(readR() < 0)
return -2.0f;
ratio0 = (float)res[0] / res0[0];
ratio1 = (float)res[1] / res0[1];
ratio2 = (float)res[2] / res0[2];
}
else if(2 == __version)
{
// how to calc ratio/123
ledOn();
int A0_0 = get_addr_dta(6, ADDR_USER_ADC_HN3);
int A0_1 = get_addr_dta(6, ADDR_USER_ADC_CO);
int A0_2 = get_addr_dta(6, ADDR_USER_ADC_NO2);
int An_0 = get_addr_dta(CH_VALUE_NH3);
int An_1 = get_addr_dta(CH_VALUE_CO);
int An_2 = get_addr_dta(CH_VALUE_NO2);
ratio0 = (float)An_0/(float)A0_0*(1023.0-A0_0)/(1023.0-An_0);
ratio1 = (float)An_1/(float)A0_1*(1023.0-A0_1)/(1023.0-An_1);
ratio2 = (float)An_2/(float)A0_2*(1023.0-A0_2)/(1023.0-An_2);
}
float c = 0;
switch(gas)
{
case CO:
{
c = pow(ratio1, -1.179)*4.385; //mod by jack
break;
}
case NO2:
{
c = pow(ratio2, 1.007)/6.855; //mod by jack
break;
}
case NH3:
{
c = pow(ratio0, -1.67)/1.47; //modi by jack
break;
}
case C3H8: //add by jack
{
c = pow(ratio0, -2.518)*570.164;
break;
}
case C4H10: //add by jack
{
c = pow(ratio0, -2.138)*398.107;
break;
}
case GAS_CH4: //add by jack
{
c = pow(ratio1, -4.363)*630.957;
break;
}
case H2: //add by jack
{
c = pow(ratio1, -1.8)*0.73;
break;
}
case C2H5OH: //add by jack
{
c = pow(ratio1, -1.552)*1.622;
break;
}
default:
break;
}
if(2==__version)ledOff();
return isnan(c)?-3:c;
}
/*********************************************************************************************************
** Function name: changeI2cAddr
** Descriptions: change I2C address of the slave MCU, and this address will be stored in EEPROM of slave MCU
*********************************************************************************************************/
void MutichannelGasSensor::changeI2cAddr(uint8_t newAddr)
{
Wire.beginTransmission(i2cAddress); // transmit to device
Wire.write(0x23); // sends one byte
Wire.write(newAddr); // sends one byte
if (Wire.endTransmission()){ // stop transmitting
__send_error = true;
} else {
i2cAddress = newAddr;
}
}
/*********************************************************************************************************
** Function name: doCalibrate
** Descriptions: tell slave to do a calibration, it will take about 8s
after the calibration, must reread the R0 values
*********************************************************************************************************/
void MutichannelGasSensor::doCalibrate(void)
{
if(1 == __version)
{
START:
sendI2C(0x22);
if(readR0() > 0)
{
for(int i=0; i<3; i++)
{
Serial.print(res0[i]);
Serial.print('\t');
}
}
else
{
delay(5000);
Serial.println("continue...");
for(int i=0; i<3; i++)
{
Serial.print(res0[i]);
Serial.print('\t');
}
Serial.println();
goto START;
}
}
else if(2 == __version)
{
unsigned int i, a0, a1, a2;
while(1)
{
a0 = get_addr_dta(CH_VALUE_NH3);
a1 = get_addr_dta(CH_VALUE_CO);
a2 = get_addr_dta(CH_VALUE_NO2);
Serial.print(a0);
Serial.print('\t');
Serial.print(a1);
Serial.print('\t');
Serial.print(a2);
Serial.println('\t');
ledOn();
int cnt = 0;
for(i=0; i<20; i++)
{
if((a0 - get_addr_dta(CH_VALUE_NH3)) > 2 || (get_addr_dta(CH_VALUE_NH3) - a0) > 2)cnt++;
if((a1 - get_addr_dta(CH_VALUE_CO)) > 2 || (get_addr_dta(CH_VALUE_CO) - a1) > 2)cnt++;
if((a2 - get_addr_dta(CH_VALUE_NO2)) > 2 || (get_addr_dta(CH_VALUE_NO2) - a2) > 2)cnt++;
if(cnt>5)
{
break;
}
delay(1000);
}
ledOff();
if(cnt <= 5)break;
delay(200);
}
Serial.print("write user adc value: ");
Serial.print(a0);Serial.print('\t');
Serial.print(a1);Serial.print('\t');
Serial.print(a2);Serial.println('\t');
unsigned char tmp[7];
tmp[0] = 7;
tmp[1] = a0>>8;
tmp[2] = a0&0xff;
tmp[3] = a1>>8;
tmp[4] = a1&0xff;
tmp[5] = a2>>8;
tmp[6] = a2&0xff;
write_i2c(i2cAddress, tmp, 7);
}
}
/*********************************************************************************************************
** Function name: powerOn
** Descriptions: power on sensor heater
*********************************************************************************************************/
void MutichannelGasSensor::powerOn(void)
{
if(__version == 1)
sendI2C(0x21);
else if(__version == 2)
{
dta_test[0] = 11;
dta_test[1] = 1;
write_i2c(i2cAddress, dta_test, 2);
}
}
/*********************************************************************************************************
** Function name: powerOff
** Descriptions: power off sensor heater
*********************************************************************************************************/
void MutichannelGasSensor::powerOff(void)
{
if(__version == 1)
sendI2C(0x20);
else if(__version == 2)
{
dta_test[0] = 11;
dta_test[1] = 0;
write_i2c(i2cAddress, dta_test, 2);
}
}
void MutichannelGasSensor::display_eeprom()
{
if(__version == 1)
{
Serial.println("ERROR: display_eeprom() is NOT support by V1 firmware.");
return ;
}
Serial.print("ADDR_IS_SET = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET));
Serial.print("ADDR_FACTORY_ADC_NH3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3));
Serial.print("ADDR_FACTORY_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO));
Serial.print("ADDR_FACTORY_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2));
Serial.print("ADDR_USER_ADC_HN3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3));
Serial.print("ADDR_USER_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO));
Serial.print("ADDR_USER_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2));
Serial.print("ADDR_I2C_ADDRESS = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_I2C_ADDRESS));
}
float MutichannelGasSensor::getR0(unsigned char ch) // 0:CH3, 1:CO, 2:NO2
{
if(__version == 1)
{
Serial.println("ERROR: getR0() is NOT support by V1 firmware.");
return -1;
}
int a = 0;
switch(ch)
{
case 0: // CH3
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3);
Serial.print("a_ch3 = ");
Serial.println(a);
break;
case 1: // CO
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO);
Serial.print("a_co = ");
Serial.println(a);
break;
case 2: // NO2
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2);
Serial.print("a_no2 = ");
Serial.println(a);
break;
default:;
}
float r = 56.0*(float)a/(1023.0-(float)a);
return r;
}
float MutichannelGasSensor::getRs(unsigned char ch) // 0:CH3, 1:CO, 2:NO2
{
if(__version == 1)
{
Serial.println("ERROR: getRs() is NOT support by V1 firmware.");
return -1;
}
int a = 0;
switch(ch)
{
case 0: // NH3
a = get_addr_dta(1);
break;
case 1: // CO
a = get_addr_dta(2);
break;
case 2: // NO2
a = get_addr_dta(3);
break;
default:;
}
float r = 56.0*(float)a/(1023.0-(float)a);
return r;
}
// 1. change i2c address to 0x04
// 2. change adc value of R0 to default
void MutichannelGasSensor::factory_setting()
{
unsigned char tmp[7];
unsigned char error;
unsigned char address = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
// change i2c to 0x04
Serial.print("I2C address is: 0x");
Serial.println(address, HEX);
Serial.println("Change I2C address to 0x04");
dta_test[0] = CMD_CHANGE_I2C;
dta_test[1] = 0x04;
write_i2c(address, dta_test, 2);
i2cAddress = 0x04;
delay(100);
getVersion();
break;
}
}
unsigned int a0 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3);
unsigned int a1 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO);
unsigned int a2 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2);
tmp[0] = 7;
tmp[1] = a0>>8;
tmp[2] = a0&0xff;
tmp[3] = a1>>8;
tmp[4] = a1&0xff;
tmp[5] = a2>>8;
tmp[6] = a2&0xff;
delay(100);
write_i2c(i2cAddress, tmp, 7);
delay(100);
}
void MutichannelGasSensor::change_i2c_address(unsigned char addr)
{
dta_test[0] = CMD_CHANGE_I2C;
dta_test[1] = addr;
write_i2c(i2cAddress, dta_test, 2);
Serial.print("FUNCTION: CHANGE I2C ADDRESS: 0X");
Serial.print(i2cAddress, HEX);
Serial.print(" > 0x");
Serial.println(addr, HEX);
i2cAddress = addr;
}
void MutichannelGasSensor::ledOn()
{
dta_test[0] = CMD_CONTROL_LED;
dta_test[1] = 1;
write_i2c(i2cAddress, dta_test, 2);
}
void MutichannelGasSensor::ledOff()
{
dta_test[0] = CMD_CONTROL_LED;
dta_test[1] = 0;
write_i2c(i2cAddress, dta_test, 2);
}
MutichannelGasSensor gas;
/*********************************************************************************************************
END FILE
*********************************************************************************************************/

View File

@ -0,0 +1,140 @@
/*
MutichannelGasSensor.h
2015 Copyright (c) Seeed Technology Inc. All right reserved.
Author: Jacky Zhang
2015-3-17
http://www.seeed.cc/
modi by Jack, 2015-8
V2 by Loovee
2016-11-11
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __MUTICHANNELGASSENSOR_H__
#define __MUTICHANNELGASSENSOR_H__
#define DEFAULT_I2C_ADDR 0x04
#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set
#define ADDR_FACTORY_ADC_NH3 2
#define ADDR_FACTORY_ADC_CO 4
#define ADDR_FACTORY_ADC_NO2 6
#define ADDR_USER_ADC_HN3 8
#define ADDR_USER_ADC_CO 10
#define ADDR_USER_ADC_NO2 12
#define ADDR_IF_CALI 14 // IF USER HAD CALI
#define ADDR_I2C_ADDRESS 20
#define CH_VALUE_NH3 1
#define CH_VALUE_CO 2
#define CH_VALUE_NO2 3
#define CMD_ADC_RES0 1 // NH3
#define CMD_ADC_RES1 2 // CO
#define CMD_ADC_RES2 3 // NO2
#define CMD_ADC_RESALL 4 // ALL CHANNEL
#define CMD_CHANGE_I2C 5 // CHANGE I2C
#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT
#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE
#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE
#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE
#define CMD_CONTROL_LED 10
#define CMD_CONTROL_PWR 11
enum{CO, NO2, NH3, C3H8, C4H10, GAS_CH4, H2, C2H5OH};
class MutichannelGasSensor{
private:
int __version;
int __send_error;
unsigned char dta_test[20];
unsigned int readChAdcValue(int ch);
unsigned int adcValueR0_NH3_Buf;
unsigned int adcValueR0_CO_Buf;
unsigned int adcValueR0_NO2_Buf;
public:
uint8_t i2cAddress; //I2C address of this MCU
uint16_t res0[3]; //sensors res0
uint16_t res[3]; //sensors res
bool r0_inited;
inline unsigned int get_addr_dta(unsigned char addr_reg);
inline unsigned int get_addr_dta(unsigned char addr_reg, unsigned char __dta);
inline void write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len);
void sendI2C(unsigned char dta);
int16_t readData(uint8_t cmd);
int16_t readR0(void);
int16_t readR(void);
float calcGas(int gas);
public:
void begin(int address);
void begin();
void changeI2cAddr(uint8_t newAddr);
void powerOn(void);
void powerOff(void);
void doCalibrate(void);
//get gas concentration, unit: ppm
float measure_CO(){return calcGas(CO);}
float measure_NO2(){return calcGas(NO2);}
float measure_NH3(){return calcGas(NH3);}
float measure_C3H8(){return calcGas(C3H8);}
float measure_C4H10(){return calcGas(C4H10);}
float measure_CH4(){return calcGas(GAS_CH4);}
float measure_H2(){return calcGas(H2);}
float measure_C2H5OH(){return calcGas(C2H5OH);}
float getR0(unsigned char ch); // 0:CH3, 1:CO, 2:NO2
float getRs(unsigned char ch); // 0:CH3, 1:CO, 2:NO2
public:
bool isError();
void ledOn();
void ledOff();
void display_eeprom();
void factory_setting();
void change_i2c_address(unsigned char addr);
unsigned char getVersion();
};
extern MutichannelGasSensor gas;
#endif
/*********************************************************************************************************
END FILE
*********************************************************************************************************/

View File

@ -1,46 +0,0 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**

View File

@ -1,26 +0,0 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.

View File

@ -1,7 +0,0 @@
This is an Arduino library for the TSL2561 digital luminosity (light) sensors.
Pick one up at http://www.adafruit.com/products/439
To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder TSL2561. Check that the TSL2561 folder contains TSL2561.cpp and TSL2561.h
Place the TSL2561 library folder your <arduinosketchfolder>/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.

View File

@ -1,301 +0,0 @@
/**************************************************************************/
/*!
@file tsl2561.c
@author K. Townsend (microBuilder.eu / adafruit.com)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL, Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#if defined ( ESP8266 )
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#include <util/delay.h>
#endif
#include <stdlib.h>
#include "TSL2561.h"
TSL2561::TSL2561(uint8_t addr) {
_addr = addr;
_initialized = false;
_integration = TSL2561_INTEGRATIONTIME_13MS;
_gain = TSL2561_GAIN_16X;
// we cant do wire initialization till later, because we havent loaded Wire yet
}
boolean TSL2561::begin(void) {
Wire.begin();
// Initialise I2C
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(TSL2561_REGISTER_ID);
#else
Wire.send(TSL2561_REGISTER_ID);
#endif
Wire.endTransmission();
Wire.requestFrom(_addr, 1);
#if ARDUINO >= 100
int x = Wire.read();
#else
int x = Wire.receive();
#endif
//Serial.print("0x"); Serial.println(x, HEX);
if (x & 0x0A ) {
//Serial.println("Found TSL2561");
} else {
return false;
}
_initialized = true;
// Set default integration time and gain
setTiming(_integration);
setGain(_gain);
// Note: by default, the device is in power down mode on bootup
disable();
return true;
}
void TSL2561::enable(void)
{
if (!_initialized) begin();
// Enable the device by setting the control bit to 0x03
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWERON);
}
void TSL2561::disable(void)
{
if (!_initialized) begin();
// Disable the device by setting the control bit to 0x03
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWEROFF);
}
void TSL2561::setGain(tsl2561Gain_t gain) {
if (!_initialized) begin();
enable();
_gain = gain;
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain);
disable();
}
void TSL2561::setTiming(tsl2561IntegrationTime_t integration)
{
if (!_initialized) begin();
enable();
_integration = integration;
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain);
disable();
}
uint32_t TSL2561::calculateLux(uint16_t ch0, uint16_t ch1)
{
unsigned long chScale;
unsigned long channel1;
unsigned long channel0;
switch (_integration)
{
case TSL2561_INTEGRATIONTIME_13MS:
chScale = TSL2561_LUX_CHSCALE_TINT0;
break;
case TSL2561_INTEGRATIONTIME_101MS:
chScale = TSL2561_LUX_CHSCALE_TINT1;
break;
default: // No scaling ... integration time = 402ms
chScale = (1 << TSL2561_LUX_CHSCALE);
break;
}
// Scale for gain (1x or 16x)
if (!_gain) chScale = chScale << 4;
// scale the channel values
channel0 = (ch0 * chScale) >> TSL2561_LUX_CHSCALE;
channel1 = (ch1 * chScale) >> TSL2561_LUX_CHSCALE;
// find the ratio of the channel values (Channel1/Channel0)
unsigned long ratio1 = 0;
if (channel0 != 0) ratio1 = (channel1 << (TSL2561_LUX_RATIOSCALE+1)) / channel0;
// round the ratio value
unsigned long ratio = (ratio1 + 1) >> 1;
unsigned int b, m;
#ifdef TSL2561_PACKAGE_CS
if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1C))
{b=TSL2561_LUX_B1C; m=TSL2561_LUX_M1C;}
else if (ratio <= TSL2561_LUX_K2C)
{b=TSL2561_LUX_B2C; m=TSL2561_LUX_M2C;}
else if (ratio <= TSL2561_LUX_K3C)
{b=TSL2561_LUX_B3C; m=TSL2561_LUX_M3C;}
else if (ratio <= TSL2561_LUX_K4C)
{b=TSL2561_LUX_B4C; m=TSL2561_LUX_M4C;}
else if (ratio <= TSL2561_LUX_K5C)
{b=TSL2561_LUX_B5C; m=TSL2561_LUX_M5C;}
else if (ratio <= TSL2561_LUX_K6C)
{b=TSL2561_LUX_B6C; m=TSL2561_LUX_M6C;}
else if (ratio <= TSL2561_LUX_K7C)
{b=TSL2561_LUX_B7C; m=TSL2561_LUX_M7C;}
else if (ratio > TSL2561_LUX_K8C)
{b=TSL2561_LUX_B8C; m=TSL2561_LUX_M8C;}
#else
if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1T))
{b=TSL2561_LUX_B1T; m=TSL2561_LUX_M1T;}
else if (ratio <= TSL2561_LUX_K2T)
{b=TSL2561_LUX_B2T; m=TSL2561_LUX_M2T;}
else if (ratio <= TSL2561_LUX_K3T)
{b=TSL2561_LUX_B3T; m=TSL2561_LUX_M3T;}
else if (ratio <= TSL2561_LUX_K4T)
{b=TSL2561_LUX_B4T; m=TSL2561_LUX_M4T;}
else if (ratio <= TSL2561_LUX_K5T)
{b=TSL2561_LUX_B5T; m=TSL2561_LUX_M5T;}
else if (ratio <= TSL2561_LUX_K6T)
{b=TSL2561_LUX_B6T; m=TSL2561_LUX_M6T;}
else if (ratio <= TSL2561_LUX_K7T)
{b=TSL2561_LUX_B7T; m=TSL2561_LUX_M7T;}
else if (ratio > TSL2561_LUX_K8T)
{b=TSL2561_LUX_B8T; m=TSL2561_LUX_M8T;}
#endif
unsigned long temp;
temp = ((channel0 * b) - (channel1 * m));
// do not allow negative lux value
if (temp < 0) temp = 0;
// round lsb (2^(LUX_SCALE-1))
temp += (1 << (TSL2561_LUX_LUXSCALE-1));
// strip off fractional portion
uint32_t lux = temp >> TSL2561_LUX_LUXSCALE;
// Signal I2C had no errors
return lux;
}
uint32_t TSL2561::getFullLuminosity (void)
{
if (!_initialized) begin();
// Enable the device by setting the control bit to 0x03
enable();
// Wait x ms for ADC to complete
switch (_integration)
{
case TSL2561_INTEGRATIONTIME_13MS:
delay(14);
break;
case TSL2561_INTEGRATIONTIME_101MS:
delay(102);
break;
default:
delay(403);
break;
}
uint32_t x;
x = read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN1_LOW);
x <<= 16;
x |= read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN0_LOW);
disable();
return x;
}
uint16_t TSL2561::getLuminosity (uint8_t channel) {
uint32_t x = getFullLuminosity();
if (channel == 0) {
// Reads two byte value from channel 0 (visible + infrared)
return (x & 0xFFFF);
} else if (channel == 1) {
// Reads two byte value from channel 1 (infrared)
return (x >> 16);
} else if (channel == 2) {
// Reads all and subtracts out just the visible!
return ( (x & 0xFFFF) - (x >> 16));
}
// unknown channel!
return 0;
}
uint16_t TSL2561::read16(uint8_t reg)
{
uint16_t x; uint16_t t;
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(_addr, 2);
#if ARDUINO >= 100
t = Wire.read();
x = Wire.read();
#else
t = Wire.receive();
x = Wire.receive();
#endif
x <<= 8;
x |= t;
return x;
}
void TSL2561::write8 (uint8_t reg, uint8_t value)
{
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write(value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}

View File

@ -1,184 +0,0 @@
/**************************************************************************/
/*!
@file tsl2561.h
@author K. Townsend (microBuilder.eu)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef _TSL2561_H_
#define _TSL2561_H_
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <Wire.h>
#define TSL2561_VISIBLE 2 // channel 0 - channel 1
#define TSL2561_INFRARED 1 // channel 1
#define TSL2561_FULLSPECTRUM 0 // channel 0
// 3 i2c address options!
#define TSL2561_ADDR_LOW 0x29
#define TSL2561_ADDR_FLOAT 0x39
#define TSL2561_ADDR_HIGH 0x49
// Lux calculations differ slightly for CS package
//#define TSL2561_PACKAGE_CS
#define TSL2561_PACKAGE_T_FN_CL
#define TSL2561_READBIT (0x01)
#define TSL2561_COMMAND_BIT (0x80) // Must be 1
#define TSL2561_CLEAR_BIT (0x40) // Clears any pending interrupt (write 1 to clear)
#define TSL2561_WORD_BIT (0x20) // 1 = read/write word (rather than byte)
#define TSL2561_BLOCK_BIT (0x10) // 1 = using block read/write
#define TSL2561_CONTROL_POWERON (0x03)
#define TSL2561_CONTROL_POWEROFF (0x00)
#define TSL2561_LUX_LUXSCALE (14) // Scale by 2^14
#define TSL2561_LUX_RATIOSCALE (9) // Scale ratio by 2^9
#define TSL2561_LUX_CHSCALE (10) // Scale channel values by 2^10
#define TSL2561_LUX_CHSCALE_TINT0 (0x7517) // 322/11 * 2^TSL2561_LUX_CHSCALE
#define TSL2561_LUX_CHSCALE_TINT1 (0x0FE7) // 322/81 * 2^TSL2561_LUX_CHSCALE
// T, FN and CL package values
#define TSL2561_LUX_K1T (0x0040) // 0.125 * 2^RATIO_SCALE
#define TSL2561_LUX_B1T (0x01f2) // 0.0304 * 2^LUX_SCALE
#define TSL2561_LUX_M1T (0x01be) // 0.0272 * 2^LUX_SCALE
#define TSL2561_LUX_K2T (0x0080) // 0.250 * 2^RATIO_SCALE
#define TSL2561_LUX_B2T (0x0214) // 0.0325 * 2^LUX_SCALE
#define TSL2561_LUX_M2T (0x02d1) // 0.0440 * 2^LUX_SCALE
#define TSL2561_LUX_K3T (0x00c0) // 0.375 * 2^RATIO_SCALE
#define TSL2561_LUX_B3T (0x023f) // 0.0351 * 2^LUX_SCALE
#define TSL2561_LUX_M3T (0x037b) // 0.0544 * 2^LUX_SCALE
#define TSL2561_LUX_K4T (0x0100) // 0.50 * 2^RATIO_SCALE
#define TSL2561_LUX_B4T (0x0270) // 0.0381 * 2^LUX_SCALE
#define TSL2561_LUX_M4T (0x03fe) // 0.0624 * 2^LUX_SCALE
#define TSL2561_LUX_K5T (0x0138) // 0.61 * 2^RATIO_SCALE
#define TSL2561_LUX_B5T (0x016f) // 0.0224 * 2^LUX_SCALE
#define TSL2561_LUX_M5T (0x01fc) // 0.0310 * 2^LUX_SCALE
#define TSL2561_LUX_K6T (0x019a) // 0.80 * 2^RATIO_SCALE
#define TSL2561_LUX_B6T (0x00d2) // 0.0128 * 2^LUX_SCALE
#define TSL2561_LUX_M6T (0x00fb) // 0.0153 * 2^LUX_SCALE
#define TSL2561_LUX_K7T (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B7T (0x0018) // 0.00146 * 2^LUX_SCALE
#define TSL2561_LUX_M7T (0x0012) // 0.00112 * 2^LUX_SCALE
#define TSL2561_LUX_K8T (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B8T (0x0000) // 0.000 * 2^LUX_SCALE
#define TSL2561_LUX_M8T (0x0000) // 0.000 * 2^LUX_SCALE
// CS package values
#define TSL2561_LUX_K1C (0x0043) // 0.130 * 2^RATIO_SCALE
#define TSL2561_LUX_B1C (0x0204) // 0.0315 * 2^LUX_SCALE
#define TSL2561_LUX_M1C (0x01ad) // 0.0262 * 2^LUX_SCALE
#define TSL2561_LUX_K2C (0x0085) // 0.260 * 2^RATIO_SCALE
#define TSL2561_LUX_B2C (0x0228) // 0.0337 * 2^LUX_SCALE
#define TSL2561_LUX_M2C (0x02c1) // 0.0430 * 2^LUX_SCALE
#define TSL2561_LUX_K3C (0x00c8) // 0.390 * 2^RATIO_SCALE
#define TSL2561_LUX_B3C (0x0253) // 0.0363 * 2^LUX_SCALE
#define TSL2561_LUX_M3C (0x0363) // 0.0529 * 2^LUX_SCALE
#define TSL2561_LUX_K4C (0x010a) // 0.520 * 2^RATIO_SCALE
#define TSL2561_LUX_B4C (0x0282) // 0.0392 * 2^LUX_SCALE
#define TSL2561_LUX_M4C (0x03df) // 0.0605 * 2^LUX_SCALE
#define TSL2561_LUX_K5C (0x014d) // 0.65 * 2^RATIO_SCALE
#define TSL2561_LUX_B5C (0x0177) // 0.0229 * 2^LUX_SCALE
#define TSL2561_LUX_M5C (0x01dd) // 0.0291 * 2^LUX_SCALE
#define TSL2561_LUX_K6C (0x019a) // 0.80 * 2^RATIO_SCALE
#define TSL2561_LUX_B6C (0x0101) // 0.0157 * 2^LUX_SCALE
#define TSL2561_LUX_M6C (0x0127) // 0.0180 * 2^LUX_SCALE
#define TSL2561_LUX_K7C (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B7C (0x0037) // 0.00338 * 2^LUX_SCALE
#define TSL2561_LUX_M7C (0x002b) // 0.00260 * 2^LUX_SCALE
#define TSL2561_LUX_K8C (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B8C (0x0000) // 0.000 * 2^LUX_SCALE
#define TSL2561_LUX_M8C (0x0000) // 0.000 * 2^LUX_SCALE
enum
{
TSL2561_REGISTER_CONTROL = 0x00,
TSL2561_REGISTER_TIMING = 0x01,
TSL2561_REGISTER_THRESHHOLDL_LOW = 0x02,
TSL2561_REGISTER_THRESHHOLDL_HIGH = 0x03,
TSL2561_REGISTER_THRESHHOLDH_LOW = 0x04,
TSL2561_REGISTER_THRESHHOLDH_HIGH = 0x05,
TSL2561_REGISTER_INTERRUPT = 0x06,
TSL2561_REGISTER_CRC = 0x08,
TSL2561_REGISTER_ID = 0x0A,
TSL2561_REGISTER_CHAN0_LOW = 0x0C,
TSL2561_REGISTER_CHAN0_HIGH = 0x0D,
TSL2561_REGISTER_CHAN1_LOW = 0x0E,
TSL2561_REGISTER_CHAN1_HIGH = 0x0F
};
typedef enum
{
TSL2561_INTEGRATIONTIME_13MS = 0x00, // 13.7ms
TSL2561_INTEGRATIONTIME_101MS = 0x01, // 101ms
TSL2561_INTEGRATIONTIME_402MS = 0x02 // 402ms
}
tsl2561IntegrationTime_t;
typedef enum
{
TSL2561_GAIN_0X = 0x00, // No gain
TSL2561_GAIN_16X = 0x10, // 16x gain
}
tsl2561Gain_t;
class TSL2561 {
public:
TSL2561(uint8_t addr);
boolean begin(void);
void enable(void);
void disable(void);
void write8(uint8_t r, uint8_t v);
uint16_t read16(uint8_t reg);
uint32_t calculateLux(uint16_t ch0, uint16_t ch1);
void setTiming(tsl2561IntegrationTime_t integration);
void setGain(tsl2561Gain_t gain);
uint16_t getLuminosity (uint8_t channel);
uint32_t getFullLuminosity ();
private:
int8_t _addr;
tsl2561IntegrationTime_t _integration;
tsl2561Gain_t _gain;
boolean _initialized;
};
#endif

View File

@ -1,63 +0,0 @@
#include <Wire.h>
#include "TSL2561.h"
// Example for demonstrating the TSL2561 library - public domain!
// connect SCL to analog 5
// connect SDA to analog 4
// connect VDD to 3.3V DC
// connect GROUND to common ground
// ADDR can be connected to ground, or vdd or left floating to change the i2c address
// The address will be different depending on whether you let
// the ADDR pin float (addr 0x39), or tie it to ground or vcc. In those cases
// use TSL2561_ADDR_LOW (0x29) or TSL2561_ADDR_HIGH (0x49) respectively
TSL2561 tsl(TSL2561_ADDR_FLOAT);
void setup(void) {
Serial.begin(9600);
if (tsl.begin()) {
Serial.println("Found sensor");
} else {
Serial.println("No sensor?");
while (1);
}
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
//tsl.setGain(TSL2561_GAIN_0X); // set no gain (for bright situtations)
tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations)
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); // shortest integration time (bright light)
//tsl.setTiming(TSL2561_INTEGRATIONTIME_101MS); // medium integration time (medium light)
//tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS); // longest integration time (dim light)
// Now we're ready to get readings!
}
void loop(void) {
// Simple data read example. Just read the infrared, fullspecrtrum diode
// or 'visible' (difference between the two) channels.
// This can take 13-402 milliseconds! Uncomment whichever of the following you want to read
uint16_t x = tsl.getLuminosity(TSL2561_VISIBLE);
//uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
//uint16_t x = tsl.getLuminosity(TSL2561_INFRARED);
Serial.println(x, DEC);
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
// That way you can do whatever math and comparisons you want!
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
Serial.print("IR: "); Serial.print(ir); Serial.print("\t\t");
Serial.print("Full: "); Serial.print(full); Serial.print("\t");
Serial.print("Visible: "); Serial.print(full - ir); Serial.print("\t");
Serial.print("Lux: "); Serial.println(tsl.calculateLux(full, ir));
delay(100);
}

View File

@ -1,9 +0,0 @@
name=TSL2561 Arduino Library
version=1.0.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for using the TSL2561 Luminosity sensor
paragraph=Arduino library for using the TSL2561 Luminosity sensor
category=Sensors
url=https://github.com/adafruit/TSL2561-Arduino-Library
architectures=*

View File

@ -108,8 +108,14 @@ bool TasmotaSerial::isValidGPIOpin(int pin)
return (pin >= -1 && pin <= 5) || (pin >= 12 && pin <= 15);
}
bool TasmotaSerial::begin(long speed) {
// Use getCycleCount() loop to get as exact timing as possible
m_bit_time = ESP.getCpuFreqMHz() *1000000 /speed;
return m_valid && (speed <= TM_SERIAL_BAUDRATE);
}
bool TasmotaSerial::begin() {
return m_valid;
return begin(TM_SERIAL_BAUDRATE);
}
void TasmotaSerial::flush() {
@ -142,8 +148,11 @@ int TasmotaSerial::available()
return avail;
}
//#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts
#ifdef TM_SERIAL_USE_IRAM
#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts
#else
#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait); wait += m_bit_time; }
#endif
size_t TasmotaSerial::write(uint8_t b)
{
@ -167,22 +176,6 @@ size_t TasmotaSerial::write(uint8_t b)
return 1;
}
/*
size_t TasmotaSerial::write(const uint8_t *buffer, size_t size)
{
if (-1 == m_tx_pin) {
return 0;
}
size_t n = 0;
// Flush input buffer on every write
m_in_pos = m_out_pos = 0;
while(size--) {
n += txWrite(*buffer++);
}
return n;
}
*/
#ifdef TM_SERIAL_USE_IRAM
void ICACHE_RAM_ATTR TasmotaSerial::rxRead()
{
@ -206,7 +199,7 @@ void TasmotaSerial::rxRead()
TM_SERIAL_WAIT;
// Store the received value in the buffer unless we have an overflow
int next = (m_in_pos+1) % TM_SERIAL_BUFFER_SIZE;
if (next != m_out_pos) {
if (next != (int)m_out_pos) {
m_buffer[m_in_pos] = rec;
m_in_pos = next;
}

View File

@ -20,20 +20,25 @@
#ifndef TasmotaSerial_h
#define TasmotaSerial_h
/*********************************************************************************************\
* TasmotaSerial supports 9600 baud with fixed buffer size of 20 bytes using optional no iram
* TasmotaSerial supports up to 9600 baud with fixed buffer size of 64 bytes using optional no iram
*
* Based on EspSoftwareSerial v3.3.1 by Peter Lerup (https://github.com/plerup/espsoftwareserial)
\*********************************************************************************************/
#define TM_SERIAL_BAUDRATE 9600
#define TM_SERIAL_BUFFER_SIZE 64
//#define TM_SERIAL_USE_IRAM // Enable to use iram (+368 bytes)
#define TM_SERIAL_BAUDRATE 9600 // Max supported baudrate
#define TM_SERIAL_BUFFER_SIZE 64 // Receive buffer size
#include <core_version.h> // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0)
#ifndef ARDUINO_ESP8266_RELEASE_2_3_0
#define TM_SERIAL_USE_IRAM // Enable to use iram (+368 bytes)
#endif
#include <Stream.h>
class TasmotaSerial : public Stream {
public:
TasmotaSerial(int receive_pin, int transmit_pin);
bool begin(long speed);
bool begin();
int peek();
@ -42,10 +47,6 @@ class TasmotaSerial : public Stream {
virtual int available();
virtual void flush();
// size_t write(const uint8_t *buffer, size_t size = 1);
// int read();
// int available();
void rxRead();
using Print::write;

36
lib/readme.txt Normal file
View File

@ -0,0 +1,36 @@
This directory is intended for the project specific (private) libraries.
PlatformIO will compile them to static libraries and link to executable file.
The source code of each library should be placed in separate directory, like
"lib/private_lib/[here are source files]".
For example, see how can be organized `Foo` and `Bar` libraries:
|--lib
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |- readme.txt --> THIS FILE
|- platformio.ini
|--src
|- main.c
Then in `src/main.c` you should use:
#include <Foo.h>
#include <Bar.h>
// rest H/C/CPP code
PlatformIO will find your libraries automatically, configure preprocessor's
include paths and build them.
More information about PlatformIO Library Dependency Finder
- http://docs.platformio.org/page/librarymanager/ldf.html

15
pio/strip-floats.py Normal file
View File

@ -0,0 +1,15 @@
Import('env')
#
# Dump build environment (for debug)
#print env.Dump()
#
flags = " ".join(env['LINKFLAGS'])
flags = flags.replace("-u _printf_float", "")
flags = flags.replace("-u _scanf_float", "")
newflags = flags.split()
env.Replace(
LINKFLAGS=newflags
)

View File

@ -12,23 +12,29 @@ src_dir = sonoff
; *** Uncomment one of the lines below to build/upload only one environment
;env_default = sonoff
;env_default = sonoff-minimal
;env_default = sonoff-xxl
;env_default = sonoff-DE
;env_default = sonoff-ES
;env_default = sonoff-FR
;env_default = sonoff-HU
;env_default = sonoff-IT
;env_default = sonoff-NL
;env_default = sonoff-PL
;env_default = sonoff-PT
;env_default = sonoff-RU
;env_default = sonoff-CN
;env_default = sonoff-minimal
;env_default = sonoff-ds18x20
[env:sonoff]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
@ -44,103 +50,172 @@ monitor_baud = 115200
; *** Upload file to OTA server using HTTP
;upload_port = domus1:80/api/upload-arduino.php
;extra_scripts = pio/http-uploader.py
[env:sonoff-DE]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=de-DE
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-ES]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=es-AR
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-FR]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=fr-FR
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-IT]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=it-IT
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-NL]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=nl-NL
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-PL]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=pl-PL
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-CN]
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=zh-CN
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
; *** Serial Monitor options
monitor_baud = 115200
;extra_scripts = pio/strip-floats.py, pio/http-uploader.py
[env:sonoff-minimal]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DBE_MINIMAL
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; Serial Monitor options
monitor_baud = 115200
[env:sonoff-ds18x20]
[env:sonoff-xxl]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DUSE_DS18x20
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DUSE_ALL_SENSORS
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; Serial Monitor options
monitor_baud = 115200
[env:sonoff-DE]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=de-DE
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-ES]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=es-AR
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-FR]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=fr-FR
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-HU]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=hu-HU
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-IT]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=it-IT
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-NL]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=nl-NL
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-PL]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=pl-PL
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-PT]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=pt-PT
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-RU]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=ru-RU
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200
[env:sonoff-CN]
;platform = espressif8266@1.5.0 ; v2.3.0
;platform = espressif8266@1.6.0 ; v2.4.0
platform = espressif8266
framework = arduino
board = esp01_1m
board_flash_mode = dout
build_flags = -Wl,-Tesp8266.flash.1m0.ld -DMY_LANGUAGE=zh-CN
lib_deps = PubSubClient, NeoPixelBus, IRremoteESP8266, ArduinoJSON
extra_scripts = pio/strip-floats.py
; *** Serial Monitor options
monitor_baud = 115200

View File

@ -1,63 +1,90 @@
/* 5.11.1h
* Rewrite webserver argument processing gaining 5k code space (#1705)
* Redesign weblog storage (#1730)
* Fix command SetOption20 (#1741)
/* 5.12.0d
* Prep for optional MQTT drivers by separating mqtt code from sonoff.ino to file xdrv_00_mqtt.ino
* Add Portuguese language file
* Add compiler check for stable lwIP version v1.4 (#1940)
* Add diacritics to Polish language file (#2005)
* Add Hungarian language file (#2024)
* Fix MQTT TLS fingerprint validation (#2033)
*
* 5.11.1g
* Add support for PMS5003 and PMS7003 particle concentration sensor
* Reinstate console weblog to 20 lines after some webpage rewrite
* Add command SetOption20 to allow update of Dimmer/Color/Ct without turning power on (#1719)
* Update language files nl-NL (#1723) and es-AR (#1722)
* 5.12.0c
* Fix intermittent exception when dns lookup is used while sleep is enabled
* Fix 5.4.0 regression turning off single press after button hold during 4x hold time
* Fix possible wifi connection problem by erasing sdk configuration parameters
* Change Polish language to using Diacritics (#2005)
*
* 5.11.1f
* Revert chunked webserver pages as it fails on many browsers due to chunks being too small (#1706)
* Reduce initial console weblog from 20 to 13 lines due to memory constraints
* 5.12.0b
* Add serial debug info
* Add Multichannel Gas sensor using MultiChannel_Gas_Sensor library (#1245)
* Add optional usage of %d or %X suffices in MQTT client to append chipid (#1871)
* Add optional usage of %d or %X suffices in MQTT topic to append chipid (#1871)
* Add optional usage of %d or %04d in ota url to be replaced with chipid (#1871)
* Add Sonoff Bridge command RfKey<x> 5 to show current RF key values either default or learned (#1884)
* Add user configurable serial GPIOs to MagicHome and Arilux modules (#1887)
* Add Russian language file (#1909)
* Add Webserver upload preflight request support (#1927)
* Add Home Assistant clear other device (#1931)
* Add Restart time to Status 1 (#1938)
* Change TSL2561 driver to joba library and delete Adafruit library (#1644)
* Change Sonoff SC JSON format (#1939)
* Fix compile error when define HOME_ASSISTANT_DISCOVERY_ENABLE is not set (#1937)
* Add optional TSL2561 driver using library Joba_Tsl2561 to be enabled in user_config.h with define USE_TSL2561_JOBA (#1951)
* Add support for sensor SHTC3 (#1967)
*
* 5.11.1e
* Replaced command Ina219Mode with command Sensor13
* Add chunked webserver pages for large pages saving memory
* Fix Non-English JSON temperature unit attachement
* Add command Sensor15 2 to start MHZ19(B) Zero Point Calibration (#1643)
* Fix Sonoff Pow Energy Today and Energy Total reading after restart (#1648)
* Rewrite function pointers to save code space and memory (#1683)
* Add option define HOME_ASSISTANT_DISCOVERY_ENABLE in user_config.h (#1685)
* Fix SOnoff Pow Energy Period roll-over (#1688)
* 5.12.0a
* Change platformio option sonoff-ds18x20 to sonoff-xxl enabling ds18x20 and all other sensors in one image
* Fix providing web page configuratin option for Friendly Name when no device (relay or light) is configured (#1850)
* Change default parameters in user_config.h to undefined for easy installation (#1851)
* Change max user configurable hold time from 10 to 25 seconds (#1851)
*
* 5.11.1d
* Add locale Decimal Separator to Web sensor page
* Add command State to retrieve device state information (same data as teleperiod state and status 11 in slightly different JSON format)
* Extent state information with Light parameters
* Fix IRSend parameter translation (#1636)
* Add optional login to Webserver AP mode (#1587, #1635)
* Fix BME680 teleperiod resistance measuring (#1647)
*
* 5.11.1c
* Make command color parameter input less strict to ease Hass support
* Add ColorTemperature to light status message
* Change PubSubClient.h define MQTT_MAX_PACKET_SIZE from 512 to 1000 for Hass support
* Make define MESSZ dependent on PubSubClient.h define MQTT_MAX_PACKET_SIZE
* Fix logging line length around 400 characters
* 5.12.0 20180209
* Change library PubSubClient.h define MQTT_MAX_PACKET_SIZE from 512 to 1000 for Home Assistant support
* Change relation of define MESSZ being dependent on PubSubClient.h define MQTT_MAX_PACKET_SIZE
* Change command color parameter input checks to less strict for Home Assistant support
* Change command Ina219Mode into command Sensor13
* Change commands HlwPCal, HlwUCal and HlwICal to PowerCal, VoltageCal and CurrentCal to be used for both Pow and S31 calibration
* Change commands HlwPSet, HlwUSet and HlwISet to PowerSet, VoltageSet and CurrentSet to be used for both Pow and S31 calibration
* Change uptime from hour to second resulting in a display of 123T13:45:21 where 123 is days
* Change module name Wemos D1 mini into Generic (#1220)
* Revert HTML change from width=100% to style=width:100% supporting HTML5 (#1358)
* Add experimental (still Hass python exceptions) Home Assistant Discovery for switch and light to be enabled by command SetOption19 1 (#1534)
* Updated French Translation (#1561)
* Fix DS18B20 temperature JSON decimal dot (#1561)
* Add Spanish language file (#1589)
* Update Italian Language file (#1594)
* Consolidate WIFI_MANAGER_SEC into WIFI_CONFIG_SEC (#1616)
* Fix Energy JSON message (#1621)
*
* 5.11.1b
* Add command PowerOnState option 5 which inverts PulseTime and allows for delayed always on after power on
* Changed OSWATCH_RESET_TIME (Blocked loop) from 30 to 120 seconds to allow slow networks (#1556)
* Add French language file (#1561)
* Change HTML from width=100% to style=width:100% supporting HTML5 (#1358)
* Change OSWATCH_RESET_TIME (Blocked loop) from 30 to 120 seconds to allow slow networks (#1556)
* Change WIFI_MANAGER_SEC into WIFI_CONFIG_SEC (#1616)
* Change function pointers code to save code space and memory (#1683)
* Change webserver argument processing gaining 5k code space (#1705)
* Change weblog memory usage (#1730, #1793, #1819)
* Update TasmotaSerial library to 1.1.0
* Update language files Italian (#1594), Dutch (#1723) and Spanish (#1722)
* Fix Non-English JSON temperature unit attachement
* Fix Arilux RF induced exception by moving interrupt handler to iram on non ESP8266/Arduino lib v2.3.0
* Fix truncated command names and wrong response for DomoticzSwitchIdx (#1571)
* Add HTTP Allow Cross Origin removed from ESP8266/Arduino 2.4.0 (#1572)
* Fix %-sign issue as printf escape character in Humidity and Sonoff SC (#1579)
*
* 5.11.1a
* Fix DS18B20 temperature JSON decimal dot (#1561)
* Fix Energy JSON message (#1621)
* Fix IRSend parameter translation (#1636)
* Fix TSL2561 device detection (#1644, #1825)
* Fix BME680 teleperiod resistance measuring (#1647)
* Fix Energy Monitoring Energy Today and Energy Total reading after restart (#1648)
* Fix IRReceive Data value (#1663)
* Fix Energy Monitoring Energy Period roll-over (#1688)
* Fix compiler warnings (#1774)
* Fix command PWM response if no PWM channel is configured (#1783)
* Add locale Decimal Separator to Web sensor page
* Add ColorTemperature to light status message
* Add command PowerOnState option 5 which inverts PulseTime and allows for delayed always on after power on
* Add OtaMagic two step Web server OTA upgrade using filename-minimal image if OTA free space is too small
* Add chinese language file (#1551)
* Add support for PMS5003 and PMS7003 particle concentration sensor
* Add command SetOption21 1 to allow Energy Monitoring when power is off on Sonoff Pow and Sonoff S31 (#1420)
* Add Chinese language file (#1551)
* Add French language file (#1561)
* Add Spanish language file (#1589)
* Add HTTP Allow Cross Origin removed from ESP8266/Arduino lib v2.4.0 (#1572)
* Add Home Assistant MQTT Discovery for switch and light to be enabled by command SetOption19 1 (#1534) or define HOME_ASSISTANT_DISCOVERY_ENABLE in user_config.h (#1685)
* Add command State to retrieve device state information (same data as teleperiod state and status 11 in slightly different JSON format)
* Add optional login to Webserver AP mode (#1587, #1635)
* Add command Sensor15 2 to start MHZ19(B) Zero Point Calibration (#1643)
* Add support for Sonoff S31 Smart Socket with Power Consumption Detection (#1626)
* Add command SetOption20 to allow update of Dimmer/Color/Ct without turning power on (#1719, #1741)
* Add NTP sync time slot based on chip id (#1773)
* Add cursor pointer to web button (#1836)
*
* 5.11.1 20180107
* Fix Sonoff Pow command handling (#1542)

View File

@ -99,6 +99,7 @@
#define D_JSON_SSID "SSId"
#define D_JSON_STARTDST "StartDST" // Start Daylight Savings Time
#define D_JSON_STARTED "Started"
#define D_JSON_STARTUPUTC "StartupUTC"
#define D_JSON_SUBNETMASK "Subnetmask"
#define D_JSON_SUCCESSFUL "Successful"
#define D_JSON_SWITCH "Switch"
@ -278,12 +279,12 @@
#define D_CMND_CURRENTLOW "CurrentLow"
#define D_CMND_CURRENTHIGH "CurrentHigh"
#define D_CMND_ENERGYRESET "EnergyReset"
#define D_CMND_HLWPCAL "HlwPcal"
#define D_CMND_HLWPSET "HlwPset"
#define D_CMND_HLWUCAL "HlwUcal"
#define D_CMND_HLWUSET "HlwUset"
#define D_CMND_HLWICAL "HlwIcal"
#define D_CMND_HLWISET "HlwIset"
#define D_CMND_POWERCAL "PowerCal"
#define D_CMND_POWERSET "PowerSet"
#define D_CMND_VOLTAGECAL "VoltageCal"
#define D_CMND_VOLTAGESET "VoltageSet"
#define D_CMND_CURRENTCAL "CurrentCal"
#define D_CMND_CURRENTSET "CurrentSet"
#define D_CMND_MAXPOWER "MaxPower"
#define D_CMND_MAXPOWERHOLD "MaxPowerHold"
#define D_CMND_MAXPOWERWINDOW "MaxPowerWindow"
@ -382,6 +383,7 @@ const char kUnitNames[] PROGMEM =
D_UNIT_WATTHOUR ;
const char S_JSON_COMMAND_NVALUE_SPACE_UNIT[] PROGMEM = "{\"%s\":\"%d %s\"}";
const char S_JSON_COMMAND_LVALUE_SPACE_UNIT[] PROGMEM = "{\"%s\":\"%lu %s\"}";
const char S_JSON_COMMAND_SVALUE_SPACE_UNIT[] PROGMEM = "{\"%s\":\"%s %s\"}";
const char S_JSON_COMMAND_NVALUE_UNIT[] PROGMEM = "{\"%s\":\"%d%s\"}";
const char S_JSON_COMMAND_NVALUE_UNIT_NVALUE_UNIT[] PROGMEM = "{\"%s\":\"%d%s (%d%s)\"}";
@ -390,10 +392,12 @@ const char S_JSON_COMMAND_NVALUE_SVALUE[] PROGMEM = "{\"%s\":\"%d (%s)
const char S_JSON_COMMAND_NVALUE_ACTIVE_NVALUE[] PROGMEM = "{\"%s\":\"%d (" D_JSON_ACTIVE " %d)\"}";
const char S_JSON_COMMAND_NVALUE[] PROGMEM = "{\"%s\":%d}";
const char S_JSON_COMMAND_LVALUE[] PROGMEM = "{\"%s\":%lu}";
const char S_JSON_COMMAND_SVALUE[] PROGMEM = "{\"%s\":\"%s\"}";
const char S_JSON_COMMAND_XVALUE[] PROGMEM = "{\"%s\":%s}"; // %s must provide quotes on non-number
const char S_JSON_COMMAND_INDEX_NVALUE[] PROGMEM = "{\"%s%d\":%d}";
const char S_JSON_COMMAND_INDEX_LVALUE[] PROGMEM = "{\"%s%d\":%lu}";
const char S_JSON_COMMAND_INDEX_SVALUE[] PROGMEM = "{\"%s%d\":\"%s\"}";
const char S_JSON_COMMAND_INDEX_SVALUE_SVALUE[] PROGMEM = "{\"%s%d\":\"%s%s\"}";
@ -445,7 +449,7 @@ const char HTTP_SNS_SEAPRESSURE[] PROGMEM = "%s{s}%s " D_PRESSUREATSEALEVEL "{m}
const char HTTP_SNS_ANALOG[] PROGMEM = "%s{s}%s " D_ANALOG_INPUT "%d{m}%d{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#if defined(USE_MHZ19) || defined(USE_SENSEAIR)
const char HTTP_SNS_CO2[] PROGMEM = "%s{s}%s " D_CO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
const char HTTP_SNS_CO2[] PROGMEM = "%s{s}%s " D_CO2 "{m}%d " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#endif // USE_WEBSERVER
const char S_MAIN_MENU[] PROGMEM = D_MAIN_MENU;

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Particals"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "None"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Particals"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "None"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Partículas"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "Ninguno"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Particules"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "None"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

457
sonoff/language/hu-HU.h Normal file
View File

@ -0,0 +1,457 @@
/*
hu-HU.h - localization for Hungarian in Hungary for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends
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/>.
*/
#ifndef _LANGUAGE_HU_HU_H_
#define _LANGUAGE_HU_HU_H_
/*************************** ATTENTION *******************************\
*
* Due to memory constraints only UTF-8 is supported.
* To save code space keep text as short as possible.
* Time and Date provided by SDK can not be localized (yet).
* Use online command StateText to translate ON, OFF, HOLD and TOGGLE.
* Use online command Prefix to translate cmnd, stat and tele.
*
\*********************************************************************/
//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English)
// "2017-03-07T11:08:02" - ISO8601:2004
#define D_YEAR_MONTH_SEPARATOR "."
#define D_MONTH_DAY_SEPARATOR "."
#define D_DATE_TIME_SEPARATOR " "
#define D_HOUR_MINUTE_SEPARATOR ":"
#define D_MINUTE_SECOND_SEPARATOR ":"
#define D_DAY3LIST "VasHétKedSzeCsüPénSzo"
#define D_MONTH3LIST "JanFebMárÁprMájJúnJúlAugSzeOktNovDec"
// Non JSON decimal separator
#define D_DECIMAL_SEPARATOR "."
// Common
#define D_ADMIN "Admin"
#define D_AIR_QUALITY "Levegő minőség"
#define D_AP "AP" // Access Point
#define D_AS "mint"
#define D_AUTO "AUTO"
#define D_BLINK "Villogás"
#define D_BLINKOFF "Villogás Ki"
#define D_BOOT_COUNT "Bootolások száma"
#define D_BRIGHTLIGHT "Max. fényerő"
#define D_BUTTON "Gomb"
#define D_BY "által" // Written by me
#define D_BYTES "Byte-ok"
#define D_CELSIUS "Celsius"
#define D_CO2 "Szén-dioxid"
#define D_CODE "kód" // Button code
#define D_COLDLIGHT "Hideg"
#define D_COMMAND "Parancs"
#define D_CONNECTED "Csatlakozva"
#define D_COUNT "Szám"
#define D_COUNTER "Számláló"
#define D_CURRENT "Áram" // As in Voltage and Current
#define D_DATA "Adat"
#define D_DARKLIGHT "Min. févnyerő"
#define D_DEBUG "Debug"
#define D_DISABLED "Letiltva"
#define D_DNS_SERVER "DNS Szerver"
#define D_DONE "Kész"
#define D_DST_TIME "DST"
#define D_EMULATION "Emuláció"
#define D_ENABLED "Engedélyezve"
#define D_ERASE "Törlés"
#define D_ERROR "Hiba"
#define D_FAHRENHEIT "Fahrenheit"
#define D_FAILED "Sikertelen"
#define D_FALLBACK "Fallback"
#define D_FALLBACK_TOPIC "Fallback Téma"
#define D_FALSE "Hamis"
#define D_FILE "File"
#define D_FREE_MEMORY "Szabad Memória"
#define D_GAS "Gáz"
#define D_GATEWAY "Gateway"
#define D_GROUP "Csoport"
#define D_HOST "Host"
#define D_HOSTNAME "Hostname"
#define D_HUMIDITY "Páratartalom"
#define D_ILLUMINANCE "Megvilágítás"
#define D_IMMEDIATE "azonnali" // Button immediate
#define D_INDEX "Index"
#define D_INFO "Info"
#define D_INITIALIZED "Inicializálva"
#define D_IP_ADDRESS "IP Cím"
#define D_LIGHT "Fény"
#define D_LWT "LWT"
#define D_MODULE "Modul"
#define D_MQTT "MQTT"
#define D_MULTI_PRESS "több lenyomás"
#define D_NOISE "Zaj"
#define D_NONE "nincs"
#define D_OFF "Ki"
#define D_OFFLINE "Offline"
#define D_OK "Ok"
#define D_ON "Be"
#define D_ONLINE "Online"
#define D_PASSWORD "Jelszó"
#define D_PORT "Port"
#define D_POWER_FACTOR "Teljesítmény tényező"
#define D_POWERUSAGE "Energiafelhasználás"
#define D_PRESSURE "Nyomás"
#define D_PRESSUREATSEALEVEL "Tengerszinti nyomás"
#define D_PROGRAM_FLASH_SIZE "Program Flash Méret"
#define D_PROGRAM_SIZE "Program Méret"
#define D_PROJECT "Projekt"
#define D_RECEIVED "Érkezett"
#define D_RESTART "Újraindítás"
#define D_RESTARTING "Újraindítás"
#define D_RESTART_REASON "Újraindítás oka:"
#define D_RESTORE "Visszaállítás"
#define D_RETAINED "mentve"
#define D_SAVE "Mentés"
#define D_SENSOR "Szenzor"
#define D_SSID "SSId"
#define D_START ""
#define D_STD_TIME "STD"
#define D_STOP "Leállítás"
#define D_SUBNET_MASK "Subnet Mask"
#define D_SUBSCRIBE_TO "Feliratkozás a"
#define D_SUCCESSFUL "Sikeres"
#define D_TEMPERATURE "Hőmérséklet"
#define D_TO "-nak"
#define D_TOGGLE "Toggle"
#define D_TOPIC "Téma"
#define D_TRANSMIT "Továbbít"
#define D_TRUE "Igaz"
#define D_UPGRADE "frissítés"
#define D_UPLOAD "Feltöltés"
#define D_UPTIME "Üzemidő"
#define D_USER "Felhasználó"
#define D_UTC_TIME "UTC"
#define D_UV_LEVEL "UV Szint"
#define D_VERSION "Verzió"
#define D_VOLTAGE "Feszültség"
#define D_WARMLIGHT "Meleg"
#define D_WEB_SERVER "Web Szerver"
// sonoff.ino
#define D_WARNING_MINIMAL_VERSION "VIGYÁZZ Ez a verzió nem támogat tartós beállításokat"
#define D_LEVEL_10 "szint 1-0"
#define D_LEVEL_01 "szint 0-1"
#define D_SERIAL_LOGGING_DISABLED "Serial logolás kikapcsolva"
#define D_SYSLOG_LOGGING_REENABLED "Syslog logolás újra-engedélyezve"
#define D_SET_BAUDRATE_TO "Baudrate beállítása"
#define D_RECEIVED_TOPIC "Érkezett Téma"
#define D_DATA_SIZE "Adat Méret"
#define D_ANALOG_INPUT "Analóg"
#define D_FINGERPRINT "TLS fingerprint hitelesítése..."
#define D_TLS_CONNECT_FAILED_TO "TLS Csatlakozás sikertelen a"
#define D_RETRY_IN "Újrapróbálás"
#define D_VERIFIED "Hitelesítve"
#define D_INSECURE "Nem biztonságos kapcsolat érvénytelen Fingerprint miatt"
#define D_CONNECT_FAILED_TO "Sikertelen csatlakozás a"
// support.ino
#define D_OSWATCH "osWatch"
#define D_BLOCKED_LOOP "Blocked Loop"
#define D_WPS_FAILED_WITH_STATUS "WPSconfig SIKERTELEN státusz:"
#define D_ACTIVE_FOR_3_MINUTES "aktválás 3 percre"
#define D_FAILED_TO_START "sikertelen indítás"
#define D_PATCH_ISSUE_2186 "Patch issue 2186"
#define D_CONNECTING_TO_AP "Csatlakozás az (AP): "
#define D_IN_MODE "be mód"
#define D_CONNECT_FAILED_NO_IP_ADDRESS "Sikertelen csatlakozás, nincs kiosztott IP cím"
#define D_CONNECT_FAILED_AP_NOT_REACHED "Sikertelen csatlakozás, AP nem elérhető"
#define D_CONNECT_FAILED_WRONG_PASSWORD "Sikertelen csatlakozás, hibás AP jelszó"
#define D_CONNECT_FAILED_AP_TIMEOUT "Sikertelen csatlakozás AP időtúllépés miatt"
#define D_ATTEMPTING_CONNECTION "Csatlakozás..."
#define D_CHECKING_CONNECTION "Kapcsolat ellenőrzése..."
#define D_QUERY_DONE "Lekérés kész. MQTT szolgáltatás aktív"
#define D_MQTT_SERVICE_FOUND "élő MQTT szolgáltatás a"
#define D_FOUND_AT "a"
#define D_SYSLOG_HOST_NOT_FOUND "Syslog Host nem található"
// settings.ino
#define D_SAVED_TO_FLASH_AT "Flash-re mentve a"
#define D_LOADED_FROM_FLASH_AT "Flash-ről betöltve a"
#define D_USE_DEFAULTS "Alapértelmezett beáll. használata"
#define D_ERASED_SECTOR "Szektor törlése"
// webserver.ino
#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "MINIMAL firmware - frissítsd!"
#define D_WEBSERVER_ACTIVE_ON "Web szerver aktív a"
#define D_WITH_IP_ADDRESS "IP címe:"
#define D_WEBSERVER_STOPPED "Webs zerver leállítva"
#define D_FILE_NOT_FOUND "File Nem Található"
#define D_REDIRECTED "Átírányítás captive portálra"
#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager AccessPoint(AP) és Station(ST) beállítása"
#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager AccessPoint(AP) beállítása"
#define D_TRYING_TO_CONNECT "Csatlakozás a hálózatra..."
#define D_RESTART_IN "Újraindítás..."
#define D_SECONDS "másodperc"
#define D_DEVICE_WILL_RESTART "Az eszköz hamarosan újraindul"
#define D_BUTTON_TOGGLE "Toggle"
#define D_CONFIGURATION "Konfigurációk"
#define D_INFORMATION "Információ"
#define D_FIRMWARE_UPGRADE "Firmware Frissítés"
#define D_CONSOLE "Konzol"
#define D_CONFIRM_RESTART "Újraindítés megerősítése"
#define D_CONFIGURE_MODULE "Eszköz konfiguráció"
#define D_CONFIGURE_WIFI "WiFi konfiguráció"
#define D_CONFIGURE_MQTT "MQTT konfiguráció"
#define D_CONFIGURE_DOMOTICZ "Domoticz konfiguráció"
#define D_CONFIGURE_LOGGING "Logolás konfiguráció"
#define D_CONFIGURE_OTHER "Egyéb konfiguráció"
#define D_CONFIRM_RESET_CONFIGURATION "Konfig resetelés megerősítve?"
#define D_RESET_CONFIGURATION "Konfiguráció reset"
#define D_BACKUP_CONFIGURATION "Konfiguráció backup"
#define D_RESTORE_CONFIGURATION "Konfiguráció visszaállítás"
#define D_MAIN_MENU "Menü"
#define D_MODULE_PARAMETERS "Modul paraméterek"
#define D_MODULE_TYPE "Modul típus"
#define D_GPIO "GPIO"
#define D_SERIAL_IN "Serial In"
#define D_SERIAL_OUT "Serial Out"
#define D_WIFI_PARAMETERS "Wifi paraméterek"
#define D_SCAN_FOR_WIFI_NETWORKS "Wifi hálózat keresése"
#define D_SCAN_DONE "Keresés kész"
#define D_NO_NETWORKS_FOUND "Nincs elérhető hálózat"
#define D_REFRESH_TO_SCAN_AGAIN "Frissíts az újra kereséshez"
#define D_DUPLICATE_ACCESSPOINT "Duplicate AccessPoint"
#define D_SKIPPING_LOW_QUALITY "Kihagyás, alacsony jelminőség"
#define D_RSSI "RSSI"
#define D_WEP "WEP"
#define D_WPA_PSK "WPA PSK"
#define D_WPA2_PSK "WPA2 PSK"
#define D_AP1_SSID "AP1 SSID"
#define D_AP1_PASSWORD "AP1 Jelszó"
#define D_AP2_SSID "AP2 SSID"
#define D_AP2_PASSWORD "AP2 Jelszó"
#define D_MQTT_PARAMETERS "MQTT paraméterek"
#define D_CLIENT "Kliens"
#define D_FULL_TOPIC "Teljes téma"
#define D_LOGGING_PARAMETERS "Logolás paraméterek"
#define D_SERIAL_LOG_LEVEL "Serial logolás szint"
#define D_WEB_LOG_LEVEL "Web logolás szint"
#define D_SYS_LOG_LEVEL "Syslog szint"
#define D_MORE_DEBUG "Részletes debug"
#define D_SYSLOG_HOST "Syslog host"
#define D_SYSLOG_PORT "Syslog port"
#define D_TELEMETRY_PERIOD "Telemetria (sec)"
#define D_OTHER_PARAMETERS "Egyéb paraméterek"
#define D_WEB_ADMIN_PASSWORD "Web Admin Jelszó"
#define D_MQTT_ENABLE "MQTT engedélyezés"
#define D_FRIENDLY_NAME "Név"
#define D_BELKIN_WEMO "Belkin WeMo"
#define D_HUE_BRIDGE "Hue Bridge"
#define D_SINGLE_DEVICE "single device"
#define D_MULTI_DEVICE "multi device"
#define D_SAVE_CONFIGURATION "Konfiguráció mentése"
#define D_CONFIGURATION_SAVED "Konfiguráció elmentve"
#define D_CONFIGURATION_RESET "Konfiguráció visszaállítása"
#define D_PROGRAM_VERSION "Program Verzió"
#define D_BUILD_DATE_AND_TIME "Build Dátum & Idő"
#define D_CORE_AND_SDK_VERSION "Core/SDK Verzió"
#define D_FLASH_WRITE_COUNT "Flashelések száma"
#define D_MAC_ADDRESS "MAC Cím"
#define D_MQTT_HOST "MQTT Host"
#define D_MQTT_PORT "MQTT Port"
#define D_MQTT_CLIENT "MQTT Cliens"
#define D_MQTT_USER "MQTT Felhasználó"
#define D_MQTT_TOPIC "MQTT Téma"
#define D_MQTT_GROUP_TOPIC "MQTT Csoport Téma"
#define D_MQTT_FULL_TOPIC "MQTT Teljes téma"
#define D_MDNS_DISCOVERY "mDNS Láthatóság"
#define D_MDNS_ADVERTISE "mDNS Hírdetés"
#define D_ESP_CHIP_ID "ESP Chip Id"
#define D_FLASH_CHIP_ID "Flash Chip Id"
#define D_FLASH_CHIP_SIZE "Flash Méret"
#define D_FREE_PROGRAM_SPACE "Szabad Program Hely"
#define D_UPGRADE_BY_WEBSERVER "Frissítés web szerverrel"
#define D_OTA_URL "OTA Url"
#define D_START_UPGRADE "Frissítés"
#define D_UPGRADE_BY_FILE_UPLOAD "Frissítés file feltöltéssel"
#define D_UPLOAD_STARTED "Feltöltés elindítva"
#define D_UPGRADE_STARTED "Frissítés elindítva"
#define D_UPLOAD_DONE "Feltöltés kész"
#define D_UPLOAD_ERR_1 "Nincs file kijelölve"
#define D_UPLOAD_ERR_2 "Nincs elég memória"
#define D_UPLOAD_ERR_3 "Magic byte is not 0xE9"
#define D_UPLOAD_ERR_4 "Program flash méret nagyobb a valós flash méretnél"
#define D_UPLOAD_ERR_5 "Feltöltés buffer hiba"
#define D_UPLOAD_ERR_6 "Feltöltés sikertelen. Endegélyezz 3-mas logolást"
#define D_UPLOAD_ERR_7 "Feltöltés megszakítva"
#define D_UPLOAD_ERR_8 "Érvénytelen file"
#define D_UPLOAD_ERR_9 "File túl nagy"
#define D_UPLOAD_ERROR_CODE "Feltöltés hiba kód"
#define D_ENTER_COMMAND "Parancsolj"
#define D_ENABLE_WEBLOG_FOR_RESPONSE "Engedélyezz 2-es weblogolást több információért"
#define D_NEED_USER_AND_PASSWORD "Kell felhasználó=<felhasználónév>&jelszó=<jelszó>"
// xdrv_wemohue.ino
#define D_MULTICAST_DISABLED "Multicast kikapcsolva"
#define D_MULTICAST_REJOINED "Multicast (újra)csatlakozás"
#define D_MULTICAST_JOIN_FAILED "Multicast csatlakozás sikertelen"
#define D_FAILED_TO_SEND_RESPONSE "Nem sikerült választ küldeni"
#define D_WEMO "WeMo"
#define D_WEMO_BASIC_EVENT "WeMo basic event"
#define D_WEMO_EVENT_SERVICE "WeMo event service"
#define D_WEMO_META_SERVICE "WeMo meta service"
#define D_WEMO_SETUP "WeMo beállítás"
#define D_RESPONSE_SENT "Válasz elküldve"
#define D_HUE "Hue"
#define D_HUE_BRIDGE_SETUP "Hue beállítás"
#define D_HUE_API_NOT_IMPLEMENTED "Hue API nincs implementálva"
#define D_HUE_API "Hue API"
#define D_HUE_POST_ARGS "Hue POST args"
#define D_3_RESPONSE_PACKETS_SENT "3 válaszcsomagok elküldve"
// xdrv_05_domoticz.ino
#define D_DOMOTICZ_PARAMETERS "Domoticz paraméterek"
#define D_DOMOTICZ_IDX "Idx"
#define D_DOMOTICZ_KEY_IDX "Key idx"
#define D_DOMOTICZ_SWITCH_IDX "Kapcsoló idx"
#define D_DOMOTICZ_SENSOR_IDX "Szenzor idx"
#define D_DOMOTICZ_TEMP "Temp"
#define D_DOMOTICZ_TEMP_HUM "Hőm,Párat"
#define D_DOMOTICZ_TEMP_HUM_BARO "Hőm,Párat,Légny"
#define D_DOMOTICZ_POWER_ENERGY "Teljesítmény,Energia"
#define D_DOMOTICZ_ILLUMINANCE "Fényerő"
#define D_DOMOTICZ_COUNT "Szám"
#define D_DOMOTICZ_VOLTAGE "Feszültség"
#define D_DOMOTICZ_CURRENT "Áram"
#define D_DOMOTICZ_AIRQUALITY "Légminőség"
#define D_DOMOTICZ_UPDATE_TIMER "Update időzítő"
// xdrv_03_energy.ino
#define D_ENERGY_TODAY "Mai Energia"
#define D_ENERGY_YESTERDAY "Tegnapi Energia"
#define D_ENERGY_TOTAL "Összes Energia"
// xsns_05_ds18b20.ino
#define D_SENSOR_BUSY "Szenzor elfoglalt"
#define D_SENSOR_CRC_ERROR "Szenzor CRC hiba"
#define D_SENSORS_FOUND "Szenzorok megtalálva"
// xsns_06_dht.ino
#define D_TIMEOUT_WAITING_FOR "Timeout waiting for"
#define D_START_SIGNAL_LOW "start signal low"
#define D_START_SIGNAL_HIGH "start signal high"
#define D_PULSE "pulse"
#define D_CHECKSUM_FAILURE "Checksum failure"
// xsns_07_sht1x.ino
#define D_SENSOR_DID_NOT_ACK_COMMAND "Szenzor nem ismerte el(ACK) a parancsot"
#define D_SHT1X_FOUND "SHT1X found"
// xsns_18_pms5003.ino
#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter
#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter
#define D_PARTICALS_BEYOND "Részecskék"
// sonoff_template.h
#define D_SENSOR_NONE "Nincs"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"
#define D_SENSOR_SI7021 "SI7021"
#define D_SENSOR_DS18X20 "DS18x20"
#define D_SENSOR_I2C_SCL "I2C SCL"
#define D_SENSOR_I2C_SDA "I2C SDA"
#define D_SENSOR_WS2812 "WS2812"
#define D_SENSOR_IRSEND "IRadó"
#define D_SENSOR_SWITCH "Kapcsoló" // Suffix "1"
#define D_SENSOR_BUTTON "Gomb" // Suffix "1"
#define D_SENSOR_RELAY "Relé" // Suffix "1i"
#define D_SENSOR_LED "Led" // Suffix "1i"
#define D_SENSOR_PWM "PWM" // Suffix "1"
#define D_SENSOR_COUNTER "Számláló" // Suffix "1"
#define D_SENSOR_IRRECV "IRvevő"
#define D_SENSOR_MHZ_RX "MHZ Rx"
#define D_SENSOR_MHZ_TX "MHZ Tx"
#define D_SENSOR_PZEM_RX "PZEM Rx"
#define D_SENSOR_PZEM_TX "PZEM Tx"
#define D_SENSOR_SAIR_RX "SAir Rx"
#define D_SENSOR_SAIR_TX "SAir Tx"
#define D_SENSOR_SPI_CS "SPI CS"
#define D_SENSOR_SPI_DC "SPI DC"
#define D_SENSOR_BACKLIGHT "Háttérvil"
#define D_SENSOR_PMS5003 "PMS5003"
// Units
#define D_UNIT_AMPERE "A"
#define D_UNIT_HOUR "ó"
#define D_UNIT_KILOOHM "kOhm"
#define D_UNIT_KILOWATTHOUR "kWh"
#define D_UNIT_LUX "lx"
#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3"
#define D_UNIT_MICROMETER "um"
#define D_UNIT_MICROSECOND "µs"
#define D_UNIT_MILLIAMPERE "mA"
#define D_UNIT_MILLISECOND "ms"
#define D_UNIT_MINUTE "p"
#define D_UNIT_PARTS_PER_DECILITER "ppd"
#define D_UNIT_PARTS_PER_MILLION "ppm"
#define D_UNIT_PRESSURE "hPa"
#define D_UNIT_SECOND "m"
#define D_UNIT_SECTORS "szektorok"
#define D_UNIT_VOLT "V"
#define D_UNIT_WATT "W"
#define D_UNIT_WATTHOUR "Wh"
// Log message prefix
#define D_LOG_APPLICATION "APP: " // Application
#define D_LOG_BRIDGE "BRG: " // Bridge
#define D_LOG_CONFIG "CFG: " // Settings
#define D_LOG_COMMAND "CMD: " // Command
#define D_LOG_DEBUG "DBG: " // Debug
#define D_LOG_DHT "DHT: " // DHT sensor
#define D_LOG_DOMOTICZ "DOM: " // Domoticz
#define D_LOG_DSB "DSB: " // DS18xB20 sensor
#define D_LOG_HTTP "HTP: " // HTTP webserver
#define D_LOG_I2C "I2C: " // I2C
#define D_LOG_IRR "IRR: " // Infra Red Received
#define D_LOG_LOG "LOG: " // Logging
#define D_LOG_MODULE "MOD: " // Module
#define D_LOG_MDNS "DNS: " // mDNS
#define D_LOG_MQTT "MQT: " // MQTT
#define D_LOG_OTHER "OTH: " // Other
#define D_LOG_RESULT "RSL: " // Result
#define D_LOG_RFR "RFR: " // RF Received
#define D_LOG_SERIAL "SER: " // Serial
#define D_LOG_SHT1 "SHT: " // SHT1x sensor
#define D_LOG_UPLOAD "UPL: " // Upload
#define D_LOG_UPNP "UPP: " // UPnP
#define D_LOG_WIFI "WIF: " // Wifi
#endif // _LANGUAGE_EN_GB_H_

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Particelle"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "None"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Stofdeeltjes"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "Geen"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

View File

@ -1,7 +1,7 @@
/*
pl-PL.h - localization for Polish without fonetick - Poland for Sonoff-Tasmota
pl-PL-d.h - localization for Polish with diacritics - Poland for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends (translated by roblad - Robert L.)
Copyright (C) 2018 Theo Arends (translated by roblad - Robert L., upgraded by R. Turala)
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
@ -17,8 +17,8 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _LANGUAGE_PL_PL_H_
#define _LANGUAGE_PL_PL_H_
#ifndef _LANGUAGE_PL_PL_D_H_
#define _LANGUAGE_PL_PL_D_H_
/*************************** ATTENTION *******************************\
*
@ -39,20 +39,20 @@
#define D_HOUR_MINUTE_SEPARATOR ":"
#define D_MINUTE_SECOND_SEPARATOR ":"
#define D_DAY3LIST "PonWtoSroCzwPiaSobNie"
#define D_MONTH3LIST "StyLutMarKwiMajCzeLipSieWrzPazLisGru"
#define D_DAY3LIST "PonWtoŚroCzwPiąSobNie"
#define D_MONTH3LIST "StyLutMarKwiMajCzeLipSieWrzPaźLisGru"
// Non JSON decimal separator
#define D_DECIMAL_SEPARATOR ","
// Common
#define D_ADMIN "Admin"
#define D_AIR_QUALITY "Jakosc powietrza"
#define D_AIR_QUALITY "Jakość powietrza"
#define D_AP "AP" // Access Point
#define D_AS "jak"
#define D_AUTO "AUTO"
#define D_BLINK "Miganie"
#define D_BLINKOFF "MiganieWyl"
#define D_BLINKOFF "MiganieWył"
#define D_BOOT_COUNT "Licznik uruchomienia"
#define D_BRIGHTLIGHT "Jasny"
#define D_BUTTON "Przycisk"
@ -63,10 +63,10 @@
#define D_CODE "kod" // Button code
#define D_COLDLIGHT "Zimny"
#define D_COMMAND "Komenda"
#define D_CONNECTED "Polaczony"
#define D_CONNECTED "Połączony"
#define D_COUNT "Licz"
#define D_COUNTER "Licznik"
#define D_CURRENT "Biezacy" // As in Voltage and Current
#define D_CURRENT "Bieżący" // As in Voltage and Current
#define D_DATA "Data"
#define D_DARKLIGHT "Ciemny"
#define D_DEBUG "Debug"
@ -77,46 +77,46 @@
#define D_EMULATION "Emulacja"
#define D_ENABLED "Otwarty"
#define D_ERASE "Nadpisz"
#define D_ERROR "Blad"
#define D_ERROR "Błąd"
#define D_FAHRENHEIT "Fahrenheita"
#define D_FAILED "Bledny"
#define D_FAILED "Błędny"
#define D_FALLBACK "Awaryjny"
#define D_FALLBACK_TOPIC "Zastepczy temat"
#define D_FALSE "Falsz"
#define D_FALLBACK_TOPIC "Zastępczy temat"
#define D_FALSE "Fałsz"
#define D_FILE "Plik"
#define D_FREE_MEMORY "Wolna pamiec"
#define D_FREE_MEMORY "Wolna pamięć"
#define D_GAS "Gas"
#define D_GATEWAY "Brama"
#define D_GROUP "Grupa"
#define D_HOST "Serwer"
#define D_HOSTNAME "Nazwa serwera"
#define D_HUMIDITY "Wilgotnosc"
#define D_ILLUMINANCE "Oswietlenie"
#define D_HUMIDITY "Wilgotność"
#define D_ILLUMINANCE "Oświetlenie"
#define D_IMMEDIATE "Natychmiastowe" // Button immediate
#define D_INDEX "Indeks"
#define D_INFO "Informacja"
#define D_INITIALIZED "Zainicjowany"
#define D_IP_ADDRESS "Adres IP"
#define D_LIGHT "Swiatlo"
#define D_LIGHT "Światło"
#define D_LWT "LWT"
#define D_MODULE "Modul"
#define D_MODULE "Moduł"
#define D_MQTT "MQTT"
#define D_MULTI_PRESS "wielokrotne-nacisniecie"
#define D_NOISE "Halas"
#define D_MULTI_PRESS "wielokrotne-naciśnięcie"
#define D_NOISE "Hałas"
#define D_NONE "Brak"
#define D_OFF "Wylaczony"
#define D_OFF "Wyłączony"
#define D_OFFLINE "Nieaktywny"
#define D_OK "Ok"
#define D_ON "Wlaczony"
#define D_ON "Włączony"
#define D_ONLINE "Aktywny"
#define D_PASSWORD "Haslo"
#define D_PASSWORD "Hasło"
#define D_PORT "Port"
#define D_POWER_FACTOR "Wspolczynik mocy"
#define D_POWER_FACTOR "Współczynik mocy"
#define D_POWERUSAGE "Moc"
#define D_PRESSURE "Cisnienie"
#define D_PRESSUREATSEALEVEL "Cisnienie na poziomie morza"
#define D_PROGRAM_FLASH_SIZE "Wielkosc programu flash"
#define D_PROGRAM_SIZE "Wielkosc programu"
#define D_PRESSURE "Ciśnienie"
#define D_PRESSUREATSEALEVEL "Ciśnienie na poziomie morza"
#define D_PROGRAM_FLASH_SIZE "Wielkość programu flash"
#define D_PROGRAM_SIZE "Wielkość programu"
#define D_PROJECT "Projekt"
#define D_RECEIVED "Otrzymany"
#define D_RESTART "Restart"
@ -135,18 +135,18 @@
#define D_SUCCESSFUL "Powodzenie"
#define D_TEMPERATURE "Temperatura"
#define D_TO "do"
#define D_TOGGLE "Przelacz"
#define D_TOGGLE "Przełącz"
#define D_TOPIC "Temat"
#define D_TRANSMIT "Wyslij"
#define D_TRANSMIT "Wyślij"
#define D_TRUE "Prawda"
#define D_UPGRADE "aktualizacji"
#define D_UPLOAD "Wgraj"
#define D_UPTIME "Uptime"
#define D_USER "Uzytkownik"
#define D_USER "Użytkownik"
#define D_UTC_TIME "UTC"
#define D_UV_LEVEL "Poziom UV"
#define D_VERSION "Wersja"
#define D_VOLTAGE "Napiecie"
#define D_VOLTAGE "Napięcie"
#define D_WARMLIGHT "Nagrzanie"
#define D_WEB_SERVER "Web Server"
@ -154,82 +154,82 @@
#define D_WARNING_MINIMAL_VERSION "WARNING This version does not support persistent settings"
#define D_LEVEL_10 "poziom 1-0"
#define D_LEVEL_01 "poziom 0-1"
#define D_SERIAL_LOGGING_DISABLED "Wylaczony dziennik na porcie szeregowym"
#define D_SERIAL_LOGGING_DISABLED "Wyłączony dziennik na porcie szeregowym"
#define D_SYSLOG_LOGGING_REENABLED "Wznowiono zapis do Syslog"
#define D_SET_BAUDRATE_TO "Ustaw szybkosc transmisji na"
#define D_SET_BAUDRATE_TO "Ustaw szybkość transmisji na"
#define D_RECEIVED_TOPIC "Otrzymany temat"
#define D_DATA_SIZE "Wielkosc danych"
#define D_DATA_SIZE "Wielkość danych"
#define D_ANALOG_INPUT "Wej_analogowe"
#define D_FINGERPRINT "Weryfikuj odcisk TLS..."
#define D_TLS_CONNECT_FAILED_TO "Nieudane polaczenie TLS do"
#define D_RETRY_IN "Sprobuj ponownie"
#define D_TLS_CONNECT_FAILED_TO "Nieudane połączenie TLS do"
#define D_RETRY_IN "Spróbuj ponownie"
#define D_VERIFIED "Zweryfikowano"
#define D_INSECURE "Nieprawidlowe polaczenie z powodu blednego odcisku TLS"
#define D_CONNECT_FAILED_TO "Nie udalo sie nawiazac polaczenia"
#define D_INSECURE "Nieprawidłowe połączenie z powodu błędnego odcisku TLS"
#define D_CONNECT_FAILED_TO "Nie udało się nawiązać połączenia"
// support.ino
#define D_OSWATCH "osWatch"
#define D_BLOCKED_LOOP "Petla zablokowana"
#define D_WPS_FAILED_WITH_STATUS "Blad WPSconfig ze statusem"
#define D_BLOCKED_LOOP "Pętla zablokowana"
#define D_WPS_FAILED_WITH_STATUS "Błąd WPSconfig ze statusem"
#define D_ACTIVE_FOR_3_MINUTES "aktywny 3 minuty"
#define D_FAILED_TO_START "nie udalo sie uruchomic"
#define D_PATCH_ISSUE_2186 "Blad latki 2186"
#define D_CONNECTING_TO_AP "Laczenie z AP"
#define D_FAILED_TO_START "nie udało się uruchomić"
#define D_PATCH_ISSUE_2186 "Błąd łatki 2186"
#define D_CONNECTING_TO_AP "Łączenie z AP"
#define D_IN_MODE "w trybie"
#define D_CONNECT_FAILED_NO_IP_ADDRESS "Polaczenie nie powiodlo sie, poniewaz nie otrzymano adresu IP"
#define D_CONNECT_FAILED_AP_NOT_REACHED "Polaczenie nie powiodlo sie jako AP nie mozna osiagnac"
#define D_CONNECT_FAILED_WRONG_PASSWORD "Polaczenie nie powiodlo sie z nieprawidlowym haslem dostepu AP"
#define D_CONNECT_FAILED_AP_TIMEOUT "Nie udalo sie nawiazac polaczenia, limit czasu AP przekroczony"
#define D_ATTEMPTING_CONNECTION "Proba polaczenia..."
#define D_CHECKING_CONNECTION "Sprawdzanie polaczenia..."
#define D_CONNECT_FAILED_NO_IP_ADDRESS "Połączenie nie powiodło sie, ponieważ nie otrzymano adresu IP"
#define D_CONNECT_FAILED_AP_NOT_REACHED "Połączenie nie powiodło sie jako AP nie można osiągnać"
#define D_CONNECT_FAILED_WRONG_PASSWORD "Połączenie nie powiodło sie z nieprawidlowym hasłem dostepu AP"
#define D_CONNECT_FAILED_AP_TIMEOUT "Nie udało się nawiązac połączenia, limit czasu AP przekroczony"
#define D_ATTEMPTING_CONNECTION "Próba połączenia..."
#define D_CHECKING_CONNECTION "Sprawdzanie połączenia..."
#define D_QUERY_DONE "Wykonano zapytanie. Znaleziono uslugi MQTT"
#define D_MQTT_SERVICE_FOUND "Usluga MQTT została znaleziona"
#define D_MQTT_SERVICE_FOUND "Usługa MQTT została znaleziona"
#define D_FOUND_AT "znalezione w"
#define D_SYSLOG_HOST_NOT_FOUND "Syslog Host nie znaleziony"
// settings.ino
#define D_SAVED_TO_FLASH_AT "Zapisane do pamieci flash w"
#define D_LOADED_FROM_FLASH_AT "Wczytane z pamieci flash z"
#define D_USE_DEFAULTS "Uzyj domyslnych"
#define D_SAVED_TO_FLASH_AT "Zapisane do pamięci flash w"
#define D_LOADED_FROM_FLASH_AT "Wczytane z pamięci flash z"
#define D_USE_DEFAULTS "Użyj domyślnych"
#define D_ERASED_SECTOR "Wymazany sektor"
// webserver.ino
#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Oprogramowanie MINIMAL - prosze uaktualnic"
#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Oprogramowanie MINIMAL - proszę uaktualnić"
#define D_WEBSERVER_ACTIVE_ON "Aktywny serwer Web"
#define D_WITH_IP_ADDRESS "z adresem IP"
#define D_WEBSERVER_STOPPED "Serwer Web zatrzymany"
#define D_FILE_NOT_FOUND "Plik nie odnaleziony"
#define D_REDIRECTED "Przekierowano do wlasnego portalu"
#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Menedzer Wifi ustawia punkt dostepowy i zachowuje stacje"
#define D_WIFIMANAGER_SET_ACCESSPOINT "Menedzer sieci Wi-Fi Access Point"
#define D_TRYING_TO_CONNECT "Probuje polaczyc urzadzenie z siecia"
#define D_REDIRECTED "Przekierowano do własnego portalu"
#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Menedżer Wifi ustawia punkt dostępowy i zachowuje stacje"
#define D_WIFIMANAGER_SET_ACCESSPOINT "Menedżer sieci Wi-Fi Access Point"
#define D_TRYING_TO_CONNECT "Próbuję połączyć urzadzenie z siecią"
#define D_RESTART_IN "Zrestartuj"
#define D_SECONDS "sekund"
#define D_DEVICE_WILL_RESTART "Urzadzenie zrestartuje sie za kilka sekund"
#define D_BUTTON_TOGGLE "Przelacznik"
#define D_DEVICE_WILL_RESTART "Urządzenie zrestartuje sie za kilka sekund"
#define D_BUTTON_TOGGLE "Przełącznik"
#define D_CONFIGURATION "Konfiguracja"
#define D_INFORMATION "Informacje"
#define D_FIRMWARE_UPGRADE "Uaktualnienie oprogramowania"
#define D_CONSOLE "Konsola"
#define D_CONFIRM_RESTART "Potwierdz restart"
#define D_CONFIRM_RESTART "Potwierdź restart"
#define D_CONFIGURE_MODULE "Konfiguruj modul"
#define D_CONFIGURE_MODULE "Konfiguruj moduł"
#define D_CONFIGURE_WIFI "Konfiguruj WiFi"
#define D_CONFIGURE_MQTT "Konfiguruj MQTT"
#define D_CONFIGURE_DOMOTICZ "Konfiguruj Domoticz"
#define D_CONFIGURE_LOGGING "Konfiguruj zapis dziennika"
#define D_CONFIGURE_OTHER "Konfiguruj inne"
#define D_CONFIRM_RESET_CONFIGURATION "Potwierdz reset ustawien"
#define D_RESET_CONFIGURATION "Reset ustawien"
#define D_BACKUP_CONFIGURATION "Kopia ustawien"
#define D_RESTORE_CONFIGURATION "Przywrocenie ustawien"
#define D_MAIN_MENU "Menu glowne"
#define D_CONFIRM_RESET_CONFIGURATION "Potwierdź reset ustawień"
#define D_RESET_CONFIGURATION "Reset ustawień"
#define D_BACKUP_CONFIGURATION "Kopia ustawień"
#define D_RESTORE_CONFIGURATION "Przywrócenie ustawień"
#define D_MAIN_MENU "Menu główne"
#define D_MODULE_PARAMETERS "Parametery modulu"
#define D_MODULE_TYPE "Typ modulu"
#define D_MODULE_PARAMETERS "Parametery modułu"
#define D_MODULE_TYPE "Typ modułu"
#define D_GPIO "GPIO"
#define D_SERIAL_IN "Serial In"
#define D_SERIAL_OUT "Serial Out"
@ -238,33 +238,33 @@
#define D_SCAN_FOR_WIFI_NETWORKS "Skanuj sieci WiFi"
#define D_SCAN_DONE "Skan wykonany"
#define D_NO_NETWORKS_FOUND "Nie znaleziono sieci"
#define D_REFRESH_TO_SCAN_AGAIN "Odswiez aby ponownie zeskanowac"
#define D_REFRESH_TO_SCAN_AGAIN "Odswież aby ponownie zeskanowac"
#define D_DUPLICATE_ACCESSPOINT "Kopiuj AP"
#define D_SKIPPING_LOW_QUALITY "Pominieto z powodu niskiej jakości sygnalu"
#define D_SKIPPING_LOW_QUALITY "Pominięto z powodu niskiej jakości sygnału"
#define D_RSSI "RSSI"
#define D_WEP "WEP"
#define D_WPA_PSK "WPA PSK"
#define D_WPA2_PSK "WPA2 PSK"
#define D_AP1_SSID "AP1 SSID"
#define D_AP1_PASSWORD "Haslo AP1"
#define D_AP1_PASSWORD "Hasło AP1"
#define D_AP2_SSID "AP2 SSID"
#define D_AP2_PASSWORD "Haslo AP2"
#define D_AP2_PASSWORD "Hasło AP2"
#define D_MQTT_PARAMETERS "Parametery MQTT"
#define D_CLIENT "Klient"
#define D_FULL_TOPIC "Pelen temat"
#define D_FULL_TOPIC "Pełen temat"
#define D_LOGGING_PARAMETERS "Opcje dziennika"
#define D_SERIAL_LOG_LEVEL "Serial poziom dziennika"
#define D_WEB_LOG_LEVEL "Web poziom dziennika"
#define D_SYS_LOG_LEVEL "System poziom dziennika"
#define D_MORE_DEBUG "Wiecej informacji debugujacych"
#define D_MORE_DEBUG "Więcej informacji debugujacych"
#define D_SYSLOG_HOST "Syslog host"
#define D_SYSLOG_PORT "Syslog port"
#define D_TELEMETRY_PERIOD "Okres telemetrii"
#define D_OTHER_PARAMETERS "Inne parametery"
#define D_WEB_ADMIN_PASSWORD "Haslo administratora Web"
#define D_WEB_ADMIN_PASSWORD "Hasło administratora Web"
#define D_MQTT_ENABLE "MQTT aktywne"
#define D_FRIENDLY_NAME "Przyjazna nazwa"
#define D_BELKIN_WEMO "Belkin WeMo"
@ -277,9 +277,9 @@
#define D_CONFIGURATION_RESET "Ustawienia zresetowane"
#define D_PROGRAM_VERSION "Wersja programu"
#define D_BUILD_DATE_AND_TIME "Dzien i godzina kompilacji"
#define D_BUILD_DATE_AND_TIME "Dzień i godzina kompilacji"
#define D_CORE_AND_SDK_VERSION "Wersja Core/SDK"
#define D_FLASH_WRITE_COUNT "Liczba zapisow do pamieci"
#define D_FLASH_WRITE_COUNT "Liczba zapisów do pamięci"
#define D_MAC_ADDRESS "Adres Mac"
#define D_MQTT_HOST "Host MQTT"
#define D_MQTT_PORT "Port MQTT"
@ -287,11 +287,11 @@
#define D_MQTT_USER "Uzytkownik MQTT"
#define D_MQTT_TOPIC "Temat MQTT"
#define D_MQTT_GROUP_TOPIC "Temat grupy MQTT"
#define D_MQTT_FULL_TOPIC "Pelen temat MQTT"
#define D_MQTT_FULL_TOPIC "Pełen temat MQTT"
#define D_MDNS_DISCOVERY "Wykrywanie mDNS"
#define D_MDNS_ADVERTISE "Rozglaszanie mDNS"
#define D_MDNS_ADVERTISE "Rozgłaszanie mDNS"
#define D_ESP_CHIP_ID "ID ukladu ESP"
#define D_FLASH_CHIP_ID "ID ukladu pamieci flash"
#define D_FLASH_CHIP_ID "ID układu pamięci flash"
#define D_FLASH_CHIP_SIZE "Rozmiar flash"
#define D_FREE_PROGRAM_SPACE "Wolne miejsce programu"
@ -299,58 +299,58 @@
#define D_OTA_URL "URL OTA"
#define D_START_UPGRADE "Start aktualizacji"
#define D_UPGRADE_BY_FILE_UPLOAD "Aktualizacja poprzez wgranie pliku"
#define D_UPLOAD_STARTED "Wgrywanie rozpoczete"
#define D_UPGRADE_STARTED "Aktualizacja rozpoczeta"
#define D_UPLOAD_DONE "Wgrywanie zakonczone"
#define D_UPLOAD_STARTED "Wgrywanie rozpoczęte"
#define D_UPGRADE_STARTED "Aktualizacja rozpoczęta"
#define D_UPLOAD_DONE "Wgrywanie zakończone"
#define D_UPLOAD_ERR_1 "Nie wybrano pliku"
#define D_UPLOAD_ERR_2 "Niewystarczajaca ilosc miejsca"
#define D_UPLOAD_ERR_2 "Niewystarczająca ilość miejsca"
#define D_UPLOAD_ERR_3 "Magiczny bajt jest inny niz 0xE9"
#define D_UPLOAD_ERR_4 "Rozmiar programu jest wiekszy niz rzeczywisty rozmiar pamieci flash"
#define D_UPLOAD_ERR_5 "Wgrywanie, bufor niezgodnosci stanu porownywanych bitow"
#define D_UPLOAD_ERR_6 "Blad wgrywania. Uruchomiono zapis do dziennika na poziomie 3"
#define D_UPLOAD_ERR_4 "Rozmiar programu jest większy niż rzeczywisty rozmiar pamieci flash"
#define D_UPLOAD_ERR_5 "Wgrywanie, bufor niezgodnosci stanu porównywanych bitow"
#define D_UPLOAD_ERR_6 "Błąd wgrywania. Uruchomiono zapis do dziennika na poziomie 3"
#define D_UPLOAD_ERR_7 "Wgrywanie przerwane"
#define D_UPLOAD_ERR_8 "Bledny plik"
#define D_UPLOAD_ERR_9 "Plik jest za duzy"
#define D_UPLOAD_ERROR_CODE "Blad wgrywania"
#define D_UPLOAD_ERR_8 "Błędny plik"
#define D_UPLOAD_ERR_9 "Plik jest za duży"
#define D_UPLOAD_ERROR_CODE "Błąd wgrywania"
#define D_ENTER_COMMAND "Wprowadz polecenie"
#define D_ENABLE_WEBLOG_FOR_RESPONSE "Wlacz poziom 2 zapisu Weblog, jesli oczekiwana jest odpowiedz"
#define D_NEED_USER_AND_PASSWORD "Wymagany uzytkownik=<username>&haslo=<password>"
#define D_ENTER_COMMAND "Wprowadź polecenie"
#define D_ENABLE_WEBLOG_FOR_RESPONSE "Włącz poziom 2 zapisu Weblog, jeśli oczekiwana jest odpowiedź"
#define D_NEED_USER_AND_PASSWORD "Wymagany użytkownik=<username>&hasło=<password>"
// xdrv_wemohue.ino
#define D_MULTICAST_DISABLED "Multicast jest wylaczony"
#define D_MULTICAST_REJOINED "Multicast (re)dolaczony"
#define D_MULTICAST_JOIN_FAILED "Multicast nie powiodlo sie"
#define D_FAILED_TO_SEND_RESPONSE "Nie udalo sie wyslac odpowiedzi"
#define D_MULTICAST_DISABLED "Multicast jest wyłączony"
#define D_MULTICAST_REJOINED "Multicast (re)dołączony"
#define D_MULTICAST_JOIN_FAILED "Multicast nie powiodło się"
#define D_FAILED_TO_SEND_RESPONSE "Nie udało się wysłać odpowiedzi"
#define D_WEMO "WeMo"
#define D_WEMO_BASIC_EVENT "WeMo podstawowe zdarzenie"
#define D_WEMO_EVENT_SERVICE "WeMo zdarzenie service"
#define D_WEMO_META_SERVICE "WeMo meta service"
#define D_WEMO_SETUP "WeMo setup"
#define D_RESPONSE_SENT "Odpowiedz wyslana"
#define D_RESPONSE_SENT "Odpowiedź wysłana"
#define D_HUE "Hue"
#define D_HUE_BRIDGE_SETUP "Hue setup"
#define D_HUE_API_NOT_IMPLEMENTED "Hue API nie zaimplementowane"
#define D_HUE_API "Hue API"
#define D_HUE_POST_ARGS "Hue POST args"
#define D_3_RESPONSE_PACKETS_SENT "3 pakiety odpowiedzi wysylane"
#define D_3_RESPONSE_PACKETS_SENT "3 pakiety odpowiedzi wysyłane"
// xdrv_05_domoticz.ino
#define D_DOMOTICZ_PARAMETERS "Parametry Domoticz"
#define D_DOMOTICZ_IDX "Idx"
#define D_DOMOTICZ_KEY_IDX "Key idx"
#define D_DOMOTICZ_SWITCH_IDX "Przelacznik idx"
#define D_DOMOTICZ_SWITCH_IDX "Przełącznik idx"
#define D_DOMOTICZ_SENSOR_IDX "Sensor idx"
#define D_DOMOTICZ_TEMP "Temp"
#define D_DOMOTICZ_TEMP_HUM "Temp,Wilg"
#define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Wilg,Cis"
#define D_DOMOTICZ_POWER_ENERGY "Moc,Energia"
#define D_DOMOTICZ_ILLUMINANCE "Oswietl."
#define D_DOMOTICZ_ILLUMINANCE "Oświetl."
#define D_DOMOTICZ_COUNT "Licznik"
#define D_DOMOTICZ_VOLTAGE "Napiecie"
#define D_DOMOTICZ_CURRENT "Prad"
#define D_DOMOTICZ_VOLTAGE "Napięcie"
#define D_DOMOTICZ_CURRENT "Prąd"
#define D_DOMOTICZ_AIRQUALITY "AirQuality"
#define D_DOMOTICZ_UPDATE_TIMER "Zaktualizuj czasomierz"
@ -360,8 +360,8 @@
#define D_ENERGY_TOTAL "Energia suma"
// xsns_05_ds18b20.ino
#define D_SENSOR_BUSY "Czujnik DS18x20 zajety"
#define D_SENSOR_CRC_ERROR "Czujnik DS18x20 blad CRC"
#define D_SENSOR_BUSY "Czujnik DS18x20 zajęty"
#define D_SENSOR_CRC_ERROR "Czujnik DS18x20 błąd CRC"
#define D_SENSORS_FOUND "Znaleziono Czujnik DS18x20"
// xsns_06_dht.ino
@ -369,10 +369,10 @@
#define D_START_SIGNAL_LOW "sygnał startowy niski"
#define D_START_SIGNAL_HIGH "sygnał startowy wysoki"
#define D_PULSE "pulse"
#define D_CHECKSUM_FAILURE "Bledna suma kontrolmna"
#define D_CHECKSUM_FAILURE "Błędna suma kontrolna"
// xsns_07_sht1x.ino
#define D_SENSOR_DID_NOT_ACK_COMMAND "Czujnik nie otrzymal komendy ACK"
#define D_SENSOR_DID_NOT_ACK_COMMAND "Czujnik nie otrzymał komendy ACK"
#define D_SHT1X_FOUND "SHT1X znaleziony"
// xsns_18_pms5003.ino
@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "Particals"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "Brak"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"
@ -455,4 +454,4 @@
#define D_LOG_UPNP "UPP: " // UPnP
#define D_LOG_WIFI "WIF: " // Wifi
#endif // _LANGUAGE_PL_PL_H_
#endif // _LANGUAGE_PL_PL_D_H_

457
sonoff/language/pt-PT.h Normal file
View File

@ -0,0 +1,457 @@
/*
pt-PT.h - localization for Portuguese - Portugal for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends and Paulo Paiva
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/>.
*/
#ifndef _LANGUAGE_PT_PT_H_
#define _LANGUAGE_PT_PT_H_
/*************************** ATTENTION *******************************\
*
* Due to memory constraints only UTF-8 is supported.
* To save code space keep text as short as possible.
* Time and Date provided by SDK can not be localized (yet).
* Use online command StateText to translate ON, OFF, HOLD and TOGGLE.
* Use online command Prefix to translate cmnd, stat and tele.
*
\*********************************************************************/
//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English)
// "2017-03-07T11:08:02" - ISO8601:2004
#define D_YEAR_MONTH_SEPARATOR "-"
#define D_MONTH_DAY_SEPARATOR "-"
#define D_DATE_TIME_SEPARATOR "T"
#define D_HOUR_MINUTE_SEPARATOR ":"
#define D_MINUTE_SECOND_SEPARATOR ":"
#define D_DAY3LIST "DomSegTerQuaQuiSexSab"
#define D_MONTH3LIST "JanFevMarAbrMaiJunJulAgoSepOutNovDez"
// Non JSON decimal separator
#define D_DECIMAL_SEPARATOR "."
// Common
#define D_ADMIN "Admin"
#define D_AIR_QUALITY "Qualidade do Ar"
#define D_AP "AP" // Ponto de Acesso
#define D_AS "como"
#define D_AUTO "AUTO"
#define D_BLINK "Piscar"
#define D_BLINKOFF "Piscar desligado"
#define D_BOOT_COUNT "Contagem de Inicialização"
#define D_BRIGHTLIGHT "Brilho"
#define D_BUTTON "Botão"
#define D_BY "por" // Write by me
#define D_BYTES "Bytes"
#define D_CELSIUS "Celsius"
#define D_CO2 "Dioxido de Carbono"
#define D_CODE "Código" // Button code
#define D_COLDLIGHT "Luz Fria"
#define D_COMMAND "Comando"
#define D_CONNECTED "Ligado"
#define D_COUNT "Contagem"
#define D_COUNTER "Contador"
#define D_CURRENT "Corrente" // As in Voltage and Current
#define D_DATA "Dados"
#define D_DARKLIGHT "Luz Escura"
#define D_DEBUG "Depurar"
#define D_DISABLED "Disabilitado"
#define D_DNS_SERVER "Servidor DNS"
#define D_DONE "Concluído"
#define D_DST_TIME "DST"
#define D_EMULATION "Emulação"
#define D_ENABLED "Habilitado"
#define D_ERASE "Apagar"
#define D_ERROR "Erro"
#define D_FAHRENHEIT "Fahrenheit"
#define D_FAILED "Falha"
#define D_FALLBACK "Retornar"
#define D_FALLBACK_TOPIC "Tópico para retornar"
#define D_FALSE "Falso"
#define D_FILE "Ficheiro"
#define D_FREE_MEMORY "Memoria Livre"
#define D_GAS "Gás"
#define D_GATEWAY "Gateway"
#define D_GROUP "Grupo"
#define D_HOST "Anfitrião"
#define D_HOSTNAME "Nome Anfitrião"
#define D_HUMIDITY "Humidade"
#define D_ILLUMINANCE "Luminâcia"
#define D_IMMEDIATE "Immediato" // Button immediate
#define D_INDEX "Indíce"
#define D_INFO "Info"
#define D_INITIALIZED "Inicializado"
#define D_IP_ADDRESS "Endereço IP"
#define D_LIGHT "Luz"
#define D_LWT "LWT"
#define D_MODULE "Módulo"
#define D_MQTT "MQTT"
#define D_MULTI_PRESS "multi-pressão"
#define D_NOISE "Ruído"
#define D_NONE "Nenhum"
#define D_OFF "Off"
#define D_OFFLINE "Desconetado"
#define D_OK "Ok"
#define D_ON "On"
#define D_ONLINE "Conetado"
#define D_PASSWORD "Palavra Chave"
#define D_PORT "Porta"
#define D_POWER_FACTOR "Factor de Potência"
#define D_POWERUSAGE "Potência"
#define D_PRESSURE "Pressão"
#define D_PRESSUREATSEALEVEL "Pressão ao nível do Mar"
#define D_PROGRAM_FLASH_SIZE "Tamanho do Programa na Flash"
#define D_PROGRAM_SIZE "Tamanho do Programa"
#define D_PROJECT "Projeto"
#define D_RECEIVED "Recebido"
#define D_RESTART "Reiniciar"
#define D_RESTARTING "A reiniciar"
#define D_RESTART_REASON "Razão do reinicio"
#define D_RESTORE "Restauro"
#define D_RETAINED "Manter"
#define D_SAVE "Salvar"
#define D_SENSOR "Sensor"
#define D_SSID "SSId"
#define D_START "Início"
#define D_STD_TIME "STD"
#define D_STOP "Parar"
#define D_SUBNET_MASK "Mascara sub rede"
#define D_SUBSCRIBE_TO "Subescrever para"
#define D_SUCCESSFUL "Successo"
#define D_TEMPERATURE "Temperatura"
#define D_TO "para"
#define D_TOGGLE "Pressionar"
#define D_TOPIC "Tópico"
#define D_TRANSMIT "Transmitir"
#define D_TRUE "Verdadeiro"
#define D_UPGRADE "Atualizar"
#define D_UPLOAD "Enviar"
#define D_UPTIME "Tempo de Atividade"
#define D_USER "Utilizador"
#define D_UTC_TIME "UTC"
#define D_UV_LEVEL "Nível UV"
#define D_VERSION "Versão"
#define D_VOLTAGE "Voltagem"
#define D_WARMLIGHT "Luz Quente"
#define D_WEB_SERVER "servidor WEB"
// sonoff.ino
#define D_WARNING_MINIMAL_VERSION "AVISO esta versão não supporta configurações persistentes"
#define D_LEVEL_10 "nível 1-0"
#define D_LEVEL_01 "nível 0-1"
#define D_SERIAL_LOGGING_DISABLED "Registro em serie desabilitado"
#define D_SYSLOG_LOGGING_REENABLED "Registro do Syslog reativado"
#define D_SET_BAUDRATE_TO "Ajuste da velocidade para"
#define D_RECEIVED_TOPIC "Topico Recebido"
#define D_DATA_SIZE "Tamanho de dados"
#define D_ANALOG_INPUT "Entrada Analógica"
#define D_FINGERPRINT "Verifique a impressão digital TLS..."
#define D_TLS_CONNECT_FAILED_TO "TLS não conseguiu ligar"
#define D_RETRY_IN "Tentativa em"
#define D_VERIFIED "Verificado"
#define D_INSECURE "Ligação insegura devido à impressão digital inválida"
#define D_CONNECT_FAILED_TO "A ligação falhou ao"
// support.ino
#define D_OSWATCH "osWatch"
#define D_BLOCKED_LOOP "Loop Bloqueado"
#define D_WPS_FAILED_WITH_STATUS "WPSconfig Falha de estado"
#define D_ACTIVE_FOR_3_MINUTES "ativo por 3 minutes"
#define D_FAILED_TO_START "Falha ao iníciar"
#define D_PATCH_ISSUE_2186 "Questão 2186"
#define D_CONNECTING_TO_AP "Ligando ao AP"
#define D_IN_MODE "em modo"
#define D_CONNECT_FAILED_NO_IP_ADDRESS "A ligação falhou porque nenhum endereço IP foi recebido"
#define D_CONNECT_FAILED_AP_NOT_REACHED "A ligação falhou porque o AP não pode ser alcançado"
#define D_CONNECT_FAILED_WRONG_PASSWORD "A ligação falhou porque a palavra chave está incorreta"
#define D_CONNECT_FAILED_AP_TIMEOUT "A ligação falhou porque o tempo excedeu"
#define D_ATTEMPTING_CONNECTION "A ligar..."
#define D_CHECKING_CONNECTION "A verificar ligação..."
#define D_QUERY_DONE "Consulta finalizada. Serviço MQTT não encontrado"
#define D_MQTT_SERVICE_FOUND "Serviço MQTT encontrado em"
#define D_FOUND_AT "encontrado em"
#define D_SYSLOG_HOST_NOT_FOUND "Syslog anfitrião não encontrado"
// settings.ino
#define D_SAVED_TO_FLASH_AT "Guardado na flash em"
#define D_LOADED_FROM_FLASH_AT "Lido da flash em"
#define D_USE_DEFAULTS "Usar predefinições"
#define D_ERASED_SECTOR "Apagar setores"
// webserver.ino
#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "MINIMO firmware - Atualizar Por favor"
#define D_WEBSERVER_ACTIVE_ON "Servidor WEB ativo em"
#define D_WITH_IP_ADDRESS "com o endereço IP"
#define D_WEBSERVER_STOPPED "Servitor WEB parou"
#define D_FILE_NOT_FOUND "Ficheiro não encontrado"
#define D_REDIRECTED "Redirecionado para o portal ativo"
#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifimanager configura o Ponto de Acesso e mantem a Estação"
#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifimanager configura o Ponto de Acesso"
#define D_TRYING_TO_CONNECT "A tentar ligar o dispositivo à rede"
#define D_RESTART_IN "Reinicia em"
#define D_SECONDS "segundos"
#define D_DEVICE_WILL_RESTART "O dispositivo irá reiniciar dentro de alguns segundos"
#define D_BUTTON_TOGGLE "Pressionar"
#define D_CONFIGURATION "Configuração"
#define D_INFORMATION "Informação"
#define D_FIRMWARE_UPGRADE "Atualização de Firmware"
#define D_CONSOLE "Consola"
#define D_CONFIRM_RESTART "Confirmar o reinicio"
#define D_CONFIGURE_MODULE "Configurar Módulo"
#define D_CONFIGURE_WIFI "Configurar WiFi"
#define D_CONFIGURE_MQTT "Configurar MQTT"
#define D_CONFIGURE_DOMOTICZ "Configurar Domoticz"
#define D_CONFIGURE_LOGGING "Configurar Logging"
#define D_CONFIGURE_OTHER "Configurar outras opções"
#define D_CONFIRM_RESET_CONFIGURATION "Apagar configuração Confirmar"
#define D_RESET_CONFIGURATION "Apagar configuração"
#define D_BACKUP_CONFIGURATION "Guardar configuração"
#define D_RESTORE_CONFIGURATION "Repor configuração"
#define D_MAIN_MENU "Menu Principal"
#define D_MODULE_PARAMETERS "Parametros do Módulo"
#define D_MODULE_TYPE "Tipo de Módulo"
#define D_GPIO "GPIO"
#define D_SERIAL_IN "Serial Entrada"
#define D_SERIAL_OUT "Serial Saída"
#define D_WIFI_PARAMETERS "Parametros Wifi"
#define D_SCAN_FOR_WIFI_NETWORKS "Em busca de redes wifi"
#define D_SCAN_DONE "Busca finalizada"
#define D_NO_NETWORKS_FOUND "Sem redes"
#define D_REFRESH_TO_SCAN_AGAIN "Nova busca"
#define D_DUPLICATE_ACCESSPOINT "Ponto de Acesso duplicado"
#define D_SKIPPING_LOW_QUALITY "Ignorado devido a baixa qualidade do sinal"
#define D_RSSI "RSSI"
#define D_WEP "WEP"
#define D_WPA_PSK "WPA PSK"
#define D_WPA2_PSK "WPA2 PSK"
#define D_AP1_SSID "AP1 SSId"
#define D_AP1_PASSWORD "AP1 Palavra Chave"
#define D_AP2_SSID "AP2 SSId"
#define D_AP2_PASSWORD "AP2 Palavra Chave"
#define D_MQTT_PARAMETERS "Parametros MQTT"
#define D_CLIENT "Cliente"
#define D_FULL_TOPIC "Tópico completo"
#define D_LOGGING_PARAMETERS "Parametros Logging"
#define D_SERIAL_LOG_LEVEL "Nível de registro serial"
#define D_WEB_LOG_LEVEL "Nível de registro WEB"
#define D_SYS_LOG_LEVEL "Nível de registro Syslog"
#define D_MORE_DEBUG "Depurar mais"
#define D_SYSLOG_HOST "Syslog anfitrião"
#define D_SYSLOG_PORT "Porta Syslog"
#define D_TELEMETRY_PERIOD "Periodo de Telemetria"
#define D_OTHER_PARAMETERS "Outros parametros"
#define D_WEB_ADMIN_PASSWORD "Palavra Chave de WEB Admin"
#define D_MQTT_ENABLE "MQTT habilitado"
#define D_FRIENDLY_NAME "Nome amigável"
#define D_BELKIN_WEMO "Belkin WeMo"
#define D_HUE_BRIDGE "Hue Bridge"
#define D_SINGLE_DEVICE "dispositivo único"
#define D_MULTI_DEVICE "multiplos dispositivos"
#define D_SAVE_CONFIGURATION "Salvar configuração"
#define D_CONFIGURATION_SAVED "Configuração guardada"
#define D_CONFIGURATION_RESET "Reinicialização da configuração"
#define D_PROGRAM_VERSION "Versão do Programa"
#define D_BUILD_DATE_AND_TIME "Data e Hora da construção"
#define D_CORE_AND_SDK_VERSION "Versão Core/SDK"
#define D_FLASH_WRITE_COUNT "contagem de gravação flash"
#define D_MAC_ADDRESS "Endereço MAC"
#define D_MQTT_HOST "MQTT Servidor"
#define D_MQTT_PORT "MQTT Porta"
#define D_MQTT_CLIENT "MQTT Cliente"
#define D_MQTT_USER "MQTT Utilizador"
#define D_MQTT_TOPIC "MQTT Tópico"
#define D_MQTT_GROUP_TOPIC "MQTT Tópico Grupo"
#define D_MQTT_FULL_TOPIC "MQTT Tópico Completo"
#define D_MDNS_DISCOVERY "Descobrir mDNS"
#define D_MDNS_ADVERTISE "Anunciar mDNS"
#define D_ESP_CHIP_ID "ESP Chip Id"
#define D_FLASH_CHIP_ID "Flash Chip Id"
#define D_FLASH_CHIP_SIZE "Flash Size"
#define D_FREE_PROGRAM_SPACE "Espaço Livre Programa"
#define D_UPGRADE_BY_WEBSERVER "Atualizar pelo servidor WEB"
#define D_OTA_URL "OTA Url"
#define D_START_UPGRADE "Iniciar atualização"
#define D_UPGRADE_BY_FILE_UPLOAD "Atualização por envio de ficheiro"
#define D_UPLOAD_STARTED "Início do envio"
#define D_UPGRADE_STARTED "Atualização Iniciada"
#define D_UPLOAD_DONE "Atualização Finalizada"
#define D_UPLOAD_ERR_1 "Nenhum ficheiro selecionado"
#define D_UPLOAD_ERR_2 "Nao existe espaço disponível"
#define D_UPLOAD_ERR_3 "Byte mágico não é 0xE9"
#define D_UPLOAD_ERR_4 "O tamanho do programa e maior do que o tamanho real da flash"
#define D_UPLOAD_ERR_5 "Envio buffer miscompare"
#define D_UPLOAD_ERR_6 "Falha no envio. Hablitar logging 3"
#define D_UPLOAD_ERR_7 "Envio cancelado"
#define D_UPLOAD_ERR_8 "Ficheiro inválido"
#define D_UPLOAD_ERR_9 "Ficheiro demasiado grande"
#define D_UPLOAD_ERROR_CODE "Código de erro do envio"
#define D_ENTER_COMMAND "Inserir comando"
#define D_ENABLE_WEBLOG_FOR_RESPONSE "Habilitar weblog 2 se resposta esperada"
#define D_NEED_USER_AND_PASSWORD "Necessário user=<nome utilizador>&password=<palavra chave>"
// xdrv_wemohue.ino
#define D_MULTICAST_DISABLED "Multicast desabilitado"
#define D_MULTICAST_REJOINED "Multicast (re)ingressou"
#define D_MULTICAST_JOIN_FAILED "Multicast falha no reingresso"
#define D_FAILED_TO_SEND_RESPONSE "Falha no envio de reposta"
#define D_WEMO "WeMo"
#define D_WEMO_BASIC_EVENT "WeMo evento básico"
#define D_WEMO_EVENT_SERVICE "WeMo evento de serviço"
#define D_WEMO_META_SERVICE "WeMo serviço meta"
#define D_WEMO_SETUP "WeMo configuração"
#define D_RESPONSE_SENT "Rsposta enviada"
#define D_HUE "Hue"
#define D_HUE_BRIDGE_SETUP "Hue setup"
#define D_HUE_API_NOT_IMPLEMENTED "Hue API nao implementada"
#define D_HUE_API "Hue API"
#define D_HUE_POST_ARGS "Hue POST args"
#define D_3_RESPONSE_PACKETS_SENT "3 pacotes de resposta enviados"
// xdrv_05_domoticz.ino
#define D_DOMOTICZ_PARAMETERS "Parametros Domoticz"
#define D_DOMOTICZ_IDX "Idx"
#define D_DOMOTICZ_KEY_IDX "Chave idx"
#define D_DOMOTICZ_SWITCH_IDX "Interruptor idx"
#define D_DOMOTICZ_SENSOR_IDX "Sensor idx"
#define D_DOMOTICZ_TEMP "Temp"
#define D_DOMOTICZ_TEMP_HUM "Temp,Hum"
#define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro"
#define D_DOMOTICZ_POWER_ENERGY "Potência,Energia"
#define D_DOMOTICZ_ILLUMINANCE "Luminâcia"
#define D_DOMOTICZ_COUNT "Contagem"
#define D_DOMOTICZ_VOLTAGE "Voltagem"
#define D_DOMOTICZ_CURRENT "Corrente"
#define D_DOMOTICZ_AIRQUALITY "Qualidade do Ar"
#define D_DOMOTICZ_UPDATE_TIMER "Tempo de atualização"
// xdrv_03_energy.ino
#define D_ENERGY_TODAY "Consumo energético de hoje"
#define D_ENERGY_YESTERDAY "Consumo energético de ontem"
#define D_ENERGY_TOTAL "Consumo total de energial"
// xsns_05_ds18b20.ino
#define D_SENSOR_BUSY "Sensor ocupado"
#define D_SENSOR_CRC_ERROR "Erro Sensor CRC"
#define D_SENSORS_FOUND "Sensors encontrados"
// xsns_06_dht.ino
#define D_TIMEOUT_WAITING_FOR "Fim do tempo de espera"
#define D_START_SIGNAL_LOW "Sinal de início baixo"
#define D_START_SIGNAL_HIGH "Sinal de início elevado"
#define D_PULSE "pulse"
#define D_CHECKSUM_FAILURE "Falha Checksum"
// xsns_07_sht1x.ino
#define D_SENSOR_DID_NOT_ACK_COMMAND "Sensor não aceitou o comando ACK"
#define D_SHT1X_FOUND "SHT1X encontrado"
// xsns_18_pms5003.ino
#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter
#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter
#define D_PARTICALS_BEYOND "Partículas"
// sonoff_template.h
#define D_SENSOR_NONE "Nenhum"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"
#define D_SENSOR_SI7021 "SI7021"
#define D_SENSOR_DS18X20 "DS18x20"
#define D_SENSOR_I2C_SCL "I2C SCL"
#define D_SENSOR_I2C_SDA "I2C SDA"
#define D_SENSOR_WS2812 "WS2812"
#define D_SENSOR_IRSEND "IRsend"
#define D_SENSOR_SWITCH "Interruptor" // Suffix "1"
#define D_SENSOR_BUTTON "Botão" // Suffix "1"
#define D_SENSOR_RELAY "Relé" // Suffix "1i"
#define D_SENSOR_LED "Led" // Suffix "1i"
#define D_SENSOR_PWM "PWM" // Suffix "1"
#define D_SENSOR_COUNTER "Contador" // Suffix "1"
#define D_SENSOR_IRRECV "IRrecv"
#define D_SENSOR_MHZ_RX "MHZ Rx"
#define D_SENSOR_MHZ_TX "MHZ Tx"
#define D_SENSOR_PZEM_RX "PZEM Rx"
#define D_SENSOR_PZEM_TX "PZEM Tx"
#define D_SENSOR_SAIR_RX "SAir Rx"
#define D_SENSOR_SAIR_TX "SAir Tx"
#define D_SENSOR_SPI_CS "SPI CS"
#define D_SENSOR_SPI_DC "SPI DC"
#define D_SENSOR_BACKLIGHT "Luz negra"
#define D_SENSOR_PMS5003 "PMS5003"
// Units
#define D_UNIT_AMPERE "A"
#define D_UNIT_HOUR "Hr"
#define D_UNIT_KILOOHM "kOhm"
#define D_UNIT_KILOWATTHOUR "kWh"
#define D_UNIT_LUX "lx"
#define D_UNIT_MICROGRAM_PER_CUBIC_METER "ug/m3"
#define D_UNIT_MICROMETER "um"
#define D_UNIT_MICROSECOND "us"
#define D_UNIT_MILLIAMPERE "mA"
#define D_UNIT_MILLISECOND "ms"
#define D_UNIT_MINUTE "Min"
#define D_UNIT_PARTS_PER_DECILITER "ppd"
#define D_UNIT_PARTS_PER_MILLION "ppm"
#define D_UNIT_PRESSURE "hPa"
#define D_UNIT_SECOND "sec"
#define D_UNIT_SECTORS "sectors"
#define D_UNIT_VOLT "V"
#define D_UNIT_WATT "W"
#define D_UNIT_WATTHOUR "Wh"
// Log message prefix
#define D_LOG_APPLICATION "APP: " // Application
#define D_LOG_BRIDGE "BRG: " // Bridge
#define D_LOG_CONFIG "CFG: " // Settings
#define D_LOG_COMMAND "CMD: " // Command
#define D_LOG_DEBUG "DBG: " // Debug
#define D_LOG_DHT "DHT: " // DHT sensor
#define D_LOG_DOMOTICZ "DOM: " // Domoticz
#define D_LOG_DSB "DSB: " // DS18xB20 sensor
#define D_LOG_HTTP "HTP: " // HTTP webserver
#define D_LOG_I2C "I2C: " // I2C
#define D_LOG_IRR "IRR: " // Infra Red Received
#define D_LOG_LOG "LOG: " // Logging
#define D_LOG_MODULE "MOD: " // Module
#define D_LOG_MDNS "DNS: " // mDNS
#define D_LOG_MQTT "MQT: " // MQTT
#define D_LOG_OTHER "OTH: " // Other
#define D_LOG_RESULT "RSL: " // Result
#define D_LOG_RFR "RFR: " // RF Received
#define D_LOG_SERIAL "SER: " // Serial
#define D_LOG_SHT1 "SHT: " // SHT1x sensor
#define D_LOG_UPLOAD "UPL: " // Upload
#define D_LOG_UPNP "UPP: " // UPnP
#define D_LOG_WIFI "WIF: " // Wifi
#endif // _LANGUAGE_PT_PT_H_

458
sonoff/language/ru-RU.h Normal file
View File

@ -0,0 +1,458 @@
/*
ru-RU.h - localization for Russian - Rissia for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends / roman-vn
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/>.
*/
#ifndef _LANGUAGE_RU_RU_H_
#define _LANGUAGE_RU_RU_H_
/*************************** ATTENTION *******************************\
*
* Due to memory constraints only UTF-8 is supported.
* To save code space keep text as short as possible.
* Time and Date provided by SDK can not be localized (yet).
* Use online command StateText to translate ON, OFF, HOLD and TOGGLE.
* Use online command Prefix to translate cmnd, stat and tele.
*
\*********************************************************************/
//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English)
// "2017-03-07T11:08:02" - ISO8601:2004
#define D_YEAR_MONTH_SEPARATOR "-"
#define D_MONTH_DAY_SEPARATOR "-"
#define D_DATE_TIME_SEPARATOR "T"
#define D_HOUR_MINUTE_SEPARATOR ":"
#define D_MINUTE_SECOND_SEPARATOR ":"
#define D_DAY3LIST "ВскПонВтрСрдЧетПятСуб"
#define D_MONTH3LIST "ЯнвФевМарАпрМайИюнИюлАвгСенОктНояДек"
// Non JSON decimal separator
#define D_DECIMAL_SEPARATOR ","
// Common
#define D_ADMIN "Admin"
#define D_AIR_QUALITY "Качество воздуха"
#define D_AP "AP" // Access Point
#define D_AS "как"
#define D_AUTO "АВТО"
#define D_BLINK "Мигать"
#define D_BLINKOFF "Не Мигать"
#define D_BOOT_COUNT "Количество загрузок"
#define D_BRIGHTLIGHT "Яркость"
#define D_BUTTON "Кнопка"
#define D_BY "by" // Written by me
#define D_BYTES "Байт"
#define D_CELSIUS "Цельсия"
#define D_CO2 "Углекислый газ"
#define D_CODE "код" // Button code
#define D_COLDLIGHT "Холодный"
#define D_COMMAND "Команда"
#define D_CONNECTED "Соединен"
#define D_COUNT "Подсчет"
#define D_COUNTER "Счетчик"
#define D_CURRENT "Ток" // As in Voltage and Current
#define D_DATA "Данные"
#define D_DARKLIGHT "Темный"
#define D_DEBUG "Отладка"
#define D_DISABLED "Блокирован"
#define D_DNS_SERVER "DNS Сервер"
#define D_DONE "Выполнено"
#define D_DST_TIME "DST"
#define D_EMULATION "Эмуляция"
#define D_ENABLED "Активно"
#define D_ERASE "Стирать"
#define D_ERROR "Ошибка"
#define D_FAHRENHEIT "Фаренгейт"
#define D_FAILED "Неудачно"
#define D_FALLBACK "Обратная связь"
#define D_FALLBACK_TOPIC "Топик обратной связи"
#define D_FALSE "Ложно"
#define D_FILE "Файл"
#define D_FREE_MEMORY "Свободная память"
#define D_GAS "Газ"
#define D_GATEWAY "Шлюз"
#define D_GROUP "Группа"
#define D_HOST "Хост"
#define D_HOSTNAME "Имя Хоста"
#define D_HUMIDITY "Влажность"
#define D_ILLUMINANCE "Освещенность"
#define D_IMMEDIATE "немедленно" // Button immediate
#define D_INDEX "Индекс"
#define D_INFO "Инфо"
#define D_INITIALIZED "Инициализировано"
#define D_IP_ADDRESS "IP Адрес"
#define D_LIGHT "Свет"
#define D_LWT "LWT"
#define D_MODULE "Модуль"
#define D_MQTT "MQTT"
#define D_MULTI_PRESS "многократное нажатие"
#define D_NOISE "Шум"
#define D_NONE "Нет"
#define D_OFF "Выкл"
#define D_OFFLINE "Офф-лайн"
#define D_OK "Ок"
#define D_ON "Вкл"
#define D_ONLINE "Он-лайн"
#define D_PASSWORD "Пароль"
#define D_PORT "Порт"
#define D_POWER_FACTOR "Коэффициент Мощности"
#define D_POWERUSAGE "Мощность"
#define D_PRESSURE "Давление"
#define D_PRESSUREATSEALEVEL "Давление на уровне моря"
#define D_PROGRAM_FLASH_SIZE "Размер Flash для программ"
#define D_PROGRAM_SIZE "Размер программы "
#define D_PROJECT "Проект"
#define D_RECEIVED "Получено"
#define D_RESTART "Перезапуск"
#define D_RESTARTING "Перезапуск"
#define D_RESTART_REASON "Причина перезагрузки"
#define D_RESTORE "восстановление"
#define D_RETAINED "нераспред."
#define D_SAVE "Сохранить"
#define D_SENSOR "Датчик"
#define D_SSID "SSId"
#define D_START "Старт"
#define D_STD_TIME "STD"
#define D_STOP "Стоп"
#define D_SUBNET_MASK "Маска Подсети"
#define D_SUBSCRIBE_TO "Подписаться на"
#define D_SUCCESSFUL "Успешно"
#define D_TEMPERATURE "Температура"
#define D_TO "до"
#define D_TOGGLE "Переключить"
#define D_TOPIC "Топик"
#define D_TRANSMIT "Передать"
#define D_TRUE "Истина"
#define D_UPGRADE "обновление"
#define D_UPLOAD "Загрузить"
#define D_UPTIME "Uptime"
#define D_USER "Пользователь"
#define D_UTC_TIME "UTC"
#define D_UV_LEVEL "УФ уровень"
#define D_VERSION "Версия"
#define D_VOLTAGE "Напряжение"
#define D_WARMLIGHT "Тепло"
#define D_WEB_SERVER "Web сервер"
// sonoff.ino
#define D_WARNING_MINIMAL_VERSION "ПРЕДУПРЕЖДЕНИЕ Эта версия не поддерживает персистентные настройки"
#define D_LEVEL_10 "уровень 1-0"
#define D_LEVEL_01 "уровень 0-1"
#define D_SERIAL_LOGGING_DISABLED "Serial logging отключен"
#define D_SYSLOG_LOGGING_REENABLED "Syslog logging включен"
#define D_SET_BAUDRATE_TO "Установить скорость передачи (Baudrate)"
#define D_RECEIVED_TOPIC "Полученный Топик"
#define D_DATA_SIZE "Размер данных"
#define D_ANALOG_INPUT "Аналоговый вход"
#define D_FINGERPRINT "Проверка TLS Fingerprint..."
#define D_TLS_CONNECT_FAILED_TO "Сбой подключения TLS к"
#define D_RETRY_IN "Повторить"
#define D_VERIFIED "Проверено"
#define D_INSECURE "Небезопасное соединение, недействительный Fingerprint"
#define D_CONNECT_FAILED_TO "Ошибка подключения к"
// support.ino
#define D_OSWATCH "osWatch"
#define D_BLOCKED_LOOP "Блокирующий цикл"
#define D_WPS_FAILED_WITH_STATUS "WPS конфигурация НЕУДАЧНА со статусом"
#define D_ACTIVE_FOR_3_MINUTES "активен в течение 3 минут"
#define D_FAILED_TO_START "не удалось запустить"
#define D_PATCH_ISSUE_2186 "Проблема с исправлением 2186"
#define D_CONNECTING_TO_AP "Подключение к AP"
#define D_IN_MODE "в режиме"
#define D_CONNECT_FAILED_NO_IP_ADDRESS "Ошибка подключения, IP-адрес не получен"
#define D_CONNECT_FAILED_AP_NOT_REACHED "Ошибка соединения, AP не может быть достигнута"
#define D_CONNECT_FAILED_WRONG_PASSWORD "Ошибка соединения, неверный пароль к AP"
#define D_CONNECT_FAILED_AP_TIMEOUT "Ошибка соединения с AP по тайм-ауту"
#define D_ATTEMPTING_CONNECTION "Попытка подключения..."
#define D_CHECKING_CONNECTION "Проверка соединения..."
#define D_QUERY_DONE "Запрос выполнен. Обнаружены службы MQTT"
#define D_MQTT_SERVICE_FOUND "MQTT сервис service найдено"
#define D_FOUND_AT "найдено в"
#define D_SYSLOG_HOST_NOT_FOUND "System лог хост не найден"
// settings.ino
#define D_SAVED_TO_FLASH_AT "Сохранено во флэш-память"
#define D_LOADED_FROM_FLASH_AT "Загружено из флэш-памяти"
#define D_USE_DEFAULTS "Использовать значение по умолчанию"
#define D_ERASED_SECTOR "Стереть сектор"
// webserver.ino
#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "Прошивка MINIMAL - пожалуйста обновите"
#define D_WEBSERVER_ACTIVE_ON "Веб-сервер активен"
#define D_WITH_IP_ADDRESS "с IP-адресом"
#define D_WEBSERVER_STOPPED "Веб-сервер остановлен"
#define D_FILE_NOT_FOUND "Файл не найден"
#define D_REDIRECTED "Перенаправлено на адаптивный портал"
#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "Wifi менеджер устанавливает Точку Доступа и сохраняет станцию"
#define D_WIFIMANAGER_SET_ACCESSPOINT "Wifi менеджер установил Точку Доступа"
#define D_TRYING_TO_CONNECT "Попытка подключения устройства к сети"
#define D_RESTART_IN "Перезапуск"
#define D_SECONDS "секунд"
#define D_DEVICE_WILL_RESTART "Устройство будет перезапущено через несколько секунд"
#define D_BUTTON_TOGGLE "Переключить"
#define D_CONFIGURATION "Конфигурация"
#define D_INFORMATION "Информация"
#define D_FIRMWARE_UPGRADE "Обновление прошивки"
#define D_CONSOLE "Консоль"
#define D_CONFIRM_RESTART "Подтвердить перезагрузку"
#define D_CONFIGURE_MODULE "Конфигурация Модуля"
#define D_CONFIGURE_WIFI "Конфигурация WiFi"
#define D_CONFIGURE_MQTT "Конфигурация MQTT"
#define D_CONFIGURE_DOMOTICZ "Конфигурация Domoticz"
#define D_CONFIGURE_LOGGING "Конфигурация Logging"
#define D_CONFIGURE_OTHER "Конфигурация прочее"
#define D_CONFIRM_RESET_CONFIGURATION "Подтвердить Сброс Конфигурации"
#define D_RESET_CONFIGURATION "Сброс Конфигурации"
#define D_BACKUP_CONFIGURATION "Резервное копирование Конфигурации"
#define D_RESTORE_CONFIGURATION "Восстановление Конфигурации"
#define D_MAIN_MENU "Главное Меню"
#define D_MODULE_PARAMETERS "Параметры модуля"
#define D_MODULE_TYPE "Тип модуля"
#define D_GPIO "GPIO"
#define D_SERIAL_IN "Serial вход"
#define D_SERIAL_OUT "Serial выход"
#define D_WIFI_PARAMETERS "Параметры Wifi"
#define D_SCAN_FOR_WIFI_NETWORKS "Сканирование беспроводных сетей Wifi"
#define D_SCAN_DONE "Сканирование завершено"
#define D_NO_NETWORKS_FOUND "Не найдено сетей"
#define D_REFRESH_TO_SCAN_AGAIN "Обновить для повторного сканирования"
#define D_DUPLICATE_ACCESSPOINT "Дублировать Точку Доступа (AP)"
#define D_SKIPPING_LOW_QUALITY "Пропущено из-за низкого качества"
#define D_RSSI "RSSI"
#define D_WEP "WEP"
#define D_WPA_PSK "WPA PSK"
#define D_WPA2_PSK "WPA2 PSK"
#define D_AP1_SSID "AP1 SSId"
#define D_AP1_PASSWORD "AP1 Пароль"
#define D_AP2_SSID "AP2 SSId"
#define D_AP2_PASSWORD "AP2 Пароль"
#define D_MQTT_PARAMETERS "Параметры MQTT"
#define D_CLIENT "Клиент"
#define D_FULL_TOPIC "Полный Топик"
#define D_LOGGING_PARAMETERS "Параметры Logging"
#define D_SERIAL_LOG_LEVEL "Serial лог уровень"
#define D_WEB_LOG_LEVEL "Web лог уровень"
#define D_SYS_LOG_LEVEL "System лог уровень"
#define D_MORE_DEBUG "Дополнительная информация для отладки"
#define D_SYSLOG_HOST "System лог хост"
#define D_SYSLOG_PORT "System лог порт"
#define D_TELEMETRY_PERIOD "Период телеметрии"
#define D_OTHER_PARAMETERS "Параметры Прочие"
#define D_WEB_ADMIN_PASSWORD "Пароль Web администратора"
#define D_MQTT_ENABLE "MQTT активен"
#define D_FRIENDLY_NAME "Дружественное Имя"
#define D_BELKIN_WEMO "Belkin WeMo"
#define D_HUE_BRIDGE "Hue Bridge"
#define D_SINGLE_DEVICE "одиночное"
#define D_MULTI_DEVICE "мульти"
#define D_SAVE_CONFIGURATION "Сохранить конфигурацию"
#define D_CONFIGURATION_SAVED "Конфигурация сохранена "
#define D_CONFIGURATION_RESET "Конфигурация сброшена"
#define D_PROGRAM_VERSION "Версия программы"
#define D_BUILD_DATE_AND_TIME "Дата & Время сборки"
#define D_CORE_AND_SDK_VERSION "Версия Core/SDK"
#define D_FLASH_WRITE_COUNT "Кол-во записей Flash"
#define D_MAC_ADDRESS "MAC Адрес"
#define D_MQTT_HOST "MQTT Хост"
#define D_MQTT_PORT "MQTT Порт"
#define D_MQTT_CLIENT "MQTT Клиент ID"
#define D_MQTT_USER "MQTT Пользователь"
#define D_MQTT_TOPIC "MQTT Топик"
#define D_MQTT_GROUP_TOPIC "MQTT Топик группы"
#define D_MQTT_FULL_TOPIC "MQTT Топик полный"
#define D_MDNS_DISCOVERY "mDNS Обнаружение"
#define D_MDNS_ADVERTISE "mDNS Транcляция"
#define D_ESP_CHIP_ID "ID чипа ESP"
#define D_FLASH_CHIP_ID "ID чипа Flash памяти"
#define D_FLASH_CHIP_SIZE "Размер Flash памяти"
#define D_FREE_PROGRAM_SPACE "Свободное пространство программ"
#define D_UPGRADE_BY_WEBSERVER "Обновление через Веб-сервер"
#define D_OTA_URL "OTA Url"
#define D_START_UPGRADE "Начать обновление"
#define D_UPGRADE_BY_FILE_UPLOAD "Обновление путем загрузки файлов"
#define D_UPLOAD_STARTED "Загрузка началась"
#define D_UPGRADE_STARTED "Обновление началось"
#define D_UPLOAD_DONE "Загрузка завершена"
#define D_UPLOAD_ERR_1 "Файл не выбран"
#define D_UPLOAD_ERR_2 "Недостаточно места"
#define D_UPLOAD_ERR_3 "Magic байт не 0xE9"
#define D_UPLOAD_ERR_4 "Размер прошивки больше, чем реальный размер флеш памяти"
#define D_UPLOAD_ERR_5 "Ошибка загрузки буфера"
#define D_UPLOAD_ERR_6 "Ошибка загрузки. Включено лог уровня 3"
#define D_UPLOAD_ERR_7 "Загрузка прервана"
#define D_UPLOAD_ERR_8 "Файл неверный"
#define D_UPLOAD_ERR_9 "Слишком большой файл"
#define D_UPLOAD_ERROR_CODE "Код ошибки загрузки"
#define D_ENTER_COMMAND "Введите команду"
#define D_ENABLE_WEBLOG_FOR_RESPONSE "Включить Веб лог уровня 2 если ожидается ответ"
#define D_NEED_USER_AND_PASSWORD "Ожидается user=<username>&password=<password>"
// xdrv_wemohue.ino
#define D_MULTICAST_DISABLED "Multicast отключен"
#define D_MULTICAST_REJOINED "Multicast (ре)соединился"
#define D_MULTICAST_JOIN_FAILED "Multicast ошибка соединения"
#define D_FAILED_TO_SEND_RESPONSE "Не удалось отправить ответ"
#define D_WEMO "WeMo"
#define D_WEMO_BASIC_EVENT "WeMo основное событие"
#define D_WEMO_EVENT_SERVICE "WeMo служба событий"
#define D_WEMO_META_SERVICE "WeMo мета-сервис"
#define D_WEMO_SETUP "WeMo настройка"
#define D_RESPONSE_SENT "Ответ отправлен"
#define D_HUE "Hue"
#define D_HUE_BRIDGE_SETUP "Hue настройка"
#define D_HUE_API_NOT_IMPLEMENTED "Hue API не реализовано"
#define D_HUE_API "Hue API"
#define D_HUE_POST_ARGS "Hue POST args"
#define D_3_RESPONSE_PACKETS_SENT "3 ответных пакета получено"
// xdrv_05_domoticz.ino
#define D_DOMOTICZ_PARAMETERS "Domoticz parameters"
#define D_DOMOTICZ_IDX "Idx"
#define D_DOMOTICZ_KEY_IDX "Key idx"
#define D_DOMOTICZ_SWITCH_IDX "Switch idx"
#define D_DOMOTICZ_SENSOR_IDX "Sensor idx"
#define D_DOMOTICZ_TEMP "Temp"
#define D_DOMOTICZ_TEMP_HUM "Temp,Hum"
#define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro"
#define D_DOMOTICZ_POWER_ENERGY "Power,Energy"
#define D_DOMOTICZ_ILLUMINANCE "Illuminance"
#define D_DOMOTICZ_COUNT "Count"
#define D_DOMOTICZ_VOLTAGE "Voltage"
#define D_DOMOTICZ_CURRENT "Current"
#define D_DOMOTICZ_AIRQUALITY "AirQuality"
#define D_DOMOTICZ_UPDATE_TIMER "Update timer"
// xdrv_03_energy.ino
#define D_ENERGY_TODAY "Энергия Сегодня"
#define D_ENERGY_YESTERDAY "Энергия Вчера"
#define D_ENERGY_TOTAL "Энергия Всего"
// xsns_05_ds18b20.ino
#define D_SENSOR_BUSY "Датчик DS18x20 занят"
#define D_SENSOR_CRC_ERROR "Датчик DS18x20 - ошибка CRC"
#define D_SENSORS_FOUND "Датчик DS18x20 найден"
// xsns_06_dht.ino
#define D_TIMEOUT_WAITING_FOR "Тайм-аут, в ожидании"
#define D_START_SIGNAL_LOW "сигнал старт низкий"
#define D_START_SIGNAL_HIGH "сигнал старт высокий"
#define D_PULSE "пульс"
#define D_CHECKSUM_FAILURE "Ошибка контрольной суммы"
// xsns_07_sht1x.ino
#define D_SENSOR_DID_NOT_ACK_COMMAND "Датчик не получил команду ACK"
#define D_SHT1X_FOUND "SHT1X найден"
// xsns_18_pms5003.ino
#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter
#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter
#define D_PARTICALS_BEYOND "Particals"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "-нет-"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"
#define D_SENSOR_SI7021 "SI7021"
#define D_SENSOR_DS18X20 "DS18x20"
#define D_SENSOR_I2C_SCL "I2C SCL"
#define D_SENSOR_I2C_SDA "I2C SDA"
#define D_SENSOR_WS2812 "WS2812"
#define D_SENSOR_IRSEND "IRsend"
#define D_SENSOR_SWITCH "Свич" // Suffix "1"
#define D_SENSOR_BUTTON "Кнопка" // Suffix "1"
#define D_SENSOR_RELAY "Реле" // Suffix "1i"
#define D_SENSOR_LED "Led" // Suffix "1i"
#define D_SENSOR_PWM "PWM" // Suffix "1"
#define D_SENSOR_COUNTER "Счетчик" // Suffix "1"
#define D_SENSOR_IRRECV "IRrecv"
#define D_SENSOR_MHZ_RX "MHZ Rx"
#define D_SENSOR_MHZ_TX "MHZ Tx"
#define D_SENSOR_PZEM_RX "PZEM Rx"
#define D_SENSOR_PZEM_TX "PZEM Tx"
#define D_SENSOR_SAIR_RX "SAir Rx"
#define D_SENSOR_SAIR_TX "SAir Tx"
#define D_SENSOR_SPI_CS "SPI CS"
#define D_SENSOR_SPI_DC "SPI DC"
#define D_SENSOR_BACKLIGHT "BkLight"
#define D_SENSOR_PMS5003 "PMS5003"
// Units
#define D_UNIT_AMPERE "А"
#define D_UNIT_HOUR "Ч"
#define D_UNIT_KILOOHM "кОм"
#define D_UNIT_KILOWATTHOUR "кВт"
#define D_UNIT_LUX "лк"
#define D_UNIT_MICROGRAM_PER_CUBIC_METER "мкг/м3"
#define D_UNIT_MICROMETER "мкм"
#define D_UNIT_MICROSECOND "мкс"
#define D_UNIT_MILLIAMPERE "мА"
#define D_UNIT_MILLISECOND "мс"
#define D_UNIT_MINUTE "мин"
#define D_UNIT_PARTS_PER_DECILITER "ppd"
#define D_UNIT_PARTS_PER_MILLION "ppm"
#define D_UNIT_PRESSURE "гПа"
#define D_UNIT_SECOND "сек"
#define D_UNIT_SECTORS "секторов"
#define D_UNIT_VOLT "В"
#define D_UNIT_WATT "Вт"
#define D_UNIT_WATTHOUR "ВтЧ"
// Log message prefix
#define D_LOG_APPLICATION "APP: " // Application
#define D_LOG_BRIDGE "BRG: " // Bridge
#define D_LOG_CONFIG "CFG: " // Settings
#define D_LOG_COMMAND "CMD: " // Command
#define D_LOG_DEBUG "DBG: " // Debug
#define D_LOG_DHT "DHT: " // DHT sensor
#define D_LOG_DOMOTICZ "DOM: " // Domoticz
#define D_LOG_DSB "DSB: " // DS18xB20 sensor
#define D_LOG_HTTP "HTP: " // HTTP webserver
#define D_LOG_I2C "I2C: " // I2C
#define D_LOG_IRR "IRR: " // Infra Red Received
#define D_LOG_LOG "LOG: " // Logging
#define D_LOG_MODULE "MOD: " // Module
#define D_LOG_MDNS "DNS: " // mDNS
#define D_LOG_MQTT "MQT: " // MQTT
#define D_LOG_OTHER "OTH: " // Other
#define D_LOG_RESULT "RSL: " // Result
#define D_LOG_RFR "RFR: " // RF Received
#define D_LOG_SERIAL "SER: " // Serial
#define D_LOG_SHT1 "SHT: " // SHT1x sensor
#define D_LOG_UPLOAD "UPL: " // Upload
#define D_LOG_UPNP "UPP: " // UPnP
#define D_LOG_WIFI "WIF: " // Wifi
#endif // _LANGUAGE_RU_RU_H_

View File

@ -381,7 +381,6 @@
#define D_PARTICALS_BEYOND "颗粒物直径大于"
// sonoff_template.h
// Max string length is 8 characters including suffixes
#define D_SENSOR_NONE "None"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"

View File

@ -46,7 +46,7 @@ typedef union { // Restricted by MISRA-C Rule 18.4 bu
uint32_t light_signal : 1; // bit 18 (v5.10.0c)
uint32_t hass_discovery : 1; // bit 19 (v5.11.1a)
uint32_t not_power_linked : 1; // bit 20 (v5.11.1f)
uint32_t spare21 : 1;
uint32_t no_power_on_check : 1; // bit 21 (v5.11.1i)
uint32_t spare22 : 1;
uint32_t spare23 : 1;
uint32_t spare24 : 1;
@ -152,12 +152,12 @@ struct SYSCFG {
uint16_t domoticz_update_timer; // 340
uint16_t pwm_range; // 342
unsigned long domoticz_relay_idx[MAX_DOMOTICZ_IDX]; // 344
unsigned long domoticz_key_idx[MAX_DOMOTICZ_IDX]; // 354
unsigned long domoticz_relay_idx[MAX_DOMOTICZ_IDX]; // 344
unsigned long domoticz_key_idx[MAX_DOMOTICZ_IDX]; // 354
unsigned long hlw_power_calibration; // 364
unsigned long hlw_voltage_calibration; // 368
unsigned long hlw_current_calibration; // 36C
unsigned long energy_power_calibration; // 364
unsigned long energy_voltage_calibration; // 368
unsigned long energy_current_calibration; // 36C
unsigned long energy_kWhtoday; // 370
unsigned long energy_kWhyesterday; // 374
uint16_t energy_kWhdoy; // 378
@ -168,11 +168,11 @@ struct SYSCFG {
uint16_t energy_min_current; // 382
uint16_t energy_max_current; // 384
uint16_t energy_max_power_limit; // 386 MaxPowerLimit
uint16_t energy_max_power_limit_hold; // 388 MaxPowerLimitHold
uint16_t energy_max_power_limit_window; // 38A MaxPowerLimitWindow
uint16_t energy_max_power_safe_limit; // 38C MaxSafePowerLimit
uint16_t energy_max_power_safe_limit_hold; // 38E MaxSafePowerLimitHold
uint16_t energy_max_power_safe_limit_window; // 390 MaxSafePowerLimitWindow
uint16_t energy_max_power_limit_hold; // 388 MaxPowerLimitHold
uint16_t energy_max_power_limit_window; // 38A MaxPowerLimitWindow
uint16_t energy_max_power_safe_limit; // 38C MaxSafePowerLimit
uint16_t energy_max_power_safe_limit_hold; // 38E MaxSafePowerLimitHold
uint16_t energy_max_power_safe_limit_window; // 390 MaxSafePowerLimitWindow
uint16_t energy_max_energy; // 392 MaxEnergy
uint16_t energy_max_energy_start; // 394 MaxEnergyStart
uint16_t mqtt_retry; // 396
@ -270,6 +270,7 @@ struct TIME_T {
char name_of_month[4];
uint16_t day_of_year;
uint16_t year;
unsigned long days;
unsigned long valid;
} RtcTime;
@ -290,7 +291,10 @@ struct XDRVMAILBOX {
uint16_t valid;
uint16_t index;
uint16_t data_len;
uint16_t payload16;
int16_t payload;
uint8_t grpflg;
uint8_t notused;
char *topic;
char *data;
} XdrvMailbox;

View File

@ -50,6 +50,10 @@
#define MTX_ADDRESS8 0
#endif
#ifndef HOME_ASSISTANT_DISCOVERY_ENABLE
#define HOME_ASSISTANT_DISCOVERY_ENABLE 0
#endif
/*********************************************************************************************\
* RTC memory
\*********************************************************************************************/
@ -123,7 +127,7 @@ void RtcSettingsDump()
for (row = 0; row < maxrow; row++) {
idx = row * CFG_COLS;
snprintf_P(log_data, sizeof(log_data), PSTR("%04X:"), idx);
snprintf_P(log_data, sizeof(log_data), PSTR("%03X:"), idx);
for (col = 0; col < CFG_COLS; col++) {
if (!(col%4)) {
snprintf_P(log_data, sizeof(log_data), PSTR("%s "), log_data);
@ -154,6 +158,7 @@ extern "C" {
extern "C" uint32_t _SPIFFS_end;
// From libraries/EEPROM/EEPROM.cpp EEPROMClass
#define SPIFFS_END ((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE
// Version 3.x config
@ -180,14 +185,11 @@ void SetFlashModeDout()
eboot_command_read(&ebcmd);
address = ebcmd.args[0];
_buffer = new uint8_t[FLASH_SECTOR_SIZE];
if (SPI_FLASH_RESULT_OK == spi_flash_read(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE)) {
if (ESP.flashRead(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE)) {
if (_buffer[2] != 3) { // DOUT
_buffer[2] = 3;
noInterrupts();
if (SPI_FLASH_RESULT_OK == spi_flash_erase_sector(address / FLASH_SECTOR_SIZE)) {
spi_flash_write(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE);
}
interrupts();
if (ESP.flashEraseSector(address / FLASH_SECTOR_SIZE)) ESP.flashWrite(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE);
}
}
delete[] _buffer;
@ -251,15 +253,11 @@ void SettingsSave(byte rotate)
}
}
Settings.save_flag++;
noInterrupts();
spi_flash_erase_sector(settings_location);
spi_flash_write(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
interrupts();
ESP.flashEraseSector(settings_location);
ESP.flashWrite(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
if (!stop_flash_rotate && rotate) {
for (byte i = 1; i < CFG_ROTATES; i++) {
noInterrupts();
spi_flash_erase_sector(settings_location -i); // Delete previous configurations by resetting to 0xFF
interrupts();
ESP.flashEraseSector(settings_location -i); // Delete previous configurations by resetting to 0xFF
delay(1);
}
}
@ -284,10 +282,8 @@ void SettingsLoad()
settings_location = SETTINGS_LOCATION +1;
for (byte i = 0; i < CFG_ROTATES; i++) {
settings_location--;
noInterrupts();
spi_flash_read(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
spi_flash_read((settings_location -1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH));
interrupts();
ESP.flashRead(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
ESP.flashRead((settings_location -1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH));
// snprintf_P(log_data, sizeof(log_data), PSTR("Cnfg: Check at %X with count %d and holder %X"), settings_location -1, _SettingsH.save_flag, _SettingsH.cfg_holder);
// AddLog(LOG_LEVEL_DEBUG);
@ -302,15 +298,10 @@ void SettingsLoad()
AddLog(LOG_LEVEL_DEBUG);
if (Settings.cfg_holder != CFG_HOLDER) {
// Auto upgrade
noInterrupts();
spi_flash_read((SETTINGS_LOCATION_3) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
spi_flash_read((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH));
if (Settings.save_flag < _SettingsH.save_flag)
spi_flash_read((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
interrupts();
if ((Settings.cfg_holder != CFG_HOLDER) || (Settings.version >= 0x04020000)) {
SettingsDefault();
}
ESP.flashRead((SETTINGS_LOCATION_3) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
ESP.flashRead((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(SYSCFGH));
if (Settings.save_flag < _SettingsH.save_flag) ESP.flashRead((SETTINGS_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(SYSCFG));
if ((Settings.cfg_holder != CFG_HOLDER) || (Settings.version >= 0x04020000)) SettingsDefault();
}
settings_hash = GetSettingsHash();
@ -318,25 +309,33 @@ void SettingsLoad()
RtcSettingsLoad();
}
void SettingsErase()
void SettingsErase(uint8_t type)
{
SpiFlashOpResult result;
/*
0 = Erase from program end until end of physical flash
1 = Erase SDK parameter area at end of linker memory model (0x0FDxxx - 0x0FFFFF) solving possible wifi errors
*/
bool result;
uint32_t _sectorStart = (ESP.getSketchSize() / SPI_FLASH_SEC_SIZE) + 1;
uint32_t _sectorEnd = ESP.getFlashChipRealSize() / SPI_FLASH_SEC_SIZE;
if (1 == type) {
_sectorStart = SETTINGS_LOCATION +2; // SDK parameter area above EEPROM area (0x0FDxxx - 0x0FFFFF)
_sectorEnd = SETTINGS_LOCATION +5;
}
boolean _serialoutput = (LOG_LEVEL_DEBUG_MORE <= seriallog_level);
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION D_ERASE " %d " D_UNIT_SECTORS), _sectorEnd - _sectorStart);
AddLog(LOG_LEVEL_DEBUG);
for (uint32_t _sector = _sectorStart; _sector < _sectorEnd; _sector++) {
noInterrupts();
result = spi_flash_erase_sector(_sector);
interrupts();
result = ESP.flashEraseSector(_sector);
if (_serialoutput) {
Serial.print(F(D_LOG_APPLICATION D_ERASED_SECTOR " "));
Serial.print(_sector);
if (SPI_FLASH_RESULT_OK == result) {
if (result) {
Serial.println(F(" " D_OK));
} else {
Serial.println(F(" " D_ERROR));
@ -347,6 +346,27 @@ void SettingsErase()
}
}
// Copied from 2.4.0 as 2.3.0 is incomplete
bool SettingsEraseConfig(void) {
const size_t cfgSize = 0x4000;
size_t cfgAddr = ESP.getFlashChipSize() - cfgSize;
for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) {
if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) {
return false;
}
}
return true;
}
void SettingsSdkErase()
{
WiFi.disconnect(true); // Delete SDK wifi config
SettingsErase(1);
SettingsEraseConfig();
delay(1000);
}
void SettingsDump(char* parms)
{
#define CFG_COLS 16
@ -378,7 +398,7 @@ void SettingsDump(char* parms)
for (row = srow; row < maxrow; row++) {
idx = row * CFG_COLS;
snprintf_P(log_data, sizeof(log_data), PSTR("%04X:"), idx);
snprintf_P(log_data, sizeof(log_data), PSTR("%03X:"), idx);
for (col = 0; col < CFG_COLS; col++) {
if (!(col%4)) {
snprintf_P(log_data, sizeof(log_data), PSTR("%s "), log_data);
@ -478,9 +498,9 @@ void SettingsDefaultSet2()
// Settings.domoticz_switch_idx[i] = 0;
}
Settings.hlw_power_calibration = HLW_PREF_PULSE;
Settings.hlw_voltage_calibration = HLW_UREF_PULSE;
Settings.hlw_current_calibration = HLW_IREF_PULSE;
Settings.energy_power_calibration = HLW_PREF_PULSE;
Settings.energy_voltage_calibration = HLW_UREF_PULSE;
Settings.energy_current_calibration = HLW_IREF_PULSE;
// Settings.energy_kWhtoday = 0;
// Settings.energy_kWhyesterday = 0;
// Settings.energy_kWhdoy = 0;

View File

@ -82,7 +82,7 @@ typedef unsigned long power_t; // Power (Relay) type
#define SERIALLOG_TIMER 600 // Seconds to disable SerialLog
#define OTA_ATTEMPTS 5 // Number of times to try fetching the new firmware
#define INPUT_BUFFER_SIZE 250 // Max number of characters in (serial) command buffer
#define INPUT_BUFFER_SIZE 255 // Max number of characters in (serial) command buffer
#define CMDSZ 24 // Max number of characters in command
#define TOPSZ 100 // Max number of characters in topic string
#define LOGSZ 400 // Max number of characters in log
@ -100,9 +100,6 @@ typedef unsigned long power_t; // Power (Relay) type
#define APP_BAUDRATE 115200 // Default serial baudrate
#define MAX_STATUS 11 // Max number of status lines
#define XDRV_MAX 10 // Max number of allowed Xdrv drivers (Update xdrv_interface.ino if changed)
#define XSNS_MAX 20 // Max number of allowed Xsns External Sensors (Update xsns_interface.ino if changed)
/*
// Removed from esp8266 core since 20171105
#define min(a,b) ((a)<(b)?(a):(b))
@ -117,6 +114,7 @@ enum WeekInMonthOptions {Last, First, Second, Third, Fourth};
enum DayOfTheWeekOptions {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
enum MonthNamesOptions {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
enum HemisphereOptions {North, South};
enum GetDateAndTimeOptions { DT_LOCAL, DT_UTC, DT_RESTART, DT_UPTIME };
enum LoggingLevels {LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE, LOG_LEVEL_ALL};
@ -146,7 +144,7 @@ enum LightTypes {LT_BASIC, LT_PWM1, LT_PWM2, LT_PWM3, LT_PWM4, LT_PWM5, LT_PWM6,
enum LichtSubtypes {LST_NONE, LST_SINGLE, LST_COLDWARM, LST_RGB, LST_RGBW, LST_RGBWC};
enum LichtSchemes {LS_POWER, LS_WAKEUP, LS_CYCLEUP, LS_CYCLEDN, LS_RANDOM, LS_MAX};
enum XsnsFunctions {FUNC_INIT, FUNC_EVERY_50_MSECOND, FUNC_EVERY_SECOND, FUNC_PREP_BEFORE_TELEPERIOD, FUNC_JSON_APPEND, FUNC_WEB_APPEND, FUNC_SAVE_BEFORE_RESTART,
enum XsnsFunctions {FUNC_INIT, FUNC_LOOP, FUNC_EVERY_50_MSECOND, FUNC_EVERY_SECOND, FUNC_PREP_BEFORE_TELEPERIOD, FUNC_JSON_APPEND, FUNC_WEB_APPEND, FUNC_SAVE_BEFORE_RESTART,
FUNC_COMMAND, FUNC_MQTT_SUBSCRIBE, FUNC_MQTT_INIT, FUNC_MQTT_DATA, FUNC_SET_POWER, FUNC_SHOW_SENSOR};
const uint8_t kDefaultRfCode[9] PROGMEM = { 0x21, 0x16, 0x01, 0x0E, 0x03, 0x48, 0x2E, 0x1A, 0x00 };

File diff suppressed because it is too large Load Diff

View File

@ -33,65 +33,115 @@ void WifiWpsStatusCallback(wps_cb_status status);
}
#endif
#define USE_DHT // Default DHT11 sensor needs no external library
#define USE_DHT // Default DHT11 sensor needs no external library
#ifdef USE_ALL_SENSORS // ===================== Configure sonoff-xxl.bin =========================
#define USE_ADC_VCC // Display Vcc in Power status. Disable for use as Analog input on selected devices
#define USE_DS18x20 // For more than one DS18x20 sensors with id sort, single scan and read retry (+1k3 code)
//#define USE_DS18x20_LEGACY // For more than one DS18x20 sensors with dynamic scan using library OneWire (+1k5 code)
#define USE_I2C // I2C using library wire (+10k code, 0k2 mem, 124 iram)
#define USE_SHT // Add I2C emulating code for SHT1X sensor (+1k4 code)
#define USE_SHT3X // Add I2C code for SHT3x sensor (+0k6 code)
#define USE_HTU // Add I2C code for HTU21/SI7013/SI7020/SI7021 sensor (+1k5 code)
#define USE_BMP // Add I2C code for BMP085/BMP180/BMP280/BME280 sensor (+4k code)
#define USE_BME680 // Add additional support for BME680 sensor using Adafruit Sensor and BME680 libraries (+6k code)
#define USE_BH1750 // Add I2C code for BH1750 sensor (+0k5 code)
#define USE_VEML6070 // Add I2C code for VEML6070 sensor (+0k5 code)
#define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Adafruit TSL2561 Arduino (+1k2 code)
#define USE_ADS1115 // Add I2C code for ADS1115 16 bit A/D converter based on Adafruit ADS1x15 library (no library needed) (+0k7 code)
//#define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code)
#define USE_INA219 // Add I2C code for INA219 Low voltage and current sensor (+1k code)
#define USE_MGS // Add I2C code for Xadow and Grove Mutichannel Gas sensor using library Multichannel_Gas_Sensor (+10k code)
#define USE_MHZ19 // Add support for MH-Z19 CO2 sensor (+2k code)
#define USE_SENSEAIR // Add support for SenseAir K30, K70 and S8 CO2 sensor (+2k3 code)
#ifndef CO2_LOW
#define CO2_LOW 800 // Below this CO2 value show green light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1)
#endif
#ifndef CO2_HIGH
#define CO2_HIGH 1200 // Above this CO2 value show red light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1)
#endif
#define USE_PMS5003 // Add support for PMS5003 and PMS7003 particle concentration sensor (+1k3 code)
#define USE_PZEM004T // Add support for PZEM004T Energy monitor (+2k code)
#define USE_IR_REMOTE // Send IR remote commands using library IRremoteESP8266 and ArduinoJson (+4k code, 0k3 mem, 48 iram)
#define USE_IR_HVAC // Support for HVAC system using IR (+2k code)
#define USE_IR_RECEIVE // Support for IR receiver (+5k5 code, 264 iram)
#define USE_WS2812 // WS2812 Led string using library NeoPixelBus (+5k code, +1k mem, 232 iram) - Disable by //
#ifndef USE_WS2812_CTYPE
#define USE_WS2812_CTYPE 1 // WS2812 Color type (0 - RGB, 1 - GRB, 2 - RGBW, 3 - GRBW)
#endif
// #define USE_WS2812_DMA // DMA supports only GPIO03 (= Serial RXD) (+1k mem). When USE_WS2812_DMA is enabled expect Exceptions on Pow
#define USE_ARILUX_RF // Add support for Arilux RF remote controller (+0k8 code, 252 iram (non 2.3.0))
#endif // USE_ALL_SENSORS =====================
#if defined(USE_DS18x20) || defined(USE_DS18x20_LEGACY)
#else
#define USE_DS18B20 // Default DS18B20 sensor needs no external library
#define USE_DS18B20 // Default DS18B20 sensor needs no external library
#endif
//#define DEBUG_THEO // Add debug code
//#define DEBUG_THEO // Add debug code
#ifdef BE_MINIMAL
#ifdef BE_MINIMAL // ========================== Configure sonoff-minimal.bin =====================
#ifdef USE_MQTT_TLS
#undef USE_MQTT_TLS // Disable TLS support won't work as the MQTTHost is not set
#undef USE_MQTT_TLS // Disable TLS support won't work as the MQTTHost is not set
#endif
#ifdef USE_DISCOVERY
#undef USE_DISCOVERY // Disable Discovery services for both MQTT and web server
#undef USE_DISCOVERY // Disable Discovery services for both MQTT and web server
#endif
#ifdef USE_DOMOTICZ
#undef USE_DOMOTICZ // Disable Domoticz
#undef USE_DOMOTICZ // Disable Domoticz
#endif
#ifdef USE_HOME_ASSISTANT
#undef USE_HOME_ASSISTANT // Disable Home Assistant
#undef USE_HOME_ASSISTANT // Disable Home Assistant
#endif
//#ifdef USE_WEBSERVER
//#undef USE_WEBSERVER // Disable Webserver
//#undef USE_WEBSERVER // Disable Webserver
//#endif
#ifdef USE_EMULATION
#undef USE_EMULATION // Disable Wemo or Hue emulation
#undef USE_EMULATION // Disable Wemo or Hue emulation
#endif
#ifdef USE_PZEM004T
#undef USE_PZEM004T // Disable PZEM004T energy sensor
#undef USE_PZEM004T // Disable PZEM004T energy sensor
#endif
#ifdef USE_DS18x20
#undef USE_DS18x20 // Disable DS18x20 sensor
#undef USE_DS18x20 // Disable DS18x20 sensor
#endif
#ifdef USE_I2C
#undef USE_I2C // Disable all I2C sensors and devices
#undef USE_I2C // Disable all I2C sensors and devices
#endif
#ifdef USE_SPI
#undef USE_SPI // Disable all SPI devices
#undef USE_SPI // Disable all SPI devices
#endif
#ifdef USE_WS2812
#undef USE_WS2812 // Disable WS2812 Led string
#undef USE_WS2812 // Disable WS2812 Led string
#endif
#ifdef USE_DS18B20
#undef USE_DS18B20 // Disable internal DS18B20 sensor
#undef USE_DS18B20 // Disable internal DS18B20 sensor
#endif
#ifdef USE_DHT
#undef USE_DHT // Disable internal DHT sensor
#undef USE_DHT // Disable internal DHT sensor
#endif
#ifdef USE_DISPLAY
#undef USE_DISPLAY // Disable Display support
#endif
#ifdef USE_MHZ19
#undef USE_MHZ19 // Disable support for MH-Z19 CO2 sensor
#endif
#ifdef USE_SENSEAIR
#undef USE_SENSEAIR // Disable support for SenseAir K30, K70 and S8 CO2 sensor
#endif
#ifdef USE_IR_REMOTE
#undef USE_IR_REMOTE // Disable IR driver
#undef USE_IR_REMOTE // Disable IR driver
#endif
#ifdef USE_ARILUX_RF
#undef USE_ARILUX_RF // Disable support for Arilux RF remote controller
#endif
#ifdef DEBUG_THEO
#undef DEBUG_THEO // Disable debug code
#undef DEBUG_THEO // Disable debug code
#endif
#endif // BE_MINIMAL
#endif // BE_MINIMAL ==========================
#ifndef SWITCH_MODE
#define SWITCH_MODE TOGGLE // TOGGLE, FOLLOW or FOLLOW_INV (the wall switch state)
#define SWITCH_MODE TOGGLE // TOGGLE, FOLLOW or FOLLOW_INV (the wall switch state)
#endif
#ifndef MQTT_FINGERPRINT
@ -99,7 +149,14 @@ void WifiWpsStatusCallback(wps_cb_status status);
#endif
#ifndef WS2812_LEDS
#define WS2812_LEDS 30 // [Pixels] Number of LEDs
#define WS2812_LEDS 30 // [Pixels] Number of LEDs
#endif
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 1000
#endif
#ifndef MQTT_KEEPALIVE
#define MQTT_KEEPALIVE 15
#endif
#ifndef MESSZ
@ -110,7 +167,7 @@ void WifiWpsStatusCallback(wps_cb_status status);
//#include <core_version.h> // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0)
#ifndef ARDUINO_ESP8266_RELEASE
#define ARDUINO_ESP8266_RELEASE "STAGED"
#define ARDUINO_ESP8266_RELEASE "STAGE"
#endif
#endif // _SONOFF_POST_H_

View File

@ -90,76 +90,6 @@ enum UserSelectablePins {
GPIO_PMS5003, // Plantower PMS5003 Serial interface
GPIO_SENSOR_END };
// Text in webpage Module Parameters and commands GPIOS and GPIO
const char kSensors[GPIO_SENSOR_END][9] PROGMEM = {
D_SENSOR_NONE,
D_SENSOR_DHT11,
D_SENSOR_AM2301,
D_SENSOR_SI7021,
D_SENSOR_DS18X20,
D_SENSOR_I2C_SCL,
D_SENSOR_I2C_SDA,
D_SENSOR_WS2812,
D_SENSOR_IRSEND,
D_SENSOR_SWITCH "1",
D_SENSOR_SWITCH "2",
D_SENSOR_SWITCH "3",
D_SENSOR_SWITCH "4",
D_SENSOR_BUTTON "1",
D_SENSOR_BUTTON "2",
D_SENSOR_BUTTON "3",
D_SENSOR_BUTTON "4",
D_SENSOR_RELAY "1",
D_SENSOR_RELAY "2",
D_SENSOR_RELAY "3",
D_SENSOR_RELAY "4",
D_SENSOR_RELAY "5",
D_SENSOR_RELAY "6",
D_SENSOR_RELAY "7",
D_SENSOR_RELAY "8",
D_SENSOR_RELAY "1i",
D_SENSOR_RELAY "2i",
D_SENSOR_RELAY "3i",
D_SENSOR_RELAY "4i",
D_SENSOR_RELAY "5i",
D_SENSOR_RELAY "6i",
D_SENSOR_RELAY "7i",
D_SENSOR_RELAY "8i",
D_SENSOR_PWM "1",
D_SENSOR_PWM "2",
D_SENSOR_PWM "3",
D_SENSOR_PWM "4",
D_SENSOR_PWM "5",
D_SENSOR_COUNTER "1",
D_SENSOR_COUNTER "2",
D_SENSOR_COUNTER "3",
D_SENSOR_COUNTER "4",
D_SENSOR_PWM "1i",
D_SENSOR_PWM "2i",
D_SENSOR_PWM "3i",
D_SENSOR_PWM "4i",
D_SENSOR_PWM "5i",
D_SENSOR_IRRECV,
D_SENSOR_LED "1",
D_SENSOR_LED "2",
D_SENSOR_LED "3",
D_SENSOR_LED "4",
D_SENSOR_LED "1i",
D_SENSOR_LED "2i",
D_SENSOR_LED "3i",
D_SENSOR_LED "4i",
D_SENSOR_MHZ_TX,
D_SENSOR_MHZ_RX,
D_SENSOR_PZEM_TX,
D_SENSOR_PZEM_RX,
D_SENSOR_SAIR_TX,
D_SENSOR_SAIR_RX,
D_SENSOR_SPI_CS,
D_SENSOR_SPI_DC,
D_SENSOR_BACKLIGHT,
D_SENSOR_PMS5003
};
// Programmer selectable GPIO functionality offset by user selectable GPIOs
enum ProgramSelectablePins {
GPIO_RXD = GPIO_SENSOR_END, // Serial interface
@ -177,6 +107,30 @@ enum ProgramSelectablePins {
GPIO_USER, // User configurable
GPIO_MAX };
// Text in webpage Module Parameters and commands GPIOS and GPIO
const char kSensorNames[] PROGMEM =
D_SENSOR_NONE "|"
D_SENSOR_DHT11 "|" D_SENSOR_AM2301 "|" D_SENSOR_SI7021 "|"
D_SENSOR_DS18X20 "|"
D_SENSOR_I2C_SCL "|" D_SENSOR_I2C_SDA "|"
D_SENSOR_WS2812 "|"
D_SENSOR_IRSEND "|"
D_SENSOR_SWITCH "1|" D_SENSOR_SWITCH "2|" D_SENSOR_SWITCH "3|" D_SENSOR_SWITCH "4|"
D_SENSOR_BUTTON "1|" D_SENSOR_BUTTON "2|" D_SENSOR_BUTTON "3|" D_SENSOR_BUTTON "4|"
D_SENSOR_RELAY "1|" D_SENSOR_RELAY "2|" D_SENSOR_RELAY "3|" D_SENSOR_RELAY "4|" D_SENSOR_RELAY "5|" D_SENSOR_RELAY "6|" D_SENSOR_RELAY "7|" D_SENSOR_RELAY "8|"
D_SENSOR_RELAY "1i|" D_SENSOR_RELAY "2i|" D_SENSOR_RELAY "3i|" D_SENSOR_RELAY "4i|" D_SENSOR_RELAY "5i|" D_SENSOR_RELAY "6i|" D_SENSOR_RELAY "7i|" D_SENSOR_RELAY "8i|"
D_SENSOR_PWM "1|" D_SENSOR_PWM "2|" D_SENSOR_PWM "3|" D_SENSOR_PWM "4|" D_SENSOR_PWM "5|"
D_SENSOR_COUNTER "1|" D_SENSOR_COUNTER "2|" D_SENSOR_COUNTER "3|" D_SENSOR_COUNTER "4|"
D_SENSOR_PWM "1i|" D_SENSOR_PWM "2i|" D_SENSOR_PWM "3i|" D_SENSOR_PWM "4i|" D_SENSOR_PWM "5i|"
D_SENSOR_IRRECV "|"
D_SENSOR_LED "1|" D_SENSOR_LED "2|" D_SENSOR_LED "3|" D_SENSOR_LED "4|"
D_SENSOR_LED "1i|" D_SENSOR_LED "2i|" D_SENSOR_LED "3i|" D_SENSOR_LED "4i|"
D_SENSOR_MHZ_TX "|" D_SENSOR_MHZ_RX "|"
D_SENSOR_PZEM_TX "|" D_SENSOR_PZEM_RX "|"
D_SENSOR_SAIR_TX "|" D_SENSOR_SAIR_RX "|"
D_SENSOR_SPI_CS "|" D_SENSOR_SPI_DC "|" D_SENSOR_BACKLIGHT "|"
D_SENSOR_PMS5003;
/********************************************************************************************/
// Supported hardware modules
@ -221,6 +175,7 @@ enum SupportedModules {
ARILUX_LC11,
SONOFF_DUAL_R2,
ARILUX_LC06,
SONOFF_S31,
MAXMODULE };
/********************************************************************************************/
@ -245,6 +200,7 @@ const uint8_t kNiceList[MAXMODULE] PROGMEM = {
SONOFF_DUAL,
SONOFF_DUAL_R2,
SONOFF_POW,
SONOFF_S31,
SONOFF_4CH,
SONOFF_4CHPRO,
SONOFF_SV,
@ -723,9 +679,10 @@ const mytmplt kModules[MAXMODULE] PROGMEM = {
0, 0, 0, 0, 0
},
{ "MagicHome", // Magic Home (aka Flux-light) (ESP8266) - https://www.aliexpress.com/item/Magic-Home-Mini-RGB-RGBW-Wifi-Controller-For-Led-Strip-Panel-light-Timing-Function-16million-colors/32686853650.html
0, 0,
GPIO_LED1_INV, // GPIO02 Blue onboard LED
0,
GPIO_USER, // GPIO01 Serial RXD and Optional sensor
GPIO_LED1_INV, // GPIO02 Blue onboard LED
GPIO_USER, // GPIO03 Serial TXD and Optional sensor
GPIO_USER, // GPIO04 IR receiver (optional)
GPIO_PWM2, // GPIO05 RGB LED Green
0, 0, 0, 0, 0, 0, // Flash connection
@ -763,9 +720,9 @@ const mytmplt kModules[MAXMODULE] PROGMEM = {
{ "Arilux LC01", // Arilux AL-LC01 (ESP8285) - https://www.banggood.com/nl/ARILUX-AL-LC01-Super-Mini-LED-WIFI-Smart-RGB-Controller-For-RGB-LED-Strip-Light-DC-9-12V-p-1058603.html
// (PwmFrequency 1111Hz)
GPIO_KEY1, // GPIO00 Optional Button
0,
GPIO_USER, // GPIO01 Serial RXD and Optional sensor
GPIO_LED2_INV, // GPIO02 RF receiver control
0,
GPIO_USER, // GPIO03 Serial TXD and Optional sensor
GPIO_ARIRFRCV, // GPIO04 IR or RF receiver (optional)
GPIO_PWM1, // GPIO05 RGB LED Red
0, 0, 0, 0, 0, 0, // Flash connection
@ -777,9 +734,9 @@ const mytmplt kModules[MAXMODULE] PROGMEM = {
{ "Arilux LC11", // Arilux AL-LC11 (ESP8266) - https://www.banggood.com/nl/ARILUX-AL-LC11-Super-Mini-LED-WIFI-APP-Controller-RF-Remote-Control-For-RGBWW-LED-Strip-DC9-28V-p-1085112.html
// (PwmFrequency 540Hz)
GPIO_KEY1, // GPIO00 Optional Button
0,
GPIO_USER, // GPIO01 Serial RXD and Optional sensor
GPIO_LED2_INV, // GPIO02 RF receiver control
0,
GPIO_USER, // GPIO03 Serial TXD and Optional sensor
GPIO_PWM2, // GPIO04 RGB LED Green
GPIO_PWM1, // GPIO05 RGB LED Red
0, 0, 0, 0, 0, 0, // Flash connection
@ -806,9 +763,9 @@ const mytmplt kModules[MAXMODULE] PROGMEM = {
},
{ "Arilux LC06", // Arilux AL-LC06 (ESP8285) - https://www.banggood.com/ARILUX-AL-LC06-LED-WIFI-Smartphone-Controller-Romote-5-Channels-DC12-24V-For-RGBWW-Strip-light-p-1061476.html
GPIO_KEY1, // GPIO00 Optional Button
0,
GPIO_USER, // GPIO01 Serial RXD and Optional sensor
GPIO_USER, // GPIO02 Empty pad
0,
GPIO_USER, // GPIO03 Serial TXD and Optional sensor
GPIO_USER, // GPIO04 W2 - PWM5
0,
0, 0, 0, 0, 0, 0, // Flash connection
@ -817,6 +774,17 @@ const mytmplt kModules[MAXMODULE] PROGMEM = {
GPIO_PWM1, // GPIO14 RGB LED Red
GPIO_USER, // GPIO15 RGBW LED White
0, 0
},
{ "Sonoff S31", // Sonoff S31 (ESP8266)
GPIO_KEY1, // GPIO00 Button
0, // GPIO01 Serial RXD 4800 baud 8E1 CSE7766 energy sensor
0,
0, // GPIO03 Serial TXD
0, 0,
0, 0, 0, 0, 0, 0, // Flash connection
GPIO_REL1, // GPIO12 Red Led and Relay (0 = Off, 1 = On)
GPIO_LED1_INV, // GPIO13 Green Led (0 = On, 1 = Off)
0, 0, 0, 0
}
};
@ -897,6 +865,22 @@ const mytmplt kModules[MAXMODULE] PROGMEM = {
0,
GPIO_PWM4, // GPIO15 RGBW LED White
0, 0
}
{ "Ledunia", // Ledunia (ESP8266) - http://ledunia.de/
GPIO_USER, // GPIO00 (D0)
GPIO_USER, // GPIO01 (D7) Serial RXD
GPIO_USER, // GPIO02 (D2)
GPIO_USER, // GPIO03 (D8) Serial TXD
GPIO_USER, // GPIO04 (D4) 4 x WS2812 Leds, (DOUT) Extents WS2812 string
GPIO_USER, // GPIO05 (D5) Blue Led
0, 0, 0, 0, 0, 0, // Flash connection
GPIO_USER, // GPIO12 (D12)
GPIO_USER, // GPIO13 (D13)
GPIO_USER, // GPIO14 (D14)
GPIO_USER, // GPIO15 (D15)
GPIO_USER, // GPIO16 (D16)
0 // ADC0 Analog input (A0)
},
*/

View File

@ -17,8 +17,8 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
IPAddress syslog_host_addr; // Syslog host IP address
unsigned long syslog_host_refresh = 0;
IPAddress syslog_host_addr; // Syslog host IP address
uint32_t syslog_host_hash = 0; // Syslog host name hash
/*********************************************************************************************\
* Watchdog extension (https://github.com/esp8266/Arduino/issues/1532)
@ -166,11 +166,12 @@ void* memchr(const void* ptr, int value, size_t num)
}
// http://clc-wiki.net/wiki/C_standard_library:string.h:strspn
// Get span until any character in string
size_t strcspn(const char *str1, const char *str2)
{
size_t ret = 0;
while (*str1) {
if (strchr(str2, *str1)) {
if (strchr(str2, *str1)) { // Slow
return ret;
} else {
str1++;
@ -179,38 +180,18 @@ size_t strcspn(const char *str1, const char *str2)
}
return ret;
}
/*
* strcspn.c --
*
* Source code for the "strcspn" library routine.
*
* Copyright 1988 Regents of the University of California
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies. The University of California
* makes no representations about the suitability of this
* software for any purpose. It is provided "as is" without
* express or implied warranty.
*/
/*
size_t strcspn(const char* str1, const char* str2)
{
char c;
const char* p;
const char* s;
for (s = str1, c = *s; c != 0; s++, c = *s) {
for (p = str2; *p != 0; p++) {
if (c == *p) return s -str1;
}
}
return s -str1;
}
*/
#endif // ARDUINO_ESP8266_RELEASE_2_3_0
// Get span until single character in string
size_t strchrspn(const char *str1, int character)
{
size_t ret = 0;
char *start = (char*)str1;
char *end = strchr(str1, character);
if (end) ret = end - start;
return ret;
}
char* dtostrfd(double number, unsigned char prec, char *s)
{
return dtostrf(number, 1, prec, s);
@ -427,12 +408,21 @@ void SetSerialBaudrate(int baudrate)
}
delay(100);
Serial.flush();
Serial.begin(baudrate);
Serial.begin(baudrate, serial_config);
delay(10);
Serial.println();
}
}
uint32_t GetHash(const char *buffer, size_t size)
{
uint32_t hash = 0;
for (uint16_t i = 0; i <= size; i++) {
hash += (uint8_t)*buffer++ * (i +1);
}
return hash;
}
/*********************************************************************************************\
* Wifi
\*********************************************************************************************/
@ -538,20 +528,20 @@ void WifiConfig(uint8_t type)
restart_flag = 2;
}
else if (WIFI_SMARTCONFIG == wifi_config_type) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_1_SMARTCONFIG D_ACTIVE_FOR_3_MINUTES));
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_1_SMARTCONFIG " " D_ACTIVE_FOR_3_MINUTES));
WiFi.beginSmartConfig();
}
else if (WIFI_WPSCONFIG == wifi_config_type) {
if (WifiWpsConfigBegin()) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG D_ACTIVE_FOR_3_MINUTES));
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG " " D_ACTIVE_FOR_3_MINUTES));
} else {
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG D_FAILED_TO_START));
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_3_WPSCONFIG " " D_FAILED_TO_START));
wifi_config_counter = 3;
}
}
#ifdef USE_WEBSERVER
else if (WIFI_MANAGER == wifi_config_type) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_2_WIFIMANAGER D_ACTIVE_FOR_3_MINUTES));
AddLog_P(LOG_LEVEL_INFO, S_LOG_WIFI, PSTR(D_WCFG_2_WIFIMANAGER " " D_ACTIVE_FOR_3_MINUTES));
WifiManagerBegin();
}
#endif // USE_WEBSERVER
@ -568,10 +558,11 @@ void WifiBegin(uint8_t flag)
#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 // (!strncmp_P(ESP.getSdkVersion(),PSTR("1.5.3"),5))
AddLog_P(LOG_LEVEL_DEBUG, S_LOG_WIFI, PSTR(D_PATCH_ISSUE_2186));
WiFi.mode(WIFI_OFF); // See https://github.com/esp8266/Arduino/issues/2186
WiFi.mode(WIFI_OFF); // See https://github.com/esp8266/Arduino/issues/2186
#endif
WiFi.disconnect();
WiFi.disconnect(true); // Delete SDK wifi config
delay(200);
WiFi.mode(WIFI_STA); // Disable AP mode
if (Settings.sleep) {
WiFi.setSleepMode(WIFI_LIGHT_SLEEP); // Allow light sleep during idle times
@ -707,6 +698,7 @@ void WifiCheck(uint8_t param)
if (WIFI_SMARTCONFIG == wifi_config_type) {
WiFi.stopSmartConfig();
}
SettingsSdkErase();
restart_flag = 2;
}
} else {
@ -1011,23 +1003,23 @@ uint32_t daylight_saving_time = 0;
uint32_t standard_time = 0;
uint32_t ntp_time = 0;
uint32_t midnight = 1451602800;
uint32_t restart_time = 0;
uint8_t midnight_now = 0;
uint8_t ntp_sync_minute = 0;
String GetBuildDateAndTime()
{
// "2017-03-07T11:08:02" - ISO8601:2004
char bdt[21];
char *str;
char *p;
char *smonth;
char mdate[] = __DATE__; // "Mar 7 2017"
int month;
int day;
int year;
char *smonth = mdate;
int day = 0;
int year = 0;
// sscanf(mdate, "%s %d %d", bdt, &day, &year); // Not implemented in 2.3.0 and probably too many code
// sscanf(mdate, "%s %d %d", bdt, &day, &year); // Not implemented in 2.3.0 and probably too much code
byte i = 0;
for (str = strtok_r(mdate, " ", &p); str && i < 3; str = strtok_r(NULL, " ", &p)) {
for (char *str = strtok_r(mdate, " ", &p); str && i < 3; str = strtok_r(NULL, " ", &p)) {
switch (i++) {
case 0: // Month
smonth = str;
@ -1039,32 +1031,71 @@ String GetBuildDateAndTime()
year = atoi(str);
}
}
month = (strstr(kMonthNamesEnglish, smonth) -kMonthNamesEnglish) /3 +1;
int month = (strstr(kMonthNamesEnglish, smonth) -kMonthNamesEnglish) /3 +1;
snprintf_P(bdt, sizeof(bdt), PSTR("%d" D_YEAR_MONTH_SEPARATOR "%02d" D_MONTH_DAY_SEPARATOR "%02d" D_DATE_TIME_SEPARATOR "%s"), year, month, day, __TIME__);
return String(bdt);
}
String GetDateAndTime()
String GetDateAndTime(byte time_type)
{
// enum GetDateAndTimeOptions { DT_LOCAL, DT_UTC, DT_RESTART, DT_UPTIME };
// "2017-03-07T11:08:02" - ISO8601:2004
char dt[21];
TIME_T tmpTime;
snprintf_P(dt, sizeof(dt), PSTR("%04d" D_YEAR_MONTH_SEPARATOR "%02d" D_MONTH_DAY_SEPARATOR "%02d" D_DATE_TIME_SEPARATOR "%02d" D_HOUR_MINUTE_SEPARATOR "%02d" D_MINUTE_SECOND_SEPARATOR "%02d"),
RtcTime.year, RtcTime.month, RtcTime.day_of_month, RtcTime.hour, RtcTime.minute, RtcTime.second);
if (DT_UPTIME == time_type) {
if (restart_time) {
BreakTime(utc_time - restart_time, tmpTime);
} else {
BreakTime(uptime, tmpTime);
}
// "P128DT14H35M44S" - ISO8601:2004 - https://en.wikipedia.org/wiki/ISO_8601 Durations
// snprintf_P(dt, sizeof(dt), PSTR("P%dDT%02dH%02dM%02dS"), ut.days, ut.hour, ut.minute, ut.second);
// "128 14:35:44" - OpenVMS
// "128T14:35:44" - Tasmota
snprintf_P(dt, sizeof(dt), PSTR("%dT%02d:%02d:%02d"),
tmpTime.days, tmpTime.hour, tmpTime.minute, tmpTime.second);
} else {
switch (time_type) {
case DT_UTC:
BreakTime(utc_time, tmpTime);
tmpTime.year += 1970;
break;
case DT_RESTART:
if (restart_time == 0) {
return "";
}
BreakTime(restart_time, tmpTime);
tmpTime.year += 1970;
break;
default:
tmpTime = RtcTime;
}
snprintf_P(dt, sizeof(dt), PSTR("%04d-%02d-%02dT%02d:%02d:%02d"),
tmpTime.year, tmpTime.month, tmpTime.day_of_month, tmpTime.hour, tmpTime.minute, tmpTime.second);
}
return String(dt);
}
String GetUtcDateAndTime()
String GetUptime()
{
// "2017-03-07T11:08:02" - ISO8601:2004
char dt[21];
char dt[16];
TIME_T tmpTime;
BreakTime(utc_time, tmpTime);
tmpTime.year += 1970;
TIME_T ut;
snprintf_P(dt, sizeof(dt), PSTR("%04d" D_YEAR_MONTH_SEPARATOR "%02d" D_MONTH_DAY_SEPARATOR "%02d" D_DATE_TIME_SEPARATOR "%02d" D_HOUR_MINUTE_SEPARATOR "%02d" D_MINUTE_SECOND_SEPARATOR "%02d"),
tmpTime.year, tmpTime.month, tmpTime.day_of_month, tmpTime.hour, tmpTime.minute, tmpTime.second);
if (restart_time) {
BreakTime(utc_time - restart_time, ut);
} else {
BreakTime(uptime, ut);
}
// "P128DT14H35M44S" - ISO8601:2004 - https://en.wikipedia.org/wiki/ISO_8601 Durations
// snprintf_P(dt, sizeof(dt), PSTR("P%dDT%02dH%02dM%02dS"), ut.days, ut.hour, ut.minute, ut.second);
// "128 14:35:44" - OpenVMS
// "128T14:35:44" - Tasmota
snprintf_P(dt, sizeof(dt), PSTR("%dT%02d:%02d:%02d"),
ut.days, ut.hour, ut.minute, ut.second);
return String(dt);
}
@ -1087,6 +1118,7 @@ void BreakTime(uint32_t time_input, TIME_T &tm)
time /= 60; // now it is hours
tm.hour = time % 24;
time /= 24; // now it is days
tm.days = time;
tm.day_of_week = ((time + 4) % 7) + 1; // Sunday is day 1
year = 0;
@ -1159,34 +1191,34 @@ uint32_t MakeTime(TIME_T &tm)
uint32_t RuleToTime(TimeChangeRule r, int yr)
{
TIME_T tm;
uint32_t t;
uint8_t m;
uint8_t w; // temp copies of r.month and r.week
TIME_T tm;
uint32_t t;
uint8_t m;
uint8_t w; // temp copies of r.month and r.week
m = r.month;
w = r.week;
if (0 == w) { // Last week = 0
if (++m > 12) { // for "Last", go to the next month
m = 1;
yr++;
}
w = 1; // and treat as first week of next month, subtract 7 days later
m = r.month;
w = r.week;
if (0 == w) { // Last week = 0
if (++m > 12) { // for "Last", go to the next month
m = 1;
yr++;
}
w = 1; // and treat as first week of next month, subtract 7 days later
}
tm.hour = r.hour;
tm.minute = 0;
tm.second = 0;
tm.day_of_month = 1;
tm.month = m;
tm.year = yr - 1970;
t = MakeTime(tm); // First day of the month, or first day of next month for "Last" rules
BreakTime(t, tm);
t += (7 * (w - 1) + (r.dow - tm.day_of_week + 7) % 7) * SECS_PER_DAY;
if (0 == r.week) {
t -= 7 * SECS_PER_DAY; //back up a week if this is a "Last" rule
}
return t;
tm.hour = r.hour;
tm.minute = 0;
tm.second = 0;
tm.day_of_month = 1;
tm.month = m;
tm.year = yr - 1970;
t = MakeTime(tm); // First day of the month, or first day of next month for "Last" rules
BreakTime(t, tm);
t += (7 * (w - 1) + (r.dow - tm.day_of_week + 7) % 7) * SECS_PER_DAY;
if (0 == r.week) {
t -= 7 * SECS_PER_DAY; // back up a week if this is a "Last" rule
}
return t;
}
String GetTime(int type)
@ -1214,43 +1246,35 @@ uint32_t Midnight()
boolean MidnightNow()
{
boolean mnflg = midnight_now;
if (mnflg) {
midnight_now = 0;
}
if (mnflg) midnight_now = 0;
return mnflg;
}
void RtcSecond()
{
byte ntpsync;
uint32_t stdoffset;
uint32_t dstoffset;
TIME_T tmpTime;
ntpsync = 0;
if (RtcTime.year < 2016) {
if (WL_CONNECTED == WiFi.status()) {
ntpsync = 1; // Initial NTP sync
}
} else {
if ((1 == RtcTime.minute) && (1 == RtcTime.second)) {
ntpsync = 1; // Hourly NTP sync at xx:01:01
}
}
if (ntpsync) {
if ((ntp_sync_minute > 59) && (RtcTime.minute > 2)) ntp_sync_minute = 1; // If sync prepare for a new cycle
uint8_t offset = (uptime < 30) ? RtcTime.second : (((ESP.getChipId() & 0xF) * 3) + 3) ; // First try ASAP to sync. If fails try once every 60 seconds based on chip id
if ((WL_CONNECTED == WiFi.status()) && (offset == RtcTime.second) && ((RtcTime.year < 2016) || (ntp_sync_minute == RtcTime.minute))) {
ntp_time = sntp_get_current_timestamp();
if (ntp_time) {
utc_time = ntp_time;
ntp_sync_minute = 60; // Sync so block further requests
if (restart_time == 0) {
restart_time = utc_time - uptime; // save first ntp time as restart time
}
BreakTime(utc_time, tmpTime);
RtcTime.year = tmpTime.year + 1970;
daylight_saving_time = RuleToTime(DaylightSavingTime, RtcTime.year);
standard_time = RuleToTime(StandardTime, RtcTime.year);
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION "(" D_UTC_TIME ") %s"), GetTime(0).c_str());
AddLog(LOG_LEVEL_DEBUG);
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION "(" D_DST_TIME ") %s"), GetTime(2).c_str());
AddLog(LOG_LEVEL_DEBUG);
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION "(" D_STD_TIME ") %s"), GetTime(3).c_str());
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_APPLICATION "(" D_UTC_TIME ") %s, (" D_DST_TIME ") %s, (" D_STD_TIME ") %s"),
GetTime(0).c_str(), GetTime(2).c_str(), GetTime(3).c_str());
AddLog(LOG_LEVEL_DEBUG);
} else {
ntp_sync_minute++; // Try again in next minute
}
}
utc_time++;
@ -1363,7 +1387,7 @@ void GetLog(byte idx, char** entry_pp, size_t* len_p)
do {
byte cur_idx = *it;
it++;
size_t tmp = strcspn(it, "\1");
size_t tmp = strchrspn(it, '\1');
tmp++; // Skip terminating '\1'
if (cur_idx == idx) { // Found the requested entry
len = tmp;
@ -1383,9 +1407,9 @@ void Syslog()
// Destroys log_data
char syslog_preamble[64]; // Hostname + Id
if ((static_cast<uint32_t>(syslog_host_addr) == 0) || ((millis() - syslog_host_refresh) > 60000)) {
WiFi.hostByName(Settings.syslog_host, syslog_host_addr);
syslog_host_refresh = millis();
if (syslog_host_hash != GetHash(Settings.syslog_host, strlen(Settings.syslog_host))) {
syslog_host_hash = GetHash(Settings.syslog_host, strlen(Settings.syslog_host));
WiFi.hostByName(Settings.syslog_host, syslog_host_addr); // If sleep enabled this might result in exception so try to do it once using hash
}
if (PortUdp.beginPacket(syslog_host_addr, Settings.syslog_port)) {
snprintf_P(syslog_preamble, sizeof(syslog_preamble), PSTR("%s ESP-"), my_hostname);
@ -1421,11 +1445,12 @@ void AddLog(byte loglevel)
{
char* it = web_log;
it++; // Skip web_log_index
it += strcspn(it, "\1"); // Skip log line
it += strchrspn(it, '\1'); // Skip log line
it++; // Skip delimiting "\1"
memmove(web_log, it, WEB_LOG_SIZE -(it-web_log)); // Move buffer forward to remove oldest log line
}
snprintf_P(web_log, sizeof(web_log), PSTR("%s%c%s%s\1"), web_log, web_log_index++, mxtime, log_data);
if (!web_log_index) web_log_index++; // Index 0 is not allowed as it is the end of char string
}
#endif // USE_WEBSERVER
if ((WL_CONNECTED == WiFi.status()) && (loglevel <= syslog_level)) {
@ -1449,6 +1474,20 @@ void AddLog_P(byte loglevel, const char *formatP, const char *formatP2)
AddLog(loglevel);
}
void AddLogSerial(byte loglevel, uint8_t *buffer, byte count)
{
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_SERIAL D_RECEIVED));
for (byte i = 0; i < count; i++) {
snprintf_P(log_data, sizeof(log_data), PSTR("%s %02X"), log_data, *(buffer++));
}
AddLog(loglevel);
}
void AddLogSerial(byte loglevel)
{
AddLogSerial(loglevel, (uint8_t*)serial_in_buffer, serial_in_byte_counter);
}
/*********************************************************************************************\
*
\*********************************************************************************************/

View File

@ -33,9 +33,12 @@
//#define MY_LANGUAGE en-GB // English in Great Britain. Enabled by Default
//#define MY_LANGUAGE es-AR // Spanish in Argentina
//#define MY_LANGUAGE fr-FR // French in France
//#define MY_LANGUAGE hu-HU // Hungarian in Hungary
//#define MY_LANGUAGE it-IT // Italian in Italy
//#define MY_LANGUAGE nl-NL // Dutch in the Netherlands
//#define MY_LANGUAGE pl-PL // Polish in Poland
//#define MY_LANGUAGE pt-PT // Portuguese in Portugal
//#define MY_LANGUAGE ru-RU // Russian in Russia
//#define MY_LANGUAGE zh-CN // Chinese (Simplified) in China
// -- Project -------------------------------------
@ -52,36 +55,37 @@
#define WIFI_SUBNETMASK "255.255.255.0" // [IpAddress3] If not using DHCP set Network mask
#define WIFI_DNS "192.168.2.27" // [IpAddress4] If not using DHCP set DNS IP address (might be equal to WIFI_GATEWAY)
#define STA_SSID1 "indebuurt1" // [Ssid1] Wifi SSID
#define STA_PASS1 "VnsqrtnrsddbrN" // [Password1] Wifi password
#define STA_SSID2 "indebuurt2" // [Ssid2] Optional alternate AP Wifi SSID
#define STA_PASS2 "VnsqrtnrsddbrN" // [Password2] Optional alternate AP Wifi password
#define STA_SSID1 "" // [Ssid1] Wifi SSID
#define STA_PASS1 "" // [Password1] Wifi password
#define STA_SSID2 "" // [Ssid2] Optional alternate AP Wifi SSID
#define STA_PASS2 "" // [Password2] Optional alternate AP Wifi password
#define WIFI_CONFIG_TOOL WIFI_WPSCONFIG // [WifiConfig] Default tool if wifi fails to connect
// (WIFI_RESTART, WIFI_SMARTCONFIG, WIFI_MANAGER, WIFI_WPSCONFIG, WIFI_RETRY, WIFI_WAIT)
// -- Syslog --------------------------------------
#define SYS_LOG_HOST "domus1" // [LogHost] (Linux) syslog host
#define SYS_LOG_HOST "" // [LogHost] (Linux) syslog host
#define SYS_LOG_PORT 514 // [LogPort] default syslog UDP port
#define SYS_LOG_LEVEL LOG_LEVEL_NONE // [SysLog]
#define SERIAL_LOG_LEVEL LOG_LEVEL_INFO // [SerialLog]
#define WEB_LOG_LEVEL LOG_LEVEL_INFO // [WebLog]
// -- Ota -----------------------------------------
#define OTA_URL "http://domus1:80/api/arduino/" PROJECT ".ino.bin" // [OtaUrl]
#define OTA_URL "http://sonoff.maddox.co.uk/tasmota/sonoff.ino.bin" // [OtaUrl]
// -- MQTT ----------------------------------------
#define MQTT_USE 1 // [SetOption3] Select default MQTT use (0 = Off, 1 = On)
// !!! TLS uses a LOT OF MEMORY (20k) so be careful to enable other options at the same time !!!
//#define USE_MQTT_TLS // EXPERIMENTAL Use TLS for MQTT connection (+53k code, +20k mem) - Disable by //
//#define USE_MQTT_TLS // EXPERIMENTAL Use TLS for MQTT connection (+53k code, +15k mem) - Disable by //
// Needs Fingerprint, TLS Port, UserId and Password
#ifdef USE_MQTT_TLS
#define MQTT_HOST "m20.cloudmqtt.com" // [MqttHost]
// #define MQTT_HOST "m20.cloudmqtt.com" // [MqttHost]
#define MQTT_HOST "" // [MqttHost]
#define MQTT_FINGERPRINT "A5 02 FF 13 99 9F 8B 39 8E F1 83 4F 11 23 65 0B 32 36 FC 07" // [MqttFingerprint]
#define MQTT_PORT 20123 // [MqttPort] MQTT TLS port
#define MQTT_USER "cloudmqttuser" // [MqttUser] Mandatory user
#define MQTT_PASS "cloudmqttpassword" // [MqttPassword] Mandatory password
#else
#define MQTT_HOST "domus1" // [MqttHost]
#define MQTT_HOST "" // [MqttHost]
#define MQTT_PORT 1883 // [MqttPort] MQTT port (10123 on CloudMQTT)
#define MQTT_USER "DVES_USER" // [MqttUser] Optional user
#define MQTT_PASS "DVES_PASS" // [MqttPassword] Optional password
@ -169,11 +173,10 @@
#define PRESSURE_RESOLUTION 1 // [PressRes] Maximum number of decimals (0 - 3) showing sensor Pressure
#define ENERGY_RESOLUTION 3 // [EnergyRes] Maximum number of decimals (0 - 5) showing energy usage in kWh
// -- Sensor code selection -----------------------
// -- Internal Analog input -----------------------
#define USE_ADC_VCC // Display Vcc in Power status. Disable for use as Analog input on selected devices
#define USE_PZEM004T // Add support for PZEM004T Energy monitor (+2k code)
// -- One wire sensors ----------------------------
// WARNING: Select none for default one DS18B20 sensor or enable one of the following two options for multiple sensors
//#define USE_DS18x20 // Optional for more than one DS18x20 sensors with id sort, single scan and read retry (+1k3 code)
//#define USE_DS18x20_LEGACY // Optional for more than one DS18x20 sensors with dynamic scan using library OneWire (+1k5 code)
@ -182,42 +185,29 @@
#define USE_I2C // I2C using library wire (+10k code, 0k2 mem, 124 iram)
#ifdef USE_I2C
#define USE_SHT // Add I2C emulating code for SHT1X sensor (+1k4 code)
#define USE_SHT3X // Add I2C code for SHT3x sensor (+0k6 code)
#define USE_SHT3X // Add I2C code for SHT3x or SHTC3 sensor (+0k7 code)
#define USE_HTU // Add I2C code for HTU21/SI7013/SI7020/SI7021 sensor (+1k5 code)
#define USE_BMP // Add I2C code for BMP085/BMP180/BMP280/BME280 sensor (+4k code)
#define USE_BME680 // Add additional support for BME680 sensor using Adafruit Sensor and BME680 libraries (+6k code)
// #define USE_BME680 // Add additional support for BME680 sensor using Adafruit Sensor and BME680 libraries (+6k code)
#define USE_BH1750 // Add I2C code for BH1750 sensor (+0k5 code)
// #define USE_VEML6070 // Add I2C code for VEML6070 sensor (+0k5 code)
// #define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Adafruit TSL2561 Arduino (+1k2 code)
// #define USE_TSL2561 // Add I2C code for TSL2561 sensor using library Joba_Tsl2561 (+2k3 code)
// #define USE_ADS1115 // Add I2C code for ADS1115 16 bit A/D converter based on Adafruit ADS1x15 library (no library needed) (+0k7 code)
// #define USE_ADS1115_I2CDEV // Add I2C code for ADS1115 16 bit A/D converter using library i2cdevlib-Core and i2cdevlib-ADS1115 (+2k code)
// #define USE_INA219 // Add I2C code for INA219 Low voltage and current sensor (+1k code)
// #define USE_DISPLAY // Add I2C Display Support for LCD, Oled and up to eigth Matrices (+19k code)
#define MTX_ADDRESS1 0x71 // [DisplayAddress[1]] I2C address of first 8x8 matrix module
#define MTX_ADDRESS2 0x74 // [DisplayAddress[2]] I2C address of second 8x8 matrix module
#define MTX_ADDRESS3 0x75 // [DisplayAddress[3]] I2C address of third 8x8 matrix module
#define MTX_ADDRESS4 0x72 // [DisplayAddress[4]] I2C address of fourth 8x8 matrix module
#define MTX_ADDRESS5 0x73 // [DisplayAddress[5]] I2C address of fifth 8x8 matrix module
#define MTX_ADDRESS6 0x76 // [DisplayAddress[6]] I2C address of sixth 8x8 matrix module
#define MTX_ADDRESS7 0x00 // [DisplayAddress[7]] I2C address of seventh 8x8 matrix module
#define MTX_ADDRESS8 0x00 // [DisplayAddress[8]] I2C address of eigth 8x8 matrix module
// #define USE_MGS // Add I2C code for Xadow and Grove Mutichannel Gas sensor using library Multichannel_Gas_Sensor (+10k code)
#define MGS_SENSOR_ADDR 0x04 // Default Mutichannel Gas sensor i2c address
#endif // USE_I2C
//#define USE_SPI // SPI using library TasmotaTFT
#ifdef USE_SPI
#ifndef USE_DISPLAY
#define USE_DISPLAY // Add SPI Display support for 320x240 and 480x320 TFT
#endif
#endif // USE_SPI
// -- Carbon dioxide (CO2) sensors ----------------
// -- Serial sensors ------------------------------
#define USE_MHZ19 // Add support for MH-Z19 CO2 sensor (+2k code)
#define USE_SENSEAIR // Add support for SenseAir K30, K70 and S8 CO2 sensor (+2k3 code)
#define CO2_LOW 800 // Below this CO2 value show green light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1)
#define CO2_HIGH 1200 // Above this CO2 value show red light (needs PWM or WS2812 RG(B) led and enable with SetOption18 1)
#define USE_PMS5003 // Add support for PMS5003 and PMS7003 particle concentration sensor (+1k3 code)
#define USE_PZEM004T // Add support for PZEM004T Energy monitor (+2k code)
// -- Low level interface devices -----------------
#define USE_IR_REMOTE // Send IR remote commands using library IRremoteESP8266 and ArduinoJson (+4k code, 0k3 mem, 48 iram)
// #define USE_IR_HVAC // Support for HVAC system using IR (+2k code)
#define USE_IR_RECEIVE // Support for IR receiver (+5k5 code, 264 iram)
@ -226,7 +216,13 @@
#define USE_WS2812_CTYPE 1 // WS2812 Color type (0 - RGB, 1 - GRB, 2 - RGBW, 3 - GRBW)
// #define USE_WS2812_DMA // DMA supports only GPIO03 (= Serial RXD) (+1k mem). When USE_WS2812_DMA is enabled expect Exceptions on Pow
#define USE_ARILUX_RF // Add support for Arilux RF remote controller (+0k8 code)
#define USE_ARILUX_RF // Add support for Arilux RF remote controller (+0k8 code, 252 iram (non 2.3.0))
/*********************************************************************************************\
* Select all sensors - overrides above undefines!!
\*********************************************************************************************/
//#define USE_ALL_SENSORS // Create sonoff-xxl with all sensors enabled (See sonoff_post.h for selected sensors)
/*********************************************************************************************\
* Compile a minimal version if upgrade memory gets tight ONLY TO BE USED FOR UPGRADE STEP 1!

View File

@ -85,7 +85,7 @@ const char HTTP_HEAD_STYLE[] PROGMEM =
"textarea{resize:none;width:98%;height:318px;padding:5px;overflow:auto;}"
"body{text-align:center;font-family:verdana;}"
"td{padding:0px;}"
"button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;-webkit-transition-duration:0.4s;transition-duration:0.4s;}"
"button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;-webkit-transition-duration:0.4s;transition-duration:0.4s;cursor:pointer;}"
"button:hover{background-color:#006cba;}"
"a{text-decoration:none;}"
".p{float:left;text-align:left;}"
@ -347,6 +347,7 @@ void StartWebserver(int type, IPAddress ipweb)
WebServer->on("/up", HandleUpgradeFirmware);
WebServer->on("/u1", HandleUpgradeFirmwareStart); // OTA
WebServer->on("/u2", HTTP_POST, HandleUploadDone, HandleUploadLoop);
WebServer->on("/u2", HTTP_OPTIONS, HandlePreflightRequest);
WebServer->on("/cm", HandleHttpCommand);
WebServer->on("/cs", HandleConsole);
WebServer->on("/ax", HandleAjaxConsoleRefresh);
@ -576,7 +577,7 @@ void HandleAjaxStatusRefresh()
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{t}"));
XsnsCall(FUNC_WEB_APPEND);
if (D_DECIMAL_SEPARATOR[0] != '.') {
for (int i = 0; i < strlen(mqtt_data); i++) {
for (uint16_t i = 0; i < strlen(mqtt_data); i++) {
if ('.' == mqtt_data[i]) {
mqtt_data[i] = D_DECIMAL_SEPARATOR[0];
}
@ -708,8 +709,7 @@ void HandleModuleConfiguration()
for (byte j = 0; j < GPIO_SENSOR_END; j++) {
if (!GetUsedInModule(j, cmodule.gp.io)) {
snprintf_P(stemp, sizeof(stemp), kSensors[j]);
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SCRIPT_MODULE2, j, j, stemp);
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SCRIPT_MODULE2, j, j, GetTextIndexed(stemp, sizeof(stemp), j, kSensorNames));
page += mqtt_data;
}
}
@ -866,8 +866,7 @@ void HandleMqttConfiguration()
page += FPSTR(HTTP_HEAD_STYLE);
page += FPSTR(HTTP_FORM_MQTT);
char str[sizeof(Settings.mqtt_client)];
GetMqttClient(str, MQTT_CLIENT_ID, sizeof(Settings.mqtt_client));
page.replace(F("{m0"), str);
page.replace(F("{m0"), GetMqttClient(str, MQTT_CLIENT_ID, sizeof(Settings.mqtt_client)));
page.replace(F("{m1"), Settings.mqtt_host);
page.replace(F("{m2"), String(Settings.mqtt_port));
page.replace(F("{m3"), Settings.mqtt_client);
@ -942,7 +941,7 @@ void HandleOtherConfiguration()
page += FPSTR(HTTP_HEAD_STYLE);
page += FPSTR(HTTP_FORM_OTHER);
page.replace(F("{r1"), (Settings.flag.mqtt_enabled) ? F(" checked") : F(""));
uint8_t maxfn = (devices_present > MAX_FRIENDLYNAMES) ? MAX_FRIENDLYNAMES : devices_present;
uint8_t maxfn = (devices_present > MAX_FRIENDLYNAMES) ? MAX_FRIENDLYNAMES : (!devices_present) ? 1 : devices_present;
for (byte i = 0; i < maxfn; i++) {
page += FPSTR(HTTP_FORM_OTHER2);
page.replace(F("{1"), String(i +1));
@ -1263,7 +1262,7 @@ void HandleUploadDone()
WifiConfigCounter();
restart_flag = 0;
mqtt_retry_counter = 0;
MqttRetryCounter(0);
String page = FPSTR(HTTP_HEAD);
page.replace(F("{v}"), FPSTR(S_INFORMATION));
@ -1325,13 +1324,14 @@ void HandleUploadLoop()
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_UPLOAD D_FILE " %s ..."), upload.filename.c_str());
AddLog(LOG_LEVEL_INFO);
if (!upload_file_type) {
mqtt_retry_counter = 60;
MqttRetryCounter(60);
#ifdef USE_EMULATION
UdpDisconnect();
#endif // USE_EMULATION
if (Settings.flag.mqtt_enabled) {
MqttClient.disconnect();
}
#ifdef USE_ARILUX_RF
AriluxRfDisable(); // Prevent restart exception on Arilux Interrupt routine
#endif // USE_ARILUX_RF
if (Settings.flag.mqtt_enabled) MqttDisconnect();
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace)) { //start with max available size
upload_error = 2;
@ -1407,7 +1407,7 @@ void HandleUploadLoop()
}
} else if (UPLOAD_FILE_ABORTED == upload.status) {
restart_flag = 0;
mqtt_retry_counter = 0;
MqttRetryCounter(0);
upload_error = 7;
if (!upload_file_type) {
Update.end();
@ -1416,6 +1416,14 @@ void HandleUploadLoop()
delay(0);
}
void HandlePreflightRequest()
{
WebServer->sendHeader(F("Access-Control-Allow-Origin"), F("*"));
WebServer->sendHeader(F("Access-Control-Allow-Methods"), F("GET, POST"));
WebServer->sendHeader(F("Access-Control-Allow-Headers"), F("authorization"));
WebServer->send(200, FPSTR(HDR_CTYPE_HTML), "");
}
void HandleHttpCommand()
{
if (HttpUser()) {
@ -1439,11 +1447,8 @@ void HandleHttpCommand()
String message = F("{\"" D_RSLT_WARNING "\":\"");
if (valid) {
byte curridx = web_log_index;
char tmp[100];
WebGetArg("cmnd", tmp, sizeof(tmp));
if (strlen(tmp)) {
// snprintf_P(svalue, sizeof(svalue), tmp); // Processes FullTopic %p
strlcpy(svalue, tmp, sizeof(svalue)); // Fixed 5.8.0b
WebGetArg("cmnd", svalue, sizeof(svalue));
if (strlen(svalue)) {
// byte syslog_now = syslog_level;
// syslog_level = 0; // Disable UDP syslog to not trigger hardware WDT - Seems to work fine since 5.7.1d (global logging)
ExecuteCommand(svalue);
@ -1510,11 +1515,8 @@ void HandleAjaxConsoleRefresh()
byte cflg = 1;
byte counter = 0; // Initial start, should never be 0 again
char tmp[100];
WebGetArg("c1", tmp, sizeof(tmp));
if (strlen(tmp)) {
// snprintf_P(svalue, sizeof(svalue), tmp); // Processes FullTopic %p
strlcpy(svalue, tmp, sizeof(svalue)); // Fixed 5.8.0b
WebGetArg("c1", svalue, sizeof(svalue));
if (strlen(svalue)) {
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_COMMAND "%s"), svalue);
AddLog(LOG_LEVEL_INFO);
// byte syslog_now = syslog_level;
@ -1523,9 +1525,9 @@ void HandleAjaxConsoleRefresh()
// syslog_level = syslog_now;
}
WebGetArg("c2", tmp, sizeof(tmp));
if (strlen(tmp)) {
counter = atoi(tmp);
WebGetArg("c2", svalue, sizeof(svalue));
if (strlen(svalue)) {
counter = atoi(svalue);
}
byte last_reset_web_log_flag = reset_web_log_flag;
@ -1594,7 +1596,7 @@ void HandleInformation()
func += F(D_PROGRAM_VERSION "}2"); func += my_version;
func += F("}1" D_BUILD_DATE_AND_TIME "}2"); func += GetBuildDateAndTime();
func += F("}1" D_CORE_AND_SDK_VERSION "}2" ARDUINO_ESP8266_RELEASE "/"); func += String(ESP.getSdkVersion());
func += F("}1" D_UPTIME "}2"); func += String(uptime); func += F(" Hours");
func += F("}1" D_UPTIME "}2"); func += GetDateAndTime(DT_UPTIME);
snprintf_P(stopic, sizeof(stopic), PSTR(" at %X"), GetSettingsAddress());
func += F("}1" D_FLASH_WRITE_COUNT "}2"); func += String(Settings.save_flag); func += stopic;
func += F("}1" D_BOOT_COUNT "}2"); func += String(Settings.bootcount);
@ -1629,7 +1631,7 @@ void HandleInformation()
func += F("}1" D_MQTT_USER "}2"); func += Settings.mqtt_user;
func += F("}1" D_MQTT_TOPIC "}2"); func += Settings.mqtt_topic;
func += F("}1" D_MQTT_GROUP_TOPIC "}2"); func += Settings.mqtt_grptopic;
GetTopic_P(stopic, CMND, Settings.mqtt_topic, "");
GetTopic_P(stopic, CMND, mqtt_topic, "");
func += F("}1" D_MQTT_FULL_TOPIC "}2"); func += stopic;
} else {

730
sonoff/xdrv_00_mqtt.ino Normal file
View File

@ -0,0 +1,730 @@
/*
xdrv_00_mqtt.ino - mqtt support for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends
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/>.
*/
/*********************************************************************************************\
* Select only ONE of the defines below - Not supported yet
\*********************************************************************************************/
// Default MQTT driver for both non-TLS and TLS connections. Blocks network if MQTT server is unavailable.
#define USE_MQTT_CLIENT 1 // Use PubSubClient library
// Replaces PubSubClient solving network hangs when MQTT server is unavailable. No TLS support
//#define USE_MQTT_CLIENT 2 // Use (patched) esp-mqtt-arduino library (+4k8 code) - non-TLS only
// Only TLS support. Unstable due to lack of memory
//#define USE_MQTT_CLIENT 3 // Use ESP8266MQTTClient library (+52k code, +15k mem) - TLS only and unstable
/*********************************************************************************************/
enum MqttCommands {
CMND_MQTTHOST, CMND_MQTTPORT, CMND_MQTTRETRY, CMND_STATETEXT, CMND_MQTTFINGERPRINT, CMND_MQTTCLIENT,
CMND_MQTTUSER, CMND_MQTTPASSWORD, CMND_FULLTOPIC, CMND_PREFIX, CMND_GROUPTOPIC, CMND_TOPIC,
CMND_BUTTONTOPIC, CMND_SWITCHTOPIC, CMND_BUTTONRETAIN, CMND_SWITCHRETAIN, CMND_POWERRETAIN, CMND_SENSORRETAIN };
const char kMqttCommands[] PROGMEM =
D_CMND_MQTTHOST "|" D_CMND_MQTTPORT "|" D_CMND_MQTTRETRY "|" D_CMND_STATETEXT "|" D_CMND_MQTTFINGERPRINT "|" D_CMND_MQTTCLIENT "|"
D_CMND_MQTTUSER "|" D_CMND_MQTTPASSWORD "|" D_CMND_FULLTOPIC "|" D_CMND_PREFIX "|" D_CMND_GROUPTOPIC "|" D_CMND_TOPIC "|"
D_CMND_BUTTONTOPIC "|" D_CMND_SWITCHTOPIC "|" D_CMND_BUTTONRETAIN "|" D_CMND_SWITCHRETAIN "|" D_CMND_POWERRETAIN "|" D_CMND_SENSORRETAIN ;
uint8_t mqtt_retry_counter = 0; // MQTT connection retry counter
uint8_t mqtt_connection_flag = 2; // MQTT connection messages flag
/*********************************************************************************************\
* MQTT driver specific code need to provide the following functions:
*
* bool MqttIsConnected()
* void MqttDisconnect()
* void MqttSubscribeLib(char *topic)
* bool MqttPublishLib(const char* topic, boolean retained)
* void MqttCheckConnection()
* void MqttLoop()
\*********************************************************************************************/
#if (1 == USE_MQTT_CLIENT) /*****************************************************************/
#include <PubSubClient.h>
// Max message size calculated by PubSubClient is (MQTT_MAX_PACKET_SIZE < 5 + 2 + strlen(topic) + plength)
#if (MQTT_MAX_PACKET_SIZE -TOPSZ -7) < MIN_MESSZ // If the max message size is too small, throw an error at compile time. See PubSubClient.cpp line 359
#error "MQTT_MAX_PACKET_SIZE is too small in libraries/PubSubClient/src/PubSubClient.h, increase it to at least 1000"
#endif
PubSubClient MqttClient(EspClient);
bool MqttIsConnected()
{
return MqttClient.connected();
}
void MqttDisconnect()
{
MqttClient.disconnect();
}
void MqttSubscribeLib(char *topic)
{
MqttClient.subscribe(topic);
MqttClient.loop(); // Solve LmacRxBlk:1 messages
}
bool MqttPublishLib(const char* topic, boolean retained)
{
return MqttClient.publish(topic, mqtt_data, retained);
}
void MqttCheckConnection()
{
if (Settings.flag.mqtt_enabled) {
if (!MqttIsConnected()) {
if (!mqtt_retry_counter) {
MqttReconnect();
} else {
mqtt_retry_counter--;
}
}
} else {
if (!mqtt_retry_counter) {
MqttReconnect();
}
}
}
void MqttLoop()
{
MqttClient.loop();
}
#elif (2 == USE_MQTT_CLIENT) /***************************************************************/
#include <MQTT.h>
MQTT *MqttClient = NULL;
bool MqttIsConnected()
{
bool result = false;
if (MqttClient) result = (MqttClient->isConnected() && !mqtt_retry_counter);
return result;
}
void MqttDisconnect()
{
if (MqttClient) MqttClient->disconnect();
}
void MqttMyDataCb(const char* topic, uint32_t topic_len, const char *data, uint32_t data_len)
{
char topicCpy[topic_len];
memcpy(topicCpy, topic, topic_len);
topicCpy[topic_len] = 0;
MqttDataHandler((char*)topicCpy, (byte*)data, data_len);
}
void MqttMyNoneCb()
{
// Do nothing
}
void MqttSubscribeLib(char *topic)
{
MqttClient->subscribe(topic);
}
bool MqttPublishLib(const char* topic, boolean retained)
{
return MqttClient->publish(topic, mqtt_data, strlen(mqtt_data), 0, retained);
}
void MqttCheckConnection()
{
if (Settings.flag.mqtt_enabled) {
if (!MqttIsConnected()) {
if (!mqtt_retry_counter) {
MqttReconnect();
} else {
mqtt_retry_counter--;
}
}
MqttReconnect();
} else {
if (!mqtt_retry_counter) {
MqttReconnect();
}
}
}
void MqttLoop()
{
// No action
}
#elif (3 == USE_MQTT_CLIENT) /***************************************************************/
#include <ESP8266MQTTClient.h>
MQTTClient MqttClient;
bool MqttIsConnected()
{
return true;
}
void MqttDisconnect()
{
// No action
}
void MqttSubscribeLib(char *topic)
{
MqttClient.subscribe(topic, 0);
}
bool MqttPublishLib(const char* topic, boolean retained)
{
return MqttClient.publish(topic, mqtt_data, 0, retained);
}
void MqttCheckConnection()
{
if (Settings.flag.mqtt_enabled) {
MqttReconnect();
} else {
if (!mqtt_retry_counter) {
MqttReconnect();
}
}
}
void MqttLoop()
{
MqttClient.handle();
}
#endif // USE_MQTT_CLIENT
/*********************************************************************************************/
void MqttRetryCounter(uint8_t value)
{
mqtt_retry_counter = value;
}
void MqttSubscribe(char *topic)
{
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_SUBSCRIBE_TO " %s"), topic);
AddLog(LOG_LEVEL_DEBUG);
MqttSubscribeLib(topic);
}
void MqttPublishDirect(const char* topic, boolean retained)
{
char sretained[CMDSZ];
char slog_type[10];
sretained[0] = '\0';
snprintf_P(slog_type, sizeof(slog_type), PSTR(D_LOG_RESULT));
if (Settings.flag.mqtt_enabled) {
if (MqttPublishLib(topic, retained)) {
snprintf_P(slog_type, sizeof(slog_type), PSTR(D_LOG_MQTT));
if (retained) {
snprintf_P(sretained, sizeof(sretained), PSTR(" (" D_RETAINED ")"));
}
}
}
snprintf_P(log_data, sizeof(log_data), PSTR("%s%s = %s"), slog_type, (Settings.flag.mqtt_enabled) ? topic : strrchr(topic,'/')+1, mqtt_data);
if (strlen(log_data) >= (sizeof(log_data) - strlen(sretained) -1)) {
log_data[sizeof(log_data) - strlen(sretained) -5] = '\0';
snprintf_P(log_data, sizeof(log_data), PSTR("%s ..."), log_data);
}
snprintf_P(log_data, sizeof(log_data), PSTR("%s%s"), log_data, sretained);
AddLog(LOG_LEVEL_INFO);
if (Settings.ledstate &0x04) {
blinks++;
}
}
void MqttPublish(const char* topic, boolean retained)
{
char *me;
if (!strcmp(Settings.mqtt_prefix[0],Settings.mqtt_prefix[1])) {
me = strstr(topic,Settings.mqtt_prefix[0]);
if (me == topic) {
mqtt_cmnd_publish += 8;
}
}
MqttPublishDirect(topic, retained);
}
void MqttPublish(const char* topic)
{
MqttPublish(topic, false);
}
void MqttPublishPrefixTopic_P(uint8_t prefix, const char* subtopic, boolean retained)
{
/* prefix 0 = cmnd using subtopic
* prefix 1 = stat using subtopic
* prefix 2 = tele using subtopic
* prefix 4 = cmnd using subtopic or RESULT
* prefix 5 = stat using subtopic or RESULT
* prefix 6 = tele using subtopic or RESULT
*/
char romram[33];
char stopic[TOPSZ];
snprintf_P(romram, sizeof(romram), ((prefix > 3) && !Settings.flag.mqtt_response) ? S_RSLT_RESULT : subtopic);
for (byte i = 0; i < strlen(romram); i++) {
romram[i] = toupper(romram[i]);
}
prefix &= 3;
GetTopic_P(stopic, prefix, mqtt_topic, romram);
MqttPublish(stopic, retained);
}
void MqttPublishPrefixTopic_P(uint8_t prefix, const char* subtopic)
{
MqttPublishPrefixTopic_P(prefix, subtopic, false);
}
void MqttPublishPowerState(byte device)
{
char stopic[TOPSZ];
char scommand[33];
if ((device < 1) || (device > devices_present)) {
device = 1;
}
GetPowerDevice(scommand, device, sizeof(scommand));
GetTopic_P(stopic, STAT, mqtt_topic, (Settings.flag.mqtt_response) ? scommand : S_RSLT_RESULT);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, scommand, GetStateText(bitRead(power, device -1)));
MqttPublish(stopic);
GetTopic_P(stopic, STAT, mqtt_topic, scommand);
snprintf_P(mqtt_data, sizeof(mqtt_data), GetStateText(bitRead(power, device -1)));
MqttPublish(stopic, Settings.flag.mqtt_power_retain);
}
void MqttPublishPowerBlinkState(byte device)
{
char scommand[33];
if ((device < 1) || (device > devices_present)) {
device = 1;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s\":\"" D_JSON_BLINK " %s\"}"),
GetPowerDevice(scommand, device, sizeof(scommand)), GetStateText(bitRead(blink_mask, device -1)));
MqttPublishPrefixTopic_P(RESULT_OR_STAT, S_RSLT_POWER);
}
/*********************************************************************************************/
void MqttConnected()
{
char stopic[TOPSZ];
if (Settings.flag.mqtt_enabled) {
// Satisfy iobroker (#299)
mqtt_data[0] = '\0';
MqttPublishPrefixTopic_P(CMND, S_RSLT_POWER);
GetTopic_P(stopic, CMND, mqtt_topic, PSTR("#"));
MqttSubscribe(stopic);
if (strstr(Settings.mqtt_fulltopic, MQTT_TOKEN_TOPIC) != NULL) {
GetTopic_P(stopic, CMND, Settings.mqtt_grptopic, PSTR("#"));
MqttSubscribe(stopic);
fallback_topic_flag = 1;
GetTopic_P(stopic, CMND, mqtt_client, PSTR("#"));
fallback_topic_flag = 0;
MqttSubscribe(stopic);
}
XdrvCall(FUNC_MQTT_SUBSCRIBE);
}
if (mqtt_connection_flag) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_CMND_MODULE "\":\"%s\",\"" D_JSON_VERSION "\":\"%s\",\"" D_JSON_FALLBACKTOPIC "\":\"%s\",\"" D_CMND_GROUPTOPIC "\":\"%s\"}"),
my_module.name, my_version, mqtt_client, Settings.mqtt_grptopic);
MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "1"));
#ifdef USE_WEBSERVER
if (Settings.webserver) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_WEBSERVER_MODE "\":\"%s\",\"" D_CMND_HOSTNAME "\":\"%s\",\"" D_CMND_IPADDRESS "\":\"%s\"}"),
(2 == Settings.webserver) ? D_ADMIN : D_USER, my_hostname, WiFi.localIP().toString().c_str());
MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "2"));
}
#endif // USE_WEBSERVER
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_RESTARTREASON "\":\"%s\"}"),
(GetResetReason() == "Exception") ? ESP.getResetInfo().c_str() : GetResetReason().c_str());
MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_INFO "3"));
if (Settings.tele_period) {
tele_period = Settings.tele_period -9;
}
status_update_timer = 2;
XdrvCall(FUNC_MQTT_INIT);
}
mqtt_connection_flag = 0;
}
void MqttReconnect()
{
char stopic[TOPSZ];
mqtt_retry_counter = Settings.mqtt_retry;
if (!Settings.flag.mqtt_enabled) {
MqttConnected();
return;
}
#ifdef USE_EMULATION
UdpDisconnect();
#endif // USE_EMULATION
if (mqtt_connection_flag > 1) { // Executed once just after power on and wifi is connected - Initial TLS check
#ifdef USE_MQTT_TLS
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_FINGERPRINT));
if (!EspClient.connect(Settings.mqtt_host, Settings.mqtt_port)) {
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_TLS_CONNECT_FAILED_TO " %s:%d. " D_RETRY_IN " %d " D_UNIT_SECOND),
Settings.mqtt_host, Settings.mqtt_port, mqtt_retry_counter);
AddLog(LOG_LEVEL_DEBUG);
EspClient.stop();
return;
}
if (EspClient.verify(Settings.mqtt_fingerprint, Settings.mqtt_host)) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_VERIFIED));
} else {
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_INSECURE));
EspClient.stop();
return;
}
EspClient.stop();
yield();
#endif // USE_MQTT_TLS
mqtt_connection_flag = 1;
// mqtt_retry_counter = 1;
// return;
}
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_ATTEMPTING_CONNECTION));
#ifndef USE_MQTT_TLS
#ifdef USE_DISCOVERY
#ifdef MQTT_HOST_DISCOVERY
if (!strlen(Settings.mqtt_host)) {
MdnsDiscoverMqttServer();
}
#endif // MQTT_HOST_DISCOVERY
#endif // USE_DISCOVERY
#endif // USE_MQTT_TLS
char *mqtt_user = NULL;
char *mqtt_pwd = NULL;
if (strlen(Settings.mqtt_user) > 0) mqtt_user = Settings.mqtt_user;
if (strlen(Settings.mqtt_pwd) > 0) mqtt_pwd = Settings.mqtt_pwd;
GetTopic_P(stopic, TELE, mqtt_topic, S_LWT);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_OFFLINE);
#if (1 == USE_MQTT_CLIENT)
MqttClient.setCallback(MqttDataHandler);
MqttClient.setServer(Settings.mqtt_host, Settings.mqtt_port);
if (MqttClient.connect(mqtt_client, mqtt_user, mqtt_pwd, stopic, 1, true, mqtt_data)) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_CONNECTED));
mqtt_retry_counter = 0;
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR(D_ONLINE));
MqttPublish(stopic, true);
MqttConnected();
} else {
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_CONNECT_FAILED_TO " %s:%d, rc %d. " D_RETRY_IN " %d " D_UNIT_SECOND),
Settings.mqtt_host, Settings.mqtt_port, MqttClient.state(), mqtt_retry_counter); //status codes are documented here http://pubsubclient.knolleary.net/api.html#state
AddLog(LOG_LEVEL_INFO);
}
#elif (2 == USE_MQTT_CLIENT)
if (!MqttClient) {
MqttClient = new MQTT(mqtt_client, Settings.mqtt_host, Settings.mqtt_port, stopic, 1, true, mqtt_data);
// MqttClient->onConnected(MqttMyNoneCb);
// MqttClient->onDisconnected(MqttMyNoneCb);
// MqttClient->onPublished(MqttMyNoneCb);
MqttClient->onData(MqttMyDataCb);
MqttClient->setUserPwd(mqtt_user, mqtt_pwd);
}
MqttClient->connect();
uint16_t mqtt_timeout = 50;
while (!MqttClient->isConnected() && mqtt_timeout--) delay(1);
if (MqttClient->isConnected()) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_CONNECTED));
mqtt_retry_counter = 0;
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR(D_ONLINE));
MqttPublish(stopic, true);
MqttConnected();
} else {
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_CONNECT_FAILED_TO " %s:%d. " D_RETRY_IN " %d " D_UNIT_SECOND),
Settings.mqtt_host, Settings.mqtt_port, mqtt_retry_counter);
AddLog(LOG_LEVEL_INFO);
}
#elif (3 == USE_MQTT_CLIENT)
//topic, data, data is continuing
MqttClient.onData([](String topic, String data, bool cont) {
MqttDataHandler((char*)topic.c_str(), (byte*)data.c_str(), strlen(data.c_str()));
});
char uri[200];
snprintf_P(uri, sizeof(uri), PSTR("mqtt://%s:%s@%s:%d#%s"), mqtt_user, mqtt_pwd, Settings.mqtt_host, Settings.mqtt_port, mqtt_client);
if (MqttClient.begin(String(uri), {.lwtTopic = stopic, .lwtMsg = mqtt_data, .lwtQos = 1, .lwtRetain = 1}, MQTT_KEEPALIVE, true)) {
AddLog_P(LOG_LEVEL_INFO, S_LOG_MQTT, PSTR(D_CONNECTED));
mqtt_retry_counter = 0;
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR(D_ONLINE));
MqttPublish(stopic, true);
MqttConnected();
} else {
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_MQTT D_CONNECT_FAILED_TO " %s:%d. " D_RETRY_IN " %d " D_UNIT_SECOND),
Settings.mqtt_host, Settings.mqtt_port, mqtt_retry_counter); //status codes are documented here http://pubsubclient.knolleary.net/api.html#state
AddLog(LOG_LEVEL_INFO);
}
#endif // USE_MQTT_CLIENT
}
/*********************************************************************************************/
bool MqttCommand()
{
char command [CMDSZ];
bool serviced = true;
char stemp1[TOPSZ];
char scommand[CMDSZ];
uint16_t i;
uint16_t index = XdrvMailbox.index;
uint16_t data_len = XdrvMailbox.data_len;
uint16_t payload16 = XdrvMailbox.payload16;
int16_t payload = XdrvMailbox.payload;
uint8_t grpflg = XdrvMailbox.grpflg;
char *type = XdrvMailbox.topic;
char *dataBuf = XdrvMailbox.data;
int command_code = GetCommandCode(command, sizeof(command), type, kMqttCommands);
if (CMND_MQTTHOST == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_host))) {
strlcpy(Settings.mqtt_host, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_HOST : dataBuf, sizeof(Settings.mqtt_host));
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_host);
}
else if (CMND_MQTTPORT == command_code) {
if (payload16 > 0) {
Settings.mqtt_port = (1 == payload16) ? MQTT_PORT : payload16;
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.mqtt_port);
}
else if (CMND_MQTTRETRY == command_code) {
if ((payload >= MQTT_RETRY_SECS) && (payload < 32001)) {
Settings.mqtt_retry = payload;
mqtt_retry_counter = Settings.mqtt_retry;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, Settings.mqtt_retry);
}
else if ((CMND_STATETEXT == command_code) && (index > 0) && (index <= 4)) {
if ((data_len > 0) && (data_len < sizeof(Settings.state_text[0]))) {
for(i = 0; i <= data_len; i++) {
if (dataBuf[i] == ' ') {
dataBuf[i] = '_';
}
}
strlcpy(Settings.state_text[index -1], dataBuf, sizeof(Settings.state_text[0]));
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, GetStateText(index -1));
}
#ifdef USE_MQTT_TLS
else if (CMND_MQTTFINGERPRINT == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_fingerprint))) {
strlcpy(Settings.mqtt_fingerprint, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_FINGERPRINT : dataBuf, sizeof(Settings.mqtt_fingerprint));
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_fingerprint);
}
#endif
else if ((CMND_MQTTCLIENT == command_code) && !grpflg) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_client))) {
strlcpy(Settings.mqtt_client, (1 == payload) ? MQTT_CLIENT_ID : dataBuf, sizeof(Settings.mqtt_client));
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_client);
}
else if (CMND_MQTTUSER == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_user))) {
strlcpy(Settings.mqtt_user, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_USER : dataBuf, sizeof(Settings.mqtt_user));
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_user);
}
else if (CMND_MQTTPASSWORD == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_pwd))) {
strlcpy(Settings.mqtt_pwd, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_PASS : dataBuf, sizeof(Settings.mqtt_pwd));
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_pwd);
}
else if (CMND_FULLTOPIC == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_fulltopic))) {
MakeValidMqtt(1, dataBuf);
if (!strcmp(dataBuf, mqtt_client)) {
payload = 1;
}
strlcpy(stemp1, (1 == payload) ? MQTT_FULLTOPIC : dataBuf, sizeof(stemp1));
if (strcmp(stemp1, Settings.mqtt_fulltopic)) {
snprintf_P(mqtt_data, sizeof(mqtt_data), (Settings.flag.mqtt_offline) ? S_OFFLINE : "");
MqttPublishPrefixTopic_P(TELE, PSTR(D_LWT), true); // Offline or remove previous retained topic
strlcpy(Settings.mqtt_fulltopic, stemp1, sizeof(Settings.mqtt_fulltopic));
restart_flag = 2;
}
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_fulltopic);
}
else if ((CMND_PREFIX == command_code) && (index > 0) && (index <= 3)) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_prefix[0]))) {
MakeValidMqtt(0, dataBuf);
strlcpy(Settings.mqtt_prefix[index -1], (1 == payload) ? (1==index)?SUB_PREFIX:(2==index)?PUB_PREFIX:PUB_PREFIX2 : dataBuf, sizeof(Settings.mqtt_prefix[0]));
// if (Settings.mqtt_prefix[index -1][strlen(Settings.mqtt_prefix[index -1])] == '/') Settings.mqtt_prefix[index -1][strlen(Settings.mqtt_prefix[index -1])] = 0;
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, index, Settings.mqtt_prefix[index -1]);
}
else if (CMND_GROUPTOPIC == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_grptopic))) {
MakeValidMqtt(0, dataBuf);
if (!strcmp(dataBuf, mqtt_client)) {
payload = 1;
}
strlcpy(Settings.mqtt_grptopic, (1 == payload) ? MQTT_GRPTOPIC : dataBuf, sizeof(Settings.mqtt_grptopic));
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_grptopic);
}
else if ((CMND_TOPIC == command_code) && !grpflg) {
if ((data_len > 0) && (data_len < sizeof(Settings.mqtt_topic))) {
MakeValidMqtt(0, dataBuf);
if (!strcmp(dataBuf, mqtt_client)) {
payload = 1;
}
strlcpy(stemp1, (1 == payload) ? MQTT_TOPIC : dataBuf, sizeof(stemp1));
if (strcmp(stemp1, Settings.mqtt_topic)) {
snprintf_P(mqtt_data, sizeof(mqtt_data), (Settings.flag.mqtt_offline) ? S_OFFLINE : "");
MqttPublishPrefixTopic_P(TELE, PSTR(D_LWT), true); // Offline or remove previous retained topic
strlcpy(Settings.mqtt_topic, stemp1, sizeof(Settings.mqtt_topic));
restart_flag = 2;
}
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.mqtt_topic);
}
else if ((CMND_BUTTONTOPIC == command_code) && !grpflg) {
if ((data_len > 0) && (data_len < sizeof(Settings.button_topic))) {
MakeValidMqtt(0, dataBuf);
if (!strcmp(dataBuf, mqtt_client)) {
payload = 1;
}
strlcpy(Settings.button_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? mqtt_topic : dataBuf, sizeof(Settings.button_topic));
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.button_topic);
}
else if (CMND_SWITCHTOPIC == command_code) {
if ((data_len > 0) && (data_len < sizeof(Settings.switch_topic))) {
MakeValidMqtt(0, dataBuf);
if (!strcmp(dataBuf, mqtt_client)) {
payload = 1;
}
strlcpy(Settings.switch_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? mqtt_topic : dataBuf, sizeof(Settings.switch_topic));
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, Settings.switch_topic);
}
else if (CMND_BUTTONRETAIN == command_code) {
if ((payload >= 0) && (payload <= 1)) {
strlcpy(Settings.button_topic, mqtt_topic, sizeof(Settings.button_topic));
if (!payload) {
for(i = 1; i <= MAX_KEYS; i++) {
send_button_power(0, i, 9); // Clear MQTT retain in broker
}
}
Settings.flag.mqtt_button_retain = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_button_retain));
}
else if (CMND_SWITCHRETAIN == command_code) {
if ((payload >= 0) && (payload <= 1)) {
strlcpy(Settings.button_topic, mqtt_topic, sizeof(Settings.button_topic));
if (!payload) {
for(i = 1; i <= MAX_SWITCHES; i++) {
send_button_power(1, i, 9); // Clear MQTT retain in broker
}
}
Settings.flag.mqtt_switch_retain = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_switch_retain));
}
else if (CMND_POWERRETAIN == command_code) {
if ((payload >= 0) && (payload <= 1)) {
if (!payload) {
for(i = 1; i <= devices_present; i++) { // Clear MQTT retain in broker
GetTopic_P(stemp1, STAT, mqtt_topic, GetPowerDevice(scommand, i, sizeof(scommand)));
mqtt_data[0] = '\0';
MqttPublish(stemp1, Settings.flag.mqtt_power_retain);
}
}
Settings.flag.mqtt_power_retain = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_power_retain));
}
else if (CMND_SENSORRETAIN == command_code) {
if ((payload >= 0) && (payload <= 1)) {
if (!payload) {
mqtt_data[0] = '\0';
MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_SENSOR), Settings.flag.mqtt_sensor_retain);
MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_ENERGY), Settings.flag.mqtt_sensor_retain);
}
Settings.flag.mqtt_sensor_retain = payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_SVALUE, command, GetStateText(Settings.flag.mqtt_sensor_retain));
}
else serviced = false;
return serviced;
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
#define XDRV_00
boolean Xdrv00(byte function)
{
boolean result = false;
switch (function) {
case FUNC_LOOP:
if (Settings.flag.mqtt_enabled) MqttLoop();
break;
case FUNC_EVERY_SECOND:
if (WL_CONNECTED == WiFi.status()) MqttCheckConnection();
break;
case FUNC_COMMAND:
if (Settings.flag.mqtt_enabled) result = MqttCommand();
break;
}
return result;
}

View File

@ -108,7 +108,7 @@ uint16_t light_wakeup_counter = 0;
uint8_t light_fixed_color_index = 1;
unsigned long strip_timer_counter = 0; // Bars and Gradient
unsigned long strip_timer_counter = 0; // Bars and Gradient
#ifdef USE_ARILUX_RF
/*********************************************************************************************\
@ -133,9 +133,12 @@ unsigned int arilux_rf_repeat_count = 0;
uint8_t arilux_rf_toggle = 0;
#ifndef ARDUINO_ESP8266_RELEASE_2_3_0
#ifndef USE_WS2812_DMA // Collides with Neopixelbus but solves RF misses
//void AriluxRfInterrupt() ICACHE_RAM_ATTR; // As iram is tight and it works this way too
void AriluxRfInterrupt() ICACHE_RAM_ATTR; // As iram is tight and it works this way too
#endif // USE_WS2812_DMA
#endif // ARDUINO_ESP8266_RELEASE_2_3_0
void AriluxRfInterrupt()
{
@ -366,13 +369,9 @@ void LightInit()
}
}
if (pin[GPIO_ARIRFRCV] < 99) {
#ifdef USE_ARILUX_RF
AriluxRfInit();
#else
if (pin[GPIO_LED2] < 99) {
digitalWrite(pin[GPIO_LED2], bitRead(led_inverted, 1)); // Turn off RF
}
#endif // USE_ARILUX_RF
}
}
#ifdef USE_WS2812 // ************************************************************************
@ -677,7 +676,7 @@ void LightSetPower()
void LightAnimate()
{
uint8_t cur_col[5];
uint16_t light_still_on;
uint16_t light_still_on = 0;
strip_timer_counter++;
if (!light_power) { // Power Off
@ -1225,11 +1224,14 @@ boolean Xdrv01(byte function)
case FUNC_EVERY_50_MSECOND:
LightAnimate();
#ifdef USE_ARILUX_RF
if (pin[GPIO_ARIRFRCV] < 99) {
AriluxRfHandler();
}
if (pin[GPIO_ARIRFRCV] < 99) AriluxRfHandler();
#endif // USE_ARILUX_RF
break;
#ifdef USE_ARILUX_RF
case FUNC_EVERY_SECOND:
if (10 == uptime) AriluxRfInit(); // Needs rest before enabling RF interrupts
break;
#endif // USE_ARILUX_RF
case FUNC_COMMAND:
result = LightCommand();
break;

View File

@ -107,8 +107,8 @@ void IrReceiveCheck()
if ((iridx < 0) || (iridx > 14)) {
iridx = 0;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_IRRECEIVED "\":{\"" D_JSON_IR_PROTOCOL "\":\"%s\",\"" D_JSON_IR_BITS "\":%d,\"" D_JSON_IR_DATA "\":\"%X\"}}"),
GetTextIndexed(sirtype, sizeof(sirtype), iridx, kIrRemoteProtocols), results.bits, results.value);
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_IRRECEIVED "\":{\"" D_JSON_IR_PROTOCOL "\":\"%s\",\"" D_JSON_IR_BITS "\":%d,\"" D_JSON_IR_DATA "\":\"%lX\"}}"),
GetTextIndexed(sirtype, sizeof(sirtype), iridx, kIrRemoteProtocols), results.bits, (uint32_t)results.value);
MqttPublishPrefixTopic_P(RESULT_OR_TELE, PSTR(D_JSON_IRRECEIVED));
#ifdef USE_DOMOTICZ
unsigned long value = results.value | (iridx << 28); // [Protocol:4, Data:28]
@ -132,7 +132,6 @@ boolean IrHvacToshiba(const char *HVAC_Mode, const char *HVAC_FanMode, boolean H
byte data[HVAC_TOSHIBA_DATALEN] = {0xF2, 0x0D, 0x03, 0xFC, 0x01, 0x00, 0x00, 0x00, 0x00};
char *p;
char *token;
uint8_t mode;
if (HVAC_Mode == NULL) {
@ -176,7 +175,7 @@ boolean IrHvacToshiba(const char *HVAC_Mode, const char *HVAC_FanMode, boolean H
else {
Temp = HVAC_Temp;
}
data[5] = (byte)Temp - 17 << 4;
data[5] = (byte)(Temp - 17) << 4;
data[HVAC_TOSHIBA_DATALEN - 1] = 0;
for (int x = 0; x < HVAC_TOSHIBA_DATALEN - 1; x++) {
@ -219,7 +218,6 @@ boolean IrHvacToshiba(const char *HVAC_Mode, const char *HVAC_FanMode, boolean H
boolean IrHvacMitsubishi(const char *HVAC_Mode, const char *HVAC_FanMode, boolean HVAC_Power, int HVAC_Temp)
{
char *p;
char *token;
uint8_t mode;
mitsubir->stateReset();
@ -286,12 +284,6 @@ boolean IrSendCommand()
uint32_t bits = 0;
uint32_t data = 0;
const char *HVAC_Mode;
const char *HVAC_FanMode;
const char *HVAC_Vendor;
int HVAC_Temp = 21;
boolean HVAC_Power = true;
for (uint16_t i = 0; i <= sizeof(dataBufUc); i++) {
dataBufUc[i] = toupper(XdrvMailbox.data[i]);
}
@ -349,6 +341,12 @@ boolean IrSendCommand()
}
#ifdef USE_IR_HVAC
else if (!strcasecmp_P(XdrvMailbox.topic, PSTR(D_CMND_IRHVAC))) {
const char *HVAC_Mode;
const char *HVAC_FanMode;
const char *HVAC_Vendor;
int HVAC_Temp = 21;
boolean HVAC_Power = true;
if (XdrvMailbox.data_len) {
StaticJsonBuffer<164> jsonBufer;
JsonObject &root = jsonBufer.parseObject(dataBufUc);

View File

@ -26,17 +26,17 @@
#define FEATURE_POWER_LIMIT true
enum EnergyHardware { ENERGY_NONE, ENERGY_HLW8012, ENERGY_PZEM004T };
enum EnergyHardware { ENERGY_NONE, ENERGY_HLW8012, ENERGY_CSE7766, ENERGY_PZEM004T };
enum EnergyCommands {
CMND_POWERLOW, CMND_POWERHIGH, CMND_VOLTAGELOW, CMND_VOLTAGEHIGH, CMND_CURRENTLOW, CMND_CURRENTHIGH,
CMND_HLWPCAL, CMND_HLWPSET, CMND_HLWUCAL, CMND_HLWUSET, CMND_HLWICAL, CMND_HLWISET,
CMND_POWERCAL, CMND_POWERSET, CMND_VOLTAGECAL, CMND_VOLTAGESET, CMND_CURRENTCAL, CMND_CURRENTSET,
CMND_ENERGYRESET, CMND_MAXENERGY, CMND_MAXENERGYSTART,
CMND_MAXPOWER, CMND_MAXPOWERHOLD, CMND_MAXPOWERWINDOW,
CMND_SAFEPOWER, CMND_SAFEPOWERHOLD, CMND_SAFEPOWERWINDOW };
const char kEnergyCommands[] PROGMEM =
D_CMND_POWERLOW "|" D_CMND_POWERHIGH "|" D_CMND_VOLTAGELOW "|" D_CMND_VOLTAGEHIGH "|" D_CMND_CURRENTLOW "|" D_CMND_CURRENTHIGH "|"
D_CMND_HLWPCAL "|" D_CMND_HLWPSET "|" D_CMND_HLWUCAL "|" D_CMND_HLWUSET "|" D_CMND_HLWICAL "|" D_CMND_HLWISET "|"
D_CMND_POWERCAL "|" D_CMND_POWERSET "|" D_CMND_VOLTAGECAL "|" D_CMND_VOLTAGESET "|" D_CMND_CURRENTCAL "|" D_CMND_CURRENTSET "|"
D_CMND_ENERGYRESET "|" D_CMND_MAXENERGY "|" D_CMND_MAXENERGYSTART "|"
D_CMND_MAXPOWER "|" D_CMND_MAXPOWERHOLD "|" D_CMND_MAXPOWERWINDOW "|"
D_CMND_SAFEPOWER "|" D_CMND_SAFEPOWERHOLD "|" D_CMND_SAFEPOWERWINDOW ;
@ -47,10 +47,12 @@ float energy_power = 0; // 123.1 W
float energy_power_factor = 0; // 0.12
float energy_daily = 0; // 12.123 kWh
float energy_total = 0; // 12345.12345 kWh
float energy_start = 0; // 12345.12345 kWh total from yesterday
float energy_start = 0; // 12345.12345 kWh total previous
unsigned long energy_kWhtoday; // 1212312345 Wh * 10^-5 (deca micro Watt hours) - 5763924 = 0.05763924 kWh = 0.058 kWh = energy_daily
unsigned long energy_period = 0; // 1212312345 Wh * 10^-5 (deca micro Watt hours) - 5763924 = 0.05763924 kWh = 0.058 kWh = energy_daily
bool energy_power_on = true;
byte energy_min_power_flag = 0;
byte energy_max_power_flag = 0;
byte energy_min_voltage_flag = 0;
@ -67,12 +69,20 @@ uint16_t energy_mplh_counter = 0;
uint16_t energy_mplw_counter = 0;
#endif // FEATURE_POWER_LIMIT
byte energy_startup = 1;
byte energy_fifth_second = 0;
Ticker ticker_energy;
/********************************************************************************************/
void EnergyUpdateToday()
{
RtcSettings.energy_kWhtoday = energy_kWhtoday;
energy_daily = (float)energy_kWhtoday / 100000000;
energy_total = (float)(RtcSettings.energy_kWhtotal + (energy_kWhtoday / 1000)) / 100000;
}
/*********************************************************************************************\
* HLW8012 - Energy
* HLW8012 - Energy (Sonoff Pow)
*
* Based on Source: Shenzhen Heli Technology Co., Ltd
\*********************************************************************************************/
@ -136,18 +146,13 @@ void HlwCf1Interrupt() // Service Voltage and Current
void HlwEverySecond()
{
unsigned long hlw_len;
unsigned long hlw_temp;
if (hlw_energy_period_counter) {
hlw_len = 10000 / hlw_energy_period_counter;
hlw_energy_period_counter = 0;
if (hlw_len) {
hlw_temp = ((HLW_PREF * Settings.hlw_power_calibration) / hlw_len) / 36;
energy_kWhtoday += hlw_temp;
RtcSettings.energy_kWhtoday = energy_kWhtoday;
energy_total = (float)(RtcSettings.energy_kWhtotal + (energy_kWhtoday / 1000)) / 100000;
energy_daily = (float)energy_kWhtoday / 100000000;
energy_kWhtoday += ((HLW_PREF * Settings.energy_power_calibration) / hlw_len) / 36;
EnergyUpdateToday();
}
}
}
@ -163,8 +168,8 @@ void HlwEvery200ms()
hlw_load_off = 1;
}
if (hlw_cf_pulse_length && (power &1) && !hlw_load_off) {
hlw_w = (HLW_PREF * Settings.hlw_power_calibration) / hlw_cf_pulse_length;
if (hlw_cf_pulse_length && energy_power_on && !hlw_load_off) {
hlw_w = (HLW_PREF * Settings.energy_power_calibration) / hlw_cf_pulse_length;
energy_power = (float)hlw_w / 10;
} else {
energy_power = 0;
@ -185,8 +190,8 @@ void HlwEvery200ms()
hlw_cf1_voltage_pulse_length = hlw_cf1_pulse_length;
hlw_cf1_voltage_max_pulse_counter = hlw_cf1_pulse_counter;
if (hlw_cf1_voltage_pulse_length && (power &1)) { // If powered on always provide voltage
hlw_u = (HLW_UREF * Settings.hlw_voltage_calibration) / hlw_cf1_voltage_pulse_length;
if (hlw_cf1_voltage_pulse_length && energy_power_on) { // If powered on always provide voltage
hlw_u = (HLW_UREF * Settings.energy_voltage_calibration) / hlw_cf1_voltage_pulse_length;
energy_voltage = (float)hlw_u / 10;
} else {
energy_voltage = 0;
@ -197,7 +202,7 @@ void HlwEvery200ms()
hlw_cf1_current_max_pulse_counter = hlw_cf1_pulse_counter;
if (hlw_cf1_current_pulse_length && energy_power) { // No current if no power being consumed
hlw_i = (HLW_IREF * Settings.hlw_current_calibration) / hlw_cf1_current_pulse_length;
hlw_i = (HLW_IREF * Settings.energy_current_calibration) / hlw_cf1_current_pulse_length;
energy_current = (float)hlw_i / 1000;
} else {
energy_current = 0;
@ -211,10 +216,10 @@ void HlwEvery200ms()
void HlwInit()
{
if (!Settings.hlw_power_calibration || (4975 == Settings.hlw_power_calibration)) {
Settings.hlw_power_calibration = HLW_PREF_PULSE;
Settings.hlw_voltage_calibration = HLW_UREF_PULSE;
Settings.hlw_current_calibration = HLW_IREF_PULSE;
if (!Settings.energy_power_calibration || (4975 == Settings.energy_power_calibration)) {
Settings.energy_power_calibration = HLW_PREF_PULSE;
Settings.energy_voltage_calibration = HLW_UREF_PULSE;
Settings.energy_current_calibration = HLW_IREF_PULSE;
}
hlw_cf_pulse_length = 0;
@ -227,7 +232,7 @@ void HlwInit()
hlw_cf1_current_max_pulse_counter = 0;
hlw_load_off = 1;
hlw_energy_period_counter = 1;
hlw_energy_period_counter = 0;
hlw_select_ui_flag = 0; // Voltage;
@ -241,6 +246,145 @@ void HlwInit()
hlw_cf1_timer = 0;
}
/*********************************************************************************************\
* CSE7766 - Energy (Sonoff S31)
*
* Based on datasheet from http://www.chipsea.com/UploadFiles/2017/08/11144342F01B5662.pdf
\*********************************************************************************************/
#define CSE_NOT_CALIBRATED 0xAA
#define CSE_PULSES_NOT_INITIALIZED -1
#define CSE_PREF 1000
#define CSE_UREF 100
uint8_t cse_receive_flag = 0;
long voltage_cycle = 0;
long current_cycle = 0;
long power_cycle = 0;
long cf_pulses = 0;
long cf_pulses_last_time = CSE_PULSES_NOT_INITIALIZED;
void CseReceived()
{
AddLogSerial(LOG_LEVEL_DEBUG_MORE);
uint8_t header = serial_in_buffer[0];
if ((header & 0xFC) == 0xFC) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR("CSE: Abnormal hardware"));
return;
}
// Calculate checksum
uint8_t checksum = 0;
for (byte i = 2; i < 23; i++) checksum += serial_in_buffer[i];
if (checksum != serial_in_buffer[23]) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR("CSE: " D_CHECKSUM_FAILURE));
return;
}
// Get chip calibration data (coefficients) and use as initial defaults
if (HLW_UREF_PULSE == Settings.energy_voltage_calibration) {
long voltage_coefficient = 191200; // uSec
if (CSE_NOT_CALIBRATED != header) {
voltage_coefficient = serial_in_buffer[2] << 16 | serial_in_buffer[3] << 8 | serial_in_buffer[4];
}
Settings.energy_voltage_calibration = voltage_coefficient / CSE_UREF;
}
if (HLW_IREF_PULSE == Settings.energy_current_calibration) {
long current_coefficient = 16140; // uSec
if (CSE_NOT_CALIBRATED != header) {
current_coefficient = serial_in_buffer[8] << 16 | serial_in_buffer[9] << 8 | serial_in_buffer[10];
}
Settings.energy_current_calibration = current_coefficient;
}
if (HLW_PREF_PULSE == Settings.energy_power_calibration) {
long power_coefficient = 5364000; // uSec
if (CSE_NOT_CALIBRATED != header) {
power_coefficient = serial_in_buffer[14] << 16 | serial_in_buffer[15] << 8 | serial_in_buffer[16];
}
Settings.energy_power_calibration = power_coefficient / CSE_PREF;
}
uint8_t adjustement = serial_in_buffer[20];
voltage_cycle = serial_in_buffer[5] << 16 | serial_in_buffer[6] << 8 | serial_in_buffer[7];
current_cycle = serial_in_buffer[11] << 16 | serial_in_buffer[12] << 8 | serial_in_buffer[13];
power_cycle = serial_in_buffer[17] << 16 | serial_in_buffer[18] << 8 | serial_in_buffer[19];
cf_pulses = serial_in_buffer[21] << 8 | serial_in_buffer[22];
// if (adjustement & 0x80) { // CF overflow
// cf_pulses += 0x10000;
// }
if (energy_power_on) { // Powered on
if (adjustement & 0x40) { // Voltage valid
energy_voltage = (float)(Settings.energy_voltage_calibration * CSE_UREF) / (float)voltage_cycle;
}
if (adjustement & 0x10) { // Power valid
if ((header & 0xF2) == 0xF2) { // Power cycle exceeds range
energy_power = 0;
} else {
energy_power = (float)(Settings.energy_power_calibration * CSE_PREF) / (float)power_cycle;
}
} else {
energy_power = 0; // Powered on but no load
}
if (adjustement & 0x20) { // Current valid
if (0 == energy_power) {
energy_current = 0;
} else {
energy_current = (float)Settings.energy_current_calibration / (float)current_cycle;
}
}
} else { // Powered off
energy_voltage = 0;
energy_power = 0;
energy_current = 0;
}
}
bool CseSerialInput()
{
if (cse_receive_flag) {
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
if (24 == serial_in_byte_counter) {
CseReceived();
cse_receive_flag = 0;
return 1;
}
} else {
if (0x5A == serial_in_byte) { // 0x5A - Packet header 2
cse_receive_flag = 1;
} else {
serial_in_byte_counter = 0;
}
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
}
serial_in_byte = 0; // Discard
return 0;
}
void CseEverySecond()
{
long cf_frequency = 0;
if (CSE_PULSES_NOT_INITIALIZED == cf_pulses_last_time) {
cf_pulses_last_time = cf_pulses; // Init after restart
} else {
if (cf_pulses < cf_pulses_last_time) { // Rolled over after 65535 pulses
cf_frequency = (65536 - cf_pulses_last_time) + cf_pulses;
} else {
cf_frequency = cf_pulses - cf_pulses_last_time;
}
if (cf_frequency && energy_power) {
cf_pulses_last_time = cf_pulses;
energy_kWhtoday += (cf_frequency * Settings.energy_power_calibration) / 36;
EnergyUpdateToday();
}
}
}
#ifdef USE_PZEM004T
/*********************************************************************************************\
* PZEM004T - Energy
@ -285,9 +429,7 @@ IPAddress pzem_ip(192, 168, 1, 1);
uint8_t PzemCrc(uint8_t *data)
{
uint16_t crc = 0;
for (uint8_t i = 0; i < sizeof(PZEMCommand) -1; i++) {
crc += *data++;
}
for (uint8_t i = 0; i < sizeof(PZEMCommand) -1; i++) crc += *data++;
return (uint8_t)(crc & 0xFF);
}
@ -296,9 +438,7 @@ void PzemSend(uint8_t cmd)
PZEMCommand pzem;
pzem.command = cmd;
for (int i = 0; i < sizeof(pzem.addr); i++) {
pzem.addr[i] = pzem_ip[i];
}
for (uint8_t i = 0; i < sizeof(pzem.addr); i++) pzem.addr[i] = pzem_ip[i];
pzem.data = 0;
uint8_t *bytes = (uint8_t*)&pzem;
@ -310,7 +450,7 @@ void PzemSend(uint8_t cmd)
bool PzemReceiveReady()
{
return PzemSerial->available() >= sizeof(PZEMCommand);
return PzemSerial->available() >= (int)sizeof(PZEMCommand);
}
bool PzemRecieve(uint8_t resp, float *data)
@ -329,6 +469,8 @@ bool PzemRecieve(uint8_t resp, float *data)
}
}
AddLogSerial(LOG_LEVEL_DEBUG_MORE, buffer, len);
if (len != sizeof(PZEMCommand)) {
// AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DEBUG "Pzem comms timeout"));
return false;
@ -375,31 +517,24 @@ void PzemEvery200ms()
float value = 0;
if (PzemRecieve(pzem_responses[pzem_read_state], &value)) {
switch (pzem_read_state) {
case 1:
energy_voltage = value; // 230.2V
case 1: // Voltage as 230.2V
energy_voltage = value;
break;
case 2:
energy_current = value; // 17.32A
case 2: // Current as 17.32A
energy_current = value;
break;
case 3:
energy_power = value; // 20W
case 3: // Power as 20W
energy_power = value;
break;
case 4:
energy_total = value / 1000; // 99999Wh
if (!energy_startup) {
if (energy_total < energy_start) {
energy_start = energy_total;
Settings.hlw_power_calibration = energy_start * 1000;
}
energy_kWhtoday = (energy_total - energy_start) * 100000000;
energy_daily = (float)energy_kWhtoday / 100000000;
}
case 4: // Total energy as 99999Wh
if (!energy_start || (value < energy_start)) energy_start = value; // Init after restart and hanlde roll-over if any
energy_kWhtoday += (value - energy_start) * 100000;
energy_start = value;
EnergyUpdateToday();
break;
}
pzem_read_state++;
if (5 == pzem_read_state) {
pzem_read_state = 1;
}
if (5 == pzem_read_state) pzem_read_state = 1;
}
}
@ -427,9 +562,8 @@ void Energy200ms()
if (5 == energy_fifth_second) {
energy_fifth_second = 0;
if (ENERGY_HLW8012 == energy_flg) {
HlwEverySecond();
}
if (ENERGY_HLW8012 == energy_flg) HlwEverySecond();
if (ENERGY_CSE7766 == energy_flg) CseEverySecond();
if (RtcTime.valid) {
if (LocalTime() == Midnight()) {
@ -438,43 +572,26 @@ void Energy200ms()
RtcSettings.energy_kWhtotal = Settings.energy_kWhtotal;
energy_kWhtoday = 0;
energy_period = energy_kWhtoday;
RtcSettings.energy_kWhtoday = energy_kWhtoday;
#ifdef USE_PZEM004T
if (ENERGY_PZEM004T == energy_flg) {
energy_start = energy_total;
Settings.hlw_power_calibration = energy_start * 1000;
}
#endif // USE_PZEM004T
EnergyUpdateToday();
energy_max_energy_state = 3;
}
if ((RtcTime.hour == Settings.energy_max_energy_start) && (3 == energy_max_energy_state)) {
energy_max_energy_state = 0;
}
if (energy_startup && (RtcTime.day_of_year == Settings.energy_kWhdoy)) {
energy_kWhtoday = Settings.energy_kWhtoday;
energy_period = energy_kWhtoday;
RtcSettings.energy_kWhtoday = energy_kWhtoday;
energy_start = (float)Settings.hlw_power_calibration / 1000; // Used by PZEM004T to store total yesterday
energy_startup = 0;
}
}
}
if (ENERGY_HLW8012 == energy_flg) {
HlwEvery200ms();
energy_power_on = (power &1) | Settings.flag.no_power_on_check;
if (ENERGY_HLW8012 == energy_flg) HlwEvery200ms();
#ifdef USE_PZEM004T
}
else if (ENERGY_PZEM004T == energy_flg) {
PzemEvery200ms();
if (ENERGY_PZEM004T == energy_flg) PzemEvery200ms();
#endif // USE_PZEM004T
}
float power_factor = 0;
if (energy_voltage && energy_current && energy_power) {
power_factor = energy_power / (energy_voltage * energy_current);
if (power_factor > 1) {
power_factor = 1;
}
if (power_factor > 1) power_factor = 1;
}
energy_power_factor = power_factor;
}
@ -483,6 +600,7 @@ void EnergySaveState()
{
Settings.energy_kWhdoy = (RtcTime.valid) ? RtcTime.day_of_year : 0;
Settings.energy_kWhtoday = energy_kWhtoday;
RtcSettings.energy_kWhtoday = energy_kWhtoday;
Settings.energy_kWhtotal = RtcSettings.energy_kWhtotal;
}
@ -490,9 +608,7 @@ boolean EnergyMargin(byte type, uint16_t margin, uint16_t value, byte &flag, byt
{
byte change;
if (!margin) {
return false;
}
if (!margin) return false;
change = save_flag;
if (type) {
flag = (value > margin);
@ -510,10 +626,10 @@ void EnergySetPowerSteadyCounter()
void EnergyMarginCheck()
{
uint16_t energy_daily_u;
uint16_t energy_power_u;
uint16_t energy_voltage_u;
uint16_t energy_current_u;
uint16_t energy_daily_u = 0;
uint16_t energy_power_u = 0;
uint16_t energy_voltage_u = 0;
uint16_t energy_current_u = 0;
boolean flag;
boolean jsonflg;
@ -522,7 +638,7 @@ void EnergyMarginCheck()
return;
}
if (power && (Settings.energy_min_power || Settings.energy_max_power || Settings.energy_min_voltage || Settings.energy_max_voltage || Settings.energy_min_current || Settings.energy_max_current)) {
if (energy_power_on && (Settings.energy_min_power || Settings.energy_max_power || Settings.energy_min_voltage || Settings.energy_max_voltage || Settings.energy_min_current || Settings.energy_max_current)) {
energy_power_u = (uint16_t)(energy_power);
energy_voltage_u = (uint16_t)(energy_voltage);
energy_current_u = (uint16_t)(energy_current * 1000);
@ -632,7 +748,7 @@ void EnergyMarginCheck()
void EnergyMqttShow()
{
// {"Time":"2017-12-16T11:48:55","ENERGY":{"Total":0.212,"Yesterday":0.000,"Today":0.014,"Period":2.0,"Power":22.0,"Factor":1.00,"Voltage":213.6,"Current":0.100}}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_TIME "\":\"%s\""), GetDateAndTime().c_str());
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"" D_JSON_TIME "\":\"%s\""), GetDateAndTime(DT_LOCAL).c_str());
EnergyShow(1);
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s}"), mqtt_data);
MqttPublishPrefixTopic_P(TELE, PSTR(D_RSLT_ENERGY), Settings.flag.mqtt_sensor_retain);
@ -702,8 +818,9 @@ boolean EnergyCommand()
case 1:
energy_kWhtoday = lnum *100000;
energy_period = energy_kWhtoday;
RtcSettings.energy_kWhtoday = energy_kWhtoday;
Settings.energy_kWhtoday = energy_kWhtoday;
RtcSettings.energy_kWhtoday = energy_kWhtoday;
energy_daily = (float)energy_kWhtoday / 100000000;
break;
case 2:
Settings.energy_kWhyesterday = lnum *100000;
@ -724,51 +841,68 @@ boolean EnergyCommand()
command, energy_total_chr, energy_yesterday_chr, stoday_energy);
status_flag = 1;
}
else if ((ENERGY_HLW8012 == energy_flg) && (CMND_HLWPCAL == command_code)) {
else if (((ENERGY_HLW8012 == energy_flg) || (ENERGY_CSE7766 == energy_flg)) && (CMND_POWERCAL == command_code)) {
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 32001)) {
Settings.hlw_power_calibration = (XdrvMailbox.payload > 4000) ? XdrvMailbox.payload : HLW_PREF_PULSE; // 12530
Settings.energy_power_calibration = (XdrvMailbox.payload > 4000) ? XdrvMailbox.payload : HLW_PREF_PULSE; // HLW = 12530, CSE = 5364
}
nvalue = Settings.hlw_power_calibration;
nvalue = Settings.energy_power_calibration;
unit = UNIT_MICROSECOND;
}
else if ((ENERGY_HLW8012 == energy_flg) && (CMND_HLWPSET == command_code)) {
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 3601) && hlw_cf_pulse_length) {
Settings.hlw_power_calibration = (XdrvMailbox.payload * 10 * hlw_cf_pulse_length) / HLW_PREF;
else if (((ENERGY_HLW8012 == energy_flg) || (ENERGY_CSE7766 == energy_flg)) && (CMND_POWERSET == command_code)) { // Watt
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 3601)) {
if ((ENERGY_HLW8012 == energy_flg) && hlw_cf_pulse_length) {
Settings.energy_power_calibration = (XdrvMailbox.payload * 10 * hlw_cf_pulse_length) / HLW_PREF;
}
else if ((ENERGY_CSE7766 == energy_flg) && power_cycle) {
Settings.energy_power_calibration = (XdrvMailbox.payload * power_cycle) / CSE_PREF;
}
}
snprintf_P(command, sizeof(command), PSTR(D_CMND_HLWPCAL));
nvalue = Settings.hlw_power_calibration;
snprintf_P(command, sizeof(command), PSTR(D_CMND_POWERCAL));
nvalue = Settings.energy_power_calibration;
unit = UNIT_MICROSECOND;
}
else if ((ENERGY_HLW8012 == energy_flg) && (CMND_HLWUCAL == command_code)) {
else if (((ENERGY_HLW8012 == energy_flg) || (ENERGY_CSE7766 == energy_flg)) && (CMND_VOLTAGECAL == command_code)) {
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 32001)) {
Settings.hlw_voltage_calibration = (XdrvMailbox.payload > 999) ? XdrvMailbox.payload : HLW_UREF_PULSE; // 1950
Settings.energy_voltage_calibration = (XdrvMailbox.payload > 999) ? XdrvMailbox.payload : HLW_UREF_PULSE; // HLW = 1950, CSE = 1912
}
nvalue = Settings.hlw_voltage_calibration;
nvalue = Settings.energy_voltage_calibration;
unit = UNIT_MICROSECOND;
}
else if ((ENERGY_HLW8012 == energy_flg) && (CMND_HLWUSET == command_code)) {
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 501) && hlw_cf1_voltage_pulse_length) {
Settings.hlw_voltage_calibration = (XdrvMailbox.payload * 10 * hlw_cf1_voltage_pulse_length) / HLW_UREF;
else if (((ENERGY_HLW8012 == energy_flg) || (ENERGY_CSE7766 == energy_flg)) && (CMND_VOLTAGESET == command_code)) { // Volt
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 501)) {
if ((ENERGY_HLW8012 == energy_flg) && hlw_cf1_voltage_pulse_length) {
Settings.energy_voltage_calibration = (XdrvMailbox.payload * 10 * hlw_cf1_voltage_pulse_length) / HLW_UREF;
}
else if ((ENERGY_CSE7766 == energy_flg) && voltage_cycle) {
Settings.energy_voltage_calibration = (XdrvMailbox.payload * voltage_cycle) / CSE_UREF;
}
}
snprintf_P(command, sizeof(command), PSTR(D_CMND_HLWUCAL));
nvalue = Settings.hlw_voltage_calibration;
snprintf_P(command, sizeof(command), PSTR(D_CMND_VOLTAGECAL));
nvalue = Settings.energy_voltage_calibration;
unit = UNIT_MICROSECOND;
}
else if ((ENERGY_HLW8012 == energy_flg) && (CMND_HLWICAL == command_code)) {
else if (((ENERGY_HLW8012 == energy_flg) || (ENERGY_CSE7766 == energy_flg)) && (CMND_CURRENTCAL == command_code)) {
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 32001)) {
Settings.hlw_current_calibration = (XdrvMailbox.payload > 1100) ? XdrvMailbox.payload : HLW_IREF_PULSE; // 3500
Settings.energy_current_calibration = (XdrvMailbox.payload > 1100) ? XdrvMailbox.payload : HLW_IREF_PULSE; // HLW = 3500, CSE = 16140
}
nvalue = Settings.hlw_current_calibration;
nvalue = Settings.energy_current_calibration;
unit = UNIT_MICROSECOND;
}
else if ((ENERGY_HLW8012 == energy_flg) && (CMND_HLWISET == command_code)) {
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 16001) && hlw_cf1_current_pulse_length) {
Settings.hlw_current_calibration = (XdrvMailbox.payload * hlw_cf1_current_pulse_length) / HLW_IREF;
else if (((ENERGY_HLW8012 == energy_flg) || (ENERGY_CSE7766 == energy_flg)) && (CMND_CURRENTSET == command_code)) { // milliAmpere
if ((XdrvMailbox.payload > 0) && (XdrvMailbox.payload < 16001)) {
if ((ENERGY_HLW8012 == energy_flg) && hlw_cf1_current_pulse_length) {
Settings.energy_current_calibration = (XdrvMailbox.payload * hlw_cf1_current_pulse_length) / HLW_IREF;
}
else if ((ENERGY_CSE7766 == energy_flg) && current_cycle) {
Settings.energy_current_calibration = (XdrvMailbox.payload * current_cycle) / 1000;
}
}
snprintf_P(command, sizeof(command), PSTR(D_CMND_HLWICAL));
nvalue = Settings.hlw_current_calibration;
snprintf_P(command, sizeof(command), PSTR(D_CMND_CURRENTCAL));
nvalue = Settings.energy_current_calibration;
unit = UNIT_MICROSECOND;
}
#if FEATURE_POWER_LIMIT
else if (CMND_MAXPOWER == command_code) {
if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload < 3601)) {
@ -833,9 +967,9 @@ boolean EnergyCommand()
}
if (!status_flag) {
if (Settings.flag.value_units) {
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE_SPACE_UNIT, command, nvalue, GetTextIndexed(sunit, sizeof(sunit), unit, kUnitNames));
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_LVALUE_SPACE_UNIT, command, nvalue, GetTextIndexed(sunit, sizeof(sunit), unit, kUnitNames));
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_NVALUE, command, nvalue);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_LVALUE, command, nvalue);
}
}
return serviced;
@ -843,24 +977,36 @@ boolean EnergyCommand()
/********************************************************************************************/
void EnergyInit()
void EnergyDrvInit()
{
energy_flg = ENERGY_NONE;
if ((pin[GPIO_HLW_SEL] < 99) && (pin[GPIO_HLW_CF1] < 99) && (pin[GPIO_HLW_CF] < 99)) {
if ((pin[GPIO_HLW_SEL] < 99) && (pin[GPIO_HLW_CF1] < 99) && (pin[GPIO_HLW_CF] < 99)) { // Sonoff Pow
energy_flg = ENERGY_HLW8012;
HlwInit();
} else if (SONOFF_S31 == Settings.module) { // Sonoff S31
baudrate = 4800;
serial_config = SERIAL_8E1;
energy_flg = ENERGY_CSE7766;
#ifdef USE_PZEM004T
} else if ((pin[GPIO_PZEM_RX] < 99) && (pin[GPIO_PZEM_TX])) {
if (PzemInit()) {
energy_flg = ENERGY_PZEM004T;
}
} else if ((pin[GPIO_PZEM_RX] < 99) && (pin[GPIO_PZEM_TX])) { // Any device with a Pzem004T
energy_flg = ENERGY_PZEM004T;
#endif // USE_PZEM004T
}
}
void EnergySnsInit()
{
if (ENERGY_HLW8012 == energy_flg) HlwInit();
#ifdef USE_PZEM004T
if ((ENERGY_PZEM004T == energy_flg) && !PzemInit()) { // PzemInit needs to be done here as earlier (serial) interrupts may lead to Exceptions
energy_flg = ENERGY_NONE;
}
#endif // USE_PZEM004T
if (energy_flg) {
energy_kWhtoday = (RtcSettingsValid()) ? RtcSettings.energy_kWhtoday : 0;
energy_kWhtoday = (RtcSettingsValid()) ? RtcSettings.energy_kWhtoday : (RtcTime.day_of_year == Settings.energy_kWhdoy) ? Settings.energy_kWhtoday : 0;
energy_period = energy_kWhtoday;
energy_startup = 1;
EnergyUpdateToday();
ticker_energy.attach_ms(200, Energy200ms);
}
}
@ -892,9 +1038,7 @@ void EnergyShow(boolean json)
float energy = 0;
if (show_energy_period) {
if (energy_period) {
energy = (float)(energy_kWhtoday - energy_period) / 100000;
}
if (energy_period) energy = (float)(energy_kWhtoday - energy_period) / 100000;
energy_period = energy_kWhtoday;
}
@ -938,6 +1082,9 @@ boolean Xdrv03(byte function)
if (energy_flg) {
switch (function) {
case FUNC_INIT:
EnergyDrvInit();
break;
case FUNC_COMMAND:
result = EnergyCommand();
break;
@ -958,7 +1105,7 @@ boolean Xsns03(byte function)
if (energy_flg) {
switch (function) {
case FUNC_INIT:
EnergyInit();
EnergySnsInit();
break;
case FUNC_EVERY_SECOND:
EnergyMarginCheck();

View File

@ -50,15 +50,9 @@ void SonoffBridgeReceived()
uint16_t low_time = 0;
uint16_t high_time = 0;
uint32_t received_id = 0;
char svalue[90];
char rfkey[8];
svalue[0] = '\0';
for (byte i = 0; i < serial_in_byte_counter; i++) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%02X "), svalue, serial_in_buffer[i]);
}
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_BRIDGE D_RECEIVED " %s"), svalue);
AddLog(LOG_LEVEL_DEBUG);
AddLogSerial(LOG_LEVEL_DEBUG);
if (0xA2 == serial_in_buffer[0]) { // Learn timeout
SonoffBridgeLearnFailed();
@ -115,15 +109,15 @@ boolean SonoffBridgeSerialInput()
{
// iTead Rf Universal Transceiver Module Serial Protocol Version 1.0 (20170420)
if (sonoff_bridge_receive_flag) {
if (!((serial_in_byte_counter == 0) && (serial_in_byte == 0))) { // Skip leading 0
if (!serial_in_byte_counter) {
if (!((0 == serial_in_byte_counter) && (0 == serial_in_byte))) { // Skip leading 0
if (0 == serial_in_byte_counter) {
sonoff_bridge_expected_bytes = 2; // 0xA0, 0xA1, 0xA2
if (serial_in_byte >= 0xA3) {
sonoff_bridge_expected_bytes = 11; // 0xA3, 0xA4, 0xA5
}
}
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
if ((sonoff_bridge_expected_bytes == serial_in_byte_counter) && (0x55 == serial_in_byte)) { // 0x55 - End of text
if ((sonoff_bridge_expected_bytes == serial_in_byte_counter) && (0x55 == serial_in_byte)) { // 0x55 - End of text
SonoffBridgeReceived();
sonoff_bridge_receive_flag = 0;
return 1;
@ -258,7 +252,7 @@ boolean SonoffBridgeCommand()
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_START_LEARNING);
}
else if (3 == XdrvMailbox.payload) { // Unlearn RF data
Settings.rf_code[XdrvMailbox.index][0] = 0;
Settings.rf_code[XdrvMailbox.index][0] = 0; // Reset sync_time MSB
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_SET_TO_DEFAULT);
}
else if (4 == XdrvMailbox.payload) { // Save RF data provided by RFSync, RfLow, RfHigh and last RfCode
@ -269,8 +263,23 @@ boolean SonoffBridgeCommand()
Settings.rf_code[XdrvMailbox.index][7] = (sonoff_bridge_last_send_code >> 8) & 0xff;
Settings.rf_code[XdrvMailbox.index][8] = sonoff_bridge_last_send_code & 0xff;
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_SAVED);
} else if (5 == XdrvMailbox.payload) { // Show default or learned RF data
uint8_t key = XdrvMailbox.index;
uint8_t index = (0 == Settings.rf_code[key][0]) ? 0 : key; // Use default if sync_time MSB = 0
uint16_t sync_time = (Settings.rf_code[index][0] << 8) | Settings.rf_code[index][1];
uint16_t low_time = (Settings.rf_code[index][2] << 8) | Settings.rf_code[index][3];
uint16_t high_time = (Settings.rf_code[index][4] << 8) | Settings.rf_code[index][5];
uint32_t code = (Settings.rf_code[index][6] << 16) | (Settings.rf_code[index][7] << 8);
if (0 == index) {
key--;
code |= (uint8_t)((0x10 << (key >> 2)) | (1 << (key & 3)));
} else {
code |= Settings.rf_code[index][8];
}
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("{\"%s%d\":{\"" D_JSON_SYNC "\":%d,\"" D_JSON_LOW "\":%d,\"" D_JSON_HIGH "\":%d,\"" D_JSON_DATA "\":\"%06X\"}}"),
command, XdrvMailbox.index, sync_time, low_time, high_time, code);
} else {
if ((1 == XdrvMailbox.payload) || (0 == Settings.rf_code[XdrvMailbox.index][0])) {
if ((1 == XdrvMailbox.payload) || (0 == Settings.rf_code[XdrvMailbox.index][0])) { // Test sync_time MSB
SonoffBridgeSend(0, XdrvMailbox.index); // Send default RF data
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_COMMAND_INDEX_SVALUE, command, XdrvMailbox.index, D_JSON_DEFAULT_SENT);
} else {

View File

@ -48,6 +48,7 @@ const char kDomoticzSensors[] PROGMEM =
D_DOMOTICZ_TEMP "|" D_DOMOTICZ_TEMP_HUM "|" D_DOMOTICZ_TEMP_HUM_BARO "|" D_DOMOTICZ_POWER_ENERGY "|" D_DOMOTICZ_ILLUMINANCE "|" D_DOMOTICZ_COUNT "|" D_DOMOTICZ_VOLTAGE "|" D_DOMOTICZ_CURRENT "|" D_DOMOTICZ_AIRQUALITY ;
const char S_JSON_DOMOTICZ_COMMAND_INDEX_NVALUE[] PROGMEM = "{\"" D_CMND_DOMOTICZ "%s%d\":%d}";
const char S_JSON_DOMOTICZ_COMMAND_INDEX_LVALUE[] PROGMEM = "{\"" D_CMND_DOMOTICZ "%s%d\":%lu}";
char domoticz_in_topic[] = DOMOTICZ_IN_TOPIC;
char domoticz_out_topic[] = DOMOTICZ_OUT_TOPIC;
@ -127,7 +128,6 @@ void DomoticzMqttSubscribe()
boolean DomoticzMqttData()
{
char stemp1[10];
char scommand[10];
unsigned long idx = 0;
int16_t nvalue;
int16_t found = 0;
@ -165,7 +165,7 @@ boolean DomoticzMqttData()
snprintf_P(XdrvMailbox.data, XdrvMailbox.data_len, PSTR("%d"), nvalue);
found = 1;
} else {
if (((power >> i) &1) == nvalue) {
if (((power >> i) &1) == (power_t)nvalue) {
return 1;
}
snprintf_P(XdrvMailbox.topic, XdrvMailbox.index, PSTR("/" D_CMND_POWER "%s"), (devices_present > 1) ? stemp1 : "");
@ -205,13 +205,13 @@ boolean DomoticzCommand()
Settings.domoticz_relay_idx[XdrvMailbox.index -1] = XdrvMailbox.payload;
restart_flag = 2;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_DOMOTICZ_COMMAND_INDEX_NVALUE, command, XdrvMailbox.index, Settings.domoticz_relay_idx[XdrvMailbox.index -1]);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_DOMOTICZ_COMMAND_INDEX_LVALUE, command, XdrvMailbox.index, Settings.domoticz_relay_idx[XdrvMailbox.index -1]);
}
else if ((CMND_KEYIDX == command_code) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= MAX_DOMOTICZ_IDX)) {
if (XdrvMailbox.payload >= 0) {
Settings.domoticz_key_idx[XdrvMailbox.index -1] = XdrvMailbox.payload;
}
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_DOMOTICZ_COMMAND_INDEX_NVALUE, command, XdrvMailbox.index, Settings.domoticz_key_idx[XdrvMailbox.index -1]);
snprintf_P(mqtt_data, sizeof(mqtt_data), S_JSON_DOMOTICZ_COMMAND_INDEX_LVALUE, command, XdrvMailbox.index, Settings.domoticz_key_idx[XdrvMailbox.index -1]);
}
else if ((CMND_SWITCHIDX == command_code) && (XdrvMailbox.index > 0) && (XdrvMailbox.index <= MAX_DOMOTICZ_IDX)) {
if (XdrvMailbox.payload >= 0) {
@ -332,7 +332,6 @@ void HandleDomoticzConfiguration()
AddLog_P(LOG_LEVEL_DEBUG, S_LOG_HTTP, S_CONFIGURE_DOMOTICZ);
char stemp[32];
char *sensortype;
String page = FPSTR(HTTP_HEAD);
page.replace(F("{v}"), FPSTR(S_CONFIGURE_DOMOTICZ));

View File

@ -89,10 +89,14 @@ void HAssDiscovery()
for (int i = 1; i <= devices_present; i++) {
is_light = ((i == devices_present) && (light_type));
snprintf_P(sidx, sizeof(sidx), PSTR("_%d"), i);
snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), (is_light) ? "light" : "switch", Settings.mqtt_topic, (1 == devices_present) ? "" : sidx);
mqtt_data[0] = '\0';
snprintf_P(sidx, sizeof(sidx), PSTR("_%d"), i);
// Clear "other" topic first in case the device has been reconfigured
snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), (is_light) ? "switch" : "light", mqtt_topic, (1 == devices_present) ? "" : sidx);
MqttPublish(stopic, true);
snprintf_P(stopic, sizeof(stopic), PSTR(HOME_ASSISTANT_DISCOVERY_PREFIX "/%s/%s%s/config"), (is_light) ? "light" : "switch", mqtt_topic, (1 == devices_present) ? "" : sidx);
if (Settings.flag.hass_discovery) {
char name[33];
char value_template[33];
@ -106,33 +110,33 @@ void HAssDiscovery()
snprintf_P(name, sizeof(name), Settings.friendlyname[i -1]);
}
GetPowerDevice(value_template, i, sizeof(value_template));
GetTopic_P(command_topic, CMND, Settings.mqtt_topic, value_template);
GetTopic_P(state_topic, STAT, Settings.mqtt_topic, S_RSLT_RESULT);
GetTopic_P(availability_topic, TELE, Settings.mqtt_topic, S_LWT);
GetTopic_P(command_topic, CMND, mqtt_topic, value_template);
GetTopic_P(state_topic, STAT, mqtt_topic, S_RSLT_RESULT);
GetTopic_P(availability_topic, TELE, mqtt_topic, S_LWT);
snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_SWITCH, name, command_topic, state_topic, value_template, Settings.state_text[0], Settings.state_text[1], availability_topic);
if (is_light) {
char brightness_command_topic[TOPSZ];
GetTopic_P(brightness_command_topic, CMND, Settings.mqtt_topic, D_CMND_DIMMER);
GetTopic_P(brightness_command_topic, CMND, mqtt_topic, D_CMND_DIMMER);
snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_DIMMER, mqtt_data, brightness_command_topic, state_topic);
if (light_subtype >= LST_RGB) {
char rgb_command_topic[TOPSZ];
GetTopic_P(rgb_command_topic, CMND, Settings.mqtt_topic, D_CMND_COLOR);
GetTopic_P(rgb_command_topic, CMND, mqtt_topic, D_CMND_COLOR);
snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_COLOR, mqtt_data, rgb_command_topic, state_topic);
/*
char effect_command_topic[TOPSZ];
GetTopic_P(effect_command_topic, CMND, Settings.mqtt_topic, D_CMND_SCHEME);
GetTopic_P(effect_command_topic, CMND, mqtt_topic, D_CMND_SCHEME);
snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_SCHEME, mqtt_data, effect_command_topic, state_topic);
*/
}
if ((LST_COLDWARM == light_subtype) || (LST_RGBWC == light_subtype)) {
char color_temp_command_topic[TOPSZ];
GetTopic_P(color_temp_command_topic, CMND, Settings.mqtt_topic, D_CMND_COLORTEMPERATURE);
GetTopic_P(color_temp_command_topic, CMND, mqtt_topic, D_CMND_COLORTEMPERATURE);
snprintf_P(mqtt_data, sizeof(mqtt_data), HASS_DISCOVER_LIGHT_CT, mqtt_data, color_temp_command_topic, state_topic);
}
}

View File

@ -18,6 +18,10 @@
*/
boolean (* const xdrv_func_ptr[])(byte) PROGMEM = { // Driver Function Pointers
#ifdef XDRV_00
&Xdrv00,
#endif
#ifdef XDRV_01
&Xdrv01,
#endif
@ -57,16 +61,96 @@ boolean (* const xdrv_func_ptr[])(byte) PROGMEM = { // Driver Function Pointer
#ifdef XDRV_10
&Xdrv10,
#endif
#ifdef XDRV_11
&Xdrv11,
#endif
#ifdef XDRV_12
&Xdrv12,
#endif
#ifdef XDRV_13
&Xdrv13,
#endif
#ifdef XDRV_14
&Xdrv14,
#endif
#ifdef XDRV_15
&Xdrv15,
#endif
#ifdef XDRV_16
&Xdrv16,
#endif
#ifdef XDRV_17
&Xdrv17,
#endif
#ifdef XDRV_18
&Xdrv18,
#endif
#ifdef XDRV_19
&Xdrv19,
#endif
#ifdef XDRV_20
&Xdrv20,
#endif
// Optional user defined drivers in range 91 - 99
#ifdef XDRV_91
&Xdrv91,
#endif
#ifdef XDRV_92
&Xdrv92,
#endif
#ifdef XDRV_93
&Xdrv93,
#endif
#ifdef XDRV_94
&Xdrv94,
#endif
#ifdef XDRV_95
&Xdrv95,
#endif
#ifdef XDRV_96
&Xdrv96,
#endif
#ifdef XDRV_97
&Xdrv97,
#endif
#ifdef XDRV_98
&Xdrv98,
#endif
#ifdef XDRV_99
&Xdrv99
#endif
};
const uint8_t xdrv_present = sizeof(xdrv_func_ptr) / sizeof(xdrv_func_ptr[0]); // Number of drivers found
boolean XdrvCommand(char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload)
boolean XdrvCommand(uint8_t grpflg, char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload, uint16_t payload16)
{
// XdrvMailbox.valid = 1;
XdrvMailbox.index = index;
XdrvMailbox.data_len = data_len;
XdrvMailbox.payload16 = payload16;
XdrvMailbox.payload = payload;
XdrvMailbox.grpflg = grpflg;
XdrvMailbox.topic = type;
XdrvMailbox.data = dataBuf;

View File

@ -544,7 +544,7 @@ void HueConfigResponse(String *response)
response->replace("{ms", WiFi.subnetMask().toString());
response->replace("{gw", WiFi.gatewayIP().toString());
response->replace("{br", HueBridgeId());
response->replace("{dt", GetUtcDateAndTime());
response->replace("{dt", GetDateAndTime(DT_UTC));
response->replace("{id", GetHueUserId());
}
@ -616,7 +616,6 @@ void HueLights(String *path)
String response;
uint8_t device = 1;
uint16_t tmp = 0;
int16_t pos = 0;
float bri = 0;
float hue = 0;
float sat = 0;
@ -624,7 +623,6 @@ void HueLights(String *path)
bool resp = false;
bool on = false;
bool change = false;
char id[4];
uint8_t maxhue = (devices_present > MAX_FRIENDLYNAMES) ? MAX_FRIENDLYNAMES : devices_present;
path->remove(0,path->indexOf("/lights")); // Remove until /lights

View File

@ -120,7 +120,7 @@ void SonoffScShow(boolean json)
dtostrfd(h, Settings.flag2.humidity_resolution, humidity);
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"" D_JSON_TEMPERATURE "\":%s,\"" D_JSON_HUMIDITY "\":%s,\"" D_JSON_LIGHT "\":%d,\"" D_JSON_NOISE "\":%d,\"" D_JSON_AIRQUALITY "\":%d"),
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"SonoffSC\":{\"" D_JSON_TEMPERATURE "\":%s,\"" D_JSON_HUMIDITY "\":%s,\"" D_JSON_LIGHT "\":%d,\"" D_JSON_NOISE "\":%d,\"" D_JSON_AIRQUALITY "\":%d}"),
mqtt_data, temperature, humidity, sc_value[2], sc_value[3], sc_value[4]);
#ifdef USE_DOMOTICZ
DomoticzTempHumSensor(temperature, humidity);

View File

@ -40,8 +40,8 @@ struct DHTSTRUCT {
char stype[12];
uint32_t lastreadtime;
uint8_t lastresult;
float t;
float h = 0;
float t = NAN;
float h = NAN;
} Dht[DHT_MAX_SENSORS];
void DhtReadPrep()
@ -56,7 +56,7 @@ int32_t DhtExpectPulse(byte sensor, bool level)
int32_t count = 0;
while (digitalRead(Dht[sensor].pin) == level) {
if (count++ >= dht_max_cycles) {
if (count++ >= (int32_t)dht_max_cycles) {
return -1; // Timeout
}
}
@ -141,7 +141,7 @@ void DhtRead(byte sensor)
boolean DhtReadTempHum(byte sensor, float &t, float &h)
{
if (!Dht[sensor].h) {
if (NAN == Dht[sensor].h) {
t = NAN;
h = NAN;
} else {
@ -203,7 +203,7 @@ void DhtInit()
pinMode(Dht[i].pin, INPUT_PULLUP);
Dht[i].lastreadtime = 0;
Dht[i].lastresult = 0;
strcpy_P(Dht[i].stype, kSensors[Dht[i].type]);
GetTextIndexed(Dht[i].stype, sizeof(Dht[i].stype), Dht[i].type, kSensorNames);
if (dht_sensors > 1) {
snprintf_P(Dht[i].stype, sizeof(Dht[i].stype), PSTR("%s-%02d"), Dht[i].stype, Dht[i].pin);
}
@ -214,11 +214,11 @@ void DhtShow(boolean json)
{
char temperature[10];
char humidity[10];
float t;
float h;
byte dsxflg = 0;
for (byte i = 0; i < dht_sensors; i++) {
float t = NAN;
float h = NAN;
if (DhtReadTempHum(i, t, h)) { // Read temperature
dtostrfd(t, Settings.flag2.temperature_resolution, temperature);
dtostrfd(h, Settings.flag2.humidity_resolution, humidity);

View File

@ -206,6 +206,7 @@ float HtuCompensatedHumidity(float humidity, float temperature)
if(temperature > 0.00 && temperature < 80.00) {
return (-0.15)*(25-temperature)+humidity;
}
return humidity;
}
/********************************************************************************************/

View File

@ -98,16 +98,16 @@ boolean Bmp180Calibration()
return false;
}
if ((cal_ac1 == 0xFFFF) |
(cal_ac2 == 0xFFFF) |
(cal_ac3 == 0xFFFF) |
if ((cal_ac1 == (int16_t)0xFFFF) |
(cal_ac2 == (int16_t)0xFFFF) |
(cal_ac3 == (int16_t)0xFFFF) |
(cal_ac4 == 0xFFFF) |
(cal_ac5 == 0xFFFF) |
(cal_ac6 == 0xFFFF) |
(cal_b1 == 0xFFFF) |
(cal_b2 == 0xFFFF) |
(cal_mc == 0xFFFF) |
(cal_md == 0xFFFF)) {
(cal_b1 == (int16_t)0xFFFF) |
(cal_b2 == (int16_t)0xFFFF) |
(cal_mc == (int16_t)0xFFFF) |
(cal_md == (int16_t)0xFFFF)) {
return false;
}
return true;
@ -128,9 +128,6 @@ double Bmp180ReadTemperature()
double Bmp180ReadPressure()
{
int32_t p;
uint8_t msb;
uint8_t lsb;
uint8_t xlsb;
I2cWrite8(bmp_address, BMP180_REG_CONTROL, BMP180_PRESSURE3); // Highest resolution
delay(2 + (4 << BMP180_OSS)); // 26ms conversion time at ultra high resolution

View File

@ -20,17 +20,21 @@
#ifdef USE_I2C
#ifdef USE_SHT3X
/*********************************************************************************************\
* SHT3X - Temperature and Humidy
* SHT3X and SHTC3 - Temperature and Humidy
*
* I2C Address: 0x44 or 0x45
* I2C Address: 0x44, 0x45 or 0x70 (SHTC3)
\*********************************************************************************************/
#define SHT3X_ADDR_GND 0x44 // address pin low (GND)
#define SHT3X_ADDR_VDD 0x45 // address pin high (VDD)
#define SHTC3_ADDR 0x70 // address for shtc3 sensor
const char kShtTypes[] PROGMEM = "SHT3X|SHT3X|SHTC3";
uint8_t sht3x_type = 0;
uint8_t sht3x_address;
uint8_t sht3x_addresses[] = { SHT3X_ADDR_GND, SHT3X_ADDR_VDD };
uint8_t sht3x_addresses[] = { SHT3X_ADDR_GND, SHT3X_ADDR_VDD, SHTC3_ADDR };
char sht3x_types[6];
bool Sht3xRead(float &t, float &h)
{
@ -40,8 +44,17 @@ bool Sht3xRead(float &t, float &h)
h = NAN;
Wire.beginTransmission(sht3x_address);
Wire.write(0x2C); // Enable clock stretching
Wire.write(0x06); // High repeatability
if (SHTC3_ADDR == sht3x_address) {
Wire.write(0x35); // Wake from
Wire.write(0x17); // sleep
Wire.endTransmission();
Wire.beginTransmission(sht3x_address);
Wire.write(0x78); // Dissable clock stretching ( I don't think that wire library support clock stretching )
Wire.write(0x66); // High resolution
} else {
Wire.write(0x2C); // Enable clock stretching
Wire.write(0x06); // High repeatability
}
if (Wire.endTransmission() != 0) { // Stop I2C transmission
return false;
}
@ -69,7 +82,8 @@ void Sht3xDetect()
for (byte i = 0; i < sizeof(sht3x_addresses); i++) {
sht3x_address = sht3x_addresses[i];
if (Sht3xRead(t, h)) {
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "SHT3X", sht3x_address);
GetTextIndexed(sht3x_types, sizeof(sht3x_types), i, kShtTypes);
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, sht3x_types, htu_address);
AddLog(LOG_LEVEL_DEBUG);
return;
}
@ -89,14 +103,14 @@ void Sht3xShow(boolean json)
dtostrfd(h, Settings.flag2.humidity_resolution, humidity);
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, "SHT3X", temperature, humidity);
snprintf_P(mqtt_data, sizeof(mqtt_data), JSON_SNS_TEMPHUM, mqtt_data, sht3x_types, temperature, humidity);
#ifdef USE_DOMOTICZ
DomoticzTempHumSensor(temperature, humidity);
#endif // USE_DOMOTICZ
#ifdef USE_WEBSERVER
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, "SHT3X", temperature, TempUnit());
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_HUM, mqtt_data, "SHT3X", humidity);
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TEMP, mqtt_data, sht3x_types, temperature, TempUnit());
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_HUM, mqtt_data, sht3x_types, humidity);
#endif // USE_WEBSERVER
}
}

View File

@ -158,6 +158,9 @@ void Mhz50ms()
mhz_response[counter++] = MhzSerial->read();
}
}
AddLogSerial(LOG_LEVEL_DEBUG_MORE, mhz_response, counter);
if (counter < 9) {
// AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DEBUG "MH-Z19 comms timeout"));
return;

View File

@ -1,7 +1,7 @@
/*
xsns_16_tsl2561.ino - TSL2561 light sensor support for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends
Copyright (C) 2018 Theo Arends and Joachim Banzhaf
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
@ -24,57 +24,62 @@
*
* I2C Addresses: 0x29 (low), 0x39 (float) or 0x49 (high)
*
* Using library https://github.com/adafruit/TSL2561-Arduino-Library
* Using library https://github.com/joba-1/Joba_Tsl2561
\*********************************************************************************************/
#include <TSL2561.h>
#include <Tsl2561Util.h>
uint8_t tsl2561_address;
uint8_t tsl2561_addresses[] = { TSL2561_ADDR_LOW, TSL2561_ADDR_FLOAT, TSL2561_ADDR_HIGH };
uint8_t tsl2561_type = 0;
//TSL2561 tsl(TSL2561_ADDR_FLOAT);
TSL2561 *tsl;
Tsl2561 Tsl(Wire);
void Tsl2561Detect()
{
if (tsl2561_type) {
return;
}
for (byte i = 0; i < sizeof(tsl2561_addresses); i++) {
tsl2561_address = tsl2561_addresses[i];
tsl = new TSL2561(tsl2561_address);
if (tsl->begin()) {
tsl->setGain(TSL2561_GAIN_16X);
tsl->setTiming(TSL2561_INTEGRATIONTIME_101MS);
tsl2561_type = 1;
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "TSL2561", tsl2561_address);
if (!Tsl.available()) {
Tsl.begin();
if (Tsl.available()) {
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "TSL2561", Tsl.address());
AddLog(LOG_LEVEL_DEBUG);
break;
}
}
}
#ifdef USE_WEBSERVER
const char HTTP_SNS_TSL2561[] PROGMEM =
"%s{s}TSL2561 " D_ILLUMINANCE "{m}%d " D_UNIT_LUX "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
"%s{s}TSL2561 " D_ILLUMINANCE "{m}%u.%03u " D_UNIT_LUX "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#endif // USE_WEBSERVER
void Tsl2561Show(boolean json)
{
if (tsl2561_type) {
uint16_t illuminance = tsl->getLuminosity(TSL2561_VISIBLE);
uint8_t id;
bool gain;
Tsl2561::exposure_t exposure;
uint16_t scaledFull, scaledIr;
uint32_t full, ir;
uint32_t milliLux;
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"TSL2561\":{\"" D_JSON_ILLUMINANCE "\":%d}"), mqtt_data, illuminance);
if (Tsl.available()) {
if (Tsl.on()) {
if( Tsl.id(id)
&& Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr)
&& Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr)
&& Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id))) {
snprintf_P(log_data, sizeof(log_data), PSTR(D_ILLUMINANCE " g:%d, e:%d, f:%u, i:%u -> %u.%03u " D_UNIT_LUX),
gain, exposure, full, ir, milliLux/1000, milliLux%1000);
AddLog(LOG_LEVEL_DEBUG);
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"TSL2561\":{\"" D_JSON_ILLUMINANCE "\":%u.%03u}"),
mqtt_data, milliLux/1000, milliLux%1000);
#ifdef USE_DOMOTICZ
DomoticzSensor(DZ_ILLUMINANCE, illuminance);
DomoticzSensor(DZ_ILLUMINANCE, (milliLux+500)/1000);
#endif // USE_DOMOTICZ
#ifdef USE_WEBSERVER
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TSL2561, mqtt_data, illuminance);
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_SNS_TSL2561, mqtt_data, milliLux/1000, milliLux%1000);
#endif // USE_WEBSERVER
}
}
Tsl.off();
}
}
}
@ -107,5 +112,5 @@ boolean Xsns16(byte function)
return result;
}
#endif // USE_TSL2561
#endif // USE_TSL2561_JOBA
#endif // USE_I2C

View File

@ -96,6 +96,9 @@ uint8_t ModbusReceive(uint16_t *value)
}
}
}
AddLogSerial(LOG_LEVEL_DEBUG_MORE, buffer, len);
if (len != sizeof(buffer)) {
return 9; // 9 = Unexpected result
}

View File

@ -56,6 +56,8 @@ boolean PmsReadData()
PmsSerial->readBytes(buffer, 32);
PmsSerial->flush(); // Make room for another burst
AddLogSerial(LOG_LEVEL_DEBUG_MORE, buffer, 32);
// get checksum ready
for (uint8_t i = 0; i < 30; i++) {
sum += buffer[i];

121
sonoff/xsns_19_mgs.ino Normal file
View File

@ -0,0 +1,121 @@
/*
xsns_19_mgs.ino - Xadow and Grove Mutichannel Gas sensor support for Sonoff-Tasmota
Copyright (C) 2018 Palich2000 and Theo Arends
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/>.
*/
#ifdef USE_I2C
#ifdef USE_MGS
/*********************************************************************************************\
* Grove - Multichannel Gas Sensor
* http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/
*
* https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git
\*********************************************************************************************/
#ifndef MGS_SENSOR_ADDR
#define MGS_SENSOR_ADDR 0x04 // Default Mutichannel Gas sensor i2c address
#endif
#include "MutichannelGasSensor.h"
void MGSInit() {
gas.begin(MGS_SENSOR_ADDR);
}
boolean MGSPrepare()
{
gas.begin(MGS_SENSOR_ADDR);
if (!gas.isError()) {
snprintf_P(log_data, sizeof(log_data), S_LOG_I2C_FOUND_AT, "MultiGasSensor", MGS_SENSOR_ADDR);
AddLog(LOG_LEVEL_DEBUG);
return true;
} else {
return false;
}
}
char* measure_gas(int gas_type, char* buffer)
{
float f = gas.calcGas(gas_type);
dtostrfd(f, 2, buffer);
return buffer;
}
#ifdef USE_WEBSERVER
const char HTTP_MGS_GAS[] PROGMEM = "%s{s}MGS %s{m}%s " D_UNIT_PARTS_PER_MILLION "{e}"; // {s} = <tr><th>, {m} = </th><td>, {e} = </td></tr>
#endif // USE_WEBSERVER
void MGSShow(boolean json)
{
char buffer[25];
if (json) {
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"MGS\":{\"NH3\":%s"), mqtt_data, measure_gas(NH3, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"CO\":%s"), mqtt_data, measure_gas(CO, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"NO2\":%s"), mqtt_data, measure_gas(NO2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C3H8\":%s"), mqtt_data, measure_gas(C3H8, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C4H10\":%s"), mqtt_data, measure_gas(C4H10, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"CH4\":%s"), mqtt_data, measure_gas(GAS_CH4, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"H2\":%s"), mqtt_data, measure_gas(H2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), PSTR("%s,\"C2H5OH\":%s}"), mqtt_data, measure_gas(C2H5OH, buffer));
#ifdef USE_WEBSERVER
} else {
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "NH3", measure_gas(NH3, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "CO", measure_gas(CO, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "NO2", measure_gas(NO2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C3H8", measure_gas(C3H8, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C4H10", measure_gas(C4H10, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "CH4", measure_gas(GAS_CH4, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "H2", measure_gas(H2, buffer));
snprintf_P(mqtt_data, sizeof(mqtt_data), HTTP_MGS_GAS, mqtt_data, "C2H5OH", measure_gas(C2H5OH, buffer));
#endif // USE_WEBSERVER
}
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
#define XSNS_19
boolean Xsns19(byte function)
{
boolean result = false;
static int detected = false;
if (i2c_flg) {
switch (function) {
case FUNC_INIT:
// MGSInit();
break;
case FUNC_PREP_BEFORE_TELEPERIOD:
detected = MGSPrepare();
break;
case FUNC_JSON_APPEND:
if (detected) MGSShow(1);
break;
#ifdef USE_WEBSERVER
case FUNC_WEB_APPEND:
if (detected) MGSShow(0);
break;
#endif // USE_WEBSERVER
}
}
return result;
}
#endif // USE_MGS
#endif // USE_I2C

View File

@ -97,6 +97,92 @@ boolean (* const xsns_func_ptr[])(byte) PROGMEM = { // Sensor Function Pointers
#ifdef XSNS_20
&Xsns20,
#endif
#ifdef XSNS_21
&Xsns21,
#endif
#ifdef XSNS_22
&Xsns22,
#endif
#ifdef XSNS_23
&Xsns23,
#endif
#ifdef XSNS_24
&Xsns24,
#endif
#ifdef XSNS_25
&Xsns25,
#endif
#ifdef XSNS_26
&Xsns26,
#endif
#ifdef XSNS_27
&Xsns27,
#endif
#ifdef XSNS_28
&Xsns28,
#endif
#ifdef XSNS_29
&Xsns29,
#endif
#ifdef XSNS_30
&Xsns30,
#endif
#ifdef XSNS_31
&Xsns31,
#endif
#ifdef XSNS_32
&Xsns32,
#endif
// Optional user defined sensors in range 91 - 99
#ifdef XSNS_91
&Xsns91,
#endif
#ifdef XSNS_92
&Xsns92,
#endif
#ifdef XSNS_93
&Xsns93,
#endif
#ifdef XSNS_94
&Xsns94,
#endif
#ifdef XSNS_95
&Xsns95,
#endif
#ifdef XSNS_96
&Xsns96,
#endif
#ifdef XSNS_97
&Xsns97,
#endif
#ifdef XSNS_98
&Xsns98,
#endif
#ifdef XSNS_99
&Xsns99
#endif
};
const uint8_t xsns_present = sizeof(xsns_func_ptr) / sizeof(xsns_func_ptr[0]); // Number of External Sensors found