-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.module
405 lines (345 loc) · 14.3 KB
/
bluetooth.module
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
<?php
define("STATUS_URL", "STATUS_CONFIG_URL");
define("CONFIG_URL", "BLUETOOTH_CONFIG_URL");
define("START_URL", "BLUETOOTH_START_URL");
define("STOP_URL", "BLUETOOTH_STOP_URL");
/**
* Support functions for managing Bluetooth BLE (Eddystone) beacons
*
* Works in conjunction with the content types defined in the bluetooth-beacons feature.
*/
/**
* Implement hook_menu
*/
function bluetooth_menu() {
$items['admin/configure/bluetooth'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array('_bluetooth_admin_form'),
'access callback' => true,
);
// parameter is either the NID of a Bluetooth Receiver or "all"
$items['ble/publish-config/%'] = array(
'page callback' => '_bluetooth_publish_beacons_config',
'page arguments' => array(2),
'access callback' => true,
);
// usage: ble/receiver/{nid,all}/{start,stop}/{all,beacons,temperature}
$items['ble/receiver/%/%/%'] = array(
'page callback' => '_bluetooth_receiver_run_state',
'page arguments' => array(2,3,4),
'access callback' => true,
);
// usage: ble/receiver/status/[nid]
$items['ble/receiver/status/%'] = array(
'page callback' => '_bluetooth_receiver_status',
'page arguments' => array(3),
'access callback' => true,
);
$items['ble/check-in'] = array(
'type' => MENU_CALLBACK,
'page callback' => '_bluetooth_check_in',
'delivery callback' => 'bluetooth_render_direct',
'access callback' => true,
);
// usage: ble/set-maximum/(bt detection nid)
$items['ble/set-maximum/%'] = array(
'type' => MENU_CALLBACK,
'page callback' => '_bluetooth_set_maximum',
'page arguments' => array(2),
'access callback' => true,
);
// usage: mqtt/publish-config/(nid)
$items['mqtt/publish-config/%'] = array(
'type' => MENU_CALLBACK,
'page callback' => "_bluetooth_publish_listener_config",
'page arguments' => array(2),
'access callback' => true,
);
return $items;
}
/**
* Check and report on the status of a receiver
*/
function _bluetooth_receiver_status($nid) {
$r = node_load($nid);
if ($r == null || $r->type != 'bt_receiver') {
drupal_set_message('Object [' . $nid . '] is not a receiver', 'error');
drupal_goto($_SERVER['HTTP_REFERER']);
}
$send_to = str_replace('%IP%', $r->field_ip_address['und'][0]['value'], variable_get(STATUS_URL));
$x = drupal_http_request($send_to, array(
'headers' => array('Content-Type:application/json'),
'method' => 'GET',
));
if ($x->code == 200) {
$status = json_decode($x->data)->status;
$s = 'beacons are ' . $status->beacons . ', temperature is ' . $status->temperature;
drupal_set_message($r->title . ' status: ' . $s, 'status');
} else {
watchdog('bluetooth', 'Error retrieving receiver status: ' . $x->error);
drupal_set_message('Error retrieving status [' . $x->code . '] receiver: ' . $r->title, 'error');
}
drupal_goto($_SERVER['HTTP_REFERER']);
}
/**
* Copy the detection object and create a 'max' reading
*/
function _bluetooth_set_maximum($nid) {
$d = node_load($nid);
if ($d == null || $d->type != 'bt_beacon_detection' || $d->field_detection_mode['und'][0]['value'] != 'live') {
drupal_set_message('Provided object [' . $nid . '] is not a live detection', 'error');
drupal_goto($_SERVER['HTTP_REFERER']);
}
$query = new EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'bt_beacon_detection')
->fieldCondition('field_detection_mode', 'value', 'max', '=')
->fieldCondition('field_beacon', 'target_id', $d->field_beacon['und'][0]['target_id'], '=')
->fieldCondition('field_receiver', 'target_id', $d->field_receiver['und'][0]['target_id'], '=')
->execute();
if ( (! isset($result['node'])) || (count($result['node']) == 0) ) {
$o = new stdClass();
$o->is_new = true;
$o->type = 'bt_beacon_detection';
$o->field_detection_mode['und'][0]['value'] = 'max';
$o->field_beacon['und'][0]['target_id'] = $d->field_beacon['und'][0]['target_id'];
$o->field_receiver['und'][0]['target_id'] = $d->field_receiver['und'][0]['target_id'];
} else {
$o = node_load(array_keys($result['node'])[0]);
}
$o->field_rssi['und'][0]['value'] = $d->field_rssi['und'][0]['value'];
node_save($o);
drupal_set_message('Successfully recorded ' . l('maximum detection', 'node/' . $o->nid), 'status');
drupal_goto($_SERVER['HTTP_REFERER']);
}
/**
* publish one or all receiver configurations
*/
function _bluetooth_publish_beacons_config($rnid) {
$receivers = _bluetooth_load_receiver_nodes($rnid);
// construct the mappings part of the configuration
$bq = new EntityFieldQuery();
$bres = $bq->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'bt_beacon')
->execute();
if (!isset($bres['node']) || count(array_keys($bres['node'])) == 0) {
watchdog('bluetooth', 'No BT_Beacon mappings found');
drupal_set_message('No Bluetooth Beacons mappings found.', 'error');
drupal_goto($_SERVER['HTTP_REFERER']);
}
$results = array();
foreach ($receivers as $nid => $rcv) {
$mappings = array();
if (isset($bres['node'])) {
foreach (array_keys($bres['node']) as $bnid) {
$b = node_load($bnid);
$rcvt = $rcv->title;
$mappings[] = array(
'sensor' => $b->title,
'path' => str_replace('%RECEIVER%', $rcvt, $b->field_sensor_path['und'][0]['value']),
'field' => str_replace('%RECEIVER%', $rcvt, $b->field_field_name['und'][0]['value']),
);
}
}
$send_to = str_replace("%IP%", $rcv->field_ip_address['und'][0]['value'], variable_get(CONFIG_URL));
$mqtt_listener = node_load($rcv->field_mqtt_broker['und'][0]['target_id']);
$config = array(
'version' => '1.2',
'name' => $rcv->title,
'controller' => $rcv->field_controller_url['und'][0]['value'],
'interface' => $rcv->field_network_interface['und'][0]['value'],
'beacons' => array(
'name' => $rcv->title,
'mqtt' => $mqtt_listener->field_mqtt_address['und'][0]['value'],
'frequency' => $rcv->field_sample_interval['und'][0]['value'],
'namespace' => $rcv->field_namespace['und'][0]['value'],
'mode' => $rcv->field_sample_method['und'][0]['value'],
'mappings' => $mappings,
),
);
if ($rcv->field_publish_temperature['und'][0]['value']) {
$config['temperature'] = array(
'mqtt' => $mqtt_listener->field_mqtt_address['und'][0]['value'],
'frequency' => $rcv->field_temperature_frequency['und'][0]['value'],
'sensor' => $rcv->field_temperature_sensor['und'][0]['value'],
'field' => $rcv->field_temperature_field['und'][0]['value'],
);
}
$x = drupal_http_request($send_to, array(
'headers' => array('Content-Type:application/json'),
'method' => 'POST',
'data' => json_encode($config),
));
if ($x->code == 200) {
drupal_set_message('Updated receiver: ' . $rcv->title, 'status');
} else {
watchdog('bluetooth', 'Error updating receiver: ' . $x->error);
drupal_set_message('Error updating [' . $x->code . '] receiver: ' . $rcv->title, 'error');
}
}
drupal_goto($_SERVER['HTTP_REFERER']);
}
/**
* Publish MQTT Listener configuration
*/
function _bluetooth_publish_listener_config($nid) {
$n = node_load($nid);
if ($n == null || $n->type != 'bt_mqtt_listener') {
drupal_set_message('The provided node is not an MQTT Listener', 'error');
return;
}
// TODO: dependency on variable name from NodeContentRest - should add an API to that module
$config = array(
'server' => $n->field_mqtt_address['und'][0]['value'],
'keepalive' => $n->field_keepalive['und'][0]['value'],
'topic' => $n->field_mqtt_topic['und'][0]['value'],
'object_endpoint' => (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]/" . variable_get("NODE_REST_CONTEXT"),
);
$send_to = $n->field_mqtt_listener_url['und'][0]['value'] . '/config';
$x = drupal_http_request($send_to, array(
'headers' => array('Content-Type:application/json'),
'method' => 'POST',
'data' => json_encode($config),
));
if ($x->code == 200) {
drupal_set_message('Updated MQTT listener configuration at ' . $send_to, 'status');
} else {
watchdog('bluetooth', 'Error updating MQTT listener: ' . $x->error);
drupal_set_message('Error updating [' . $x->code . '] listener: ' . $n->title, 'error');
}
drupal_goto($_SERVER['HTTP_REFERER']);
}
/**
* Support function - load receiver nodes
*
* @param rcvr - 'all' or NID of a receiver
*
* @return associative array nid => node
*/
function _bluetooth_load_receiver_nodes($rcvr) {
if ($rcvr == 'all') {
$query = new EntityFieldQuery();
$res = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'bt_receiver')
->execute();
$receivers = (isset($res['node'])) ? node_load_multiple(array_keys($res['node'])) : array();
} else {
$receivers = array($rcvr => node_load($rcvr));
}
return $receivers;
}
/**
* Menu callback to operate on receivers
*
* @param $receivers = 'all' or the NID of a single receiver
* @param $action = 'start' or 'stop'
* @param $sensor = 'all' , 'beacons' or 'temperature'
*/
function _bluetooth_receiver_run_state($receivers,$action,$sensor) {
$rcv_nodes = _bluetooth_load_receiver_nodes($receivers);
$op = ($action == "start") ? variable_get(START_URL) : variable_get(STOP_URL);
$results = array();
foreach ($rcv_nodes as $nid => $r) {
$send_to = str_replace("%IP%", $r->field_ip_address['und'][0]['value'], $op) . '/' . $sensor;
$x = drupal_http_request($send_to, array(
'headers' => array('Content-Type:application/json'),
'method' => 'GET',
));
if ($x->code == 200) {
drupal_set_message('Set ' . $sensor . ' sensors to ' . $action . ' on ' . $r->title, 'status');
} else {
watchdog('bluetooth', 'Error updating sensor states: ' . $x->error);
drupal_set_message('Error [' . $x->code . '] updating ' . $r->title, 'error');
}
}
drupal_goto($_SERVER['HTTP_REFERER']);
}
/**
* Administration form
*/
function _bluetooth_admin_form($form, $form_state) {
$form['status'] = array(
'#type' => 'textfield',
'#title' => 'Status',
'#description' => 'Endpoint formula for getting the current status of a receiver',
'#default_value' => variable_get(STATUS_URL, ''),
);
$form['config'] = array(
'#type' => 'textfield',
'#title' => 'Configuration',
'#description' => 'Endpoint formula for sending a new configuration to the receiver',
'#default_value' => variable_get(CONFIG_URL, ''),
);
$form['start'] = array(
'#type' => 'textfield',
'#title' => 'Start',
'#description' => 'Endpoint formula for starting the receiver',
'#default_value' => variable_get(START_URL, ''),
);
$form['stop'] = array(
'#type' => 'textfield',
'#title' => 'Stop',
'#description' => 'Endpoint formula for stopping the receiver',
'#default_value' => variable_get(STOP_URL, ''),
);
$form['info'] = array(
'#type' => 'markup',
'#markup' => "Substitution Pattern: %IP% is the receiver<br>",
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function _bluetooth_admin_form_submit($form, $form_state) {
variable_set(STATUS_URL, $form_state['values']['status']);
variable_set(CONFIG_URL, $form_state['values']['config']);
variable_set(START_URL, $form_state['values']['start']);
variable_set(STOP_URL, $form_state['values']['stop']);
drupal_set_message('Values udpated', 'status');
}
/**
* Check-in function for when a receiver comes online
*
* json parameter in data block contains {"name", "controller", "address", "interface"}
*/
function _bluetooth_check_in() {
$params = json_decode($_POST['json']);
// Find a receiver with that name
$query = new EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'bt_receiver')
->propertyCondition('title', $params->name, '=')
->execute();
$ret = '{"status": "success"}';
if (isset($result['node']) && count($result['node']) == 1) {
$o = node_load(array_keys($result['node'])[0]);
$o->field_ip_address['und'][0]['value'] = $params->address;
$o->field_controller_url['und'][0]['value'] = $params->controller;
$o->field_network_interface['und'][0]['value'] = $params->interface;
watchdog('bluetooth', 'Existing receiver checked in : '. $params->name);
node_save($o);
} else if ( (!isset($result['node'])) || count($result['node']) == 0) {
$o = new stdClass();
$o->type = 'bt_receiver';
$o->title = $params->name;
$o->field_ip_address['und'][0]['value'] = $params->address;
$o->field_controller_url['und'][0]['value'] = $params->controller;
$o->field_network_interface['und'][0]['value'] = $params->interface;
watchdog('bt_planview', 'New receiver checked in : '. $params->name);
node_save($o);
} else {
watchdog('bluetooth', 'Check-in from ' . $params['name'] . ' returned multiple objects');
$ret = '{"status": "error", "description": "Multiple receiver objects found"}';
}
return $ret;
}
/**
* Delivery function for data
*/
function bluetooth_render_direct($page_callback_result) {
print $page_callback_result;
}