aboutsummaryrefslogtreecommitdiffstats
path: root/android/sensors-port.c
blob: 6831fe35faa69928150a6171b958d114a0811129 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "android/sdk-controller-socket.h"
#include "android/sensors-port.h"
#include "android/hw-sensors.h"
#include "android/utils/debug.h"

#define  E(...)    derror(__VA_ARGS__)
#define  W(...)    dwarning(__VA_ARGS__)
#define  D(...)    VERBOSE_PRINT(sensors_port,__VA_ARGS__)
#define  D_ACTIVE  VERBOSE_CHECK(sensors_port)

#define TRACE_ON    1

#if TRACE_ON
#define  T(...)    VERBOSE_PRINT(sensors_port,__VA_ARGS__)
#else
#define  T(...)
#endif

/* Timeout (millisec) to use when communicating with SDK controller. */
#define SDKCTL_SENSORS_TIMEOUT      3000

/*
 * Queries sent to sensors port of the SDK controller.
 */

/* Queries the port for list of available sensors. */
#define SDKCTL_SENSORS_QUERY_LIST   1

/*
 * Messages sent between the emuator, and  sensors port of the SDK controller.
 */

/* Starts sensor emulation. */
#define SDKCTL_SENSORS_START            1
/* Stops sensor emulation. */
#define SENSOR_SENSORS_STOP             2
/* Enables emulation for a sensor. */
#define SDKCTL_SENSORS_ENABLE           3
/* Disables emulation for a sensor. */
#define SDKCTL_SENSORS_DISABLE          4
/* This message delivers sensor values. */
#define SDKCTL_SENSORS_SENSOR_EVENT     5


/* Describes a sensor on the device.
 * When SDK controller sensors port replies to a "list" query, it replies with
 * a flat buffer containing entries of this type following each other. End of
 * each entry is a zero-terminator for its 'sensor_name' field. The end of the
 * entire list is marked with an entry, containing -1 at its 'sensor_id' field.
 */
typedef struct SensorEntry {
    /* Identifies sensor on the device. Value -1 indicates list terminator,
     * rather than a valid sensor descriptor. */
    int     sensor_id;
    /* Beginning of zero-terminated sensor name. */
    char    sensor_name[1];
} SensorEntry;

/* Describes a sensor in the array of emulated sensors. */
typedef struct SensorDescriptor {
    /* Identifies sensor on the device. */
    int         sensor_id;
    /* Identifies sensor in emulator. */
    int         emulator_id;
    /* Sensor name. */
    char*       sensor_name;
} SensorDescriptor;

/* Sensor event message descriptor.
 * Entries of this type are sent along with SDKCTL_SENSORS_SENSOR_EVENT message
 */
typedef struct SensorEvent {
    /* Identifies a device sensor for which values have been delivered. */
    int     sensor_id;
    /* Sensor values. */
    float   fvalues[3];
} SensorEvent;

/* Sensors port descriptor. */
struct AndroidSensorsPort {
    /* Caller identifier. */
    void*               opaque;
    /* Communication socket. */
    SDKCtlSocket*       sdkctl;
    /* Lists sensors available for emulation. */
    SensorDescriptor**  sensors;
    /* Number of sensors in 'sensors' list. */
    int                 sensors_count;
};

/********************************************************************************
 *                          Sensors port internals
 *******************************************************************************/

/* Checks if sensor descriptor is the terminator.
 * Return:
 *  Boolean, 1 if it is a terminator, 0 if it is not.
 */
static int
_sensor_entry_is_terminator(const SensorEntry* entry)
{
    return entry == NULL || entry->sensor_id == -1;
}

/* Gets next sensor descriptor.
 * Return:
 *  Next sensor desciptor, or NULL if there are no more descriptors in the list.
 */
static const SensorEntry*
_sensor_entry_next(const SensorEntry* entry)
{
    if (!_sensor_entry_is_terminator(entry)) {
        /* Next descriptor begins right after zero-terminator for the sensor_name
         * field of this descriptor. */
        entry = (const SensorEntry*)(entry->sensor_name + strlen(entry->sensor_name) + 1);
        if (!_sensor_entry_is_terminator(entry)) {
            return entry;
        }
    }
    return NULL;
}

/* Gets number of entries in the list. */
static int
_sensor_entry_list_size(const SensorEntry* entry) {
    int ret = 0;
    while (!_sensor_entry_is_terminator(entry)) {
        ret++;
        entry = _sensor_entry_next(entry);
    }
    return ret;
}

/* Discards sensors saved in AndroidSensorsPort's array. */
static void
_sensors_port_discard_sensors(AndroidSensorsPort* asp)
{
    if (asp->sensors != NULL) {
        int n;
        for (n = 0; n < asp->sensors_count; n++) {
            if (asp->sensors[n] != NULL) {
                free(asp->sensors[n]->sensor_name);
                AFREE(asp->sensors[n]);
            }
        }
        free(asp->sensors);
        asp->sensors = NULL;
    }
    asp->sensors_count = 0;
}


/* Destroys and frees the descriptor. */
static void
_sensors_port_free(AndroidSensorsPort* asp)
{
    if (asp != NULL) {
        _sensors_port_discard_sensors(asp);
        if (asp->sdkctl != NULL) {
            sdkctl_socket_release(asp->sdkctl);
        }
        AFREE(asp);
    }
}

/* Parses flat sensor list, and saves its entries into 'sensors' array filed of
 * the AndroidSensorsPort descriptor. */
static void
_sensors_port_save_sensors(AndroidSensorsPort* asp, const SensorEntry* list)
{
    const int count = _sensor_entry_list_size(list);
    if (count != 0) {
        int n;
        /* Allocate array for sensor descriptors. */
        asp->sensors = malloc(sizeof(SensorDescriptor*) * count);

        /* Iterate through the flat sensor list, filling up array of emulated
         * sensors. */
        const SensorEntry* entry = _sensor_entry_is_terminator(list) ? NULL : list;
        for (n = 0; n < count &&  entry != NULL; n++) {
            /* Get emulator-side ID for the sensor. < 0 value indicates that
             * sensor is not supported by the emulator. */
            const int emulator_id =
                android_sensors_get_id_from_name((char*)entry->sensor_name);
            if (emulator_id >= 0) {
                SensorDescriptor* desc;
                ANEW0(desc);
                desc->emulator_id   = emulator_id;
                desc->sensor_id     = entry->sensor_id;
                desc->sensor_name   = ASTRDUP(entry->sensor_name);

                asp->sensors[asp->sensors_count++] = desc;
                D("Sensors: Emulated sensor '%s': Device id = %d, Emulator id = %d",
                  desc->sensor_name, desc->sensor_id, desc->emulator_id);
            } else {
                D("Sensors: Sensor '%s' is not support by emulator",
                  entry->sensor_name);
            }
            entry = _sensor_entry_next(entry);
        }
        D("Sensors: Emulating %d sensors", asp->sensors_count);
    }
}

/* Finds sensor descriptor for an SDK controller-side ID. */
static const SensorDescriptor*
_sensor_from_sdkctl_id(AndroidSensorsPort* asp, int id)
{
    int n;
    for (n = 0; n < asp->sensors_count; n++) {
        if (asp->sensors[n]->sensor_id == id) {
            return asp->sensors[n];
        }
    }
    return NULL;
}

/* Initiates sensor emulation.
 * Param:
 *  asp - Android sensors port instance returned from sensors_port_create.
 * Return:
 *  Zero on success, failure otherwise.
 */
static void
_sensors_port_start(AndroidSensorsPort* asp)
{
    int n;

    if (!sdkctl_socket_is_port_ready(asp->sdkctl)) {
        /* SDK controller side is not ready for emulation. Retreat... */
        D("Sensors: SDK controller side is not ready for emulation.");
        return;
    }

    /* Disable all sensors, and reenable only those that are emulated by
     * hardware. */
    sensors_port_disable_sensor(asp, "all");

    /* Walk throuh the list of enabled sensors enabling them on the device. */
    for (n = 0; n < asp->sensors_count; n++) {
        if (android_sensors_get_sensor_status(asp->sensors[n]->emulator_id) == 1) {
            /* Reenable emulation for this sensor. */
            sensors_port_enable_sensor(asp, asp->sensors[n]->sensor_name);
            D("Sensors: Sensor '%s' is enabled on SDK controller.",
              asp->sensors[n]->sensor_name);
        }
    }

    /* Start the emulation. */
    SDKCtlMessage* const msg =
        sdkctl_message_send(asp->sdkctl, SDKCTL_SENSORS_START, NULL, 0);
    sdkctl_message_release(msg);

    D("Sensors: Emulation has been started.");
}

/********************************************************************************
 *                          Sensors port callbacks
 *******************************************************************************/

/* Completion for the "list" query. */
static AsyncIOAction
_on_sensor_list_query(void* query_opaque,
                      SDKCtlQuery* query,
                      AsyncIOState status)
{
    AndroidSensorsPort* const asp = (AndroidSensorsPort*)(query_opaque);
    if (status != ASIO_STATE_SUCCEEDED) {
        /* We don't really care about failures at this point. They will
         * eventually surface up in another place. */
        return ASIO_ACTION_DONE;
    }

    /* Parse query response which is a flat list of SensorEntry entries. */
    const SensorEntry* const list =
        (const SensorEntry*)sdkctl_query_get_buffer_out(query);
    D("Sensors: Sensor list received with %d sensors.",
      _sensor_entry_list_size(list));
    _sensors_port_save_sensors(asp, list);

    /* At this point we are ready to statr sensor emulation. */
    _sensors_port_start(asp);

    return ASIO_ACTION_DONE;
}

/* A callback that is invoked on sensor events.
 * Param:
 *  asp - AndroidSensorsPort instance.
 *  event - Sensor event.
 */
static void
_on_sensor_event(AndroidSensorsPort* asp, const SensorEvent* event)
{
    /* Find corresponding server descriptor. */
    const SensorDescriptor* const desc =
        _sensor_from_sdkctl_id(asp, event->sensor_id);
    if (desc != NULL) {
        T("Sensors: %s -> %f, %f, %f", desc->sensor_name,
          event->fvalues[0], event->fvalues[1],
          event->fvalues[2]);
        /* Fire up sensor change in the guest. */
        android_sensors_set(desc->emulator_id, event->fvalues[0],
                            event->fvalues[1], event->fvalues[2]);
    } else {
        W("Sensors: No descriptor for sensor %d", event->sensor_id);
    }
}

/* A callback that is invoked on SDK controller socket connection events. */
static AsyncIOAction
_on_sensors_socket_connection(void* client_opaque,
                             SDKCtlSocket* sdkctl,
                             AsyncIOState status)
{
    AndroidSensorsPort* const asp = (AndroidSensorsPort*)client_opaque;
    if (status == ASIO_STATE_FAILED) {
        /* Disconnection could mean that user is swapping devices. New device may
         * have different set of sensors, so we need to re-query sensor list on
         * reconnection. */
        _sensors_port_discard_sensors(asp);

        /* Reconnect (after timeout delay) on failures */
        if (sdkctl_socket_is_handshake_ok(sdkctl)) {
            sdkctl_socket_reconnect(sdkctl, SDKCTL_DEFAULT_TCP_PORT,
                                    SDKCTL_SENSORS_TIMEOUT);
        }
    }
    return ASIO_ACTION_DONE;
}

