aboutsummaryrefslogtreecommitdiff
path: root/src/sensors/zjs_sensor_light.c
blob: 53cc261eecf668ef2480e0896a727168d140058f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2017, Intel Corporation.

// C includes
#include <string.h>

// ZJS includes
#include "zjs_common.h"
#include "zjs_sensor.h"
#include "zjs_sensor_light.h"
#include "zjs_util.h"

static sensor_instance_t *g_instance = NULL;

static void onchange(void *h, const void *argv)
{
    sensor_handle_t *handle = (sensor_handle_t *)h;
    jerry_value_t obj = handle->sensor_obj;

    double d;

    // reading is a ptr to double
    d = *((double *)argv);
    zjs_obj_add_readonly_number(obj, "illuminance", d);
    zjs_sensor_trigger_change(obj);
}

static void onstop(void *h, const void *argv)
{
    sensor_handle_t *handle = (sensor_handle_t *)h;
    jerry_value_t obj = handle->sensor_obj;

    jerry_value_t null_val = jerry_create_null();
    zjs_set_readonly_property(obj, "illuminance", null_val);
}

static ZJS_DECL_FUNC(zjs_sensor_constructor)
{
    ZJS_VALIDATE_ARGS(Z_OBJECT);

    jerry_value_t sensor_obj =
        ZJS_CHAIN_FUNC_ARGS(zjs_sensor_create, g_instance, SENSOR_CHAN_LIGHT,
                            ADC_DEVICE_NAME, -1, 100, onchange, NULL, onstop);

    if (!jerry_value_is_error(sensor_obj)) {
        ZVAL null_val = jerry_create_null();
        zjs_set_readonly_property(sensor_obj, "illuminance", null_val);
    }

    return sensor_obj;
}

sensor_instance_t *zjs_sensor_light_init()
{
    if (g_instance)
        return g_instance;

    g_instance = zjs_sensor_create_instance("AmbientLightSensor",
                                            zjs_sensor_constructor);
    return g_instance;
}

void zjs_sensor_light_cleanup()
{
    if (g_instance) {
        zjs_sensor_free_instance(g_instance);
        g_instance = NULL;
    }
}