pull/16/head
Martin Ger 2017-09-29 01:46:42 +02:00
rodzic a365bf8278
commit 2d7c43145e
11 zmienionych plików z 954 dodań i 26 usunięć

Wyświetl plik

@ -33,14 +33,14 @@ ESPPORT ?= /dev/ttyUSB0
TARGET = app
# which modules (subdirectories) of the project to include in compiling
MODULES = driver user mqtt ntp easygpio cJSON
MODULES = driver user mqtt ntp easygpio pwm
#EXTRA_INCDIR = $(BUILD_AREA)/esp-open-sdk/esp-open-lwip/include include
EXTRA_INCDIR = include
LIB_MODULES = mqtt
# libraries used in this project, mainly provided by the SDK
LIBS = c gcc hal pp phy net80211 lwip wpa main
LIBS = c gcc hal pp phy net80211 lwip wpa main ssl
# compiler flags using during compilation of source files
CFLAGS = -Os -g -O2 -Wpointer-arith -Wundef -Werror -Wl,-EL -fno-inline-functions -nostdlib -mlongcalls -mtext-section-literals -D__ets__ -DICACHE_FLASH -DUSE_OPTIMIZE_PRINTF -Desp8266

Wyświetl plik

@ -1,7 +1,7 @@
# esp_uMQTT_broker
An MQTT Broker/Client with scripting support on the ESP8266
This program enables the ESP8266 to become the central node in a small distributed IoT system. It implements an MQTT Broker and a simple scripted rule engine with event/action statements that links together the MQTT sensors and actors. It can act as STA, as AP, or as both and it can connect to another MQTT broker (i.e. in the cloud). Here it can act as bridge and forward and rewrite topics in both directions. Also it can write on local GPIO pins and react on GPIO interrupts.
This program enables the ESP8266 to become the central node in a small distributed IoT system. It implements an MQTT Broker and a simple scripted rule engine with event/action statements that links together the MQTT sensors and actors. It can act as STA, as AP, or as both and it can connect to another MQTT broker (i.e. in the cloud). Here it can act as bridge and forward and rewrite topics in both directions. Also it can write to local GPIO pins, react on GPIO interrupts, and drive GPIO pins with PWM.
Find a video that explains the ideas and the architecture of the project at: https://www.youtube.com/watch?v=0K9q4IuB_oA
@ -233,8 +233,9 @@ In general, scripts have the following BNF:
unsubscribe (local|remote) <topic-id> |
settimer <num> <expr> |
setvar ($[any ASCII]* | @<num>) = <expr> |
gpio_pinmode <num> [pullup]
gpio_pinmode <num> (input|output) [pullup] |
gpio_out <num> <expr> |
gpio_pwm <num> <num> |
if <expr> then <action> [else <action>] endif |
print <expr> | println <expr> |
system <expr> |

Plik binarny nie jest wyświetlany.

Plik binarny nie jest wyświetlany.

340
pwm/LICENSE 100644
Wyświetl plik

@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
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.
{description}
Copyright (C) {year} {fullname}
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.

455
pwm/pwm.c 100644
Wyświetl plik