/* A callback that is invoked on SDK controller port connection events. */
static void
_on_sensors_port_connection(void* client_opaque,
                           SDKCtlSocket* sdkctl,
                           SdkCtlPortStatus status)
{
    AndroidSensorsPort* const asp = (AndroidSensorsPort*)client_opaque;
    switch (status) {
        case SDKCTL_PORT_CONNECTED: {
            D("Sensors: SDK Controller is connected.");
            /* Query list of available sensors. */
            SDKCtlQuery* const query =
                sdkctl_query_build_and_send(asp->sdkctl, SDKCTL_SENSORS_QUERY_LIST,
                                            0, NULL, NULL, NULL,
                                            _on_sensor_list_query, asp,
                                            SDKCTL_SENSORS_TIMEOUT);
            sdkctl_query_release(query);
            break;
        }

        case SDKCTL_PORT_DISCONNECTED:
            _sensors_port_discard_sensors(asp);
            D("Sensors: SDK Controller is disconnected.");
            break;

        case SDKCTL_PORT_ENABLED:
            _sensors_port_start(asp);
            D("Sensors: SDK Controller is enabled.");
            break;

        case SDKCTL_PORT_DISABLED:
            D("Sensors: SDK Controller is disabled.");
            break;

        case SDKCTL_HANDSHAKE_CONNECTED:
            D("Sensors: SDK Controller has succeeded handshake, and port is connected.");
            break;

        case SDKCTL_HANDSHAKE_NO_PORT:
            D("Sensors: SDK Controller has succeeded handshake, and port is not connected.");
            break;

        case SDKCTL_HANDSHAKE_DUP:
            E("Sensors: SDK Controller has failed the handshake due to port duplication.");
            sdkctl_socket_disconnect(sdkctl);
            break;

        case SDKCTL_HANDSHAKE_UNKNOWN_QUERY:
            E("Sensors: SDK Controller has failed the handshake due to unknown query.");
            sdkctl_socket_disconnect(sdkctl);
            break;

        case SDKCTL_HANDSHAKE_UNKNOWN_RESPONSE:
        default:
            E("Sensors: Handshake has failed due to unknown reasons.");
            sdkctl_socket_disconnect(sdkctl);
            break;
    }
}

/* A callback that is invoked when a message is received from SDK controller. */
static void
_on_sensors_message(void* client_opaque,
                   SDKCtlSocket* sdkctl,
                   SDKCtlMessage* message,
                   int msg_type,
                   void* msg_data,
                   int msg_size)
{
    AndroidSensorsPort* const asp = (AndroidSensorsPort*)client_opaque;
    switch (msg_type) {
        case SDKCTL_SENSORS_SENSOR_EVENT:
            _on_sensor_event(asp, (const SensorEvent*)msg_data);
            break;

        default:
            E("Sensors: Unknown message type %d", msg_type);
            break;
    }
}

/********************************************************************************
 *                          Sensors port API
 *******************************************************************************/

AndroidSensorsPort*
sensors_port_create(void* opaque)
{
    AndroidSensorsPort* asp;

    ANEW0(asp);
    asp->opaque = opaque;
    asp->sensors = NULL;
    asp->sensors_count = 0;
    asp->sdkctl = sdkctl_socket_new(SDKCTL_SENSORS_TIMEOUT, "sensors",
                                    _on_sensors_socket_connection,
                                    _on_sensors_port_connection,
                                    _on_sensors_message, asp);
    sdkctl_init_recycler(asp->sdkctl, 76, 8);
    sdkctl_socket_connect(asp->sdkctl, SDKCTL_DEFAULT_TCP_PORT,
                          SDKCTL_SENSORS_TIMEOUT);
    return asp;
}

void
sensors_port_destroy(AndroidSensorsPort* asp)
{
    if (asp->sdkctl != NULL) {
        sdkctl_socket_disconnect(asp->sdkctl);
    }
    _sensors_port_free(asp);
}

int
sensors_port_enable_sensor(AndroidSensorsPort* asp, const char* name)
{
    if (asp->sdkctl != NULL && sdkctl_socket_is_port_ready(asp->sdkctl)) {
        SDKCtlMessage* const msg = sdkctl_message_send(asp->sdkctl,
                                                       SDKCTL_SENSORS_ENABLE,
                                                       name, strlen(name));
        sdkctl_message_release(msg);
        return 0;
    } else {
        return -1;
    }
}

int
sensors_port_disable_sensor(AndroidSensorsPort* asp, const char* name)
{
    if (asp->sdkctl != NULL && sdkctl_socket_is_port_ready(asp->sdkctl)) {
        SDKCtlMessage* const msg = sdkctl_message_send(asp->sdkctl,
                                                       SDKCTL_SENSORS_DISABLE,
                                                       name, strlen(name));
        sdkctl_message_release(msg);
        return 0;
    } else {
        return -1;
    }
}