Skip to content

Instantly share code, notes, and snippets.

@mcollina
Last active December 15, 2015 23:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcollina/5337389 to your computer and use it in GitHub Desktop.
Save mcollina/5337389 to your computer and use it in GitHub Desktop.
NetworkButtonJSON

NetworkButtonJSON

NetworkButtonJSON is a forest of network enabled leds that switch on and off on simultaneosly. Join the forest, build a networked LED.

You should:

  • mount an Arduino Ethernet Shield.
  • build an Arduino-based prototype with the following schema: Schema
  • download the sources in the following gist: https://gist.github.com/1704547
  • have fun!

Usage

GET your current led state with curl http://qest.me/topics/light.

Change your led's state:

  • by going to qest,
  • by issuing a PUT request curl -v -X PUT -d '{ "light": true }' -H "Content-Type: application/json" http://qest.me/topics/light
/*
Copyright (c) 2001, Interactive Matter, Marcus Nowotny
Based on the cJSON Library, Copyright (C) 2009 Dave Gamble
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.
*/
// aJSON
// aJson Library for Arduino.
// This library is suited for Atmega328 based Arduinos.
// The RAM on ATmega168 based Arduinos is too limited
/******************************************************************************
* Includes
******************************************************************************/
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <ctype.h>
#include <avr/pgmspace.h>
#include "aJSON.h"
#include "stringbuffer.h"
/******************************************************************************
* Definitions
******************************************************************************/
//Default buffer sizes - buffers get initialized and grow acc to that size
#define BUFFER_DEFAULT_SIZE 4
//how much digits after . for float
#define FLOAT_PRECISION 5
bool
aJsonStream::available()
{
if (bucket != EOF)
return true;
while (stream()->available())
{
/* Make an effort to skip whitespace. */
int ch = this->getch();
if (ch > 32)
{
this->ungetch(ch);
return true;
}
}
return false;
}
int
aJsonStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
// In case input was malformed - can happen, this is the
// real world, we can end up in a situation where the parser
// would expect another character and end up stuck on
// stream()->available() forever, hence the 500ms timeout.
unsigned long i= millis()+500;
while ((!stream()->available()) && (millis() < i)) /* spin with a timeout*/;
return stream()->read();
}
void
aJsonStream::ungetch(char ch)
{
bucket = ch;
}
size_t
aJsonStream::write(uint8_t ch)
{
return stream()->write(ch);
}
size_t
aJsonStream::readBytes(uint8_t *buffer, size_t len)
{
for (size_t i = 0; i < len; i++)
{
int ch = this->getch();
if (ch == EOF)
{
return i;
}
buffer[i] = ch;
}
return len;
}
int
aJsonClientStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
while (!stream()->available() && stream()->connected()) /* spin */;
if (!stream()->connected())
{
stream()->stop();
return EOF;
}
return stream()->read();
}
bool
aJsonStringStream::available()
{
if (bucket != EOF)
return true;
return inbuf_len > 0;
}
int
aJsonStringStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
if (!inbuf || !inbuf_len)
{
return EOF;
}
char ch = *inbuf++;
inbuf_len--;
return ch;
}
size_t
aJsonStringStream::write(uint8_t ch)
{
if (!outbuf || outbuf_len <= 1)
{
return 0;
}
*outbuf++ = ch; outbuf_len--;
*outbuf = 0;
return 1;
}
// Internal constructor.
aJsonObject*
aJsonClass::newItem()
{
aJsonObject* node = (aJsonObject*) malloc(sizeof(aJsonObject));
if (node)
memset(node, 0, sizeof(aJsonObject));
return node;
}
// Delete a aJsonObject structure.
void
aJsonClass::deleteItem(aJsonObject *c)
{
aJsonObject *next;
while (c)
{
next = c->next;
if (!(c->type & aJson_IsReference) && c->child)
{
deleteItem(c->child);
}
if ((c->type == aJson_String) && c->valuestring)
{
free(c->valuestring);
}
if (c->name)
{
free(c->name);
}
free(c);
c = next;
}
}
// Parse the input text to generate a number, and populate the result into item.
int
aJsonStream::parseNumber(aJsonObject *item)
{
int i = 0;
char sign = 1;
int in = this->getch();
if (in == EOF)
{
return EOF;
}
// It is easier to decode ourselves than to use sscnaf,
// since so we can easier decide between int & double
if (in == '-')
{
//it is a negative number
sign = -1;
in = this->getch();
if (in == EOF)
{
return EOF;
}
}
if (in >= '0' && in <= '9')
do
{
i = (i * 10) + (in - '0');
in = this->getch();
}
while (in >= '0' && in <= '9'); // Number?
//end of integer part � or isn't it?
if (!(in == '.' || in == 'e' || in == 'E'))
{
item->valueint = i * (int) sign;
item->type = aJson_Int;
}
//ok it seems to be a double
else
{
double n = (double) i;
int scale = 0;
int subscale = 0;
char signsubscale = 1;
if (in == '.')
{
in = this->getch();
do
{
n = (n * 10.0) + (in - '0'), scale--;
in = this->getch();
}
while (in >= '0' && in <= '9');
} // Fractional part?
if (in == 'e' || in == 'E') // Exponent?
{
in = this->getch();
if (in == '+')
{
in = this->getch();
}
else if (in == '-')
{
signsubscale = -1;
in = this->getch();
}
while (in >= '0' && in <= '9')
{
subscale = (subscale * 10) + (in - '0'); // Number?
in = this->getch();
}
}
n = sign * n * pow(10.0, ((double) scale + (double) subscale
* (double) signsubscale)); // number = +/- number.fraction * 10^+/- exponent
item->valuefloat = n;
item->type = aJson_Float;
}
//preserve the last character for the next routine
this->ungetch(in);
return 0;
}
// Render the number nicely from the given item into a string.
int
aJsonStream::printInt(aJsonObject *item)
{
if (item != NULL)
{
return this->print(item->valueint, DEC);
}
//printing nothing is ok
return 0;
}
int
aJsonStream::printFloat(aJsonObject *item)
{
if (item != NULL)
{
double d = item->valuefloat;
if (d<0.0) {
this->print("-");
d=-d;
}
//print the integer part
unsigned long integer_number = (unsigned long)d;
this->print(integer_number, DEC);
this->print(".");
//print the fractional part
double fractional_part = d - ((double)integer_number);
//we do a do-while since we want to print at least one zero
//we just support a certain number of digits after the '.'
int n = FLOAT_PRECISION;
fractional_part += 0.5/pow(10.0, FLOAT_PRECISION);
do {
//make the first digit non fractional(shift it before the '.'
fractional_part *= 10.0;
//create an int out of it
unsigned int digit = (unsigned int) fractional_part;
//print it
this->print(digit, DEC);
//remove it from the number
fractional_part -= (double)digit;
n--;
} while ((fractional_part!=0) && (n>0));
}
//printing nothing is ok
return 0;
}
// Parse the input text into an unescaped cstring, and populate item.
int
aJsonStream::parseString(aJsonObject *item)
{
//we do not need to skip here since the first byte should be '\"'
int in = this->getch();
if (in != '\"')
{
return EOF; // not a string!
}
item->type = aJson_String;
//allocate a buffer & track how long it is and how much we have read
string_buffer* buffer = stringBufferCreate();
if (buffer == NULL)
{
//unable to allocate the string
return EOF;
}
in = this->getch();
if (in == EOF)
{
stringBufferFree(buffer);
return EOF;
}
while (in != EOF)
{
while (in != '\"' && in >= 32)
{
if (in != '\\')
{
stringBufferAdd((char) in, buffer);
}
else
{
in = this->getch();
if (in == EOF)
{
stringBufferFree(buffer);
return EOF;
}
switch (in)
{
case '\\':
stringBufferAdd('\\', buffer);
break;
case '\"':
stringBufferAdd('\"', buffer);
break;
case 'b':
stringBufferAdd('\b', buffer);
break;
case 'f':
stringBufferAdd('\f', buffer);
break;
case 'n':
stringBufferAdd('\n', buffer);
break;
case 'r':
stringBufferAdd('\r', buffer);
break;
case 't':
stringBufferAdd('\t', buffer);
break;
default:
//we do not understand it so we skip it
break;
}
}
in = this->getch();
if (in == EOF)
{
stringBufferFree(buffer);
return EOF;
}
}
//the string ends here
item->valuestring = stringBufferToString(buffer);
return 0;
}
//we should not be here but it is ok
return 0;
}
// Render the cstring provided to an escaped version that can be printed.
int
aJsonStream::printStringPtr(const char *str)
{
this->print("\"");
char* ptr = (char*) str;
if (ptr != NULL)
{
while (*ptr != 0)
{
if ((unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\')
{
this->print(*ptr);
ptr++;
}
else
{
this->print('\\');
switch (*ptr++)
{
case '\\':
this->print('\\');
break;
case '\"':
this->print('\"');
break;
case '\b':
this->print('b');
break;
case '\f':
this->print('f');
break;
case '\n':
this->print('n');
break;
case '\r':
this->print('r');
break;
case '\t':
this->print('t');
break;
default:
break; // eviscerate with prejudice.
}
}
}
}
this->print('\"');
return 0;
}
// Invote print_string_ptr (which is useful) on an item.
int
aJsonStream::printString(aJsonObject *item)
{
return this->printStringPtr(item->valuestring);
}
// Utility to jump whitespace and cr/lf
int
aJsonStream::skip()
{
int in = this->getch();
while (in != EOF && (in <= 32))
{
in = this->getch();
}
if (in != EOF)
{
this->ungetch(in);
return 0;
}
return EOF;
}
// Utility to flush our buffer in case it contains garbage
// since the parser will return the buffer untouched if it
// cannot understand it.
int
aJsonStream::flush()
{
int in = this->getch();
while(in != EOF)
{
in = this->getch();
}
return EOF;
}
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(char *value)
{
aJsonStringStream stringStream(value, NULL);
aJsonObject* result = parse(&stringStream);
return result;
}
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(aJsonStream* stream)
{
return parse(stream, NULL);
}
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(aJsonStream* stream, char** filter)
{
if (stream == NULL)
{
return NULL;
}
aJsonObject *c = newItem();
if (!c)
return NULL; /* memory fail */
stream->skip();
if (stream->parseValue(c, filter) == EOF)
{
deleteItem(c);
return NULL;
}
return c;
}
// Render a aJsonObject item/entity/structure to text.
int
aJsonClass::print(aJsonObject* item, aJsonStream* stream)
{
return stream->printValue(item);
}
char*
aJsonClass::print(aJsonObject* item)
{
char* outBuf = (char*) malloc(256); /* XXX: Dynamic size. */
if (outBuf == NULL)
{
return NULL;
}
aJsonStringStream stringStream(NULL, outBuf, 256);
print(item, &stringStream);
return outBuf;
}
// Parser core - when encountering text, process appropriately.
int
aJsonStream::parseValue(aJsonObject *item, char** filter)
{
if (this->skip() == EOF)
{
return EOF;
}
//read the first byte from the stream
int in = this->getch();
if (in == EOF)
{
return EOF;
}
this->ungetch(in);
if (in == '\"')
{
return this->parseString(item);
}
else if (in == '-' || (in >= '0' && in <= '9'))
{
return this->parseNumber(item);
}
else if (in == '[')
{
return this->parseArray(item, filter);
}
else if (in == '{')
{
return this->parseObject(item, filter);
}
//it can only be null, false or true
else if (in == 'n')
{
//a buffer to read the value
char buffer[] =
{ 0, 0, 0, 0 };
if (this->readBytes((uint8_t*) buffer, 4) != 4)
{
return EOF;
}
if (!strncmp(buffer, "null", 4))
{
item->type = aJson_NULL;
return 0;
}
else
{
return EOF;
}
}
else if (in == 'f')
{
//a buffer to read the value
char buffer[] =
{ 0, 0, 0, 0, 0 };
if (this->readBytes((uint8_t*) buffer, 5) != 5)
{
return EOF;
}
if (!strncmp(buffer, "false", 5))
{
item->type = aJson_False;
item->valuebool = 0;
return 0;
}
}
else if (in == 't')
{
//a buffer to read the value
char buffer[] =
{ 0, 0, 0, 0 };
if (this->readBytes((uint8_t*) buffer, 4) != 4)
{
return EOF;
}
if (!strncmp(buffer, "true", 4))
{
item->type = aJson_True;
item->valuebool = -1;
return 0;
}
}
return EOF; // failure.
}
// Render a value to text.
int
aJsonStream::printValue(aJsonObject *item)
{
int result = 0;
if (item == NULL)
{
//nothing to do
return 0;
}
switch (item->type)
{
case aJson_NULL:
result = this->print("null");
break;
case aJson_False:
result = this->print("false");
break;
case aJson_True:
result = this->print("true");
break;
case aJson_Int:
result = this->printInt(item);
break;
case aJson_Float:
result = this->printFloat(item);
break;
case aJson_String:
result = this->printString(item);
break;
case aJson_Array:
result = this->printArray(item);
break;
case aJson_Object:
result = this->printObject(item);
break;
}
return result;
}
// Build an array from input text.
int
aJsonStream::parseArray(aJsonObject *item, char** filter)
{
int in = this->getch();
if (in != '[')
{
return EOF; // not an array!
}
item->type = aJson_Array;
this->skip();
in = this->getch();
//check for empty array
if (in == ']')
{
return 0; // empty array.
}
//now put back the last character
this->ungetch(in);
aJsonObject *child;
char first = -1;
while ((first) || (in == ','))
{
aJsonObject *new_item = aJsonClass::newItem();
if (new_item == NULL)
{
return EOF; // memory fail
}
if (first)
{
item->child = new_item;
first = 0;
}
else
{
child->next = new_item;
new_item->prev = child;
}
child = new_item;
this->skip();
if (this->parseValue(child, filter))
{
return EOF;
}
this->skip();
in = this->getch();
}
if (in == ']')
{
return 0; // end of array
}
else
{
return EOF; // malformed.
}
}
// Render an array to text
int
aJsonStream::printArray(aJsonObject *item)
{
if (item == NULL)
{
//nothing to do
return 0;
}
aJsonObject *child = item->child;
if (this->print('[') == EOF)
{
return EOF;
}
while (child)
{
if (this->printValue(child) == EOF)
{
return EOF;
}
child = child->next;
if (child)
{
if (this->print(',') == EOF)
{
return EOF;
}
}
}
if (this->print(']') == EOF)
{
return EOF;
}
return 0;
}
// Build an object from the text.
int
aJsonStream::parseObject(aJsonObject *item, char** filter)
{
int in = this->getch();
if (in != '{')
{
return EOF; // not an object!
}
item->type = aJson_Object;
this->skip();
//check for an empty object
in = this->getch();
if (in == '}')
{
return 0; // empty object.
}
//preserve the char for the next parser
this->ungetch(in);
aJsonObject* child;
char first = -1;
while ((first) || (in == ','))
{
aJsonObject* new_item = aJsonClass::newItem();
if (new_item == NULL)
{
return EOF; // memory fail
}
if (first)
{
first = 0;
item->child = new_item;
}
else
{
child->next = new_item;
new_item->prev = child;
}
child = new_item;
this->skip();
if (this->parseString(child) == EOF)
{
return EOF;
}
this->skip();
child->name = child->valuestring;
child->valuestring = NULL;
in = this->getch();
if (in != ':')
{
return EOF; // fail!
}
// skip any spacing, get the value.
this->skip();
if (this->parseValue(child, filter) == EOF)
{
return EOF;
}
this->skip();
in = this->getch();
}
if (in == '}')
{
return 0; // end of array
}
else
{
return EOF; // malformed.
}
}
// Render an object to text.
int
aJsonStream::printObject(aJsonObject *item)
{
if (item == NULL)
{
//nothing to do
return 0;
}
aJsonObject *child = item->child;
if (this->print('{') == EOF)
{
return EOF;
}
while (child)
{
if (this->printStringPtr(child->name) == EOF)
{
return EOF;
}
if (this->print(':') == EOF)
{
return EOF;
}
if (this->printValue(child) == EOF)
{
return EOF;
}
child = child->next;
if (child)
{
if (this->print(',') == EOF)
{
return EOF;
}
}
}
if (this->print('}') == EOF)
{
return EOF;
}
return 0;
}
// Get Array size/item / object item.
unsigned char
aJsonClass::getArraySize(aJsonObject *array)
{
aJsonObject *c = array->child;
unsigned char i = 0;
while (c)
i++, c = c->next;
return i;
}
aJsonObject*
aJsonClass::getArrayItem(aJsonObject *array, unsigned char item)
{
aJsonObject *c = array->child;
while (c && item > 0)
item--, c = c->next;
return c;
}
aJsonObject*
aJsonClass::getObjectItem(aJsonObject *object, const char *string)
{
aJsonObject *c = object->child;
while (c && strcasecmp(c->name, string))
c = c->next;
return c;
}
// Utility for array list handling.
void
aJsonClass::suffixObject(aJsonObject *prev, aJsonObject *item)
{
prev->next = item;
item->prev = prev;
}
// Utility for handling references.
aJsonObject*
aJsonClass::createReference(aJsonObject *item)
{
aJsonObject *ref = newItem();
if (!ref)
return 0;
memcpy(ref, item, sizeof(aJsonObject));
ref->name = 0;
ref->type |= aJson_IsReference;
ref->next = ref->prev = 0;
return ref;
}
// Add item to array/object.
void
aJsonClass::addItemToArray(aJsonObject *array, aJsonObject *item)
{
aJsonObject *c = array->child;
if (!item)
return;
if (!c)
{
array->child = item;
}
else
{
while (c && c->next)
c = c->next;
suffixObject(c, item);
}
}
void
aJsonClass::addItemToObject(aJsonObject *object, const char *string,
aJsonObject *item)
{
if (!item)
return;
if (item->name)
free(item->name);
item->name = strdup(string);
addItemToArray(object, item);
}
void
aJsonClass::addItemReferenceToArray(aJsonObject *array, aJsonObject *item)
{
addItemToArray(array, createReference(item));
}
void
aJsonClass::addItemReferenceToObject(aJsonObject *object, const char *string,
aJsonObject *item)
{
addItemToObject(object, string, createReference(item));
}
aJsonObject*
aJsonClass::detachItemFromArray(aJsonObject *array, unsigned char which)
{
aJsonObject *c = array->child;
while (c && which > 0)
c = c->next, which--;
if (!c)
return 0;
if (c->prev)
c->prev->next = c->next;
if (c->next)
c->next->prev = c->prev;
if (c == array->child)
array->child = c->next;
c->prev = c->next = 0;
return c;
}
void
aJsonClass::deleteItemFromArray(aJsonObject *array, unsigned char which)
{
deleteItem(detachItemFromArray(array, which));
}
aJsonObject*
aJsonClass::detachItemFromObject(aJsonObject *object, const char *string)
{
unsigned char i = 0;
aJsonObject *c = object->child;
while (c && strcasecmp(c->name, string))
i++, c = c->next;
if (c)
return detachItemFromArray(object, i);
return 0;
}
void
aJsonClass::deleteItemFromObject(aJsonObject *object, const char *string)
{
deleteItem(detachItemFromObject(object, string));
}
// Replace array/object items with new ones.
void
aJsonClass::replaceItemInArray(aJsonObject *array, unsigned char which,
aJsonObject *newitem)
{
aJsonObject *c = array->child;
while (c && which > 0)
c = c->next, which--;
if (!c)
return;
newitem->next = c->next;
newitem->prev = c->prev;
if (newitem->next)
newitem->next->prev = newitem;
if (c == array->child)
array->child = newitem;
else
newitem->prev->next = newitem;
c->next = c->prev = 0;
deleteItem(c);
}
void
aJsonClass::replaceItemInObject(aJsonObject *object, const char *string,
aJsonObject *newitem)
{
unsigned char i = 0;
aJsonObject *c = object->child;
while (c && strcasecmp(c->name, string))
i++, c = c->next;
if (c)
{
newitem->name = strdup(string);
replaceItemInArray(object, i, newitem);
}
}
// Create basic types:
aJsonObject*
aJsonClass::createNull()
{
aJsonObject *item = newItem();
if (item)
item->type = aJson_NULL;
return item;
}
aJsonObject*
aJsonClass::createTrue()
{
aJsonObject *item = newItem();
if (item)
{
item->type = aJson_True;
item->valuebool = -1;
}
return item;
}
aJsonObject*
aJsonClass::createFalse()
{
aJsonObject *item = newItem();
if (item)
{
item->type = aJson_False;
item->valuebool = 0;
}
return item;
}
aJsonObject*
aJsonClass::createItem(char b)
{
aJsonObject *item = newItem();
if (item)
{
item->type = b ? aJson_True : aJson_False;
item->valuebool = b ? -1 : 0;
}
return item;
}
aJsonObject*
aJsonClass::createItem(int num)
{
aJsonObject *item = newItem();
if (item)
{
item->type = aJson_Int;
item->valueint = (int) num;
}
return item;
}
aJsonObject*
aJsonClass::createItem(double num)
{
aJsonObject *item = newItem();
if (item)
{
item->type = aJson_Float;
item->valuefloat = num;
}
return item;
}
aJsonObject*
aJsonClass::createItem(const char *string)
{
aJsonObject *item = newItem();
if (item)
{
item->type = aJson_String;
item->valuestring = strdup(string);
}
return item;
}
aJsonObject*
aJsonClass::createArray()
{
aJsonObject *item = newItem();
if (item)
item->type = aJson_Array;
return item;
}
aJsonObject*
aJsonClass::createObject()
{
aJsonObject *item = newItem();
if (item)
item->type = aJson_Object;
return item;
}
// Create Arrays:
aJsonObject*
aJsonClass::createIntArray(int *numbers, unsigned char count)
{
unsigned char i;
aJsonObject *n = 0, *p = 0, *a = createArray();
for (i = 0; a && i < count; i++)
{
n = createItem(numbers[i]);
if (!i)
a->child = n;
else
suffixObject(p, n);
p = n;
}
return a;
}
aJsonObject*
aJsonClass::createFloatArray(double *numbers, unsigned char count)
{
unsigned char i;
aJsonObject *n = 0, *p = 0, *a = createArray();
for (i = 0; a && i < count; i++)
{
n = createItem(numbers[i]);
if (!i)
a->child = n;
else
suffixObject(p, n);
p = n;
}
return a;
}
aJsonObject*
aJsonClass::createDoubleArray(double *numbers, unsigned char count)
{
unsigned char i;
aJsonObject *n = 0, *p = 0, *a = createArray();
for (i = 0; a && i < count; i++)
{
n = createItem(numbers[i]);
if (!i)
a->child = n;
else
suffixObject(p, n);
p = n;
}
return a;
}
aJsonObject*
aJsonClass::createStringArray(const char **strings, unsigned char count)
{
unsigned char i;
aJsonObject *n = 0, *p = 0, *a = createArray();
for (i = 0; a && i < count; i++)
{
n = createItem(strings[i]);
if (!i)
a->child = n;
else
suffixObject(p, n);
p = n;
}
return a;
}
void
aJsonClass::addNullToObject(aJsonObject* object, const char* name)
{
addItemToObject(object, name, createNull());
}
void
aJsonClass::addTrueToObject(aJsonObject* object, const char* name)
{
addItemToObject(object, name, createTrue());
}
void
aJsonClass::addFalseToObject(aJsonObject* object, const char* name)
{
addItemToObject(object, name, createFalse());
}
void
aJsonClass::addNumberToObject(aJsonObject* object, const char* name, int n)
{
addItemToObject(object, name, createItem(n));
}
void
aJsonClass::addNumberToObject(aJsonObject* object, const char* name, double n)
{
addItemToObject(object, name, createItem(n));
}
void
aJsonClass::addStringToObject(aJsonObject* object, const char* name,
const char* s)
{
addItemToObject(object, name, createItem(s));
}
//TODO conversion routines btw. float & int types?
aJsonClass aJson;
/*
Copyright (c) 2001, Interactive Matter, Marcus Nowotny
Based on the cJSON Library, Copyright (C) 2009 Dave Gamble
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 aJson__h
#define aJson__h
#include <Print.h>
#include <Stream.h>
#include <Client.h>
#include <Arduino.h> // To get access to the Arduino millis() function
/******************************************************************************
* Definitions
******************************************************************************/
// aJson Types:
#define aJson_False 0
#define aJson_True 1
#define aJson_NULL 2
#define aJson_Int 3
#define aJson_Float 4
#define aJson_String 5
#define aJson_Array 6
#define aJson_Object 7
#define aJson_IsReference 128
#ifndef EOF
#define EOF -1
#endif
// The aJson structure:
typedef struct aJsonObject {
char *name; // The item's name string, if this item is the child of, or is in the list of subitems of an object.
struct aJsonObject *next, *prev; // next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem
struct aJsonObject *child; // An array or object item will have a child pointer pointing to a chain of the items in the array/object.
char type; // The type of the item, as above.
union {
char *valuestring; // The item's string, if type==aJson_String
char valuebool; //the items value for true & false
int valueint; // The item's number, if type==aJson_Number
double valuefloat; // The item's number, if type==aJson_Number
};
} aJsonObject;
/* aJsonStream is stream representation of aJson for its internal use;
* it is meant to abstract out differences between Stream (e.g. serial
* stream) and Client (which may or may not be connected) or provide even
* stream-ish interface to string buffers. */
class aJsonStream : public Print {
public:
aJsonStream(Stream *stream_)
: stream_obj(stream_), bucket(EOF)
{}
/* Use this to check if more data is available, as aJsonStream
* can read some more data than really consumed and automatically
* skips separating whitespace if you use this method. */
virtual bool available();
int parseNumber(aJsonObject *item);
int printInt(aJsonObject *item);
int printFloat(aJsonObject *item);
int parseString(aJsonObject *item);
int printStringPtr(const char *str);
int printString(aJsonObject *item);
int skip();
int flush();
int parseValue(aJsonObject *item, char** filter);
int printValue(aJsonObject *item);
int parseArray(aJsonObject *item, char** filter);
int printArray(aJsonObject *item);
int parseObject(aJsonObject *item, char** filter);
int printObject(aJsonObject *item);
protected:
/* Blocking load of character, returning EOF if the stream
* is exhausted. */
/* Base implementation just looks at bucket, returns EOF
* otherwise; descendats take care of the real reading. */
virtual int getch();
virtual size_t readBytes(uint8_t *buffer, size_t len);
/* Return the character back to the front of the stream
* after loading it with getch(). Only returning a single
* character is supported. */
virtual void ungetch(char ch);
/* Inherited from class Print. */
virtual size_t write(uint8_t ch);
/* stream attribute is used only from virtual functions,
* therefore an object inheriting aJsonStream may avoid
* using streams completely. */
Stream *stream_obj;
/* Use this accessor for stream retrieval; some subclasses
* may use their own stream subclass. */
virtual inline Stream *stream() { return stream_obj; }
/* bucket is EOF by default. Otherwise, it is a character
* to be returned by next getch() - returned by a call
* to ungetch(). */
int bucket;
};
/* JSON stream that consumes data from a connection (usually
* Ethernet client) until the connection is closed. */
class aJsonClientStream : public aJsonStream {
public:
aJsonClientStream(Client *stream_)
: aJsonStream(NULL), client_obj(stream_)
{}
private:
virtual int getch();
Client *client_obj;
virtual inline Client *stream() { return client_obj; }
};
/* JSON stream that is bound to input and output string buffer. This is
* for internal usage by string-based aJsonClass methods. */
/* TODO: Elastic output buffer support. */
class aJsonStringStream : public aJsonStream {
public:
/* Either of inbuf, outbuf can be NULL if you do not care about
* particular I/O direction. */
aJsonStringStream(char *inbuf_, char *outbuf_ = NULL, size_t outbuf_len_ = 0)
: aJsonStream(NULL), inbuf(inbuf_), outbuf(outbuf_), outbuf_len(outbuf_len_)
{
inbuf_len = inbuf ? strlen(inbuf) : 0;
}
virtual bool available();
private:
virtual int getch();
virtual size_t write(uint8_t ch);
char *inbuf, *outbuf;
size_t inbuf_len, outbuf_len;
};
class aJsonClass {
/******************************************************************************
* Constructors
******************************************************************************/
/******************************************************************************
* User API
******************************************************************************/
public:
// Supply a block of JSON, and this returns a aJson object you can interrogate. Call aJson.deleteItem when finished.
aJsonObject* parse(aJsonStream* stream); //Reads from a stream
aJsonObject* parse(aJsonStream* stream,char** filter_values); //Read from a file, but only return values include in the char* array filter_values
aJsonObject* parse(char *value); //Reads from a string
// Render a aJsonObject entity to text for transfer/storage. Free the char* when finished.
int print(aJsonObject *item, aJsonStream* stream);
char* print(aJsonObject* item);
//Renders a aJsonObject directly to a output stream
char stream(aJsonObject *item, aJsonStream* stream);
// Delete a aJsonObject entity and all sub-entities.
void deleteItem(aJsonObject *c);
// Returns the number of items in an array (or object).
unsigned char getArraySize(aJsonObject *array);
// Retrieve item number "item" from array "array". Returns NULL if unsuccessful.
aJsonObject* getArrayItem(aJsonObject *array, unsigned char item);
// Get item "string" from object. Case insensitive.
aJsonObject* getObjectItem(aJsonObject *object, const char *string);
// These calls create a aJsonObject item of the appropriate type.
aJsonObject* createNull();
aJsonObject* createTrue();
aJsonObject* createFalse();
aJsonObject* createItem(char b);
aJsonObject* createItem(int num);
aJsonObject* createItem(double num);
aJsonObject* createItem(const char *string);
aJsonObject* createArray();
aJsonObject* createObject();
// These utilities create an Array of count items.
aJsonObject* createIntArray(int *numbers, unsigned char count);
aJsonObject* createFloatArray(double *numbers, unsigned char count);
aJsonObject* createDoubleArray(double *numbers, unsigned char count);
aJsonObject* createStringArray(const char **strings, unsigned char count);
// Append item to the specified array/object.
void addItemToArray(aJsonObject *array, aJsonObject *item);
void addItemToObject(aJsonObject *object, const char *string,
aJsonObject *item);
// Append reference to item to the specified array/object. Use this when you want to add an existing aJsonObject to a new aJsonObject, but don't want to corrupt your existing aJsonObject.
void addItemReferenceToArray(aJsonObject *array, aJsonObject *item);
void addItemReferenceToObject(aJsonObject *object, const char *string,
aJsonObject *item);
// Remove/Detach items from Arrays/Objects.
aJsonObject* detachItemFromArray(aJsonObject *array, unsigned char which);
void deleteItemFromArray(aJsonObject *array, unsigned char which);
aJsonObject* detachItemFromObject(aJsonObject *object, const char *string);
void deleteItemFromObject(aJsonObject *object, const char *string);
// Update array items.
void replaceItemInArray(aJsonObject *array, unsigned char which,
aJsonObject *newitem);
void replaceItemInObject(aJsonObject *object, const char *string,
aJsonObject *newitem);
void addNullToObject(aJsonObject* object, const char* name);
void addTrueToObject(aJsonObject* object, const char* name);
void addFalseToObject(aJsonObject* object, const char* name);
void addNumberToObject(aJsonObject* object, const char* name, int n);
void addNumberToObject(aJsonObject* object, const char* name, double n);
void addStringToObject(aJsonObject* object, const char* name,
const char* s);
protected:
friend class aJsonStream;
static aJsonObject* newItem();
private:
void suffixObject(aJsonObject *prev, aJsonObject *item);
aJsonObject* createReference(aJsonObject *item);
};
extern aJsonClass aJson;
#endif
#include <SPI.h>
#include <Ethernet.h>
#include "PubSubClient.h"
#include "aJSON.h"
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
0x28, 0x37, 0x37, 0x01, 0x64, 0xA1 };
// 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
IPAddress ip;
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 8; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int ledState = HIGH; // variable for storing the led state
void callback(char* topic, byte* payload,int length) {
Serial.print("Received topic update: ");
char * string;
string = (char*) malloc(length + 1);
memcpy(string, payload, length);
string[length] = '\0';
Serial.println(string);
aJsonObject* root = aJson.parse(string);
free(string);
aJsonObject* value = aJson.getObjectItem(root, "value");
if (value->valuebool) {
ledState = HIGH;
} else {
ledState = LOW;
}
Serial.print("New led state: ");
Serial.println(ledState);
digitalWrite(ledPin, ledState);
aJson.deleteItem(root);
Serial.println("---------");
}
PubSubClient client;
const String server = String("qest.me");
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 500; // interval at which to blink (milliseconds)
void setup() {
// initialize the LED pin as an output:
pinMode(13, OUTPUT);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
// open the serial port
Serial.begin(9600);
digitalWrite(13, HIGH);
// start the Ethernet connection:
delay(500);
digitalWrite(13, LOW);
Serial.println("Trying to get an IP address using DHCP");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
return;
}
// print your local IP address:
Serial.print("My IP address: ");
ip = Ethernet.localIP();
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(ip[thisByte], DEC);
Serial.print(".");
}
Serial.println();
client = PubSubClient(server, 1883, callback);
mqttConnect();
digitalWrite(13, HIGH);
digitalWrite(ledPin, ledState);
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
if (ledState == HIGH) {
ledState = LOW;
}
else {
ledState = HIGH;
}
digitalWrite(ledPin, ledState);
publishLedState();
}
}
mqttConnect();
}
void publishLedState() {
aJsonObject *root;
char *json_String;
root=aJson.createObject();
Serial.print("Led state: ");
Serial.println(ledState);
if (ledState == HIGH) {
aJson.addTrueToObject(root,"value");
} else {
aJson.addFalseToObject(root,"value");
}
json_String = aJson.print(root);
Serial.print("Sending: ");
Serial.println(json_String);
client.publish("light", json_String);
aJson.deleteItem(root);
free(json_String);
Serial.println("---------");
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Connecting..");
client.connect("arduino");
char startTime[40] = "";
char s1[20];
itoa(millis(), s1, 10);
strcat(startTime, "started ");
strcat(startTime, s1);
client.publish("foo", startTime);
Serial.println(" done!");
client.subscribe("light");
}
client.loop();
}
/*
PubSubClient.cpp - A simple client for MQTT.
Nicholas O'Leary
http://knolleary.net
*/
#include "PubSubClient.h"
#include <EthernetClient.h>
#include <string.h>
PubSubClient::PubSubClient() : _client() {
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,int)) : _client() {
this->callback = callback;
this->ip = ip;
this->port = port;
}
PubSubClient::PubSubClient(String domain, uint16_t port, void (*callback)(char*,uint8_t*,int)) : _client() {
this->callback = callback;
this->domain = domain;
this->port = port;
}
int PubSubClient::connect(char *id) {
return connect(id,0,0,0,0);
}
int PubSubClient::connect(char *id, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) {
if (!connected()) {
int result = 0;
if (domain != NULL) {
char c[40];
this->domain.toCharArray(c, 40);
result = _client.connect(c, this->port);
} else {
result = _client.connect(this->ip, this->port);
}
if (result) {
nextMsgId = 1;
uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p',MQTTPROTOCOLVERSION};
uint8_t length = 0;
int j;
for (j = 0;j<9;j++) {
buffer[length++] = d[j];
}
if (willTopic) {
buffer[length++] = 0x06|(willQos<<3)|(willRetain<<5);
} else {
buffer[length++] = 0x02;
}
buffer[length++] = 0;
buffer[length++] = (KEEPALIVE/1000);
length = writeString(id,buffer,length);
if (willTopic) {
length = writeString(willTopic,buffer,length);
length = writeString(willMessage,buffer,length);
}
write(MQTTCONNECT,buffer,length);
lastOutActivity = millis();
lastInActivity = millis();
while (!_client.available()) {
long t= millis();
if (t-lastInActivity > KEEPALIVE) {
_client.stop();
return 0;
}
}
uint8_t len = readPacket();
if (len == 4 && buffer[3] == 0) {
lastInActivity = millis();
pingOutstanding = false;
return 1;
}
}
_client.stop();
}
return 0;
}
uint8_t PubSubClient::readByte() {
while(!_client.available()) {}
return _client.read();
}
uint8_t PubSubClient::readPacket() {
uint8_t len = 0;
buffer[len++] = readByte();
uint8_t multiplier = 1;
uint8_t length = 0;
uint8_t digit = 0;
do {
digit = readByte();
buffer[len++] = digit;
length += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) != 0);
for (int i = 0;i<length;i++)
{
if (len < MAX_PACKET_SIZE) {
buffer[len++] = readByte();
} else {
readByte();
len = 0; // This will cause the packet to be ignored.
}
}
return len;
}
int PubSubClient::loop() {
if (connected()) {
long t = millis();
if ((t - lastInActivity > KEEPALIVE) || (t - lastOutActivity > KEEPALIVE)) {
if (pingOutstanding) {
_client.stop();
return 0;
} else {
_client.write(MQTTPINGREQ);
_client.write((uint8_t)0);
lastOutActivity = t;
lastInActivity = t;
pingOutstanding = true;
}
}
if (_client.available()) {
uint8_t len = readPacket();
if (len > 0) {
lastInActivity = t;
uint8_t type = buffer[0]&0xF0;
if (type == MQTTPUBLISH) {
if (callback) {
uint8_t tl = (buffer[2]<<3)+buffer[3];
char topic[tl+1];
for (int i=0;i<tl;i++) {
topic[i] = buffer[4+i];
}
topic[tl] = 0;
// ignore msgID - only support QoS 0 subs
uint8_t *payload = buffer+4+tl;
callback(topic,payload,len-4-tl);
}
} else if (type == MQTTPINGREQ) {
_client.write(MQTTPINGRESP);
_client.write((uint8_t)0);
} else if (type == MQTTPINGRESP) {
pingOutstanding = false;
}
}
}
return 1;
}
return 0;
}
int PubSubClient::publish(char* topic, char* payload) {
return publish(topic,(uint8_t*)payload,strlen(payload));
}
int PubSubClient::publish(char* topic, uint8_t* payload, uint8_t plength) {
return publish(topic, payload, plength, 0);
}
int PubSubClient::publish(char* topic, uint8_t* payload, uint8_t plength, uint8_t retained) {
if (connected()) {
uint8_t length = writeString(topic,buffer,0);
int i;
for (i=0;i<plength;i++) {
buffer[length++] = payload[i];
}
uint8_t header = MQTTPUBLISH;
if (retained != 0) {
header |= 1;
}
write(header,buffer,length);
return 1;
}
return 0;
}
int PubSubClient::write(uint8_t header, uint8_t* buf, uint8_t length) {
_client.write(header);
_client.write(length);
_client.write(buf,length);
lastOutActivity = millis();
return 0;
}
void PubSubClient::subscribe(char* topic) {
if (connected()) {
uint8_t length = 2;
nextMsgId++;
buffer[0] = nextMsgId >> 8;
buffer[1] = nextMsgId - (buffer[0]<<8);
length = writeString(topic, buffer,length);
buffer[length++] = 0; // Only do QoS 0 subs
write(MQTTSUBSCRIBE,buffer,length);
}
}
void PubSubClient::disconnect() {
_client.write(MQTTDISCONNECT);
_client.write((uint8_t)0);
_client.stop();
lastInActivity = millis();
lastOutActivity = millis();
}
uint8_t PubSubClient::writeString(char* string, uint8_t* buf, uint8_t pos) {
char* idp = string;
uint8_t i = 0;
pos += 2;
while (*idp) {
buf[pos++] = *idp++;
i++;
}
buf[pos-i-2] = 0;
buf[pos-i-1] = i;
return pos;
}
int PubSubClient::connected() {
int rc = (int)_client.connected();
if (!rc) _client.stop();
return rc;
}
/*
PubSubClient.h - A simple client for MQTT.
Nicholas O'Leary
http://knolleary.net
*/
#ifndef PubSubClient_h
#define PubSubClient_h
#include "Ethernet.h"
#include "EthernetClient.h"
#define MAX_PACKET_SIZE 128
#define KEEPALIVE 15000 // max value = 255000
// from mqtt-v3r1
#define MQTTPROTOCOLVERSION 3
#define MQTTCONNECT 1 << 4 // Client request to connect to Server
#define MQTTCONNACK 2 << 4 // Connect Acknowledgment
#define MQTTPUBLISH 3 << 4 // Publish message
#define MQTTPUBACK 4 << 4 // Publish Acknowledgment
#define MQTTPUBREC 5 << 4 // Publish Received (assured delivery part 1)
#define MQTTPUBREL 6 << 4 // Publish Release (assured delivery part 2)
#define MQTTPUBCOMP 7 << 4 // Publish Complete (assured delivery part 3)
#define MQTTSUBSCRIBE 8 << 4 // Client Subscribe request
#define MQTTSUBACK 9 << 4 // Subscribe Acknowledgment
#define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request
#define MQTTUNSUBACK 11 << 4 // Unsubscribe Acknowledgment
#define MQTTPINGREQ 12 << 4 // PING Request
#define MQTTPINGRESP 13 << 4 // PING Response
#define MQTTDISCONNECT 14 << 4 // Client is Disconnecting
#define MQTTReserved 15 << 4 // Reserved
class PubSubClient {
private:
EthernetClient _client;
uint8_t buffer[MAX_PACKET_SIZE];
uint8_t nextMsgId;
long lastOutActivity;
long lastInActivity;
bool pingOutstanding;
void (*callback)(char*,uint8_t*,int);
uint8_t readPacket();
uint8_t readByte();
int write(uint8_t header, uint8_t* buf, uint8_t length);
uint8_t writeString(char* string, uint8_t* buf, uint8_t pos);
uint8_t *ip;
String domain;
uint16_t port;
public:
PubSubClient();
PubSubClient(uint8_t *, uint16_t, void(*)(char*,uint8_t*,int));
PubSubClient(String, uint16_t, void(*)(char*,uint8_t*,int));
int connect(char *);
int connect(char*, char*, uint8_t, uint8_t, char*);
void disconnect();
int publish(char *, char *);
int publish(char *, uint8_t *, uint8_t);
int publish(char *, uint8_t *, uint8_t, uint8_t);
void subscribe(char *);
int loop();
int connected();
};
#endif
/*
* aJson
* stringbuffer.c
*
* http://interactive-matter.org/
*
* This file is part of aJson.
*
* aJson 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.
*
* aJson 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 aJson. If not, see <http://www.gnu.org/licenses/>.
*
* Created on: 14.10.2010
* Author: marcus
*/
#include <stdlib.h>
#include <string.h>
#include "stringbuffer.h"
//Default buffer size for strings
#define BUFFER_SIZE 256
//there is a static buffer allocated, which is used to decode strings to
//strings cannot be longer than the buffer
char global_buffer[BUFFER_SIZE];
string_buffer*
stringBufferCreate(void)
{
string_buffer* result = malloc(sizeof(string_buffer));
if (result == NULL)
{
return NULL;
}
result->string = global_buffer;
memset((void*) global_buffer, 0, BUFFER_SIZE);
//unused - but will be usefull after realloc got fixd
/* if (result->string==NULL) {
free(result);
return NULL;
}
result->memory=BUFFER_DEFAULT_SIZE;*/
result->memory = BUFFER_SIZE;
result->string_length = 0;
return result;
}
char
stringBufferAdd(char value, string_buffer* buffer)
{
if (buffer->string_length >= buffer->memory)
{
//this has to be enabled after realloc works
/*char* new_string = (char*) realloc((void*) buffer->string, (buffer->memory
+ BUFFER_DEFAULT_SIZE) * sizeof(char));
if (new_string == NULL)
{
free(buffer->string);
buffer->string = NULL;
return -1;
} else {
buffer->string = new_string;
}
buffer->memory += BUFFER_DEFAULT_SIZE;*/
//in the meantime we just drop it
return 0; //EOF would be a better choice - but that breaks json decoding
}
buffer->string[buffer->string_length] = value;
buffer->string_length += 1;
return 0;
}
char*
stringBufferToString(string_buffer* buffer)
{
//this is the realloc dependent function - it does not work
// char* result = buffer->string;
//ensure that the string ends with 0
if (buffer->string_length == 0 || buffer->string[(buffer->string_length - 1)]
!= 0)
{
stringBufferAdd(0, buffer);
}
/* char* string = realloc(result, buffer->string_length);
if (string==NULL) {
free(result);
}
buffer->string=NULL;
free(buffer);
return string;*/
char* result = malloc(buffer->string_length * sizeof(char));
if (result == NULL)
{
return NULL;
}
strcpy(result, global_buffer);
buffer->string = NULL;
free(buffer);
return result;
}
void
stringBufferFree(string_buffer* buffer)
{
if (buffer == NULL)
{
//hmm it was null before - whatever
return;
}
//this is not needed in this realloc free concept
/*
if (buffer->string!=NULL) {
free(buffer->string);
}
*/
free(buffer);
}
/*
* aJson
* stringbuffer.h
*
* http://interactive-matter.org/
*
* This file is part of aJson.
*
* aJson 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.
*
* aJson 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 aJson. If not, see <http://www.gnu.org/licenses/>.
*
* Created on: 14.10.2010
* Author: marcus
*/
#ifndef STRINGBUFFER_H_
#define STRINGBUFFER_H_
typedef struct
{
char* string;
unsigned int memory;
unsigned int string_length;
} string_buffer;
#ifdef __cplusplus
extern "C"
{
#endif
string_buffer*
stringBufferCreate(void);
char
stringBufferAdd(char value, string_buffer* buffer);
char*
stringBufferToString(string_buffer* buffer);
void
stringBufferFree(string_buffer* buffer);
#ifdef __cplusplus
}
#endif
#endif /* STRINGBUFFER_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment