Example #1
0
void CIMoteTerminal::BufferAppend(char * y){
	size_t len = strlen(y);
	for(size_t i = 0; i < len; i++)
		BufferAppend(y[i], false);
	ScrollToBottom();
	UpdateText();
}
Example #2
0
Buffer* BufferNewFrom(const char *data, unsigned int length)
{
    Buffer *buffer = BufferNewWithCapacity(length + 1);
    BufferAppend(buffer, data, length);

    return buffer;
}
Example #3
0
void BufferSet(Buffer *buffer, const char *bytes, unsigned int length)
{
    assert(buffer);
    assert(bytes);

    BufferClear(buffer);

    BufferAppend(buffer, bytes, length);
}
Example #4
0
void TestAppend(CuTest* tc)
{
    buffer_t *buf = BufferCreate();
    uint8_t data[2] = { 1, 2 };
    BufferAppend(buf, data, sizeof(data));
    CuAssertIntEquals(tc, 2, BufferGetSize(buf));
    CuAssertIntEquals(tc, 1, BufferGetByte(buf, 0));
    CuAssertIntEquals(tc, 2, BufferGetByte(buf, 1));
    BufferDestroy(&buf);
}
Example #5
0
void TestGetBlock(CuTest* tc)
{
    buffer_t *buf = BufferCreate();
    uint8_t data1[4] = { 1, 2, 3, 4 };
    BufferAppend(buf, data1, sizeof(data1));
    uint8_t *block;

    // Test case when not enough data in the buffer.
    CuAssertIntEquals(tc, 0, BufferGetBlock(buf, &block, 0, 8));

    // Add more data to the buffer.
    uint8_t data2[4] = { 5, 6, 7, 8 };
    BufferAppend(buf, data2, sizeof(data2));

    // Test case when enough data in the buffer.
    CuAssertIntEquals(tc, 1, BufferGetBlock(buf, &block, 0, 8));
    uint8_t check_data[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    CuAssertIntEquals(tc, 0, memcmp(block, check_data, 8));
    BufferDestroy(&buf);
}
Example #6
0
void TestAccessBufferData(CuTest* tc)
{
    buffer_t *buf = BufferCreate();
    uint8_t data1[4] = { 1, 2, 3, 4 };
    BufferAppend(buf, data1, sizeof(data1));
    uint8_t *buffer_data;
    size_t buffer_size;
    BufferGetData(buf, &buffer_data, &buffer_size);
    CuAssertTrue(tc, buffer_data != NULL);
    CuAssertIntEquals(tc, 4, buffer_size);

    BufferDestroy(&buf);
}
Example #7
0
void TestCopyBuffer(CuTest* tc)
{
    buffer_t *buf = BufferCreate();
    uint8_t data[4] = { 1, 2, 3, 4 };
    BufferAppend(buf, data, sizeof(data));
    uint8_t *data_out;
    size_t size_out;
    BufferCopy(buf, 2, &data_out, &size_out);
    CuAssertIntEquals(tc, 2, size_out);
    CuAssertIntEquals(tc, 0, memcmp(data, data_out, 2));
    free(data_out);
    BufferDestroy(&buf);
}
Example #8
0
File: vars.c Project: amousset/core
size_t ExtractScalarPrefix(Buffer *out, const char *str, size_t len)
{
    assert(str);
    if (len == 0)
    {
        return 0;
    }

    const char *dollar_point = NULL;
    for (size_t i = 0; i < (len - 1); i++)
    {
        if (str[i] == '$')
        {
            if (str[i + 1] == '(' || str[i + 1] == '{')
            {
                dollar_point = str + i;
                break;
            }
        }
    }

    if (!dollar_point)
    {
        BufferAppend(out, str, len);
        return len;
    }
    else if (dollar_point > str)
    {
        size_t prefix_len = dollar_point - str;
        if (prefix_len > 0)
        {
            BufferAppend(out, str, prefix_len);
        }
        return prefix_len;
    }
    return 0;
}
Example #9
0
void TestExtractBuffer(CuTest* tc)
{
    buffer_t *buf = BufferCreate();
    uint8_t data[4] = { 1, 2, 3, 4 };
    BufferAppend(buf, data, sizeof(data));
    uint8_t *data_out;
    size_t size_out;
    BufferExtract(buf, 2, &data_out, &size_out);
    CuAssertIntEquals(tc, 2, size_out);
    CuAssertIntEquals(tc, 0, memcmp(data, data_out, 2));
    free(data_out);
    CuAssertIntEquals(tc, 2, BufferGetSize(buf));
    CuAssertIntEquals(tc, 3, BufferGetByte(buf, 0));
    CuAssertIntEquals(tc, 4, BufferGetByte(buf, 1));
    BufferDestroy(&buf);
}
Example #10
0
static void RenderContent(Buffer *out, const char *content, size_t len, bool html, bool skip_content)
{
    if (skip_content)
    {
        return;
    }

    if (html)
    {
        RenderHTMLContent(out, content, len);
    }
    else
    {
        BufferAppend(out, content, len);
    }
}
Example #11
0
void BufferAppendChar(Buffer *buffer, char byte)
{
    if (buffer->used < (buffer->capacity - 1))
    {
        buffer->buffer[buffer->used] = byte;
        buffer->used++;

        if (buffer->mode == BUFFER_BEHAVIOR_CSTRING)
        {
            buffer->buffer[buffer->used] = '\0';
        }
    }
    else
    {
        BufferAppend(buffer, &byte, 1);
    }
}
Example #12
0
void ZmtpReaderPush(zmtpreader_t *self, const uint8_t *data, size_t len)
{
    assert(self);
    BufferAppend(self->buffer, data, len);
    int processed = 0; // Number of bytes processed

    while (!self->error) {
        processed = 0;
        switch (self->state) {
            case ZMTP_STATE_INIT: // Get a greeting
                processed = ZmtpReader_Greeting(self);
                break;
            case ZMTP_STATE_WAIT_HANDSHAKE:
                processed = ZmtpReader_Handshake(self);
                break;
            case ZMTP_STATE_WAIT_PACKET:
                processed = ZmtpReader_Frame(self);
            default:
                break;
        }
        if (processed == 0)
            break;
    }
}
Example #13
0
int	CookiePath::GetCookieRequest(
		time_t this_time,
		BOOL is_secure,
		BOOL is_server,
		unsigned short port,
		int &version,
		int &max_version,
		BOOL third_party_only,
		BOOL already_have_password,
		BOOL already_have_authentication,
		BOOL &have_password,
		BOOL &have_authentication,
		BOOL is_full_path,
		char* buf, int buf_len,
		BOOL for_http,
		BOOL allow_dollar_cookies,
		BOOL& seen_cookie2)
{
	int buf_used = 0;
	char* buf_p = buf;
	Cookie* ck = (Cookie*) cookie_list.First();
	while (ck)
	{
		Cookie* next_ck = ck->Suc();
		if (ck->Expires() && ck->Expires() < this_time)
		{
			OP_DELETE(ck);
		}
		else if ((is_secure || !ck->Secure())  &&
				(for_http || !ck->HTTPOnly()) &&
				(is_full_path || !ck->FullPathOnly())
				 && (is_server || !ck->SendOnlyToServer()) &&
				 (ck->Version() == 0 || ck->CheckPort(port)) &&
				 (!third_party_only || ck->GetAcceptedAsThirdParty()) &&
				 (allow_dollar_cookies || *ck->Name().CStr() != '$')
		)
		{

			int name_len = ck->Name().Length();
			int value_len = ck->Value().Length();

			int ver = ck->Version();
			if(version > ver)
				version = ver;

			if(ver > max_version)
				max_version = ver;

			if (ck->GetCookieType() == COOKIE2_COOKIE)
				seen_cookie2 = TRUE;

			int dom_len = (ver ? ck->Received_Domain().Length() : 0) ;
			int path_len = (ver && ck->Received_Path().HasContent() ? ck->Received_Path().Length()+1:  0) ;
			int port_len = (ver ? (ck->Port().HasContent() ? ck->Port().Length() : (ck->PortReceived() ? 1 : 0)) : 0) ;
			if ((name_len + value_len + 3 +
			    (dom_len ? dom_len + 10 : 0) +
			    (path_len ? path_len + 8 : 0) +
			    (port_len ? port_len + 8 : 0)) < buf_len - buf_used)
			{
				if (buf_used)
					BufferAppend(buf_p, "; ", 2);
				BufferAppend(buf_p, ck->Name().CStr());

				if (value_len > 0 || ck->Assigned())
				{
					*buf_p++ = '=';
					BufferAppend(buf_p, ck->Value().CStr());
				}

				if(ver > 0)
				{
					if(path_len)
					{
						BufferAppend(buf_p, "; $Path=\"");
						BufferAppend(buf_p, ck->Received_Path().CStr());
						*buf_p++ = '"';
						*buf_p = '\0';
					}
					if(dom_len)
					{
						BufferAppend(buf_p, "; $Domain=");
						BufferAppend(buf_p, ck->Received_Domain().CStr());
					}
					if(ck->PortReceived())
					{
						if(ck->Port().CStr())
						{
							BufferAppend(buf_p, "; $Port=\"");
							BufferAppend(buf_p, ck->Port().CStr());
							*buf_p++ = '"';
							*buf_p = '\0';
						}
						else
							BufferAppend(buf_p, "; $Port");
					}
				}
				if(g_pcnet->GetIntegerPref(PrefsCollectionNetwork::TagUrlsUsingPasswordRelatedCookies))
				{
					if(ck->GetHavePassword())
						have_password = TRUE;
					if(ck->GetHaveAuthentication())
						have_authentication = TRUE;
					if(already_have_password)
						ck->SetHavePassword(TRUE);
					if(already_have_authentication)
						ck->SetHaveAuthentication(TRUE);
				}
				buf_used = buf_p - buf;

				ck->SetLastUsed(this_time);
			}
		}
		ck = next_ck;
	}

	return buf_used;
}
Example #14
0
static void test_appendBuffer(void)
{
    char *element0 = xstrdup("element0");
    unsigned int element0size = strlen(element0);
    const char *element0pointer = NULL;
    char *element1 = xstrdup("element1");
    unsigned int element1size = strlen(element1);
    const char *element1pointer = NULL;
    char *element2 = (char *)xmalloc(2 * DEFAULT_BUFFER_SIZE + 2);
    unsigned int element2size = 2 * DEFAULT_BUFFER_SIZE + 1;
    char *element3 = (char *)xmalloc(DEFAULT_MEMORY_CAP * 2);
    unsigned int element3size = 2 * DEFAULT_MEMORY_CAP;

    Buffer *buffer = BufferNew();
    assert_true(buffer != NULL);
    // Initialize the buffer with a small string
    assert_int_equal(element0size, BufferAppend(buffer, element0, element0size));
    element0pointer = buffer->buffer;
    assert_int_equal(element0size, buffer->used);
    assert_int_equal(element0size, BufferSize(buffer));
    assert_string_equal(element0, buffer->buffer);
    assert_string_equal(element0, BufferData(buffer));
    assert_int_equal(DEFAULT_BUFFER_SIZE, buffer->capacity);
    // Attach a small string to it
    assert_int_equal(element0size + element1size, BufferAppend(buffer, element1, element1size));
    element1pointer = buffer->buffer;
    assert_true(element0pointer == element1pointer);
    assert_int_equal(buffer->used, element0size + element1size);
    assert_int_equal(BufferSize(buffer), element0size + element1size);
    char *shortAppend = NULL;
    shortAppend = (char *)xmalloc(element0size + element1size + 1);
    strcpy(shortAppend, element0);
    strcat(shortAppend, element1);
    assert_string_equal(shortAppend, buffer->buffer);
    assert_string_equal(shortAppend, BufferData(buffer));

    /*
     * Zero the string and start again.
     */
    BufferZero(buffer);
    assert_int_equal(element0size, BufferAppend(buffer, element0, element0size));
    element0pointer = buffer->buffer;
    assert_int_equal(element0size, buffer->used);
    assert_int_equal(element0size, BufferSize(buffer));
    assert_string_equal(element0, buffer->buffer);
    assert_string_equal(element0, BufferData(buffer));

    /*
     * Larger than the allocated buffer, this means we will allocate more memory
     * copy stuff into the new buffer and all that.
     */
    int i = 0;
    for (i = 0; i < element2size; ++i)
        element2[i] = 'a';
    element2[element2size] = '\0';
    assert_int_equal(element0size + element2size, BufferAppend(buffer, element2, element2size));
    assert_int_equal(buffer->used, element0size + element2size);
    assert_int_equal(BufferSize(buffer), element0size + element2size);
    char *longAppend = NULL;
    longAppend = (char *)xmalloc(element0size + element2size + 1);
    strcpy(longAppend, element0);
    strcat(longAppend, element2);
    assert_string_equal(longAppend, buffer->buffer);
    assert_string_equal(longAppend, BufferData(buffer));
    /*
     * A buffer that is so large that it will get rejected by our memory cap
     */
    BufferZero(buffer);
    for (i = 0; i < element3size; ++i)
    {
        element3[i] = 'b';
    }
    element3[element3size - 1] = '\0';
    assert_int_equal(-1, BufferAppend(buffer, element3, element3size));
    /*
     * Boundary checks, BUFFER_SIZE-1, BUFFER_SIZE and BUFFER_SIZE+1
     */
    Buffer *bm1 = BufferNew();
    Buffer *be = BufferNew();
    Buffer *bp1 = BufferNew();
    char buffer_m1[DEFAULT_BUFFER_SIZE - 1];
    char buffer_0[DEFAULT_BUFFER_SIZE];
    char buffer_p1[DEFAULT_BUFFER_SIZE + 1];
    unsigned int bm1_size = DEFAULT_BUFFER_SIZE - 1;
    unsigned int be_size = DEFAULT_BUFFER_SIZE;
    unsigned int bp1_size = DEFAULT_BUFFER_SIZE + 1;
    for (i = 0; i < DEFAULT_BUFFER_SIZE - 1; ++i)
    {
        buffer_m1[i] = 'c';
        buffer_0[i] = 'd';
        buffer_p1[i] = 'e';
    }
    /*
     * One shorter, that means the buffer remains the same size as before.
     */
    buffer_m1[DEFAULT_BUFFER_SIZE - 2] = '\0';
    assert_int_equal(bm1_size, BufferAppend(bm1, buffer_m1, bm1_size));
    assert_int_equal(bm1->capacity, DEFAULT_BUFFER_SIZE);
    /*
     * Same size, it should allocate one more block
     */
    buffer_0[DEFAULT_BUFFER_SIZE - 1] = '\0';
    assert_int_equal(be_size, BufferAppend(be, buffer_0, be_size));
    assert_int_equal(be->capacity, 2 * DEFAULT_BUFFER_SIZE);
    /*
     * 1 more, it should allocate one more block
     */
    buffer_p1[DEFAULT_BUFFER_SIZE] = '\0';
    assert_int_equal(bp1_size, BufferAppend(bp1, buffer_p1, bp1_size));
    assert_int_equal(bp1->capacity, 2 * DEFAULT_BUFFER_SIZE);
    /*
     * Destroy the buffer and good night.
     */
    free(shortAppend);
    free(longAppend);
    assert_int_equal(0, BufferDestroy(&buffer));
    assert_int_equal(0, BufferDestroy(&bm1));
    assert_int_equal(0, BufferDestroy(&be));
    assert_int_equal(0, BufferDestroy(&bp1));
    free (element0);
    free (element1);
    free (element2);
    free (element3);
}
Example #15
0
/**
 * Expand a #string into Buffer #out, returning the pointer to the string
 * itself, inside the Buffer #out. If #out is NULL then the buffer will be
 * created and destroyed internally.
 *
 * @retval NULL something went wrong
 */
char *ExpandScalar(const EvalContext *ctx, const char *ns, const char *scope,
                   const char *string, Buffer *out)
{
    bool out_belongs_to_us = false;

    if (out == NULL)
    {
        out               = BufferNew();
        out_belongs_to_us = true;
    }

    assert(string != NULL);
    assert(out != NULL);
    Buffer *current_item = BufferNew();

    for (const char *sp = string; *sp != '\0'; sp++)
    {
        BufferClear(current_item);
        ExtractScalarPrefix(current_item, sp, strlen(sp));

        BufferAppend(out, BufferData(current_item), BufferSize(current_item));
        sp += BufferSize(current_item);
        if (*sp == '\0')
        {
            break;
        }

        BufferClear(current_item);
        char varstring = sp[1];
        ExtractScalarReference(current_item,  sp, strlen(sp), true);
        sp += BufferSize(current_item) + 2;

        if (IsCf3VarString(BufferData(current_item)))
        {
            Buffer *temp = BufferCopy(current_item);
            BufferClear(current_item);
            ExpandScalar(ctx, ns, scope, BufferData(temp), current_item);
            BufferDestroy(temp);
        }

        if (!IsExpandable(BufferData(current_item)))
        {
            VarRef *ref = VarRefParseFromNamespaceAndScope(
                BufferData(current_item),
                ns, scope, CF_NS, '.');
            DataType value_type;
            const void *value = EvalContextVariableGet(ctx, ref, &value_type);
            VarRefDestroy(ref);

            switch (DataTypeToRvalType(value_type))
            {
            case RVAL_TYPE_SCALAR:
                assert(value != NULL);
                BufferAppendString(out, value);
                continue;
                break;

            case RVAL_TYPE_CONTAINER:
            {
                assert(value != NULL);
                const JsonElement *jvalue = value;      /* instead of casts */
                if (JsonGetElementType(jvalue) == JSON_ELEMENT_TYPE_PRIMITIVE)
                {
                    BufferAppendString(out, JsonPrimitiveGetAsString(jvalue));
                    continue;
                }
                break;
            }
            default:
                /* TODO Log() */
                break;
            }
        }

        if (varstring == '{')
        {
            BufferAppendF(out, "${%s}", BufferData(current_item));
        }
        else
        {
            BufferAppendF(out, "$(%s)", BufferData(current_item));
        }
    }

    BufferDestroy(current_item);

    LogDebug(LOG_MOD_EXPAND, "ExpandScalar( %s : %s . %s )  =>  %s",
             SAFENULL(ns), SAFENULL(scope), string, BufferData(out));

    return out_belongs_to_us ? BufferClose(out) : BufferGet(out);
}
Example #16
0
VarRef *VarRefParseFromNamespaceAndScope(const char *qualified_name, const char *_ns, const char *_scope, char ns_separator, char scope_separator)
{
    char *ns = NULL;

    const char *indices_start = strchr(qualified_name, '[');

    const char *scope_start = strchr(qualified_name, ns_separator);
    if (scope_start && (!indices_start || scope_start < indices_start))
    {
        ns = xstrndup(qualified_name, scope_start - qualified_name);
        scope_start++;
    }
    else
    {
        scope_start = qualified_name;
    }

    char *scope = NULL;

    const char *lval_start = strchr(scope_start, scope_separator);

    if (lval_start && (!indices_start || lval_start < indices_start))
    {
        lval_start++;
        scope = xstrndup(scope_start, lval_start - scope_start - 1);
    }
    else
    {
        lval_start = scope_start;
    }

    char *lval = NULL;
    char **indices = NULL;
    size_t num_indices = 0;

    if (indices_start)
    {
        indices_start++;
        lval = xstrndup(lval_start, indices_start - lval_start - 1);

        assert("Index brackets in variable expression did not balance" && IndexBracketsBalance(indices_start - 1));

        num_indices = IndexCount(indices_start - 1);
        indices = xmalloc(num_indices * sizeof(char *));

        Buffer *buf = BufferNew();
        size_t cur_index = 0;
        for (const char *c = indices_start; *c != '\0'; c++)
        {
            if (*c == '[')
            {
                cur_index++;
            }
            else if (*c == ']')
            {
                indices[cur_index] = xstrdup(BufferData(buf));
                BufferZero(buf);
            }
            else
            {
                BufferAppend(buf, c, sizeof(char));
            }
        }
        BufferDestroy(&buf);
    }
    else
    {
        lval = xstrdup(lval_start);
    }

    assert(lval);

    if (!scope && !_scope)
    {
        assert(ns == NULL && "A variable missing a scope should not have a namespace");
    }

    VarRef *ref = xmalloc(sizeof(VarRef));

    ref->ns = ns ? ns : (_ns ? xstrdup(_ns) : NULL);
    ref->scope = scope ? scope : (_scope ? xstrdup(_scope) : NULL);
    ref->lval = lval;
    ref->indices = indices;
    ref->num_indices = num_indices;

    ref->hash = VarRefHash(ref);

    return ref;
}
Example #17
0
void CIMoteTerminal::BufferAppend(CString x){
	for(int i = 0; i < x.GetLength(); i++)
		BufferAppend(x[i], false);
	ScrollToBottom();
	UpdateText();
}
Example #18
0
void CIMoteTerminal::BufferAppend(char * y, DWORD len){
	for(size_t i = 0; i < len; i++)
		BufferAppend(y[i], false);
	ScrollToBottom();
	UpdateText();
}
Example #19
0
int LoadFileAsItemList(Item **liststart, const char *file, EditDefaults edits)
{
    {
        struct stat statbuf;
        if (stat(file, &statbuf) == -1)
        {
            Log(LOG_LEVEL_VERBOSE, "The proposed file '%s' could not be loaded. (stat: %s)", file, GetErrorStr());
            return false;
        }

        if (edits.maxfilesize != 0 && statbuf.st_size > edits.maxfilesize)
        {
            Log(LOG_LEVEL_INFO, "File '%s' is bigger than the limit edit.max_file_size = %jd > %d bytes", file,
                  (intmax_t) statbuf.st_size, edits.maxfilesize);
            return (false);
        }

        if (!S_ISREG(statbuf.st_mode))
        {
            Log(LOG_LEVEL_INFO, "%s is not a plain file", file);
            return false;
        }
    }

    FILE *fp = safe_fopen(file, "r");
    if (!fp)
    {
        Log(LOG_LEVEL_INFO, "Couldn't read file '%s' for editing. (fopen: %s)", file, GetErrorStr());
        return false;
    }

    Buffer *concat = BufferNew();

    size_t line_size = CF_BUFSIZE;
    char *line = xmalloc(line_size);
    bool result = true;

    for (;;)
    {
        ssize_t num_read = CfReadLine(&line, &line_size, fp);
        if (num_read == -1)
        {
            if (!feof(fp))
            {
                Log(LOG_LEVEL_ERR,
                    "Unable to read contents of '%s'. (fread: %s)",
                    file, GetErrorStr());
                result = false;
            }
            break;
        }

        if (edits.joinlines && *(line + strlen(line) - 1) == '\\')
        {
            *(line + strlen(line) - 1) = '\0';

            BufferAppend(concat, line, num_read);
        }
        else
        {
            BufferAppend(concat, line, num_read);
            if (!feof(fp) || (BufferSize(concat) > 0))
            {
                AppendItem(liststart, BufferData(concat), NULL);
            }
        }

        BufferZero(concat);
    }

    free(line);
    BufferDestroy(concat);
    fclose(fp);
    return result;
}
Example #20
0
File: expand.c Project: tzz/core
bool ExpandScalar(const EvalContext *ctx, const char *ns, const char *scope, const char *string, Buffer *out)
{
    assert(string);

    bool returnval = true;

    if (strlen(string) == 0)
    {
        return false;
    }

    // TODO: cleanup, optimize this mess
    Buffer *var = BufferNew();
    Buffer *current_item = BufferNew();
    Buffer *temp = BufferNew();
    for (const char *sp = string; /* No exit */ ; sp++)     /* check for varitems */
    {
        char varstring = false;
        size_t increment = 0;

        if (*sp == '\0')
        {
            break;
        }

        BufferZero(current_item);
        ExtractScalarPrefix(current_item, sp, strlen(sp));

        BufferAppend(out, BufferData(current_item), BufferSize(current_item));
        sp += BufferSize(current_item);

        if (*sp == '\0')
        {
            break;
        }

        BufferZero(var);
        if (*sp == '$')
        {
            switch (*(sp + 1))
            {
            case '(':
                varstring = ')';
                ExtractScalarReference(var, sp, strlen(sp), false);
                if (BufferSize(var) == 0)
                {
                    BufferAppendChar(out, '$');
                    continue;
                }
                break;

            case '{':
                varstring = '}';
                ExtractScalarReference(var, sp, strlen(sp), false);
                if (BufferSize(var) == 0)
                {
                    BufferAppendChar(out, '$');
                    continue;
                }
                break;

            default:
                BufferAppendChar(out, '$');
                continue;
            }
        }

        BufferZero(current_item);
        {
            BufferZero(temp);
            ExtractScalarReference(temp, sp, strlen(sp), true);

            if (IsCf3VarString(BufferData(temp)))
            {
                ExpandScalar(ctx, ns, scope, BufferData(temp), current_item);
            }
            else
            {
                BufferAppend(current_item, BufferData(temp), BufferSize(temp));
            }
        }

        increment = BufferSize(var) - 1;

        char name[CF_MAXVARSIZE] = "";
        if (!IsExpandable(BufferData(current_item)))
        {
            DataType type = DATA_TYPE_NONE;
            const void *value = NULL;
            {
                VarRef *ref = VarRefParseFromNamespaceAndScope(BufferData(current_item), ns, scope, CF_NS, '.');
                value = EvalContextVariableGet(ctx, ref, &type);
                VarRefDestroy(ref);
            }

            if (value)
            {
                switch (type)
                {
                case DATA_TYPE_STRING:
                case DATA_TYPE_INT:
                case DATA_TYPE_REAL:
                    BufferAppend(out, value, strlen(value));
                    break;

                case DATA_TYPE_STRING_LIST:
                case DATA_TYPE_INT_LIST:
                case DATA_TYPE_REAL_LIST:
                case DATA_TYPE_NONE:
                    if (varstring == '}')
                    {
                        snprintf(name, CF_MAXVARSIZE, "${%s}", BufferData(current_item));
                    }
                    else
                    {
                        snprintf(name, CF_MAXVARSIZE, "$(%s)", BufferData(current_item));
                    }

                    BufferAppend(out, name, strlen(name));
                    returnval = false;
                    break;

                default:
                    Log(LOG_LEVEL_DEBUG, "Returning Unknown Scalar ('%s' => '%s')", string, BufferData(out));
                    BufferDestroy(var);
                    BufferDestroy(current_item);
                    BufferDestroy(temp);
                    return false;

                }
            }
            else
            {
                if (varstring == '}')
                {
                    snprintf(name, CF_MAXVARSIZE, "${%s}", BufferData(current_item));
                }
                else
                {
                    snprintf(name, CF_MAXVARSIZE, "$(%s)", BufferData(current_item));
                }

                BufferAppend(out, name, strlen(name));
                returnval = false;
            }
        }

        sp += increment;
        BufferZero(current_item);
    }

    BufferDestroy(var);
    BufferDestroy(current_item);
    BufferDestroy(temp);

    return returnval;
}
Example #21
0
LRESULT CIMoteTerminal::OnReceiveSerialData(WPARAM wParam, LPARAM lParam)
{
	//following couple of lines allow us to debug a raw datastream
	char *rxstring = (char *)lParam;
	DWORD numBytesReceived = (DWORD) wParam;
	BufferAppend(rxstring, numBytesReceived);
	delete []rxstring;
	return TRUE;

#if 0
	DWORD i,offset;
	//TRACE("Rx...Buffer = %#X\tNumBytesReceived = %d\n",rxstring,numBytesReceived);
	/*****
	data format for the accelerometer data looks something like:
	0{2 bit addr}{5 data bits} {1}{7 data bits}
	******/
	for(offset=0; offset<numBytesReceived; offset++)
	{
		//find the correct first bytes
		if((rxstring[offset]  & 0xE0) == 0)
		{
			break;
		}
	}
	//offset current points to the correct first element for us to look at
	//start reconstructing the 16 bit numbers and doing the divide
	
	for(i=offset;(i+6)<numBytesReceived; i+=6)
	{	
		static bool init = false;
		POINT point;
		DWORD B,C,D,Tx, Ty,T;
		int Rx, Ry;
		B = ((rxstring[i] & 0x1F)<<7) | (rxstring[i+1] & 0x7F);
		C = ((rxstring[i+2] & 0x1F)<<7) | (rxstring[i+3] & 0x7F);
		D = ((rxstring[i+4] & 0x1F)<<7) | (rxstring[i+5] & 0x7F);
		Tx = B;
		Ty = D-C;
		T = C/2 + D/2 - B/2;

		Rx = ((Tx << 16) / T) - (65536/2);
		Ry = ((Ty << 16) / T) - (65536/2);
		//point.x =(LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]) -(65536/2);
		//point.x = (LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]);
		//TRACE("%d %d = %d\n",rxstring[i], rxstring[i+1], point.x);
		//TRACE("Found T, index %d \n", byte_index);
		//TRACE("Tx = %d, Ty = %d, T = %d, Rx = %d, Ry = %d\n",Tx, Ty, T, Rx, Ry);
		point.x = (LONG) Rx;
		point.y = (LONG) Ry;

		if(!init)
		{
			CIMoteCartesianPlot *pFrame=CreateNewView(0,0xDEADBEEF,0);
			pFrame->SetMappingFunction(-2,2);
			init = true;
		}
		AddPoint(point, 0);
	}
		
	delete rxstring;

	
	return TRUE;
//#endif;
	POINT point;
	static bool bGotBeef = 0;
	static bool bFirstTime = true;
	static unsigned short NumDataBytes;
	static unsigned short NumBytesProcessed;
	//static int MoteIDs[NUMCHANNELS];
	static unsigned short SensorID;
	static unsigned int MoteID;
	static unsigned int SensorType;
	static unsigned int ExtraInfo;
	static unsigned int TimeID;
	static unsigned int ChannelID;
	static unsigned char HeaderIndex;
	static unsigned char Header[16];
	unsigned short *short_ptr;
	unsigned int *int_ptr;
	DWORD byte_index;
	static unsigned char LastByte = 0;
//	unsigned int ProblemIndex;
	unsigned int EmptyChannel;
	static unsigned int NumProblems = 0;
	CString logentry;
	static bool bPrintheader=true;
	CTime time;
	static int Tx, Ty, T, Rx, Ry, Tb, Tc, Td, b0, b1;
	static int CurrentCounter, CurrentByte;
	// Hack, for now statically allocate 
	static unsigned char *CameraBuffer;
	static unsigned int CurrentCameraID;
	static unsigned int CameraBufferIndex;
	static unsigned int SegmentIndex;
	static bool PictureInProgress;
	static unsigned int LastPicID;

#define MAX_PIC_SIZE 80000
#define INVALID_SENSOR 0
#define PH_SENSOR 1
#define PRESSURE_SENSOR 2
#define ACCELEROMETER_SENSOR 3
#define CAMERA_SENSOR 4

#define FIRST_SEGMENT 0x1111
#define MID_SEGMENT 0
#define END_OF_PIC 0xffff

	for(int channel = 0; (channel < NUMCHANNELS) && bFirstTime; channel++) {
		MoteIDs[channel] = 0;
		HeaderIndex = 0;
		CurrentCameraID = 0;
		CameraBuffer = NULL;
		CameraBufferIndex = 0;
		PictureInProgress = false;
	}

	if (bFirstTime) {
		// Figure out the start of the file names
		CFileFind finder;
		CString TempName;
		unsigned int TempID;
		LastPicID = 0;
		BOOL bResult = finder.FindFile("c:\\icam\\*.jpg");

		while (bResult) {
			bResult = finder.FindNextFile();
			TempName = finder.GetFileName();
			if (sscanf((LPCSTR)TempName, "%d.jpg", &TempID) == 1) {
				// valid pic id
				if (LastPicID < TempID) {
					LastPicID = TempID;
				}
			}
		}
		LastPicID++;
	}


	bFirstTime = false;
	TRACE("Rx...Buffer = %#X\tNumBytesReceived = %d\n",rxstring,numBytesReceived);
	byte_index = 0;
	while(byte_index < numBytesReceived) {
		// Look for DEADBEEF, get all header info
		for(; (byte_index < numBytesReceived) && !bGotBeef; byte_index++) {
			switch (HeaderIndex) {
			case 0:
				if (rxstring[byte_index] == 0xEF) {
					HeaderIndex = 1;
				}
				break;
			case 1:
				if (rxstring[byte_index] == 0xBE) {
					HeaderIndex = 2;
				} else {
					HeaderIndex = 0;
				}
				break;
			case 2:
				if (rxstring[byte_index] == 0xAD) {
					HeaderIndex = 3;
				} else {
					HeaderIndex = 0;
				}
				break;
			case 3:
				if (rxstring[byte_index] == 0xDE) {
					HeaderIndex = 4;
				} else {
					HeaderIndex = 0;
				}
				break;
			case 13:
				// Done with header
				CurrentCounter = 0;
				CurrentByte = 0;
				bGotBeef = 1;
				Header[HeaderIndex] = rxstring[byte_index];
				/*
				* Header :
				* DEADBEEF (4B)
				* MOTE ID (4B)
				* Sensor TYPE (2B)
				* LENGTH (2B)
				* Extra Info (2B)
				* 
				*/
				int_ptr = (unsigned int *) &(Header[4]);
				MoteID = *int_ptr;
				short_ptr = (unsigned short *) &(Header[8]);
				SensorType = *short_ptr;
				short_ptr++;
				NumDataBytes = *short_ptr;
				short_ptr++;
				ExtraInfo = *short_ptr;
				NumBytesProcessed = 0;
				ChannelID = NUMCHANNELS;
				EmptyChannel = NUMCHANNELS;

				if (SensorType == CAMERA_SENSOR) {
					// check with segment
					TRACE("Camera seg %x, buf Index %d, NumDataBytes %d\r\n",
						ExtraInfo, CameraBufferIndex, NumDataBytes);
					if (ExtraInfo == FIRST_SEGMENT) {
						// first segment
						CurrentCameraID = MoteID;
						CameraBufferIndex = 0;						
						if (!PictureInProgress) {
							// create buffer
							CameraBuffer = new unsigned char[MAX_PIC_SIZE];
							PictureInProgress = true;
						}
					}
					SegmentIndex = 0;	// Per segment index
					break;	// don't process the channel stuff
				}
				// Find mote channel, 
				for(int channel = 0; channel < NUMCHANNELS; channel++) {
					if (MoteIDs[channel] == MoteID) {
						ChannelID = channel;
						break;
					} else {
						if (MoteIDs[channel] == 0) {
							EmptyChannel = channel;
						}
					}
				}
				

				if (ChannelID == NUMCHANNELS) {
					// Didn't find a channel
					if (EmptyChannel < NUMCHANNELS) {
						// assign the mote id to this channel
						MoteIDs[EmptyChannel] = MoteID;
						ChannelID = EmptyChannel;
						CIMoteCartesianPlot *pFrame=CreateNewView(ChannelID,MoteID,SensorID);
						/*
							Note to LAMA:  below is an example of how to use the setmapping function
							pFrame->SetMappingFunction(slope, offset, minrange, maxrange
						*/
						switch(SensorType) {
							case PH_SENSOR:
								pFrame->SetMappingFunction(0,14);
								rawdata = false;
								break;
							case PRESSURE_SENSOR:
								pFrame->SetMappingFunction(0,20.684);
								//pFrame->SetMappingFunction(0,300);
								rawdata = false;
								break;
							case ACCELEROMETER_SENSOR:
								pFrame->SetMappingFunction(-2,2);
								rawdata = false;
								break;
							default :
								//pFrame->SetMappingFunction(1,1,0,14);
								pFrame->SetMappingFunction(-32768,32768);
						}
						//UpdateAllViews(NULL);
					}  
					/*
					* NOTE: if ChannelID is not assigned, 
					* the processing will remain the same, but the data won't
					* be displayed.
					* TODO : handle later
					*/
				}
				//log transaction info to file here:
				if(bPrintheader)
				{
					logentry.Format("Timestamp, iMoteID, # of Bytes\r\n");
					//logfile<<logentry<<endl;
					SaveLogEntry(&logentry);
					bPrintheader=false;
				}
				time=time.GetCurrentTime();
				//logfile<<time.Format("%c");
				SaveLogEntry(&time.Format("%c"));
				logentry.Format(", %#X, %d\r\n",MoteID, NumDataBytes);
				//logfile<<logentry<<endl;
				SaveLogEntry(&logentry);				
				break;
			default:
				Header[HeaderIndex] = rxstring[byte_index];
				HeaderIndex++;
				break;
			}
		}
		if (!bGotBeef) {
			delete []rxstring;
			return TRUE;
		}
		// Got DEADBEEF, process data
		for(; byte_index <numBytesReceived; byte_index++,NumBytesProcessed ++) {
			if (NumBytesProcessed >= NumDataBytes) {
				// go back to start, look for DEADBEEF again
				bGotBeef = false;
				HeaderIndex = 0;
				TRACE("Mote ID %lx, NumBytes %ld, byte index %d \n", MoteID, NumDataBytes, byte_index);
				//MoteID = 0;
				//NumDataBytes = 0;
				break;
			}
			if (rawdata) {	//RAW_BYTES mode, no processing
				// Assume data is 2 bytes long, and back to back
				if (CurrentByte == 0) {
					b0 = rxstring[byte_index];
					CurrentByte = 1;
				} else {
					b1 = rxstring[byte_index];
					CurrentByte = 0;
					int sample_data;
					sample_data = (b1 <<8) + b0;
					//sample_data -= 0x2000;
					//sample_data = sample_data << 2;
					point.x = (LONG) sample_data;
					point.y = 0;
					//TRACE("sample is %d\r\n", sample_data);
					if (ChannelID < NUMCHANNELS) {
						// valid channel
						AddPoint(point, ChannelID);
					}
				}
			} else {
				if (CurrentByte == 0) {
					b0 = rxstring[byte_index];
					CurrentByte = 1;
					if (SensorType == CAMERA_SENSOR) {
						// just copy data
						CameraBuffer[CameraBufferIndex] = b0;
						SegmentIndex++;
						CameraBufferIndex++;
					}
				} else {
					b1 = rxstring[byte_index];
					CurrentByte = 0;
					switch(SensorType) {
						case PH_SENSOR:
							/*
							* A/D maps 0-5V range to 0-32 K 
							* pH = -7.752 * V + 16.237
							* V = raw_data * 5 / 32768
							* The plot output expects the 0 - 14 range to be represented in -32 - 32 K
							* point.x = (-7.752 * (raw_data * 5/32768) + 16.237) * 64K / 14 - 32K
							*/
							double ph_data;
							ph_data = (b1 <<8) + b0;
							ph_data = -7.752 * (ph_data/ 32768) * 5 + 16.237;
							ph_data = (ph_data * 65536 / 14) - 32768;
							point.x = (LONG) ph_data;
							point.y = 0;
							if (ChannelID < NUMCHANNELS) {
								// valid channel
								AddPoint(point, ChannelID);
							}
							break;
						case PRESSURE_SENSOR:
							/*
							* A/D maps 0-5V range to 0-32 K 
							* The plot output expects the 0 - 20.684 range to be represented in -32 - 32 K
							* point.x = (raw_data * 5/32768) * 64K / 20.684 - 32K
							*/
							int pressure_data;
							pressure_data = (b1 <<8) + b0;
							pressure_data = pressure_data * 2 - 32768;
							point.x = (LONG) pressure_data;
							point.y = 0;
							if (ChannelID < NUMCHANNELS) {
								// valid channel
								AddPoint(point, ChannelID);
							}
							break;
						case ACCELEROMETER_SENSOR:
							// TRACE("CurrentCounter %d, ByteIndex %d \n", CurrentCounter, byte_index);
							switch (CurrentCounter) {
								case 0:
									Tx = (b0 <<8) + b1;;	
									CurrentCounter = 1;
									//TRACE("Found Tx, index %d \n", byte_index);
									break;
								case 1:
									Ty = (b0 <<8) + b1;
									CurrentCounter = 2;
									//TRACE("Found Ty, index %d \n", byte_index);
									break;
								case 2:
									T = (b0 <<8) + b1;
									Rx = ((Tx << 16) / T) - (65536/2);
									Ry = ((Ty << 16) / T) - (65536/2);
									//point.x =(LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]) -(65536/2);
									//point.x = (LONG)( (rxstring[byte_index]<<8) + rxstring[byte_index+1]);
									//TRACE("%d %d = %d\n",rxstring[i], rxstring[i+1], point.x);
									//TRACE("Found T, index %d \n", byte_index);
									//TRACE("Tx = %d, Ty = %d, T = %d, Rx = %d, Ry = %d\n",Tx, Ty, T, Rx, Ry);
									point.x = (LONG) Rx;
									point.y = (LONG) Ry;
									if (ChannelID < NUMCHANNELS) {
										// valid channel
										AddPoint(point, ChannelID);
									}
									CurrentCounter = 0;
									break;
								default:
									break;
							}
							break;
						
						case CAMERA_SENSOR:
							// just copy data
							CameraBuffer[CameraBufferIndex] = b1;
							SegmentIndex++;
							CameraBufferIndex++;
							break;
						
					}
				}
			//for now, just save the point in the x field of the structure
			}
			//NumBytesProcessed += 2;		
		}
		TRACE("NumBytesProcessed %d, NumDataBytes %d\r\n", NumBytesProcessed, NumDataBytes);
		// Check if we reached the end of a picture, write it to file
		if ((SensorType == CAMERA_SENSOR) && (NumBytesProcessed == NumDataBytes) &&
			(ExtraInfo == END_OF_PIC)) {
				// Create output buffer , assume header < 1000
				unsigned char *JpgImage;
				int JpgImageLen;
				JpgImage = new unsigned char[CameraBufferIndex+1000];
				// build jpeg image
				BuildJPG(CameraBuffer, CameraBufferIndex, JpgImage, &JpgImageLen);
				// write to file
				char pszFileName[200];
				CFile PictureFile;
				CFileException fileException;

				sprintf(pszFileName, "c:\\icam\\%d.jpg", LastPicID);
				LastPicID++;

				if ( !PictureFile.Open( pszFileName, CFile::modeCreate |   
									CFile::modeWrite | CFile::typeBinary,
									&fileException ) )
				{
					TRACE( "Can't open file %s, error = %u\n",
								pszFileName, fileException.m_cause );
				}
				//PictureFile.Write(CameraBuffer, CameraBufferIndex);
				PictureFile.Write(JpgImage, JpgImageLen);
				PictureFile.Close();
				TRACE("Wrote Jpeg image raw %d\r\n", CameraBufferIndex);
				
				delete []CameraBuffer;
				delete []JpgImage;
				PictureInProgress = false;
		}
	}
	delete []rxstring;
	return TRUE;
#endif;
}
Example #22
0
File: expand.c Project: awsiv/core
bool ExpandScalar(const EvalContext *ctx,
                  const char *ns, const char *scope, const char *string,
                  Buffer *out)
{
    assert(string);
    if (strlen(string) == 0)
    {
        return true;
    }

    bool fully_expanded = true;

    Buffer *current_item = BufferNew();
    for (const char *sp = string; *sp != '\0'; sp++)
    {
        BufferClear(current_item);
        ExtractScalarPrefix(current_item, sp, strlen(sp));

        BufferAppend(out, BufferData(current_item), BufferSize(current_item));
        sp += BufferSize(current_item);
        if (*sp == '\0')
        {
            break;
        }

        BufferClear(current_item);
        char varstring = sp[1];
        ExtractScalarReference(current_item,  sp, strlen(sp), true);
        sp += BufferSize(current_item) + 2;

        if (IsCf3VarString(BufferData(current_item)))
        {
            Buffer *temp = BufferCopy(current_item);
            BufferClear(current_item);
            ExpandScalar(ctx, ns, scope, BufferData(temp), current_item);
            BufferDestroy(temp);
        }

        if (!IsExpandable(BufferData(current_item)))
        {
            DataType type = CF_DATA_TYPE_NONE;
            const void *value = NULL;
            {
                VarRef *ref = VarRefParseFromNamespaceAndScope(BufferData(current_item), ns, scope, CF_NS, '.');
                value = EvalContextVariableGet(ctx, ref, &type);
                VarRefDestroy(ref);
            }

            if (value)
            {
                switch (DataTypeToRvalType(type))
                {
                case RVAL_TYPE_SCALAR:
                    BufferAppendString(out, value);
                    continue;

                case RVAL_TYPE_CONTAINER:
                    if (JsonGetElementType((JsonElement*)value) == JSON_ELEMENT_TYPE_PRIMITIVE)
                    {
                        BufferAppendString(out, JsonPrimitiveGetAsString((JsonElement*)value));
                        continue;
                    }
                    break;

                default:
                    break;
                }
            }
        }

        if (varstring == '{')
        {
            BufferAppendF(out, "${%s}", BufferData(current_item));
        }
        else
        {
            BufferAppendF(out, "$(%s)", BufferData(current_item));
        }
    }

    BufferDestroy(current_item);

    return fully_expanded;
}