File: context.c

package info (click to toggle)
ruby-nfc 3.1.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 160 kB
  • sloc: ansic: 304; ruby: 129; makefile: 5
file content (63 lines) | stat: -rw-r--r-- 1,453 bytes parent folder | download | duplicates (3)
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
#include <nfc.h>

static VALUE allocate(VALUE klass) {
    nfc_context * context;
    nfc_init(&context);
    return Data_Wrap_Struct(klass, NULL, nfc_exit, context);
}

static VALUE open_dev(VALUE self, VALUE name)
{
    nfc_context * ctx;
    nfc_device * dev;
    VALUE device;

    Data_Get_Struct(self, nfc_context, ctx);

    if (NIL_P(name)) {
	dev = nfc_open(ctx, NULL);
    } else {
	dev = nfc_open(ctx, StringValuePtr(name));
    }

    if (NULL == dev)
	rb_raise(rb_eRuntimeError, "Unable to open the device");

    if(nfc_initiator_init(dev) < 0)
	rb_raise(rb_eRuntimeError, "Could not initialize device");

    device = Data_Wrap_Struct(cNfcDevice, 0, nfc_close, dev);
    rb_iv_set(device, "@context", self);
    return device;
}

static VALUE devices(VALUE self, VALUE len)
{
    nfc_context *ctx;
    nfc_connstring * strs;
    size_t found, i;
    VALUE devs;

    Data_Get_Struct(self, nfc_context, ctx);

    strs = malloc(sizeof(nfc_connstring) * len);

    found = nfc_list_devices(ctx, strs, 10);
    devs = rb_ary_new2(found);
    for (i = 0; i < found; i++) {
	rb_ary_push(devs, rb_str_new2(strs[i]));
    }
    free(strs);
    return devs;
}

void init_context()
{
    VALUE cContext = rb_define_class_under(mNfc, "Context", rb_cObject);
    rb_define_alloc_func(cContext, allocate);

    rb_define_method(cContext, "devices", devices, 1);
    rb_define_method(cContext, "open", open_dev, 1);
}

/* vim: set noet sws=4 sw=4: */