@ -0,0 +1,455 @@
/*
* Copyright (C) 2016 Stefan Brüns <stefan.bruens@rwth-aachen.de>
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Set the following three defines to your needs */
#include "user_config.h"
#ifndef SDK_PWM_PERIOD_COMPAT_MODE
#define SDK_PWM_PERIOD_COMPAT_MODE 0
#endif
#ifndef PWM_MAX_CHANNELS
#define PWM_MAX_CHANNELS 8
#endif
#define PWM_DEBUG 0
#define PWM_USE_NMI 1
/* no user servicable parts beyond this point */
#define PWM_MAX_TICKS 0x7fffff
#if SDK_PWM_PERIOD_COMPAT_MODE
#define PWM_PERIOD_TO_TICKS(x) (x * 0.2)
#define PWM_DUTY_TO_TICKS(x) (x * 5)
#define PWM_MAX_DUTY (PWM_MAX_TICKS * 0.2)
#define PWM_MAX_PERIOD (PWM_MAX_TICKS * 5)
#else
#define PWM_PERIOD_TO_TICKS(x) (x)
#define PWM_DUTY_TO_TICKS(x) (x)
#define PWM_MAX_DUTY PWM_MAX_TICKS
#define PWM_MAX_PERIOD PWM_MAX_TICKS
#endif
#include <c_types.h>
#include <pwm.h>
#include <eagle_soc.h>
#include <ets_sys.h>
#include "easygpio.h"
// from SDK hw_timer.c
#define TIMER1_DIVIDE_BY_16 0x0004
#define TIMER1_ENABLE_TIMER 0x0080
struct pwm_phase {
uint32_t ticks; ///< delay until next phase, in 200ns units
uint16_t on_mask; ///< GPIO mask to switch on
uint16_t off_mask; ///< GPIO mask to switch off
};
/* Three sets of PWM phases, the active one, the one used
* starting with the next cycle, and the one updated
* by pwm_start. After the update pwm_next_set
* is set to the last updated set. pwm_current_set is set to
* pwm_next_set from the interrupt routine during the first
* pwm phase
*/
typedef struct pwm_phase (pwm_phase_array)[PWM_MAX_CHANNELS + 2];
static pwm_phase_array pwm_phases[3];
static struct {
struct pwm_phase* next_set;
struct pwm_phase* current_set;
uint8_t current_phase;
} pwm_state;
static uint32_t pwm_period;
static uint32_t pwm_period_ticks;
static uint32_t pwm_duty[PWM_MAX_CHANNELS];
static uint16_t gpio_mask[PWM_MAX_CHANNELS];
static uint8_t pwm_channels;
// 3-tuples of MUX_REGISTER, MUX_VALUE and GPIO number
typedef uint32_t (pin_info_type)[3];
struct gpio_regs {
uint32_t out; /* 0x60000300 */
uint32_t out_w1ts; /* 0x60000304 */
uint32_t out_w1tc; /* 0x60000308 */
uint32_t enable; /* 0x6000030C */
uint32_t enable_w1ts; /* 0x60000310 */
uint32_t enable_w1tc; /* 0x60000314 */
uint32_t in; /* 0x60000318 */
uint32_t status; /* 0x6000031C */
uint32_t status_w1ts; /* 0x60000320 */
uint32_t status_w1tc; /* 0x60000324 */
};
static struct gpio_regs* gpio = (struct gpio_regs*)(0x60000300);
struct timer_regs {
uint32_t frc1_load; /* 0x60000600 */
uint32_t frc1_count; /* 0x60000604 */
uint32_t frc1_ctrl; /* 0x60000608 */
uint32_t frc1_int; /* 0x6000060C */
uint8_t pad[16];
uint32_t frc2_load; /* 0x60000620 */
uint32_t frc2_count; /* 0x60000624 */
uint32_t frc2_ctrl; /* 0x60000628 */
uint32_t frc2_int; /* 0x6000062C */
uint32_t frc2_alarm; /* 0x60000630 */
};
static struct timer_regs* timer = (struct timer_regs*)(0x60000600);
static void
pwm_intr_handler(void)
{
if ((pwm_state.current_set[pwm_state.current_phase].off_mask == 0) &&
(pwm_state.current_set[pwm_state.current_phase].on_mask == 0)) {
pwm_state.current_set = pwm_state.next_set;
pwm_state.current_phase = 0;
}
do {
// force write to GPIO registers on each loop
asm volatile ("" : : : "memory");
gpio->out_w1ts = (uint32_t)(pwm_state.current_set[pwm_state.current_phase].on_mask);
gpio->out_w1tc = (uint32_t)(pwm_state.current_set[pwm_state.current_phase].off_mask);
uint32_t ticks = pwm_state.current_set[pwm_state.current_phase].ticks;
pwm_state.current_phase++;
if (ticks) {
if (ticks >= 16) {
// constant interrupt overhead
ticks -= 9;
timer->frc1_int &= ~FRC1_INT_CLR_MASK;
WRITE_PERI_REG(&timer->frc1_load, ticks);
return;
}
ticks *= 4;
do {
ticks -= 1;
// stop compiler from optimizing delay loop to noop
asm volatile ("" : : : "memory");
} while (ticks > 0);
}
} while (1);
}
/**
* period: initial period (base unit 1us OR 200ns)
* duty: array of initial duty values, may be NULL, may be freed after pwm_init
* pwm_channel_num: number of channels to use
* pin_info_list: array of pin_info
*/
void ICACHE_FLASH_ATTR
pwm_init(uint32_t period, uint32_t *duty, uint32_t pwm_channel_num,
uint32_t (*pin_info_list)[3])
{
int i, j, n;
pwm_channels = pwm_channel_num;
if (pwm_channels > PWM_MAX_CHANNELS)
pwm_channels = PWM_MAX_CHANNELS;
for (i = 0; i < 3; i++) {
for (j = 0; j < (PWM_MAX_CHANNELS + 2); j++) {
pwm_phases[i][j].ticks = 0;
pwm_phases[i][j].on_mask = 0;
pwm_phases[i][j].off_mask = 0;
}
}
pwm_state.current_set = pwm_state.next_set = 0;
pwm_state.current_phase = 0;
uint32_t all = 0;
// PIN info: MUX-Register, Mux-Setting, PIN-Nr
for (n = 0; n < pwm_channels; n++) {
pin_info_type* pin_info = &pin_info_list[n];
// PIN_FUNC_SELECT((*pin_info)[0], (*pin_info)[1]);
easygpio_pinMode((*pin_info)[2], EASYGPIO_NOPULL, EASYGPIO_OUTPUT);
gpio_mask[n] = 1 << (*pin_info)[2];
all |= 1 << (*pin_info)[2];
if (duty)
pwm_set_duty(duty[n], n);
}
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, all);
GPIO_REG_WRITE(GPIO_ENABLE_W1TS_ADDRESS, all);
pwm_set_period(period);
#if PWM_USE_NMI
ETS_FRC_TIMER1_NMI_INTR_ATTACH(pwm_intr_handler);
#else
ETS_FRC_TIMER1_INTR_ATTACH(pwm_intr_handler, NULL);
#endif
TM1_EDGE_INT_ENABLE();
timer->frc1_int &= ~FRC1_INT_CLR_MASK;
timer->frc1_ctrl = 0;
pwm_start();
}
__attribute__ ((noinline))
static uint8_t ICACHE_FLASH_ATTR
_pwm_phases_prep(struct pwm_phase* pwm)
{
uint8_t n, phases;
uint16_t off_mask = 0;
for (n = 0; n < pwm_channels + 2; n++) {
pwm[n].ticks = 0;
pwm[n].on_mask = 0;
pwm[n].off_mask = 0;
}
phases = 1;
for (n = 0; n < pwm_channels; n++) {
uint32_t ticks = PWM_DUTY_TO_TICKS(pwm_duty[n]);
if (ticks == 0) {
pwm[0].off_mask |= gpio_mask[n];
} else if (ticks >= pwm_period_ticks) {
pwm[0].on_mask |= gpio_mask[n];
} else {
if (ticks < (pwm_period_ticks/2)) {
pwm[phases].ticks = ticks;
pwm[0].on_mask |= gpio_mask[n];
pwm[phases].off_mask = gpio_mask[n];
} else {
pwm[phases].ticks = pwm_period_ticks - ticks;
pwm[phases].on_mask = gpio_mask[n];
pwm[0].off_mask |= gpio_mask[n];
}
phases++;
}
}
pwm[phases].ticks = pwm_period_ticks;
// bubble sort, lowest to hightest duty
n = 2;
while (n < phases) {
if (pwm[n].ticks < pwm[n - 1].ticks) {
struct pwm_phase t = pwm[n];
pwm[n] = pwm[n - 1];
pwm[n - 1] = t;
if (n > 2)
n--;
} else {
n++;
}
}
#if PWM_DEBUG
int t = 0;
for (t = 0; t <= phases; t++) {
ets_printf("%d @%d: %04x %04x\n", t, pwm[t].ticks, pwm[t].on_mask, pwm[t].off_mask);
}
#endif
// shift left to align right edge;
uint8_t l = 0, r = 1;
while (r <= phases) {
uint32_t diff = pwm[r].ticks - pwm[l].ticks;
if (diff && (diff <= 16)) {
uint16_t mask = pwm[r].on_mask | pwm[r].off_mask;
pwm[l].off_mask ^= pwm[r].off_mask;
pwm[l].on_mask ^= pwm[r].on_mask;
pwm[0].off_mask ^= pwm[r].on_mask;
pwm[0].on_mask ^= pwm[r].off_mask;
pwm[r].ticks = pwm_period_ticks - diff;
pwm[r].on_mask ^= mask;
pwm[r].off_mask ^= mask;
} else {
l = r;
}
r++;
}
#if PWM_DEBUG
for (t = 0; t <= phases; t++) {
ets_printf("%d @%d: %04x %04x\n", t, pwm[t].ticks, pwm[t].on_mask, pwm[t].off_mask);
}
#endif
// sort again
n = 2;
while (n <= phases) {
if (pwm[n].ticks < pwm[n - 1].ticks) {
struct pwm_phase t = pwm[n];
pwm[n] = pwm[n - 1];
pwm[n - 1] = t;
if (n > 2)
n--;
} else {
n++;
}
}
// merge same duty
l = 0, r = 1;
while (r <= phases) {
if (pwm[r].ticks == pwm[l].ticks) {
pwm[l].off_mask |= pwm[r].off_mask;
pwm[l].on_mask |= pwm[r].on_mask;
pwm[r].on_mask = 0;
pwm[r].off_mask = 0;
} else {
l++;
if (l != r) {
struct pwm_phase t = pwm[l];
pwm[l] = pwm[r];
pwm[r] = t;
}
}
r++;
}
phases = l;
#if PWM_DEBUG
for (t = 0; t <= phases; t++) {
ets_printf("%d @%d: %04x %04x\n", t, pwm[t].ticks, pwm[t].on_mask, pwm[t].off_mask);
}
#endif
// transform absolute end time to phase durations
for (n = 0; n < phases; n++) {
pwm[n].ticks =
pwm[n + 1].ticks - pwm[n].ticks;
// subtract common overhead
pwm[n].ticks--;
}
pwm[phases].ticks = 0;
// do a cyclic shift if last phase is short
if (pwm[phases - 1].ticks < 16) {
for (n = 0; n < phases - 1; n++) {
struct pwm_phase t = pwm[n];
pwm[n] = pwm[n + 1];
pwm[n + 1] = t;
}
}
#if PWM_DEBUG
for (t = 0; t <= phases; t++) {
ets_printf("%d +%d: %04x %04x\n", t, pwm[t].ticks, pwm[t].on_mask, pwm[t].off_mask);
}
ets_printf("\n");
#endif
return phases;
}
void ICACHE_FLASH_ATTR
pwm_start(void)
{
pwm_phase_array* pwm = &pwm_phases[0];
if ((*pwm == pwm_state.next_set) ||
(*pwm == pwm_state.current_set))
pwm++;
if ((*pwm == pwm_state.next_set) ||
(*pwm == pwm_state.current_set))
pwm++;
uint8_t phases = _pwm_phases_prep(*pwm);
// all with 0% / 100% duty - stop timer
if (phases == 1) {
if (pwm_state.next_set) {
#if PWM_DEBUG
ets_printf("PWM stop\n");
#endif
timer->frc1_ctrl = 0;
ETS_FRC1_INTR_DISABLE();
}
pwm_state.next_set = NULL;
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, (*pwm)[0].on_mask);
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, (*pwm)[0].off_mask);
return;
}
// start if not running
if (!pwm_state.next_set) {
#if PWM_DEBUG
ets_printf("PWM start\n");
#endif
pwm_state.current_set = pwm_state.next_set = *pwm;
pwm_state.current_phase = phases - 1;
ETS_FRC1_INTR_ENABLE();
RTC_REG_WRITE(FRC1_LOAD_ADDRESS, 0);
timer->frc1_ctrl = TIMER1_DIVIDE_BY_16 | TIMER1_ENABLE_TIMER;
return;
}
pwm_state.next_set = *pwm;
}
void ICACHE_FLASH_ATTR
pwm_set_duty(uint32_t duty, uint8_t channel)
{
if (channel > PWM_MAX_CHANNELS)
return;
if (duty > PWM_MAX_DUTY)
duty = PWM_MAX_DUTY;
pwm_duty[channel] = duty;
}
uint32_t ICACHE_FLASH_ATTR
pwm_get_duty(uint8_t channel)
{
if (channel > PWM_MAX_CHANNELS)
return 0;
return pwm_duty[channel];
}
void ICACHE_FLASH_ATTR
pwm_set_period(uint32_t period)
{
pwm_period = period;
if (pwm_period > PWM_MAX_PERIOD)
pwm_period = PWM_MAX_PERIOD;
pwm_period_ticks = PWM_PERIOD_TO_TICKS(period);
}
uint32_t ICACHE_FLASH_ATTR
pwm_get_period(void)
{
return pwm_period;
}
uint32_t ICACHE_FLASH_ATTR
get_pwm_version(void)
{
return 1;
}
void ICACHE_FLASH_ATTR
set_pwm_debug_en(uint8_t print_en)
{
(void) print_en;
}

