joulescope_driver 0.0.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,412 +1,412 @@
1
- /*
2
- * Copyright 2024 Jetperch LLC
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- #include <assert.h>
18
- #include <stdint.h>
19
- #include <cstring> // memset
20
- #include "joulescope_driver.h"
21
-
22
- static const uint32_t _TIMEOUT_MS_INIT = 5000;
23
- static const uint32_t _TIMEOUT_MS = 2000;
24
-
25
-
26
- Napi::Object JoulescopeDriver::Init(Napi::Env env, Napi::Object exports) {
27
- Napi::Function func =
28
- DefineClass(env, "JoulescopeDriver", {
29
- InstanceMethod("publish", &JoulescopeDriver::publish),
30
- InstanceMethod("query", &JoulescopeDriver::query),
31
- InstanceMethod("subscribe", &JoulescopeDriver::subscribe),
32
- InstanceMethod("finalize", &JoulescopeDriver::finalize)
33
- });
34
-
35
- Napi::FunctionReference* constructor = new Napi::FunctionReference();
36
- *constructor = Napi::Persistent(func);
37
- env.SetInstanceData(constructor);
38
-
39
- exports.Set("JoulescopeDriver", func);
40
- return exports;
41
- }
42
-
43
- JoulescopeDriver::JoulescopeDriver(const Napi::CallbackInfo& info)
44
- : Napi::ObjectWrap<JoulescopeDriver>(info) {
45
- Napi::Env env = info.Env();
46
- this->context_ = NULL;
47
- int32_t status = jsdrv_initialize(&this->context_, NULL, _TIMEOUT_MS_INIT);
48
- if (status) {
49
- napi_throw_error(env, NULL, "jsdrv_initialize failed");
50
- return;
51
- }
52
- }
53
-
54
- static uint32_t parse_timeout(Napi::Env env, Napi::Value value) {
55
- int64_t timeout_ms = _TIMEOUT_MS;
56
- if (value.IsNull()) {
57
- ; // use default
58
- } else if (value.IsNumber()) {
59
- timeout_ms = value.As<Napi::Number>().Int64Value();
60
- if (timeout_ms > 4294967295LL) {
61
- timeout_ms = 4294967295LL;
62
- } else if (timeout_ms < 0) {
63
- timeout_ms = _TIMEOUT_MS;
64
- }
65
- } else {
66
- Napi::TypeError::New(env, "timeout_ms invalid type").ThrowAsJavaScriptException();
67
- // use default
68
- }
69
- return (uint32_t) timeout_ms;
70
- }
71
-
72
- Napi::Value JoulescopeDriver::publish(const Napi::CallbackInfo& info) {
73
- Napi::Env env = info.Env();
74
- if (info.Length() != 3) {
75
- Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
76
- return env.Undefined();
77
- }
78
- uint32_t timeout_ms = parse_timeout(env, info[2]);
79
-
80
- if (!info[0].IsString()) {
81
- Napi::TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
82
- return env.Undefined();
83
- }
84
- std::string topic = info[0].As<Napi::String>();
85
- std::string value_str;
86
-
87
- struct jsdrv_union_s value;
88
- memset(&value, 0, sizeof(value));
89
- if (info[1].IsString()) {
90
- value.type = JSDRV_UNION_STR;
91
- value.flags = JSDRV_UNION_FLAG_CONST;
92
- value_str = info[1].As<Napi::String>();
93
- value.value.str = value_str.c_str();
94
- } else if (info[1].IsNumber()) {
95
- value.value.i64 = info[1].As<Napi::Number>().Int64Value();
96
- if ((value.value.i64 >= 0) && (value.value.i64 < 4294967296LL)) {
97
- value.type = JSDRV_UNION_U32;
98
- } else if ((value.value.i64 >= -2147483648LL) && (value.value.i64 < 2147483648LL)) {
99
- value.type = JSDRV_UNION_I32;
100
- } else {
101
- value.type = JSDRV_UNION_I64;
102
- }
103
- } else {
104
- Napi::TypeError::New(env, "unsupported value type").ThrowAsJavaScriptException();
105
- return env.Undefined();
106
- }
107
- if (topic.find_first_of("!") == std::string::npos) {
108
- value.flags |= JSDRV_UNION_FLAG_RETAIN;
109
- }
110
-
111
- int32_t status = jsdrv_publish(this->context_, topic.c_str(), &value, timeout_ms);
112
- if (status) {
113
- napi_throw_error(env, NULL, "jsdrv_publish failed");
114
- }
115
- return env.Undefined();
116
- }
117
-
118
- static Napi::Value obj_value1(Napi::Env env, double v1, const char * units) {
119
- Napi::Object obj = Napi::Object::New(env);
120
- obj.Set("value", v1);
121
- obj.Set("units", units);
122
- return obj;
123
- }
124
-
125
- static Napi::Value obj_value2(Napi::Env env, double v1, double v2, const char * units) {
126
- Napi::Object obj = Napi::Object::New(env);
127
- Napi::Float64Array value = Napi::Float64Array::New(env, 2);
128
- value[0] = v1;
129
- value[1] = v2;
130
- obj.Set("value", value);
131
- obj.Set("units", units);
132
- return obj;
133
- }
134
-
135
- static Napi::Value obj_time_map(Napi::Env env, const struct jsdrv_time_map_s * time_map) {
136
- Napi::Object obj = Napi::Object::New(env);
137
- obj.Set("offset_time", time_map->offset_time);
138
- obj.Set("offset_counter", time_map->offset_counter);
139
- obj.Set("counter_rate", time_map->counter_rate);
140
- return obj;
141
- }
142
-
143
- static double time64_to_ms(int64_t t) {
144
- int64_t t_ms = JSDRV_TIME_TO_MILLISECONDS(t);
145
- t_ms += ((int64_t) 1514764800) * 1000;
146
- return (double) t_ms;
147
- }
148
-
149
- static Napi::Value stream_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
150
- const struct jsdrv_stream_signal_s * s = (const struct jsdrv_stream_signal_s *) value->value.bin;
151
- Napi::Object obj = Napi::Object::New(env);
152
- obj.Set("sample_id", s->sample_id);
153
- obj.Set("utc", time64_to_ms(jsdrv_time_from_counter(&s->time_map, s->sample_id)));
154
- obj.Set("field_id", s->field_id);
155
- obj.Set("index", s->index);
156
- obj.Set("sample_rate", s->sample_rate);
157
- obj.Set("decimate_factor", s->decimate_factor);
158
- obj.Set("time_map", obj_time_map(env, &s->time_map));
159
- if (JSDRV_DATA_TYPE_FLOAT == s->element_type) {
160
- if (32 == s->element_size_bits) {
161
- Napi::Float32Array data = Napi::Float32Array::New(env, s->element_count);
162
- float * data_src = (float *) s->data;
163
- for (size_t idx = 0; idx < s->element_count; ++idx) {
164
- data[idx] = data_src[idx];
165
- }
166
- obj.Set("data", data);
167
- } else if (64 == s->element_size_bits) {
168
- Napi::Float64Array data = Napi::Float64Array::New(env, s->element_count);
169
- double * data_src = (double *) s->data;
170
- for (size_t idx = 0; idx < s->element_count; ++idx) {
171
- data[idx] = data_src[idx];
172
- }
173
- obj.Set("data", data);
174
- }
175
- } else if (JSDRV_DATA_TYPE_UINT == s->element_type) {
176
- if (1 == s->element_size_bits) {
177
- Napi::Uint8Array data = Napi::Uint8Array::New(env, s->element_count);
178
- uint8_t * data_src = (uint8_t *) s->data;
179
- for (size_t idx = 0; idx < s->element_count; ++idx) {
180
- data[idx] = (data_src[idx >> 3] >> (idx & 7)) & 1;
181
- }
182
- obj.Set("data", data);
183
- } else if (4 == s->element_size_bits) {
184
- Napi::Uint8Array data = Napi::Uint8Array::New(env, s->element_count);
185
- uint8_t * data_src = (uint8_t *) s->data;
186
- for (size_t idx = 0; idx < s->element_count; ++idx) {
187
- data[idx] = (data_src[idx >> 1] >> (4 * (idx & 1))) & 0x0f;
188
- }
189
- obj.Set("data", data);
190
- } else if (8 == s->element_size_bits) {
191
- Napi::Uint8Array data = Napi::Uint8Array::New(env, s->element_count);
192
- uint8_t * data_src = (uint8_t *) s->data;
193
- for (size_t idx = 0; idx < s->element_count; ++idx) {
194
- data[idx] = data_src[idx];
195
- }
196
- obj.Set("data", data);
197
- }
198
- } else if (JSDRV_DATA_TYPE_INT == s->element_type) {
199
- if (16 == s->element_size_bits) {
200
- Napi::Int16Array data = Napi::Int16Array::New(env, s->element_count);
201
- int16_t * data_src = (int16_t *) s->data;
202
- for (size_t idx = 0; idx < s->element_count; ++idx) {
203
- data[idx] = data_src[idx];
204
- }
205
- obj.Set("data", data);
206
- }
207
- }
208
- return obj;
209
- }
210
-
211
- static Napi::Value stats_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
212
- const struct jsdrv_statistics_s * s =(const struct jsdrv_statistics_s *) value->value.bin;
213
- uint32_t sample_freq = s->sample_freq;
214
- uint64_t samples_full_rate = s->block_sample_count * (uint64_t) s->decimate_factor;
215
- uint64_t sample_id_start = s->block_sample_id;
216
- uint64_t sample_id_end = s->block_sample_id + samples_full_rate;
217
- uint64_t t_start = sample_id_start / sample_freq;
218
- uint64_t t_delta = samples_full_rate / sample_freq;
219
-
220
- Napi::Object obj = Napi::Object::New(env);
221
- Napi::Object time = Napi::Object::New(env);
222
- time.Set("samples", obj_value2(env, (double) sample_id_start, (double) sample_id_end, "samples"));
223
- time.Set("sample_freq", obj_value1(env, (double) sample_freq, "Hz"));
224
- time.Set("utc", obj_value2(
225
- env,
226
- time64_to_ms(jsdrv_time_from_counter(&s->time_map, sample_id_start)),
227
- time64_to_ms(jsdrv_time_from_counter(&s->time_map, sample_id_end)),
228
- "ms"));
229
- time.Set("range", obj_value2(env, (double) t_start, (double) (t_start + t_delta), "s"));
230
- time.Set("delta", obj_value1(env, (double) t_delta, "s"));
231
- time.Set("decimate_factor", obj_value1(env, (double) s->decimate_factor, "samples"));
232
- time.Set("decimate_sample_count", obj_value1(env, (double) s->block_sample_count, "samples"));
233
- time.Set("accum_samples", obj_value2(env, (double) s->accum_sample_id, (double) sample_id_end, "samples"));
234
- obj.Set("time_map", obj_time_map(env, &s->time_map));
235
-
236
- Napi::Object signals = Napi::Object::New(env);
237
- obj.Set("signals", signals);
238
-
239
- Napi::Object current = Napi::Object::New(env);
240
- current.Set("avg", obj_value1(env, s->i_avg, "A"));
241
- current.Set("std", obj_value1(env, s->i_std, "A"));
242
- current.Set("min", obj_value1(env, s->i_min, "A"));
243
- current.Set("max", obj_value1(env, s->i_max, "A"));
244
- current.Set("p2p", obj_value1(env, s->i_max - s->i_min, "A"));
245
- current.Set("integral", obj_value1(env, s->i_avg * t_delta, "C"));
246
- signals.Set("current", current);
247
-
248
- Napi::Object voltage = Napi::Object::New(env);
249
- voltage.Set("avg", obj_value1(env, s->v_avg, "V"));
250
- voltage.Set("std", obj_value1(env, s->v_std, "V"));
251
- voltage.Set("min", obj_value1(env, s->v_min, "V"));
252
- voltage.Set("max", obj_value1(env, s->v_max, "V"));
253
- voltage.Set("p2p", obj_value1(env, s->v_max - s->v_min, "V"));
254
- signals.Set("voltage", voltage);
255
-
256
- Napi::Object power = Napi::Object::New(env);
257
- power.Set("avg", obj_value1(env, s->p_avg, "W"));
258
- power.Set("std", obj_value1(env, s->p_std, "W"));
259
- power.Set("min", obj_value1(env, s->p_min, "W"));
260
- power.Set("max", obj_value1(env, s->p_max, "W"));
261
- power.Set("p2p", obj_value1(env, s->p_max - s->p_min, "W"));
262
- power.Set("integral", obj_value1(env, s->p_avg * t_delta, "J"));
263
- signals.Set("power", power);
264
-
265
- Napi::Object accumulators = Napi::Object::New(env);
266
- obj.Set("accumulators", accumulators);
267
- accumulators.Set("charge", obj_value1(env, s->charge_f64, "C"));
268
- accumulators.Set("energy", obj_value1(env, s->energy_f64, "J"));
269
- obj.Set("source", "sensor");
270
-
271
- return obj;
272
- }
273
-
274
- static Napi::Value buffer_info_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
275
- return env.Undefined(); // todo
276
- }
277
-
278
- static Napi::Value buffer_rsp_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
279
- return env.Undefined(); // todo
280
- }
281
-
282
- static Napi::Value bin_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
283
- switch (value->app) {
284
- case JSDRV_PAYLOAD_TYPE_STREAM: return stream_to_js(env, value);
285
- case JSDRV_PAYLOAD_TYPE_STATISTICS: return stats_to_js(env, value);
286
- case JSDRV_PAYLOAD_TYPE_BUFFER_INFO: return buffer_info_to_js(env, value);
287
- case JSDRV_PAYLOAD_TYPE_BUFFER_RSP: return buffer_rsp_to_js(env, value);
288
- default:
289
- return env.Undefined(); // todo
290
- }
291
- }
292
-
293
-
294
- static Napi::Value union_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
295
- // https://github.com/nodejs/node-addon-api/blob/main/doc/value.md
296
- // printf("union_to_js type=%d\n", value->type);
297
- switch (value->type) {
298
- case JSDRV_UNION_NULL: return env.Null();
299
- case JSDRV_UNION_STR: return Napi::String::New(env, value->value.str);
300
- case JSDRV_UNION_JSON: {
301
- Napi::String json_string = Napi::String::New(env, value->value.str);
302
- Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
303
- Napi::Function parse = json.Get("parse").As<Napi::Function>();
304
- return parse.Call(json, { json_string }).As<Napi::Object>();
305
- }
306
- case JSDRV_UNION_BIN: return bin_to_js(env, value);
307
- case JSDRV_UNION_F32: return Napi::Number::New(env, static_cast<double>(value->value.f32));
308
- case JSDRV_UNION_F64: return Napi::Number::New(env, static_cast<double>(value->value.f64));
309
- case JSDRV_UNION_U8: return Napi::Number::New(env, static_cast<double>(value->value.u8));
310
- case JSDRV_UNION_U16: return Napi::Number::New(env, static_cast<double>(value->value.u16));
311
- case JSDRV_UNION_U32: return Napi::Number::New(env, static_cast<double>(value->value.u32));
312
- case JSDRV_UNION_U64: return Napi::Number::New(env, static_cast<double>(value->value.u64));
313
- case JSDRV_UNION_I8: return Napi::Number::New(env, static_cast<double>(value->value.i8));
314
- case JSDRV_UNION_I16: return Napi::Number::New(env, static_cast<double>(value->value.i16));
315
- case JSDRV_UNION_I32: return Napi::Number::New(env, static_cast<double>(value->value.i32));
316
- case JSDRV_UNION_I64: return Napi::Number::New(env, static_cast<double>(value->value.i64));
317
- default: return env.Undefined();
318
- }
319
- }
320
-
321
- Napi::Value JoulescopeDriver::query(const Napi::CallbackInfo& info) {
322
- Napi::Env env = info.Env();
323
- if (info.Length() != 2) {
324
- Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
325
- return env.Undefined();
326
- }
327
-
328
- std::string topic_str = info[0].As<Napi::String>();
329
- uint32_t timeout_ms = parse_timeout(env, info[1]);
330
- struct jsdrv_union_s v;
331
- char byte_str[1024];
332
- memset(&v, 0, sizeof(v));
333
- v.type = JSDRV_UNION_BIN;
334
- v.size = sizeof(byte_str);
335
- v.value.str = byte_str;
336
- int32_t status = jsdrv_query(this->context_, topic_str.c_str(), &v, timeout_ms);
337
- if (status) {
338
- napi_throw_error(env, NULL, "jsdrv_query failed");
339
- return env.Undefined();
340
- }
341
- return union_to_js(env, &v);
342
- }
343
-
344
- struct subscribe_context {
345
- public:
346
- subscribe_context() {}
347
- std::string topic;
348
- uint8_t flags;
349
- Napi::ThreadSafeFunction fn;
350
- };
351
-
352
- void _subscribe_fn(void * user_data, const char * topic, const struct jsdrv_union_s * value) {
353
- struct subscribe_context * context = (struct subscribe_context *) user_data;
354
- std::string topic_str = topic;
355
- struct jsdrv_union_s * value_cpy = (struct jsdrv_union_s *) malloc(sizeof(*value) + value->size);
356
- if (NULL == value_cpy) {
357
- return;
358
- }
359
- *value_cpy = *value;
360
-
361
- if (value->size) {
362
- uint8_t *ptr = (uint8_t *) &value_cpy[1];
363
- value_cpy->value.bin = ptr;
364
- memcpy(ptr, value->value.bin, value->size);
365
- }
366
-
367
- auto callback = [topic_str]( Napi::Env env, Napi::Function jsCallback, const struct jsdrv_union_s * value) {
368
- jsCallback.Call( {Napi::String::New(env, topic_str), union_to_js(env, value)} );
369
- free((void *) value);
370
- };
371
-
372
- context->fn.NonBlockingCall(value_cpy, callback);
373
- }
374
-
375
- Napi::Value JoulescopeDriver::subscribe(const Napi::CallbackInfo& info) { // topic, flags, fn, timeout
376
- // JSDRV_API int32_t jsdrv_subscribe(struct jsdrv_context_s * context, const char * topic, uint8_t flags,
377
- // jsdrv_subscribe_fn cbk_fn, void * cbk_user_data,
378
- // uint32_t timeout_ms);
379
- Napi::Env env = info.Env();
380
- if (info.Length() != 4) {
381
- Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
382
- return env.Undefined();
383
- }
384
- subscribe_context * context = new subscribe_context();
385
- context->topic = info[0].As<Napi::String>();
386
- context->flags = (uint8_t) (info[1].As<Napi::Number>().Uint32Value());
387
- Napi::Function fn = info[2].As<Napi::Function>();
388
- uint32_t timeout_ms = parse_timeout(env, info[3]);
389
- context->fn = Napi::ThreadSafeFunction::New(env, fn, "jsdrv_subscribe_fn", 0, 1);
390
- int32_t status = jsdrv_subscribe(this->context_, context->topic.c_str(), context->flags,
391
- _subscribe_fn, context, timeout_ms);
392
- if (status) {
393
- delete context;
394
- napi_throw_error(env, NULL, "jsdrv_subscribe failed");
395
- return env.Undefined();
396
- }
397
- struct jsdrv_context_s * jsdrv_context = this->context_;
398
-
399
- auto unsub_fn = [env, jsdrv_context, context, timeout_ms](const Napi::CallbackInfo& info) -> Napi::Value {
400
- jsdrv_unsubscribe(jsdrv_context, context->topic.c_str(), _subscribe_fn, context, timeout_ms);
401
- context->fn.Release();
402
- delete context;
403
- return env.Undefined();
404
- };
405
- return Napi::Function::New(env, unsub_fn);
406
- }
407
-
408
- Napi::Value JoulescopeDriver::finalize(const Napi::CallbackInfo& info) {
409
- jsdrv_finalize(this->context_, _TIMEOUT_MS_INIT);
410
- this->context_ = NULL;
411
- return info.Env().Undefined();
412
- }
1
+ /*
2
+ * Copyright 2024 Jetperch LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ #include <assert.h>
18
+ #include <stdint.h>
19
+ #include <cstring> // memset
20
+ #include "joulescope_driver.h"
21
+
22
+ static const uint32_t _TIMEOUT_MS_INIT = 5000;
23
+ static const uint32_t _TIMEOUT_MS = 2000;
24
+
25
+
26
+ Napi::Object JoulescopeDriver::Init(Napi::Env env, Napi::Object exports) {
27
+ Napi::Function func =
28
+ DefineClass(env, "JoulescopeDriver", {
29
+ InstanceMethod("publish", &JoulescopeDriver::publish),
30
+ InstanceMethod("query", &JoulescopeDriver::query),
31
+ InstanceMethod("subscribe", &JoulescopeDriver::subscribe),
32
+ InstanceMethod("finalize", &JoulescopeDriver::finalize)
33
+ });
34
+
35
+ Napi::FunctionReference* constructor = new Napi::FunctionReference();
36
+ *constructor = Napi::Persistent(func);
37
+ env.SetInstanceData(constructor);
38
+
39
+ exports.Set("JoulescopeDriver", func);
40
+ return exports;
41
+ }
42
+
43
+ JoulescopeDriver::JoulescopeDriver(const Napi::CallbackInfo& info)
44
+ : Napi::ObjectWrap<JoulescopeDriver>(info) {
45
+ Napi::Env env = info.Env();
46
+ this->context_ = NULL;
47
+ int32_t status = jsdrv_initialize(&this->context_, NULL, _TIMEOUT_MS_INIT);
48
+ if (status) {
49
+ napi_throw_error(env, NULL, "jsdrv_initialize failed");
50
+ return;
51
+ }
52
+ }
53
+
54
+ static uint32_t parse_timeout(Napi::Env env, Napi::Value value) {
55
+ int64_t timeout_ms = _TIMEOUT_MS;
56
+ if (value.IsNull()) {
57
+ ; // use default
58
+ } else if (value.IsNumber()) {
59
+ timeout_ms = value.As<Napi::Number>().Int64Value();
60
+ if (timeout_ms > 4294967295LL) {
61
+ timeout_ms = 4294967295LL;
62
+ } else if (timeout_ms < 0) {
63
+ timeout_ms = _TIMEOUT_MS;
64
+ }
65
+ } else {
66
+ Napi::TypeError::New(env, "timeout_ms invalid type").ThrowAsJavaScriptException();
67
+ // use default
68
+ }
69
+ return (uint32_t) timeout_ms;
70
+ }
71
+
72
+ Napi::Value JoulescopeDriver::publish(const Napi::CallbackInfo& info) {
73
+ Napi::Env env = info.Env();
74
+ if (info.Length() != 3) {
75
+ Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
76
+ return env.Undefined();
77
+ }
78
+ uint32_t timeout_ms = parse_timeout(env, info[2]);
79
+
80
+ if (!info[0].IsString()) {
81
+ Napi::TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
82
+ return env.Undefined();
83
+ }
84
+ std::string topic = info[0].As<Napi::String>();
85
+ std::string value_str;
86
+
87
+ struct jsdrv_union_s value;
88
+ memset(&value, 0, sizeof(value));
89
+ if (info[1].IsString()) {
90
+ value.type = JSDRV_UNION_STR;
91
+ value.flags = JSDRV_UNION_FLAG_CONST;
92
+ value_str = info[1].As<Napi::String>();
93
+ value.value.str = value_str.c_str();
94
+ } else if (info[1].IsNumber()) {
95
+ value.value.i64 = info[1].As<Napi::Number>().Int64Value();
96
+ if ((value.value.i64 >= 0) && (value.value.i64 < 4294967296LL)) {
97
+ value.type = JSDRV_UNION_U32;
98
+ } else if ((value.value.i64 >= -2147483648LL) && (value.value.i64 < 2147483648LL)) {
99
+ value.type = JSDRV_UNION_I32;
100
+ } else {
101
+ value.type = JSDRV_UNION_I64;
102
+ }
103
+ } else {
104
+ Napi::TypeError::New(env, "unsupported value type").ThrowAsJavaScriptException();
105
+ return env.Undefined();
106
+ }
107
+ if (topic.find_first_of("!") == std::string::npos) {
108
+ value.flags |= JSDRV_UNION_FLAG_RETAIN;
109
+ }
110
+
111
+ int32_t status = jsdrv_publish(this->context_, topic.c_str(), &value, timeout_ms);
112
+ if (status) {
113
+ napi_throw_error(env, NULL, "jsdrv_publish failed");
114
+ }
115
+ return env.Undefined();
116
+ }
117
+
118
+ static Napi::Value obj_value1(Napi::Env env, double v1, const char * units) {
119
+ Napi::Object obj = Napi::Object::New(env);
120
+ obj.Set("value", v1);
121
+ obj.Set("units", units);
122
+ return obj;
123
+ }
124
+
125
+ static Napi::Value obj_value2(Napi::Env env, double v1, double v2, const char * units) {
126
+ Napi::Object obj = Napi::Object::New(env);
127
+ Napi::Float64Array value = Napi::Float64Array::New(env, 2);
128
+ value[0] = v1;
129
+ value[1] = v2;
130
+ obj.Set("value", value);
131
+ obj.Set("units", units);
132
+ return obj;
133
+ }
134
+
135
+ static Napi::Value obj_time_map(Napi::Env env, const struct jsdrv_time_map_s * time_map) {
136
+ Napi::Object obj = Napi::Object::New(env);
137
+ obj.Set("offset_time", time_map->offset_time);
138
+ obj.Set("offset_counter", time_map->offset_counter);
139
+ obj.Set("counter_rate", time_map->counter_rate);
140
+ return obj;
141
+ }
142
+
143
+ static double time64_to_ms(int64_t t) {
144
+ int64_t t_ms = JSDRV_TIME_TO_MILLISECONDS(t);
145
+ t_ms += ((int64_t) 1514764800) * 1000;
146
+ return (double) t_ms;
147
+ }
148
+
149
+ static Napi::Value stream_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
150
+ const struct jsdrv_stream_signal_s * s = (const struct jsdrv_stream_signal_s *) value->value.bin;
151
+ Napi::Object obj = Napi::Object::New(env);
152
+ obj.Set("sample_id", s->sample_id);
153
+ obj.Set("utc", time64_to_ms(jsdrv_time_from_counter(&s->time_map, s->sample_id)));
154
+ obj.Set("field_id", s->field_id);
155
+ obj.Set("index", s->index);
156
+ obj.Set("sample_rate", s->sample_rate);
157
+ obj.Set("decimate_factor", s->decimate_factor);
158
+ obj.Set("time_map", obj_time_map(env, &s->time_map));
159
+ if (JSDRV_DATA_TYPE_FLOAT == s->element_type) {
160
+ if (32 == s->element_size_bits) {
161
+ Napi::Float32Array data = Napi::Float32Array::New(env, s->element_count);
162
+ float * data_src = (float *) s->data;
163
+ for (size_t idx = 0; idx < s->element_count; ++idx) {
164
+ data[idx] = data_src[idx];
165
+ }
166
+ obj.Set("data", data);
167
+ } else if (64 == s->element_size_bits) {
168
+ Napi::Float64Array data = Napi::Float64Array::New(env, s->element_count);
169
+ double * data_src = (double *) s->data;
170
+ for (size_t idx = 0; idx < s->element_count; ++idx) {
171
+ data[idx] = data_src[idx];
172
+ }
173
+ obj.Set("data", data);
174
+ }
175
+ } else if (JSDRV_DATA_TYPE_UINT == s->element_type) {
176
+ if (1 == s->element_size_bits) {
177
+ Napi::Uint8Array data = Napi::Uint8Array::New(env, s->element_count);
178
+ uint8_t * data_src = (uint8_t *) s->data;
179
+ for (size_t idx = 0; idx < s->element_count; ++idx) {
180
+ data[idx] = (data_src[idx >> 3] >> (idx & 7)) & 1;
181
+ }
182
+ obj.Set("data", data);
183
+ } else if (4 == s->element_size_bits) {
184
+ Napi::Uint8Array data = Napi::Uint8Array::New(env, s->element_count);
185
+ uint8_t * data_src = (uint8_t *) s->data;
186
+ for (size_t idx = 0; idx < s->element_count; ++idx) {
187
+ data[idx] = (data_src[idx >> 1] >> (4 * (idx & 1))) & 0x0f;
188
+ }
189
+ obj.Set("data", data);
190
+ } else if (8 == s->element_size_bits) {
191
+ Napi::Uint8Array data = Napi::Uint8Array::New(env, s->element_count);
192
+ uint8_t * data_src = (uint8_t *) s->data;
193
+ for (size_t idx = 0; idx < s->element_count; ++idx) {
194
+ data[idx] = data_src[idx];
195
+ }
196
+ obj.Set("data", data);
197
+ }
198
+ } else if (JSDRV_DATA_TYPE_INT == s->element_type) {
199
+ if (16 == s->element_size_bits) {
200
+ Napi::Int16Array data = Napi::Int16Array::New(env, s->element_count);
201
+ int16_t * data_src = (int16_t *) s->data;
202
+ for (size_t idx = 0; idx < s->element_count; ++idx) {
203
+ data[idx] = data_src[idx];
204
+ }
205
+ obj.Set("data", data);
206
+ }
207
+ }
208
+ return obj;
209
+ }
210
+
211
+ static Napi::Value stats_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
212
+ const struct jsdrv_statistics_s * s =(const struct jsdrv_statistics_s *) value->value.bin;
213
+ uint32_t sample_freq = s->sample_freq;
214
+ uint64_t samples_full_rate = s->block_sample_count * (uint64_t) s->decimate_factor;
215
+ uint64_t sample_id_start = s->block_sample_id;
216
+ uint64_t sample_id_end = s->block_sample_id + samples_full_rate;
217
+ uint64_t t_start = sample_id_start / sample_freq;
218
+ uint64_t t_delta = samples_full_rate / sample_freq;
219
+
220
+ Napi::Object obj = Napi::Object::New(env);
221
+ Napi::Object time = Napi::Object::New(env);
222
+ time.Set("samples", obj_value2(env, (double) sample_id_start, (double) sample_id_end, "samples"));
223
+ time.Set("sample_freq", obj_value1(env, (double) sample_freq, "Hz"));
224
+ time.Set("utc", obj_value2(
225
+ env,
226
+ time64_to_ms(jsdrv_time_from_counter(&s->time_map, sample_id_start)),
227
+ time64_to_ms(jsdrv_time_from_counter(&s->time_map, sample_id_end)),
228
+ "ms"));
229
+ time.Set("range", obj_value2(env, (double) t_start, (double) (t_start + t_delta), "s"));
230
+ time.Set("delta", obj_value1(env, (double) t_delta, "s"));
231
+ time.Set("decimate_factor", obj_value1(env, (double) s->decimate_factor, "samples"));
232
+ time.Set("decimate_sample_count", obj_value1(env, (double) s->block_sample_count, "samples"));
233
+ time.Set("accum_samples", obj_value2(env, (double) s->accum_sample_id, (double) sample_id_end, "samples"));
234
+ obj.Set("time_map", obj_time_map(env, &s->time_map));
235
+
236
+ Napi::Object signals = Napi::Object::New(env);
237
+ obj.Set("signals", signals);
238
+
239
+ Napi::Object current = Napi::Object::New(env);
240
+ current.Set("avg", obj_value1(env, s->i_avg, "A"));
241
+ current.Set("std", obj_value1(env, s->i_std, "A"));
242
+ current.Set("min", obj_value1(env, s->i_min, "A"));
243
+ current.Set("max", obj_value1(env, s->i_max, "A"));
244
+ current.Set("p2p", obj_value1(env, s->i_max - s->i_min, "A"));
245
+ current.Set("integral", obj_value1(env, s->i_avg * t_delta, "C"));
246
+ signals.Set("current", current);
247
+
248
+ Napi::Object voltage = Napi::Object::New(env);
249
+ voltage.Set("avg", obj_value1(env, s->v_avg, "V"));
250
+ voltage.Set("std", obj_value1(env, s->v_std, "V"));
251
+ voltage.Set("min", obj_value1(env, s->v_min, "V"));
252
+ voltage.Set("max", obj_value1(env, s->v_max, "V"));
253
+ voltage.Set("p2p", obj_value1(env, s->v_max - s->v_min, "V"));
254
+ signals.Set("voltage", voltage);
255
+
256
+ Napi::Object power = Napi::Object::New(env);
257
+ power.Set("avg", obj_value1(env, s->p_avg, "W"));
258
+ power.Set("std", obj_value1(env, s->p_std, "W"));
259
+ power.Set("min", obj_value1(env, s->p_min, "W"));
260
+ power.Set("max", obj_value1(env, s->p_max, "W"));
261
+ power.Set("p2p", obj_value1(env, s->p_max - s->p_min, "W"));
262
+ power.Set("integral", obj_value1(env, s->p_avg * t_delta, "J"));
263
+ signals.Set("power", power);
264
+
265
+ Napi::Object accumulators = Napi::Object::New(env);
266
+ obj.Set("accumulators", accumulators);
267
+ accumulators.Set("charge", obj_value1(env, s->charge_f64, "C"));
268
+ accumulators.Set("energy", obj_value1(env, s->energy_f64, "J"));
269
+ obj.Set("source", "sensor");
270
+
271
+ return obj;
272
+ }
273
+
274
+ static Napi::Value buffer_info_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
275
+ return env.Undefined(); // todo
276
+ }
277
+
278
+ static Napi::Value buffer_rsp_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
279
+ return env.Undefined(); // todo
280
+ }
281
+
282
+ static Napi::Value bin_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
283
+ switch (value->app) {
284
+ case JSDRV_PAYLOAD_TYPE_STREAM: return stream_to_js(env, value);
285
+ case JSDRV_PAYLOAD_TYPE_STATISTICS: return stats_to_js(env, value);
286
+ case JSDRV_PAYLOAD_TYPE_BUFFER_INFO: return buffer_info_to_js(env, value);
287
+ case JSDRV_PAYLOAD_TYPE_BUFFER_RSP: return buffer_rsp_to_js(env, value);
288
+ default:
289
+ return env.Undefined(); // todo
290
+ }
291
+ }
292
+
293
+
294
+ static Napi::Value union_to_js(Napi::Env env, const struct jsdrv_union_s * value) {
295
+ // https://github.com/nodejs/node-addon-api/blob/main/doc/value.md
296
+ // printf("union_to_js type=%d\n", value->type);
297
+ switch (value->type) {
298
+ case JSDRV_UNION_NULL: return env.Null();
299
+ case JSDRV_UNION_STR: return Napi::String::New(env, value->value.str);
300
+ case JSDRV_UNION_JSON: {
301
+ Napi::String json_string = Napi::String::New(env, value->value.str);
302
+ Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
303
+ Napi::Function parse = json.Get("parse").As<Napi::Function>();
304
+ return parse.Call(json, { json_string }).As<Napi::Object>();
305
+ }
306
+ case JSDRV_UNION_BIN: return bin_to_js(env, value);
307
+ case JSDRV_UNION_F32: return Napi::Number::New(env, static_cast<double>(value->value.f32));
308
+ case JSDRV_UNION_F64: return Napi::Number::New(env, static_cast<double>(value->value.f64));
309
+ case JSDRV_UNION_U8: return Napi::Number::New(env, static_cast<double>(value->value.u8));
310
+ case JSDRV_UNION_U16: return Napi::Number::New(env, static_cast<double>(value->value.u16));
311
+ case JSDRV_UNION_U32: return Napi::Number::New(env, static_cast<double>(value->value.u32));
312
+ case JSDRV_UNION_U64: return Napi::Number::New(env, static_cast<double>(value->value.u64));
313
+ case JSDRV_UNION_I8: return Napi::Number::New(env, static_cast<double>(value->value.i8));
314
+ case JSDRV_UNION_I16: return Napi::Number::New(env, static_cast<double>(value->value.i16));
315
+ case JSDRV_UNION_I32: return Napi::Number::New(env, static_cast<double>(value->value.i32));
316
+ case JSDRV_UNION_I64: return Napi::Number::New(env, static_cast<double>(value->value.i64));
317
+ default: return env.Undefined();
318
+ }
319
+ }
320
+
321
+ Napi::Value JoulescopeDriver::query(const Napi::CallbackInfo& info) {
322
+ Napi::Env env = info.Env();
323
+ if (info.Length() != 2) {
324
+ Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
325
+ return env.Undefined();
326
+ }
327
+
328
+ std::string topic_str = info[0].As<Napi::String>();
329
+ uint32_t timeout_ms = parse_timeout(env, info[1]);
330
+ struct jsdrv_union_s v;
331
+ char byte_str[1024];
332
+ memset(&v, 0, sizeof(v));
333
+ v.type = JSDRV_UNION_BIN;
334
+ v.size = sizeof(byte_str);
335
+ v.value.str = byte_str;
336
+ int32_t status = jsdrv_query(this->context_, topic_str.c_str(), &v, timeout_ms);
337
+ if (status) {
338
+ napi_throw_error(env, NULL, "jsdrv_query failed");
339
+ return env.Undefined();
340
+ }
341
+ return union_to_js(env, &v);
342
+ }
343
+
344
+ struct subscribe_context {
345
+ public:
346
+ subscribe_context() {}
347
+ std::string topic;
348
+ uint8_t flags;
349
+ Napi::ThreadSafeFunction fn;
350
+ };
351
+
352
+ void _subscribe_fn(void * user_data, const char * topic, const struct jsdrv_union_s * value) {
353
+ struct subscribe_context * context = (struct subscribe_context *) user_data;
354
+ std::string topic_str = topic;
355
+ struct jsdrv_union_s * value_cpy = (struct jsdrv_union_s *) malloc(sizeof(*value) + value->size);
356
+ if (NULL == value_cpy) {
357
+ return;
358
+ }
359
+ *value_cpy = *value;
360
+
361
+ if (value->size) {
362
+ uint8_t *ptr = (uint8_t *) &value_cpy[1];
363
+ value_cpy->value.bin = ptr;
364
+ memcpy(ptr, value->value.bin, value->size);
365
+ }
366
+
367
+ auto callback = [topic_str]( Napi::Env env, Napi::Function jsCallback, const struct jsdrv_union_s * value) {
368
+ jsCallback.Call( {Napi::String::New(env, topic_str), union_to_js(env, value)} );
369
+ free((void *) value);
370
+ };
371
+
372
+ context->fn.NonBlockingCall(value_cpy, callback);
373
+ }
374
+
375
+ Napi::Value JoulescopeDriver::subscribe(const Napi::CallbackInfo& info) { // topic, flags, fn, timeout
376
+ // JSDRV_API int32_t jsdrv_subscribe(struct jsdrv_context_s * context, const char * topic, uint8_t flags,
377
+ // jsdrv_subscribe_fn cbk_fn, void * cbk_user_data,
378
+ // uint32_t timeout_ms);
379
+ Napi::Env env = info.Env();
380
+ if (info.Length() != 4) {
381
+ Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
382
+ return env.Undefined();
383
+ }
384
+ subscribe_context * context = new subscribe_context();
385
+ context->topic = info[0].As<Napi::String>();
386
+ context->flags = (uint8_t) (info[1].As<Napi::Number>().Uint32Value());
387
+ Napi::Function fn = info[2].As<Napi::Function>();
388
+ uint32_t timeout_ms = parse_timeout(env, info[3]);
389
+ context->fn = Napi::ThreadSafeFunction::New(env, fn, "jsdrv_subscribe_fn", 0, 1);
390
+ int32_t status = jsdrv_subscribe(this->context_, context->topic.c_str(), context->flags,
391
+ _subscribe_fn, context, timeout_ms);
392
+ if (status) {
393
+ delete context;
394
+ napi_throw_error(env, NULL, "jsdrv_subscribe failed");
395
+ return env.Undefined();
396
+ }
397
+ struct jsdrv_context_s * jsdrv_context = this->context_;
398
+
399
+ auto unsub_fn = [env, jsdrv_context, context, timeout_ms](const Napi::CallbackInfo& info) -> Napi::Value {
400
+ jsdrv_unsubscribe(jsdrv_context, context->topic.c_str(), _subscribe_fn, context, timeout_ms);
401
+ context->fn.Release();
402
+ delete context;
403
+ return env.Undefined();
404
+ };
405
+ return Napi::Function::New(env, unsub_fn);
406
+ }
407
+
408
+ Napi::Value JoulescopeDriver::finalize(const Napi::CallbackInfo& info) {
409
+ jsdrv_finalize(this->context_, _TIMEOUT_MS_INIT);
410
+ this->context_ = NULL;
411
+ return info.Env().Undefined();
412
+ }