-
Notifications
You must be signed in to change notification settings - Fork 11
/
ble_sensor_mqtt_pub.c
2540 lines (2162 loc) · 123 KB
/
ble_sensor_mqtt_pub.c
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ble_sensor_mqtt_pub.c
// gcc -o ble_sensor_mqtt_pub ble_sensor_mqtt_pub.c -l bluetooth -l paho-mqtt3c
// 202102030607
//
// decode BLE temperature sensor temperature and humidity data from BLE advertising packets
// and publish to MQTT
// sensors supported:
// 1 = Xiaomi LYWSD03MMC-ATC https://github.com/atc1441/ATC_MiThermometer
// 2 = Govee H5052
// 3 = Govee H5072
// 4 = Govee H5102
// 5 = Govee H5075
// 6 = Govee H5074
//
// based on work by:
// Intel Edison Playground
// Copyright (c) 2015 Damian Kołakowski. All rights reserved.
//
// YAML config parsing based on:
// https://github.com/smavros/yaml-to-struct
//
#define VERSION_MAJOR 3
#define VERSION_MINOR 0
// why is it so hard to get the base name of the program withOUT the .c extension!!!!!!!
#define PROGRAM_NAME "ble_sensor_mqtt_pub"
// program configuration file,
// holds list of BLE sensors to track
#define CONFIGURATION_FILE "/etc/ble_sensor_mqtt_pub.yaml"
#define MAX_SENSORS 64
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <yaml.h>
#include "MQTTClient.h"
// logging setup
// LOG_EMERG
// A panic condition was reported to all processes.
// LOG_ALERT
// A condition that should be corrected immediately.
// LOG_CRIT
// A critical condition.
// LOG_ERR
// An error message.
// LOG_WARNING
// A warning message.
// LOG_NOTICE
// A condition requiring special handling.
// LOG_INFO
// A general information message.
// LOG_DEBUG
// A message useful for debugging programs.
// int logging_level = LOG_INFO;
// int logging_level = LOG_ERR;
int logging_level = LOG_DEBUG;
#define RSYSLOG_ADDRESS "192.168.2.5"
#define LOGMESSAGESIZE 512
char log_message[LOGMESSAGESIZE];
// Paho MQTT setup
//#define ADDRESS "tcp://192.168.2.242:1883"
char mqtt_server_address[128];
// #define CLIENTID PROGRAM_NAME
#define MQTTCLIENTIDSIZE 128
char z_client_id_mqtt[MQTTCLIENTIDSIZE];
#define QOS 1
#define TIMEOUT 10000L
// MONITOR THIS AS YOU ADD MORE UNITS!!!!!!!!!!!!!!!!!
#define MAXIMUM_JSON_MESSAGE 2048
// MQTT topic definitions
// code to publish topic will append mac address of unit to this base
// base topic:
// each sensor with publish it's data under this base, example:
// homeassistant/sensor/ble-temp/A4:C1:38:DB:64:96
//char topic_base[128];
//const char topic_base[] = "homeassistant/sensor/ble-temp/";
// under the base topic, this sub topic will publish statistics
// topic for hourly statistics
const char topic_statistics[] = "$SYS/hour-stats";
struct hci_request ble_hci_request(uint16_t ocf, int clen, void *status, void *cparam)
{
struct hci_request rq;
memset(&rq, 0, sizeof(rq));
rq.ogf = OGF_LE_CTL;
rq.ocf = ocf;
rq.cparam = cparam;
rq.clen = clen;
rq.rparam = status;
rq.rlen = 1;
return rq;
}
typedef struct
{
int type;
char mac[19];
char location[64];
char name[64];
char unique[64];
char my_id[64];
char make[64];
char model[64];
int readings_per_hour;
} sensor_t;
typedef struct
{
char mqtt_server_url[128];
char mqtt_base_topic[128];
char mqtt_username[64];
char mqtt_password[64];
int bluetooth_adapter;
int scan_type;
int scan_window;
int scan_interval;
int publish_type;
int auto_configure;
int auto_conf_stats;
int auto_conf_tempf;
int auto_conf_tempc;
int auto_conf_hum;
int auto_conf_battery;
int auto_conf_voltage;
int auto_conf_signal;
char syslog_address[64];
int logging_level;
sensor_t sensors[MAX_SENSORS];
} config_t;
/* Global parser */
unsigned int parser(config_t *config, char **argv);
/* Parser utilities */
void init_prs(FILE *fp, yaml_parser_t *parser);
void parse_next(yaml_parser_t *parser, yaml_event_t *event);
void clean_prs(FILE *fp, yaml_parser_t *parser, yaml_event_t *event);
/* Parser actions */
void event_switch(bool *seq_status, unsigned int *map_seq, config_t *config,
yaml_parser_t *parser, yaml_event_t *event, FILE *fp);
void to_data(bool *seq_status, unsigned int *map_seq, config_t *config,
yaml_parser_t *parser, yaml_event_t *event, FILE *fp);
void to_data_from_map(char *buf, unsigned int *map_seq, config_t *config,
yaml_parser_t *parser, yaml_event_t *event, FILE *fp);
/* Post parsing utilities */
void print_data(unsigned int sensor_count, config_t *config);
// returns a structure with info about each bluetooth adapter found on system and returns number of adapters found
static int hci_devlist(struct hci_dev_info **di, int *num)
{
int i;
if ((*di = malloc(HCI_MAX_DEV * sizeof(**di))) == NULL)
{
printf("Couldn't allocated memory for hci_devlist: %s", strerror(errno));
exit(1);
}
for (i = *num = 0; i < HCI_MAX_DEV; i++)
if (hci_devinfo(i, &(*di)[*num]) == 0)
(*num)++;
return 0;
}
char advertising_packet_type_desc[9][30] =
{
"ADV_IND 0 (0000)",
"ADV_DIRECT_IND 1 (0001)",
"ADV_NONCONN_IND 2 (0010)",
"SCAN_REQ 3 (0011)",
"SCAN_RSP 4 (0100)",
"CONNECT_REQ 5 (0101)",
"ADV_SCAN_IND 6 (0110)",
"ADV_EXT_IND 7 (0111)",
"AUX_CONNECT_RSP 8 (1000)"};
// used for printing packet info during debugging
// https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
// this function sends a log message to a remote syslog server
// call with:
// log level
// hostname of logging server
// program name that is sending log message
// message
void send_remote_syslog_message(int log_level, char *hostname, char *program_name, char *message)
{
int sockfd, n;
int serverlen;
int message_length;
struct sockaddr_in serveraddr;
struct hostent *server;
#define LOGBUFFERSIZE 1024
char syslogbuf[LOGBUFFERSIZE];
#define RSYSLOGPORT 514
// socket: create the socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
fprintf(stderr, "ERROR opening socket for remote syslog write");
exit(1);
}
// gethostbyname: get the server's DNS entry
server = gethostbyname(hostname);
if (server == NULL)
{
fprintf(stderr, "ERROR, no such host as %s for remote syslog write\n", hostname);
exit(1);
}
// build the server's Internet address
bzero((char *)&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(RSYSLOGPORT);
// build the syslog message
message_length = snprintf(syslogbuf, LOGBUFFERSIZE, "<%d>%s %s", LOG_USER + log_level, program_name, message);
// fprintf(stdout, "%s\n", syslogbuf);
// send the message to the server
serverlen = sizeof(serveraddr);
n = sendto(sockfd, syslogbuf, strlen(syslogbuf), 0, (struct sockaddr *)&serveraddr, serverlen);
if (n < 0)
{
fprintf(stderr, "ERROR in sendto for remote syslog write\n");
exit(1);
}
return;
}
// catch <ctr>-c to exit program
static volatile bool keep_running = true;
void intHandler(int dummy)
{
keep_running = false;
}
// MQTT async routines
volatile MQTTClient_deliveryToken deliveredtoken;
void delivered(void *context, MQTTClient_deliveryToken dt)
{
// printf("Message with token value %d delivery confirmed\n", dt);
deliveredtoken = dt;
}
// MQTT received message handler
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
int i;
char *payloadptr;
fprintf(stdout, "Message arrived\n");
fprintf(stdout, " topic: %s\n", topicName);
fprintf(stdout, " message: ");
payloadptr = message->payload;
for (i = 0; i < message->payloadlen; i++)
{
putc(*payloadptr++, stdout);
}
fprintf(stdout, "\n");
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
// MQTT connection to server lost handler
void connlost(void *context, char *cause)
{
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d MQTT Server Connection lost", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "MQTT Server Connection lost, cause: %s\n", cause);
exit(1);
}
// for reading configuration file
// read a field from the input line
char *getfield(char *line, int num)
{
char *tok;
for (tok = strtok(line, ",");
tok && *tok;
tok = strtok(NULL, ",\n"))
{
if (!--num)
return tok;
}
return NULL;
}
// trim leading and trailing white space from a character string
// https://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way
char *trim(char *str)
{
int isspace(int);
size_t len = 0;
char *frontp = str;
char *endp = NULL;
if (str == NULL)
{
return NULL;
}
if (str[0] == '\0')
{
return str;
}
len = strlen(str);
endp = str + len;
// Move the front and back pointers to address the first non-whitespace
// characters from each end.
while (isspace((unsigned char)*frontp))
{
++frontp;
}
if (endp != frontp)
{
while (isspace((unsigned char)*(--endp)) && endp != frontp)
{
}
}
if (frontp != str && endp == frontp)
*str = '\0';
else if (str + len - 1 != endp)
*(endp + 1) = '\0';
// Shift the string so that it starts at str so that if it's dynamically
// allocated, we can still free it on the returned pointer. Note the reuse
// of endp to mean the front of the string buffer now.
endp = str;
if (frontp != str)
{
while (*frontp)
{
*endp++ = *frontp++;
}
*endp = '\0';
}
return str;
}
int main(int argc, char *argv[])
{
// startup
fprintf(stdout, "%s v%2d.%02d\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
// handle signals, SIGINT
struct sigaction act;
act.sa_handler = intHandler;
sigaction(SIGINT, &act, NULL);
if (argc != 2)
{
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Start program with a single argument pointing to yaml config file\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Start program with a single argument pointing to yaml config file\n");
exit(1);
}
config_t config;
int sensor_count;
sensor_count = parser(&config, argv);
int x;
for (x = 0; x < sensor_count; x++)
{
if (config.publish_type)
{
strcpy(config.sensors[x].my_id, config.sensors[x].unique);
}
else
{
strcpy(config.sensors[x].my_id, config.sensors[x].mac);
}
switch (config.sensors[x].type)
{
case 1:
strcpy(config.sensors[x].make, "Xiaomi");
strcpy(config.sensors[x].model, "LYWSD03MMC-ATC");
break;
case 2:
strcpy(config.sensors[x].make, "Govee");
strcpy(config.sensors[x].model, "H5052");
break;
case 3:
strcpy(config.sensors[x].make, "Govee");
strcpy(config.sensors[x].model, "H5072");
break;
case 4:
strcpy(config.sensors[x].make, "Govee");
strcpy(config.sensors[x].model, "H5102");
break;
case 5:
strcpy(config.sensors[x].make, "Govee");
strcpy(config.sensors[x].model, "H5075");
break;
case 6:
strcpy(config.sensors[x].make, "Govee");
strcpy(config.sensors[x].model, "H5074");
break;
default:
strcpy(config.sensors[x].make, "");
strcpy(config.sensors[x].model, "");
}
}
logging_level = config.logging_level;
if (logging_level > LOG_NOTICE)
{
print_data(sensor_count, &config);
}
int hci_devs_num;
struct hci_dev_info *hci_devs;
int ret, status;
// bluetooth adapter mac address
char bluetooth_adapter_mac[19];
// adapter number
int bluetooth_adapter_number;
// get the info about each of the bluetooth adapters in system
if (hci_devlist(&hci_devs, &hci_devs_num))
{
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Couldn't enumerate HCI devices: %s", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, strerror(errno));
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Couldn't enumerate HCI devices: %s", strerror(errno));
exit(1);
}
else
{
fprintf(stdout, "%u Bluetooth adapter(s) in system.\n", hci_devs_num);
}
// get requested adapter number from command line
bluetooth_adapter_number = config.bluetooth_adapter;
int ble_scan_type; // 0 = passive, 1 = active scan
ble_scan_type = config.scan_type;
if (ble_scan_type != 1)
{
ble_scan_type = 0;
}
//int ble_scan_interval = 65; // value * 0.625 ms, scan every 41 milliseconds
//int ble_scan_window = 750; // value * 0.625 ms, window 469 milliseconds
int ble_scan_window = 48; // value * 0.625 ms, window 30 milliseconds
int ble_scan_interval = 1500; // value * 0.625 ms, scan every 975 milliseconds
ble_scan_window = config.scan_window;
if (ble_scan_window == 0)
{
ble_scan_window = 48;
}
ble_scan_interval = config.scan_interval;
if (ble_scan_interval == 0)
{
ble_scan_interval = 1500;
}
if (bluetooth_adapter_number < 0 || bluetooth_adapter_number > hci_devs_num - 1)
{
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Enter bluetooth adapter number between 0 and %u !!\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, hci_devs_num - 1);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Enter bluetooth adapter number between 0 and %u !!\n", hci_devs_num - 1);
exit(1);
}
// get MAC address for adapter selected
strcpy(bluetooth_adapter_mac, batostr(&hci_devs[bluetooth_adapter_number].bdaddr));
// log startup of program
// strcpy(log_message, "test message *****");
setlogmask(LOG_UPTO(LOG_INFO));
openlog(PROGRAM_NAME, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Starting.", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_INFO, "%s", log_message);
// maximum number of sensors
// #define MAXIMUM_UNITS 40
// number of devices read from configuration file
int mac_total;
int sensor_data_start;
// total number of devices read from configuration file
mac_total = sensor_count;
fprintf(stdout, "Total devices in configuration file : %d\n", mac_total);
// // create the MQTT topic from the base topic string and the MAC address of sensor
// int topic_length;
// char topic_buffer[200];
// int topic_buffer_size = 200;
// initialize MQTT
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
// set MQTT client ID to program name plus bluetooth mac address, to allow multiple instances on one machine
snprintf(z_client_id_mqtt, MQTTCLIENTIDSIZE, "%s-%s", PROGRAM_NAME, bluetooth_adapter_mac);
fprintf(stdout, "MQTT client name : %s\n", z_client_id_mqtt);
MQTTClient_create(&client, config.mqtt_server_url, z_client_id_mqtt, MQTTCLIENT_PERSISTENCE_NONE, NULL);
// MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.username = config.mqtt_username;
conn_opts.password = config.mqtt_password;
MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d failed to connect to MQTT server", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Failed to connect to MQTT server, return code %d\n", rc);
exit(1);
}
// Get HCI device.
const int bluetooth_device = hci_open_dev(hci_get_route(&hci_devs[bluetooth_adapter_number].bdaddr));
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Bluetooth Adapter : %u has MAC address : %s\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, bluetooth_adapter_number, bluetooth_adapter_mac);
send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_INFO, "%s", log_message);
fprintf(stdout, "Bluetooth Adapter : %u has MAC address : %s\n", bluetooth_adapter_number, bluetooth_adapter_mac);
if (bluetooth_device < 0)
{
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d failed to open HCI device", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Failed to open HCI device, return code %d\n", bluetooth_device);
exit(1);
}
// Set BLE scan parameters
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Advertising scan type (0=passive, 1=active): %u\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, ble_scan_type);
send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_INFO, "%s", log_message);
fprintf(stdout, "Advertising scan type (0=passive, 1=active): %u\n", ble_scan_type);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Advertising scan window : %u %.1f ms\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, ble_scan_window, ble_scan_window * 0.625);
send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_INFO, "%s", log_message);
fprintf(stdout, "Advertising scan window : %4u, %4.1f ms\n", ble_scan_window, ble_scan_window * 0.625);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Advertising scan interval : %u %.1f ms\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, ble_scan_interval, ble_scan_interval * 0.625);
send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_INFO, "%s", log_message);
fprintf(stdout, "Advertising scan interval : %4u, %4.1f ms\n", ble_scan_interval, ble_scan_interval * 0.625);
le_set_scan_parameters_cp scan_params_cp;
memset(&scan_params_cp, 0, sizeof(scan_params_cp));
// BLE PASSIVE OR ACTIVE SCAN ***************************************************************************************
scan_params_cp.type = ble_scan_type; // 0x00 for passive scan, 0x01 for active scan (to get scan response packets)
scan_params_cp.interval = htobs(ble_scan_interval);
scan_params_cp.window = htobs(ble_scan_window);
// scan_params_cp.interval = htobs(0x0010);
// scan_params_cp.window = htobs(0x0010);
scan_params_cp.own_bdaddr_type = 0x00; // Public Device Address (default).
scan_params_cp.filter = 0x00; // Accept all.
struct hci_request scan_params_rq = ble_hci_request(OCF_LE_SET_SCAN_PARAMETERS, LE_SET_SCAN_PARAMETERS_CP_SIZE, &status, &scan_params_cp);
ret = hci_send_req(bluetooth_device, &scan_params_rq, 1000);
if (ret < 0)
{
hci_close_dev(bluetooth_device);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to set scan parameters data", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Failed to set scan parameters data, you must run this program as ROOT, return code %d\n", ret);
exit(1);
}
// Set BLE events report mask.
le_set_event_mask_cp event_mask_cp;
memset(&event_mask_cp, 0, sizeof(le_set_event_mask_cp));
int i = 0;
for (i = 0; i < 8; i++)
event_mask_cp.mask[i] = 0xFF;
struct hci_request set_mask_rq = ble_hci_request(OCF_LE_SET_EVENT_MASK, LE_SET_EVENT_MASK_CP_SIZE, &status, &event_mask_cp);
ret = hci_send_req(bluetooth_device, &set_mask_rq, 1000);
if (ret < 0)
{
hci_close_dev(bluetooth_device);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to set event mask", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Failed to set event mask, return code %d\n", ret);
exit(1);
}
// Enable scanning.
le_set_scan_enable_cp scan_cp;
memset(&scan_cp, 0, sizeof(scan_cp));
scan_cp.enable = 0x01; // Enable flag.
scan_cp.filter_dup = 0x00; // Filtering disabled.
struct hci_request enable_adv_rq = ble_hci_request(OCF_LE_SET_SCAN_ENABLE, LE_SET_SCAN_ENABLE_CP_SIZE, &status, &scan_cp);
ret = hci_send_req(bluetooth_device, &enable_adv_rq, 1000);
if (ret < 0)
{
hci_close_dev(bluetooth_device);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to enable scan", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Failed to enable scan, return code %d\n", ret);
exit(1);
}
// Get Results.
struct hci_filter nf;
hci_filter_clear(&nf);
hci_filter_set_ptype(HCI_EVENT_PKT, &nf);
hci_filter_set_event(EVT_LE_META_EVENT, &nf);
ret = setsockopt(bluetooth_device, SOL_HCI, HCI_FILTER, &nf, sizeof(nf));
if (ret < 0)
{
hci_close_dev(bluetooth_device);
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Could not set socket options", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_ERR, "%s", log_message);
fprintf(stderr, "Could not set socket options, return code %d\n", ret);
exit(1);
}
snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Scanning....", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message);
syslog(LOG_INFO, "%s", log_message);
// fprintf(stdout, "%s v%2d.%02d\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR);
fprintf(stdout, "Scanning....\n");
fflush(stdout);
// bluetooth advertising packet buffer
uint8_t ble_adv_buf[HCI_MAX_EVENT_SIZE];
evt_le_meta_event *meta_event;
le_advertising_info *adv_info;
int bluetooth_adv_packet_length;
// create the MQTT topic from the base topic string and the MAC address of sensor
int topic_length;
char topic_buffer[200];
int topic_buffer_size = 200;
// MQTT payload buffer
int payload_length;
char payload_buffer[MAXIMUM_JSON_MESSAGE];
// int payload_buff_size = 300;
// holds current time of current advertising packet that is received
time_t rawtime = time(NULL);
struct tm tm = *gmtime(&rawtime);
struct tm *time_packet_received;
// get the current hour, keep track every time we roll over to a new hour
int hour_current;
int hour_last;
time_t gmt_time_now;
struct tm tnp = *gmtime(&gmt_time_now);
time(&gmt_time_now);
tnp = *gmtime(&gmt_time_now);
hour_current = tnp.tm_hour;
if (hour_current == 0)
{
hour_last = 23;
}
else
{
hour_last = hour_current - 1;
}
fprintf(stdout, "current hour (GMT) = %d\n", hour_current);
fprintf(stdout, "last hour (GMT) = %d\n", hour_last);
if (config.auto_configure)
{
if (logging_level > LOG_INFO)
{
fprintf(stdout, "=========\n");
fprintf(stdout, "Begining auto configuration of devices\n");
}
if (config.auto_conf_stats)
{
payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE,
"{\"~\":\"%s$SYS/hour-stats\",\"name\":\"BLE Temperature Reading Hourly Stats\",\"uniq_id\":\"ble-tmp-hourly-stats\",\"stat_t\":\"~\",\"unit_of_meas\":\"Pkts\",\"val_tpl\":\"{{value_json.total_adv_packets}}\"}",
config.mqtt_base_topic);
if (payload_length >= MAXIMUM_JSON_MESSAGE)
// if (payload_length >= payload_buff_size)
{
fprintf(stderr, "MQTT payload too long, %d\n", payload_length);
exit(-1);
}
// // create the MQTT topic from the base topic string and the MAC address of sensor
// int topic_length;
// char topic_buffer[200];
// int topic_buffer_size = 200;
topic_length = snprintf(topic_buffer, topic_buffer_size, "%shourly-stats/config", config.mqtt_base_topic);
// publish the message and wait for success
pubmsg.payload = payload_buffer;
pubmsg.payloadlen = payload_length;
pubmsg.qos = QOS;
pubmsg.retained = 1;
deliveredtoken = 0;
MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token);
// wait for messqge to be delivered to server
// printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt);
while (deliveredtoken != token)
;
}
for (x = 0; x < sensor_count; x++)
{
if (logging_level > LOG_INFO)
{
fprintf(stdout, " Configuring: %s\n", config.sensors[x].my_id);
}
if (config.sensors[x].type != 99)
{
// configure temp F sensor
if (config.auto_conf_tempf)
{
payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE,
"{\"~\":\"%s%s\",\"dev_cla\":\"temperature\",\"name\":\"%s-F\",\"uniq_id\":\"%s-F\",\"stat_t\":\"~/state\",\"unit_of_meas\":\"°F\",\"val_tpl\":\"{{value_json.tempf}}\",\"dev\":{\"name\":\"%s\",\"ids\":\"%s\",\"sa\":\"%s\",\"cns\":[[\"mac\", \"%s\"]],\"mf\":\"%s\",\"mdl\":\"%s\"} }",
config.mqtt_base_topic,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].location,
config.sensors[x].mac,
config.sensors[x].make,
config.sensors[x].model);
if (payload_length >= MAXIMUM_JSON_MESSAGE)
// if (payload_length >= payload_buff_size)
{
fprintf(stderr, "MQTT payload too long, %d\n", payload_length);
exit(-1);
}
// // create the MQTT topic from the base topic string and the MAC address of sensor
topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sF/config", config.mqtt_base_topic, config.sensors[x].my_id);
// publish the message and wait for success
pubmsg.payload = payload_buffer;
pubmsg.payloadlen = payload_length;
pubmsg.qos = QOS;
pubmsg.retained = 1;
deliveredtoken = 0;
MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token);
// wait for messqge to be delivered to server
// printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt);
while (deliveredtoken != token)
;
}
// configure temp C sensor
if (config.auto_conf_tempc)
{
payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE,
"{\"~\":\"%s%s\",\"dev_cla\":\"temperature\",\"name\":\"%s-T\",\"uniq_id\":\"%s-T\",\"stat_t\":\"~/state\",\"unit_of_meas\":\"°C\",\"val_tpl\":\"{{value_json.tempc}}\",\"dev\":{\"name\":\"%s\",\"ids\":\"%s\",\"sa\":\"%s\",\"cns\":[[\"mac\", \"%s\"]],\"mf\":\"%s\",\"mdl\":\"%s\"} }",
config.mqtt_base_topic,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].location,
config.sensors[x].mac,
config.sensors[x].make,
config.sensors[x].model);
if (payload_length >= MAXIMUM_JSON_MESSAGE)
// if (payload_length >= payload_buff_size)
{
fprintf(stderr, "MQTT payload too long, %d\n", payload_length);
exit(-1);
}
// // create the MQTT topic from the base topic string and the MAC address of sensor
topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sT/config", config.mqtt_base_topic, config.sensors[x].my_id);
// publish the message and wait for success
pubmsg.payload = payload_buffer;
pubmsg.payloadlen = payload_length;
pubmsg.qos = QOS;
pubmsg.retained = 1;
deliveredtoken = 0;
MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token);
// wait for messqge to be delivered to server
// printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt);
while (deliveredtoken != token)
;
}
// configure hum sensor
if (config.auto_conf_hum)
{
payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE,
"{\"~\":\"%s%s\",\"dev_cla\":\"humidity\",\"name\":\"%s-H\",\"uniq_id\":\"%s-H\",\"stat_t\":\"~/state\",\"unit_of_meas\":\"%%\",\"val_tpl\":\"{{value_json.humidity}}\",\"dev\":{\"name\":\"%s\",\"ids\":\"%s\",\"sa\":\"%s\",\"cns\":[[\"mac\", \"%s\"]],\"mf\":\"%s\",\"mdl\":\"%s\"} }",
config.mqtt_base_topic,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].location,
config.sensors[x].mac,
config.sensors[x].make,
config.sensors[x].model);
if (payload_length >= MAXIMUM_JSON_MESSAGE)
// if (payload_length >= payload_buff_size)
{
fprintf(stderr, "MQTT payload too long, %d\n", payload_length);
exit(-1);
}
// // create the MQTT topic from the base topic string and the MAC address of sensor
topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sH/config", config.mqtt_base_topic, config.sensors[x].my_id);
// publish the message and wait for success
pubmsg.payload = payload_buffer;
pubmsg.payloadlen = payload_length;
pubmsg.qos = QOS;
pubmsg.retained = 1;
deliveredtoken = 0;
MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token);
// wait for messqge to be delivered to server
// printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt);
while (deliveredtoken != token)
;
}
// configure battery sensor
if (config.auto_conf_battery)
{
payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE,
"{\"~\":\"%s%s\",\"dev_cla\":\"battery\",\"name\":\"%s-B\",\"uniq_id\":\"%s-B\",\"stat_t\":\"~/state\",\"unit_of_meas\":\"%%\",\"val_tpl\":\"{{value_json.batterypct}}\",\"dev\":{\"name\":\"%s\",\"ids\":\"%s\",\"sa\":\"%s\",\"cns\":[[\"mac\", \"%s\"]],\"mf\":\"%s\",\"mdl\":\"%s\"} }",
config.mqtt_base_topic,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].location,
config.sensors[x].mac,
config.sensors[x].make,
config.sensors[x].model);
if (payload_length >= MAXIMUM_JSON_MESSAGE)
// if (payload_length >= payload_buff_size)
{
fprintf(stderr, "MQTT payload too long, %d\n", payload_length);
exit(-1);
}
// // create the MQTT topic from the base topic string and the MAC address of sensor
topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sB/config", config.mqtt_base_topic, config.sensors[x].my_id);
// publish the message and wait for success
pubmsg.payload = payload_buffer;
pubmsg.payloadlen = payload_length;
pubmsg.qos = QOS;
pubmsg.retained = 1;
deliveredtoken = 0;
MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token);
// wait for messqge to be delivered to server
// printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt);
while (deliveredtoken != token)
;
}
// configure voltage sensor only an option for sensor type 1
if (config.auto_conf_voltage && config.sensors[x].type == 1)
{
payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE,
"{\"~\":\"%s%s\",\"dev_cla\":\"voltage\",\"name\":\"%s-V\",\"uniq_id\":\"%s-V\",\"stat_t\":\"~/state\",\"unit_of_meas\":\"mV\",\"val_tpl\":\"{{value_json.batterymv}}\",\"dev\":{\"name\":\"%s\",\"ids\":\"%s\",\"sa\":\"%s\",\"cns\":[[\"mac\", \"%s\"]],\"mf\":\"%s\",\"mdl\":\"%s\"} }",
config.mqtt_base_topic,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].name,
config.sensors[x].my_id,
config.sensors[x].location,
config.sensors[x].mac,
config.sensors[x].make,
config.sensors[x].model);
if (payload_length >= MAXIMUM_JSON_MESSAGE)
// if (payload_length >= payload_buff_size)
{
fprintf(stderr, "MQTT payload too long, %d\n", payload_length);
exit(-1);
}
// // create the MQTT topic from the base topic string and the MAC address of sensor
// int topic_length;
// char topic_buffer[200];
// int topic_buffer_size = 200;
topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sV/config", config.mqtt_base_topic, config.sensors[x].my_id);
// publish the message and wait for success