Wyświetl plik

@ -56,6 +56,11 @@ void config_load_default(sysconfig_p config) {
config->ntp_interval = 300000000;
config->ntp_timezone = 0;
#endif
#ifdef GPIO
#ifdef GPIO_PWM
config->pwm_period = 5000;
#endif
#endif
}
int config_load(sysconfig_p config) {

Wyświetl plik

@ -68,8 +68,16 @@ typedef struct
uint32_t ntp_interval; // Sync interval in usec
int16_t ntp_timezone; // Timezone (hour offset to GMT)
#endif
#ifdef GPIO
#ifdef GPIO_PWM
uint32_t pwm_period; // PWM period
#endif
#endif
} sysconfig_t, *sysconfig_p;
// The global config
extern sysconfig_t config;
int config_load(sysconfig_p config);
void config_save(sysconfig_p config);

Wyświetl plik

@ -3,13 +3,19 @@
#include "osapi.h"
#include "lang.h"
#include "user_config.h"
#include "config_flash.h"
#include "mqtt_topics.h"
#ifdef NTP
#include "ntp.h"
#endif
#ifdef GPIO
#include "easygpio.h"
#ifdef GPIO_PWM
#include "pwm.h"
#endif
#endif
#define lang_debug //os_printf
#define lang_log(...) {if (lang_logging){char log_buffer[256]; os_sprintf (log_buffer, "%s: ", get_timestr()); con_print(log_buffer); os_sprintf (log_buffer, __VA_ARGS__); con_print(log_buffer);}}
@ -32,11 +38,17 @@ typedef struct _timestamp_entry_t {
#ifdef GPIO
typedef struct _gpio_entry_t {
uint8_t no;
os_timer_t inttimer;
uint8_t no;
bool val;
} gpio_entry_t;
static gpio_entry_t gpios[MAX_GPIOS];
int gpio_counter;
#ifdef GPIO_PWM
static uint8_t pwm_channels[PWM_MAX_CHANNELS];
int pwm_counter;
#endif
#endif
bool lang_logging = false;
@ -54,7 +66,6 @@ char *interpreter_timestamp;
int interpreter_gpio;
int interpreter_gpioval;
int ts_counter;
int gpio_counter;
static os_timer_t timers[MAX_TIMERS];
var_entry_t vars[MAX_VARS];
@ -190,7 +201,35 @@ void ICACHE_FLASH_ATTR stop_gpios() {
gpio_pin_intr_state_set(GPIO_ID_PIN(gpios[i].no), GPIO_PIN_INTR_DISABLE);
}
}
#endif
#ifdef GPIO_PWM
int32_t ICACHE_FLASH_ATTR pwm_channel_from_pin(int pin) {
int32_t i;
for (i = 0; i < pwm_counter; i++) {
if (pin == pwm_channels[i])
return i;
}
return -1;
}
void ICACHE_FLASH_ATTR init_pwm() {
uint32 io_info[pwm_counter][3];
int32_t i;
if (!script_enabled || pwm_counter == 0)
return;
for (i = 0; i < pwm_counter; i++) {
io_info[i][2] = pwm_channels[i];
}
// initial duty: all off
pwm_init(config.pwm_period, NULL, pwm_counter, io_info);
pwm_start();
}
#endif /* GPIO_PWM */
#endif /* GPIO */
void ICACHE_FLASH_ATTR test_tokens(void) {
int i;
@ -510,6 +549,10 @@ int ICACHE_FLASH_ATTR parse_event(int next_token, bool * happend) {
if (syn_chk) {
if (gpio_no > 16)
return syntax_error(next_token + 1, "invalid gpio number");
#ifdef GPIO_PWM
if (pwm_channel_from_pin(gpio_no) != -1)
return syntax_error(next_token, "pin defined as pwm before");
#endif
if (!is_token(next_token+2, "pullup") && !is_token(next_token+2, "nopullup"))
return syntax_error(next_token + 2, "expected 'pullup' or 'nopullup'");
int pullup = is_token(next_token+2, "pullup") ? EASYGPIO_PULLUP : EASYGPIO_NOPULL;
@ -812,10 +855,10 @@ int ICACHE_FLASH_ATTR parse_action(int next_token, bool doit) {
slot_no--;
uint8_t slots[MAX_FLASH_SLOTS*FLASH_SLOT_LEN];
blob_load(1, slots, sizeof(slots));
blob_load(1, (uint32_t *)slots, sizeof(slots));
os_memcpy(&slots[slot_no*FLASH_SLOT_LEN], var_data, var_len);
slots[slot_no*FLASH_SLOT_LEN+FLASH_SLOT_LEN-1] = '\0';
blob_save(1, slots, sizeof(slots));
blob_save(1, (uint32_t *)slots, sizeof(slots));
} else {
if (var_len > this_var->buffer_len - 1) {
@ -843,7 +886,10 @@ int ICACHE_FLASH_ATTR parse_action(int next_token, bool doit) {
uint32_t gpio_no = atoi(my_token[next_token + 1]);
if (gpio_no > 16)
return syntax_error(next_token + 1, "invalid gpio number");
#ifdef GPIO_PWM
if (syn_chk && pwm_channel_from_pin(gpio_no) != -1)
return syntax_error(next_token, "pin defined as pwm before");
#endif
int pullup = EASYGPIO_NOPULL;
int inout = EASYGPIO_OUTPUT;
if (is_token(next_token+2, "input")) {
@ -852,7 +898,7 @@ int ICACHE_FLASH_ATTR parse_action(int next_token, bool doit) {
pullup = EASYGPIO_PULLUP;
next_token++;
}
else if (syn_chk && !is_token(next_token+2, "output"))
} else if (syn_chk && !is_token(next_token+2, "output")) {
return syntax_error(next_token + 2, "expected 'input' or 'output'");
}
@ -882,11 +928,36 @@ int ICACHE_FLASH_ATTR parse_action(int next_token, bool doit) {
easygpio_outputSet(gpio_no, atoi(gpio_data) != 0);
}
}
#endif
else if (is_token(next_token, "write_flash")) {
#ifdef GPIO_PWM
else if (is_token(next_token, "gpio_pwm")) {
len_check(1);
uint32_t gpio_no = atoi(my_token[next_token + 1]);
if (gpio_no > 16)
return syntax_error(next_token + 1, "invalid gpio number");
if (syn_chk && pwm_channel_from_pin(gpio_no) == -1) {
if (pwm_counter >= PWM_MAX_CHANNELS)
return syntax_error(next_token, "too many pwm channels");
pwm_channels[pwm_counter] = gpio_no;
pwm_counter++;
}
char *pwm_data;
int pwm_len;
Value_Type pwm_type;
if ((next_token = parse_expression(next_token + 2, &pwm_data, &pwm_len, &pwm_type, doit)) == -1)
return -1;
uint32_t pwm_channel = pwm_channel_from_pin(gpio_no);
if (doit && pwm_channel != -1) {
lang_log("gpio_pwm %d %s\r\n", gpio_no, pwm_data);
pwm_set_duty((atoi(pwm_data)*config.pwm_period)/1000, pwm_channel);
pwm_start();
}
}
#endif
#endif
else
return syntax_error(next_token, "action command expected");
@ -1165,7 +1236,7 @@ int ICACHE_FLASH_ATTR parse_value(int next_token, char **data, int *data_len, Va
if (!syn_chk) {
slot_no--;
uint8_t slots[MAX_FLASH_SLOTS*FLASH_SLOT_LEN];
blob_load(1, slots, sizeof(slots));
blob_load(1, (uint32_t *)slots, sizeof(slots));
os_memcpy(tmp_buffer, &slots[slot_no*FLASH_SLOT_LEN], FLASH_SLOT_LEN);
*data = tmp_buffer;
*data_len = os_strlen(tmp_buffer);
@ -1199,7 +1270,12 @@ int ICACHE_FLASH_ATTR interpreter_syntax_check() {
interpreter_data_len = 0;
os_bzero(&timestamps, sizeof(timestamps));
ts_counter = 0;
#ifdef GPIO
gpio_counter = 0;
#ifdef GPIO_PWM
pwm_counter = 0;
#endif
#endif
return parse_statement(0);
}
@ -1219,7 +1295,7 @@ int ICACHE_FLASH_ATTR interpreter_config() {
slot_no--;
uint8_t slots[MAX_FLASH_SLOTS*FLASH_SLOT_LEN];
blob_load(1, slots, sizeof(slots));
blob_load(1, (uint32_t *)slots, sizeof(slots));
val = &slots[slot_no*FLASH_SLOT_LEN];
if (val[0] == '\0')
val = "_undefined_";
@ -1238,11 +1314,20 @@ int ICACHE_FLASH_ATTR interpreter_init() {
return -1;
lang_debug("interpreter_init\r\n");
#ifdef GPIO
#ifdef GPIO_PWM
init_pwm();
#endif
#endif
interpreter_status = INIT;
interpreter_topic = interpreter_data = "";
interpreter_data_len = 0;
return parse_statement(0);
int ret_val = parse_statement(0);
#ifdef GPIO
init_gpios();
#endif
return ret_val;
}
int ICACHE_FLASH_ATTR interpreter_reconnect(void) {
@ -1261,11 +1346,15 @@ int ICACHE_FLASH_ATTR interpreter_topic_received(const char *topic, const char *
if (!script_enabled)
return -1;
uint8_t data_null[data_len+1];
os_memcpy(data_null, data, data_len);
data_null[data_len] = '\0';
lang_debug("interpreter_topic_received\r\n");
interpreter_status = (local) ? TOPIC_LOCAL : TOPIC_REMOTE;
interpreter_topic = (char *)topic;
interpreter_data = (char *)data;
interpreter_data = data_null;
interpreter_data_len = data_len;
return parse_statement(0);

Wyświetl plik

@ -16,6 +16,9 @@
// Define this if you want to have it work as a MQTT client
#define MQTT_CLIENT 1
// Define this if you need SSL for the *MQTT client*
//#define MQTT_SSL_ENABLE 1
#define MQTT_BUF_SIZE 1024
#define MQTT_KEEPALIVE 120 /*seconds*/
#define MQTT_RECONNECT_TIMEOUT 5 /*seconds*/
@ -34,6 +37,7 @@
#define MAX_SCRIPT_SIZE 0x1000
#define MAX_TIMERS 4
#define MAX_GPIOS 3
#define PWM_MAX_CHANNELS 8
#define MAX_VARS 10
#define DEFAULT_VAR_LEN 16
#define MAX_TIMESTAMPS 6
@ -45,6 +49,11 @@
//
#define GPIO 1
//
// Define this if you want to have additionally GPIO PWM support in scripts.
//
#define GPIO_PWM 1
//
// Define this if you want to have NTP support.
//

Wyświetl plik

@ -17,6 +17,13 @@
#include "mqtt_topiclist.h"
#include "mqtt_retainedlist.h"
#ifdef GPIO
//#include "easygpio.h"
#include "pwm.h"
#define PWM_CHANNELS 5
const uint32_t period = 5000; // * 200ns ^= 1 kHz
#endif
#ifdef NTP
#include "ntp.h"
uint64_t t_ntp_resync = 0;
@ -398,6 +405,12 @@ void ICACHE_FLASH_ATTR console_handle_command(struct espconn *pespconn) {
#ifdef SCRIPTED
os_sprintf(response, "script <port>\r\nshow [script|vars]\r\n");
to_console(response);
#ifdef GPIO
#ifdef GPIO_PWM
os_sprintf(response, "set pwm_period <val>\r\n");
to_console(response);
#endif
#endif
#endif
#ifdef NTP
os_sprintf(response, "time\r\nset [ntp_server|ntp_interval|<ntp_timezone> <val>\r\n");
@ -624,10 +637,12 @@ void ICACHE_FLASH_ATTR console_handle_command(struct espconn *pespconn) {
}
int i;
for (i = 0; i < MAX_VARS; i++) {
if (!vars[i].free) {
os_sprintf(response, "%s: %s\r\n", vars[i].name, vars[i].data);
to_console(response);
if (script_enabled) {
for (i = 0; i < MAX_VARS; i++) {
if (!vars[i].free) {
os_sprintf(response, "%s: %s\r\n", vars[i].name, vars[i].data);
to_console(response);
}
}
}
@ -1031,6 +1046,15 @@ void ICACHE_FLASH_ATTR console_handle_command(struct espconn *pespconn) {
}
goto command_handled;
}
#ifdef GPIO
#ifdef GPIO_PWM
if (strcmp(tokens[1], "pwm_period") == 0) {
config.pwm_period = atoi(tokens[2]);
os_sprintf(response, "PWM period set\r\n");
goto command_handled;
}
#endif
#endif
#endif
#ifdef NTP
if (strcmp(tokens[1], "ntp_server") == 0) {
@ -1611,9 +1635,6 @@ void user_init() {
#ifdef SCRIPTED
timestamps_init = false;
interpreter_init();
#ifdef GPIO
init_gpios();
#endif
#endif
// Start the timer