Refactor GENERIC_RESOURCE macro

Now callback functions get the URI of the request, this allows to use a
single resource for multiple different URIs.
The is_json flag is now gone for the to-string function, instead the
macro has an is_str flag. If set this automagically produces quotes
around the string for json output.
Now from-string functions can return an error-code, 0 for success, -1
for error.
This commit is contained in:
Ralf Schlatterbeck 2016-02-26 07:54:05 +01:00
parent c7daa7c45d
commit c6165a3bcf
9 changed files with 106 additions and 68 deletions

View file

@ -17,17 +17,18 @@
#include "generic_resource.h"
#include "led_pwm.h"
void pwm_from_string (const char *name, const char *s)
int pwm_from_string (const char *name, const char *uri, const char *s)
{
uint32_t tmp = strtoul (s, NULL, 10);
if (tmp > 255) {
tmp = 255;
}
pwm = tmp;
return 0;
}
size_t
pwm_to_string (const char *name, uint8_t is_json, char *buf, size_t bufsize)
pwm_to_string (const char *name, const char *uri, char *buf, size_t bufsize)
{
return snprintf (buf, bufsize, "%d", pwm);
}
@ -36,11 +37,12 @@ GENERIC_RESOURCE \
( led_pwm
, LED PWM
, duty-cycle
, 0
, pwm_from_string
, pwm_to_string
);
void period_from_string (const char *name, const char *s)
int period_from_string (const char *name, const char *uri, const char *s)
{
uint32_t tmp = (strtoul (s, NULL, 10) + 50) / 100;
if (tmp > 10) {
@ -50,10 +52,11 @@ void period_from_string (const char *name, const char *s)
tmp = 1;
}
period_100ms = tmp;
return 0;
}
size_t
period_to_string (const char *name, uint8_t is_json, char *buf, size_t bufsize)
period_to_string (const char *name, const char *uri, char *buf, size_t bufsize)
{
return snprintf (buf, bufsize, "%d", period_100ms * 100);
}
@ -62,12 +65,13 @@ GENERIC_RESOURCE \
( led_period
, LED Period
, ms
, 0
, period_from_string
, period_to_string
);
size_t
analog2_v (const char *name, uint8_t is_json, char *buf, size_t bufsize)
analog2_v (const char *name, const char *uri, char *buf, size_t bufsize)
{
return snprintf
(buf, bufsize, "%d.%03d", analog2_voltage / 1000, analog2_voltage % 1000);
@ -77,12 +81,13 @@ GENERIC_RESOURCE \
( analog2_voltage
, Analog 2 voltage
, V
, 0
, NULL
, analog2_v
);
size_t
analog5_v (const char *name, uint8_t is_json, char *buf, size_t bufsize)
analog5_v (const char *name, const char *uri, char *buf, size_t bufsize)
{
return snprintf
(buf, bufsize, "%d.%03d", analog5_voltage / 1000, analog5_voltage % 1000);
@ -92,6 +97,7 @@ GENERIC_RESOURCE \
( analog5_voltage
, Analog 5 voltage
, V
, 0
, NULL
, analog5_v
);