├── sensor-humidity-24h.png ├── sensor-temperature-24h.png ├── sensor-readings-per-hour-24h.png ├── ble_sensor_mqtt_pub.service ├── hack_ble.sh ├── .gitignore ├── Makefile ├── rc.local ├── detailed-build-instructions.txt ├── ble_sensor_mqtt_pub.yaml ├── README.md ├── LICENSE └── ble_sensor_mqtt_pub.c /sensor-humidity-24h.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcoder/bluetooth-temperature-sensors/HEAD/sensor-humidity-24h.png -------------------------------------------------------------------------------- /sensor-temperature-24h.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcoder/bluetooth-temperature-sensors/HEAD/sensor-temperature-24h.png -------------------------------------------------------------------------------- /sensor-readings-per-hour-24h.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcoder/bluetooth-temperature-sensors/HEAD/sensor-readings-per-hour-24h.png -------------------------------------------------------------------------------- /ble_sensor_mqtt_pub.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=BLE Sensor MQTT service 3 | Documentation=https://github.com/deepcoder/bluetooth-temperature-sensors 4 | After=network-online.target 5 | Wants=network-online.target 6 | 7 | [Service] 8 | Type=simple 9 | Restart=always 10 | RestartSec=10s 11 | TimeoutSec=3s 12 | ExecStart=/usr/bin/ble_sensor_mqtt_pub /etc/ble_sensor_mqtt_pub.yaml 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /hack_ble.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | trap "echo Exited!; exit;" SIGINT SIGTERM 4 | 5 | if [ $EUID -ne 0 ]; then 6 | echo "This script should be run as root." > /dev/stderr 7 | exit 1 8 | fi 9 | 10 | while : 11 | do 12 | echo 'Running ble_sensor_mqtt_pub' 13 | date '+%Y%m%d%H%M%S' 14 | echo "Press [CTRL+C] to stop.." 15 | cd /home/pi/atc-govee 16 | /home/pi/atc-govee/ble_sensor_mqtt_pub /home/pi/atc-govee/ble_sensor_mqtt_pub.yaml 17 | done 18 | 19 | 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | *.log 26 | *.sql 27 | *.sqlite 28 | 29 | # OS generated files # 30 | ###################### 31 | .DS_Store 32 | .DS_Store? 33 | ._* 34 | .Spotlight-V100 35 | .Trashes 36 | ehthumbs.db 37 | Thumbs.db 38 | 39 | ble_sensor_mqtt_pub 40 | .vscode 41 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .POSIX: 2 | .SUFFIXES: 3 | 4 | CC = gcc 5 | #CFLAGS = -Wall -Wextra -pedantic -std=c99 -O2 6 | CFLAGS = -Wall -Wextra -O2 7 | 8 | all: ble_sensor_mqtt_pub 9 | 10 | ble_sensor_mqtt_pub : ble_sensor_mqtt_pub.c 11 | $(CC) $(CFLAGS) $< -lyaml -lbluetooth -lpaho-mqtt3c -o $@ 12 | 13 | 14 | .PHONY : install 15 | install: 16 | install -m 755 ble_sensor_mqtt_pub /usr/bin/ 17 | install -m 644 ble_sensor_mqtt_pub.service /etc/systemd/system/ 18 | ifeq (,$(wildcard /etc/ble_sensor_mqtt_pub.yaml)) 19 | install -m 600 ble_sensor_mqtt_pub.yaml /etc/ 20 | # Config using /etc/ble_sensor_mqtt_pub.yaml 21 | else 22 | # Leaving existing config at /etc/ble_sensor_mqtt_pub.yaml 23 | endif 24 | # Start service with 'systemctl start ble_sensor_mqtt_pub' 25 | # Set service to start at boot with 'systemctl enable ble_sensor_mqtt_pub' 26 | 27 | .PHONY : uninstall 28 | uninstall: 29 | systemctl stop ble_sensor_mqtt_pub 30 | systemctl disable ble_sensor_mqtt_pub 31 | rm -f /usr/bin/ble_sensor_mqtt_pub 32 | rm -f /etc/systemd/system/ble_sensor_mqtt_pub.service 33 | # Leaving config file if it exists 34 | 35 | .PHONY : clean 36 | clean : 37 | rm ble_sensor_mqtt_pub 38 | -------------------------------------------------------------------------------- /rc.local: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 202202021651 3 | ########!/bin/sh -e 4 | # 5 | # rc.local 6 | # 7 | # This script is executed at the end of each multiuser runlevel. 8 | # Make sure that the script will "exit 0" on success or any other 9 | # value on error. 10 | # 11 | # In order to enable or disable this script just change the execution 12 | # bits. 13 | # 14 | # By default this script does nothing. 15 | 16 | # Print the IP address 17 | _IP=$(hostname -I) || true 18 | if [ "$_IP" ]; then 19 | printf "My IP address is %s\n" "$_IP" 20 | fi 21 | 22 | # wait for networks to start 23 | 24 | STATE="error"; 25 | 26 | while [ $STATE == "error" ]; do 27 | #do a ping and check that its not a default message or change to grep for something else 28 | STATE=$(ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error) 29 | 30 | #sleep for 2 seconds and try again 31 | sleep 2 32 | done 33 | 34 | # if this file exists then skip processing 35 | declare SKIP_PROCESSING="/home/pi/ble-sensors/skip.txt" 36 | 37 | if [ -f "$SKIP_PROCESSING" ]; then 38 | echo "$SKIP_PROCESSING exists, not starting ble monitor." 39 | exit 1 40 | fi 41 | 42 | su pi -c 'tmux new-session -d -s ble' 43 | su pi -c 'tmux send-keys sudo Space /home/pi/ble-sensors/hack_ble.sh C-m' 44 | 45 | 46 | exit 0 47 | 48 | 49 | -------------------------------------------------------------------------------- /detailed-build-instructions.txt: -------------------------------------------------------------------------------- 1 | build rapsberry pi ble to mqtt 2 | 202012161409 3 | 4 | 5 | sudo dd bs=1m if=2020-08-20-raspios-buster-armhf-full.img of=/dev/rdisk6 conv=sync 6 | 7 | touch /Volumes/boot/ssh 8 | 9 | vi /Volumes/boot/wpa_supplicant.conf 10 | ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev 11 | update_config=1 12 | country=US 13 | 14 | network={ 15 | ssid="xxx" 16 | psk="yyy" 17 | key_mgmt=WPA-PSK 18 | } 19 | 20 | diskutil eject /dev/disk6 21 | 22 | boot the pi 23 | find on network 24 | 25 | sudo raspi-config 26 | # wait for network 27 | # consistent network names 28 | 29 | 30 | edit /etc/dhcpcd.conf 31 | interface eth0 32 | static ip_address=192.168.x.y/24 33 | static routers=192.168.x.x 34 | static domain_name_servers=1.1.1.1 35 | 36 | interface enxb827ebczzzzz 37 | static ip_address=192.168.x.y/24 38 | static routers=192.168.x.x 39 | static domain_name_servers=1.1.1.1 40 | 41 | removed /etc/wpa_supplicant.conf 42 | 43 | sudo apt-get update 44 | sudo apt-get full-upgrade 45 | reboot 46 | sudo apt-get install tmux 47 | 48 | fix login warning: 49 | /etc/profile.d/sshpwd.sh 50 | /etc/xdg/lxsession/LXDE-pi/sshpwd.sh 51 | 52 | mkdir ~/.ssh 53 | cat .ssh/id_rsa.pub | ssh pi@192.168.x.y 'cat >> .ssh/authorized_keys' 54 | 55 | create .vimrc for pi and root 56 | 57 | sudo mkdir /media/pi 58 | sudo mkdir /media/pi/nas 59 | 60 | vi /home/pi/.NASCREDS 61 | 62 | user=xxx 63 | password=yyy 64 | 65 | in /etc/fstab 66 | 67 | //192.168.x.y/nas /media/pi/nas cifs credentials=/home/pi/.NASCREDS,uid=pi,gid=pi,vers=1.0,comment=x-systemd.automount 0 0 68 | 69 | # test it 70 | sudo mount -a 71 | 72 | mkdir ~/ble-sensors 73 | cd ~/ble-sensors 74 | git clone https://github.com/deepcoder/bluetooth-temperature-sensors.git 75 | sudo apt-get install libbluetooth-dev 76 | git clone https://github.com/eclipse/paho.mqtt.c.git 77 | cd paho.mqtt.c 78 | make 79 | sudo make install 80 | cd .. 81 | cd bluetooth-temperature-sensors 82 | gcc -o ble_sensor_mqtt_pub ble_sensor_mqtt_pub.c -lbluetooth -l paho-mqtt3c 83 | cp ble_sensor_mqtt_pub .. 84 | cd .. 85 | create ble_sensor_mqtt_pub.csv 86 | create hack_ble.sh 87 | ===== 88 | #!/bin/bash 89 | 90 | trap "echo Exited!; exit;" SIGINT SIGTERM 91 | 92 | if [ $EUID -ne 0 ]; then 93 | echo "This script should be run as root." > /dev/stderr 94 | exit 1 95 | fi 96 | 97 | while : 98 | do 99 | echo 'Running ble_sensor_mqtt_pub' 100 | date '+%Y%m%d%H%M%S' 101 | echo "Press [CTRL+C] to stop.." 102 | cd /home/pi/ble-sensors 103 | /home/pi/ble-sensors/ble_sensor_mqtt_pub 0 1 200 500 104 | done 105 | ===== 106 | chmod +x hack_ble.sh 107 | 108 | sudo vi /etc/rc.local 109 | ===== 110 | #!/bin/bash 111 | 112 | ########!/bin/sh -e 113 | # 114 | # rc.local 115 | # 116 | # This script is executed at the end of each multiuser runlevel. 117 | # Make sure that the script will "exit 0" on success or any other 118 | # value on error. 119 | # 120 | # In order to enable or disable this script just change the execution 121 | # bits. 122 | # 123 | # By default this script does nothing. 124 | 125 | # Print the IP address 126 | _IP=$(hostname -I) || true 127 | if [ "$_IP" ]; then 128 | printf "My IP address is %s\n" "$_IP" 129 | fi 130 | 131 | # wait for networks to start 132 | 133 | STATE="error"; 134 | 135 | while [ $STATE == "error" ]; do 136 | #do a ping and check that its not a default message or change to grep for something else 137 | STATE=$(ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error) 138 | 139 | #sleep for 2 seconds and try again 140 | sleep 2 141 | done 142 | 143 | su pi -c 'tmux new-session -d -s ble' 144 | su pi -c 'tmux send-keys sudo Space /home/pi/ble-sensors/hack_ble.sh C-m' 145 | 146 | 147 | exit 0 148 | ===== 149 | hciconfig 150 | hci0: Type: Primary Bus: UART 151 | BD Address: cc:bb:aa:zz:yy:xx ACL MTU: 1021:8 SCO MTU: 64:1 152 | UP RUNNING 153 | RX bytes:1476 acl:0 sco:0 events:90 errors:0 154 | TX bytes:3274 acl:0 sco:0 commands:90 errors:0 155 | 156 | tmux attach -t ble 157 | 158 | -------------------------------------------------------------------------------- /ble_sensor_mqtt_pub.yaml: -------------------------------------------------------------------------------- 1 | # config.yaml file for configuring blue tooth sensors 2 | 3 | # MQTT server URL with port number 4 | mqtt_server_url: "tcp://172.148.5.11:1883" 5 | 6 | # MQTT base topic with a trailing slash 7 | # for HA autoconfig to work this should be either "homeassistant/sensor/" or "homeassistant/sensor/[something]/" 8 | mqtt_base_topic: "homeassistant/sensor/ble-temp/" 9 | 10 | # set to empty if not used 11 | mqtt_username: "mosquitto" 12 | mqtt_password: "mosquitto_pass" 13 | 14 | # bluetooth adapter = integer number of bluetooth devices, run hciconfig to see your adapters, 1st adapter is referenced as 0 in this program 15 | bluetooth_adapter: 0 16 | 17 | # scan type = 0 for passive, 1 for active advertising scan, some BLE sensors only share data on type 4 response active advertising packets 18 | scan_type: 1 19 | 20 | # integer number that is multiplied by 0.625 to set advertising scanning window in milliseconds. Try 100 to start. 21 | scan_window: 100 22 | 23 | # integer number that is multiplied by 0.625 to set advertising scanning interval in milliseconds. Try 1000 to start. 24 | scan_interval: 1000 25 | 26 | # 0 to publish via legecy style (by MAC directly into base), 1 to publish new style (by unique id into 'state'). Must be 1 for auto_configure to work. 27 | publish_type: 1 28 | 29 | # create HomeAssistant autoconfiguration entries, 1 to enable, 0 to disable 30 | auto_configure: 1 31 | 32 | # Create Sesnor for hourly statistics in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 33 | auto_conf_stats: 1 34 | 35 | # Create temp sensor in C in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 36 | # Note that HA will convert this to F if your settings are for F 37 | # will be created as [name]-T 38 | auto_conf_tempc: 1 39 | 40 | # Create temp sensor in F in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 41 | # will be created as [name]-F 42 | auto_conf_tempf: 1 43 | 44 | # Create hummity sensor in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 45 | # will be created as [name]-H 46 | auto_conf_hum: 1 47 | 48 | # Create battery percentage sensors in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 49 | # will be created as [name]-B 50 | auto_conf_battery: 1 51 | 52 | # Create battery voltage sensors in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 53 | # will be created as [name]-V 54 | auto_conf_voltage: 1 55 | 56 | # Create signal strength sensors in Home Assitant if auto_confiutgure is enabled, 1 to enable, 0 to disable 57 | # will be created as [name]-S 58 | auto_conf_signal: 1 59 | 60 | # not implemented yet 61 | syslog_address: "192.168.88.2" 62 | 63 | # set log level 64 | # 0 = LOG_EMERG - system is unusable 65 | # 1 = LOG_ALERT - action must be taken immediately 66 | # 2 = LOG_CRIT - critical conditions 67 | # 3 = LOG_ERR - error conditions 68 | # 4 = LOG_WARNING - warning conditions 69 | # 5 = LOG_NOTICE - normal but significant condition 70 | # 6 = LOG_INFO - informational 71 | # 7 = LOG_DEBUG - debug-level messages 72 | 73 | logging_level: "7" 74 | 75 | #### config for each sensor 76 | 77 | # Name: when auto configure is used thie will be the Name of the device, the root of the Friendly Name, as well as the basis HA uses for creating the entity name 78 | # Unique: name used for topic publishing and used as unique ID for HA auto config - no spaces or odd characters allowed 79 | # Location: used with HA auto config to auto assign sensors to a specific area 80 | # Types: 81 | # 1 = Xiaomi LYWSD03MMC-ATC https://github.com/atc1441/ATC_MiThermometer 82 | # 2 = Govee H5052 (type 4 advertising packets) 83 | # 3 = Govee H5072 84 | # 4 = Govee H5102 85 | # 5 = Govee H5075 86 | # 6 = Govee H5074 (type 4 advertising packets) 87 | # 99 = Display raw type 0 and type 4 advertising packets for this BLE MAC address 88 | # MAC: the MAC address of the sensor 89 | 90 | sensors: 91 | - name: "Living Room Temp/Hum" 92 | unique: "th_living_room" 93 | location: "Living Room" 94 | type: 1 95 | mac: "DD:C1:38:70:0C:24" 96 | 97 | - name: "Shared Bathroom Temp/Hum" 98 | unique: "th_bathroom" 99 | Location: "Shared Bathroom" 100 | type: 3 101 | mac: "DD:C1:38:AC:77:44" 102 | 103 | - name: "Attic Temp/Hum" 104 | unique: "th_attic" 105 | location: "Attic" 106 | type: 3 107 | mac: "DD:12:1D:22:80:77" 108 | 109 | - name: "LYWSD03MMC test" 110 | unique: "th_test" 111 | location: "Garage" 112 | type: 99 113 | mac: "DD:C1:38:AC:28:A2" 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bluetooth temperature sensors 2 | Read Bluetooth Advertising Packets from BLE temperature sensors and publish data to MQTT. This C language program runs on Linux. I have successfully used it on Raspberry Pi OS, Ubuntu 18 and Ubuntu 20. 3 | 4 | This program decodes the bluetooth advertising packets for the following BLE temperature and humidity sensors: 5 | ``` 6 | // 1 = Xiaomi LYWSD03MMC-ATC https://github.com/atc1441/ATC_MiThermometer or https://github.com/pvvx/ATC_MiThermometer 7 | // 2 = Govee H5052 (type 4 advertising packets) 8 | // 3 = Govee H5072 9 | // 4 = Govee H5102 10 | // 5 = Govee H5075 11 | // 6 = Govee H5074 (type 4 advertising packets) 12 | // 99 = Display raw type 0 and type 4 advertising packets for this BLE MAC address 13 | ``` 14 | When using the LYWSD03MMC you need to flash one of the custom firmwares above. Both the atc1441 and pvvx custom formats are supported. With pvvx custom you get more resolution for humidity. 15 | 16 | The program uses the bluetooth and mqtt client libraries, steps to image Raspberry Pi and install necessary libraries to compile program are show at bottom of this readme. 17 | 18 | Presuming reasonably modern systemd based linux system you can build and run like this: 19 | ``` 20 | sudo apt install libssl-dev libbluetooth-dev libyaml-dev 21 | 22 | git clone https://github.com/eclipse/paho.mqtt.c.git 23 | cd paho.mqtt.c/ 24 | make 25 | sudo make install 26 | cd .. 27 | 28 | git clone https://github.com/deepcoder/bluetooth-temperature-sensors.git 29 | cd bluetooth-temperature-sensors 30 | make 31 | sudo make install 32 | 33 | #edit for your config /etc/bluetooth-temperature-sensors.yaml 34 | systemctl start ble_sensor_mqtt_pub 35 | 36 | # if you want to start at boot 37 | systemctl enable ble_sensor_mqtt_pub 38 | ``` 39 | 40 | ## Example JSON published to MQTT topic if using legacy publishing (won't work with HA auto configuration): 41 | ``` 42 | topic: 43 | homeassistant/sensor/ble-temp/A4:C1:38:22:13:D0 44 | 45 | payload: 46 | {"timestamp":"20201206025836","mac-address":"A4:C1:38:22:13:D0","rssi":-69,"temperature":64.4,"units":"F","temperature-celsius":18.0,"humidity":44.0,"battery-pct":93,"sensor-name":"","location":"H5072 Kitchen","sensor-type":"3"} 47 | ``` 48 | 49 | ## Example JSON published to MQTT topic if using new style publishing: 50 | ``` 51 | topic: 52 | homeassistant/sensor/ble-temp/th_kitchen/state 53 | 54 | payload: 55 | {"timestamp":"20201206025836","mac":"A4:C1:38:22:13:D0","rssi":-69,"tempf":64.4,"units":"F","tempc":18.0,"humidity":44.0,"batterypct":93,"name":"Kitchen Temp/Hum","location":"Kitchen","type":"3"} 56 | ``` 57 | 58 | At the top of each hour the program will publish a count of the total number of advertising packets seen for each sensor in the prior hour to MQTT. This is useful to check the bluetooth frequency reception for each sensor as well as the quality and frequency of readings for each sensor type. The sub topic for this is: 59 | ``` 60 | $SYS/hour-stats 61 | ``` 62 | Example: 63 | ``` 64 | { 65 | "timestamp": "20201206110010", 66 | "aa:bb:cc:dd:ee:ff": { 67 | "count": 365, 68 | "location": "LYWSD03MMC Living Room" 69 | }, 70 | "aa:bb:cc:dd:ee:ff": { 71 | "count": 140, 72 | "location": "LYWSD03MMC Shared Bathroom" 73 | }, 74 | . 75 | . 76 | . 77 | . 78 | 79 | }, 80 | "aa:bb:cc:dd:ee:ff": { 81 | "count": 384, 82 | "location": "LYWSD03MMC Dining Room" 83 | }, 84 | "aa:bb:cc:dd:ee:ff": { 85 | "count": 397, 86 | "location": "LYWSD03MMC Attic" 87 | }, 88 | "aa:bb:cc:dd:ee:ff": { 89 | "count": 288, 90 | "location": "H5052 Refrigerator" 91 | }, 92 | "aa:bb:cc:dd:ee:ff": { 93 | "count": 767, 94 | "location": "H5052 Backyard" 95 | }, 96 | "aa:bb:cc:dd:ee:ff": { 97 | "count": 680, 98 | "location": "H5052 Freezer" 99 | }, 100 | . 101 | . 102 | . 103 | . 104 | "aa:bb:cc:dd:ee:ff": { 105 | "count": 330, 106 | "location": "H5072 Kitchen" 107 | }, 108 | "aa:bb:cc:dd:ee:ff": { 109 | "count": 351, 110 | "location": "H5102 test unit" 111 | }, 112 | "aa:bb:cc:dd:ee:ff": { 113 | "count": 344, 114 | "location": "H5075 test unit" 115 | }, 116 | "aa:bb:cc:dd:ee:ff": { 117 | "count": 433, 118 | "location": "H5074 test unit" 119 | }, 120 | "total_adv_packets": 7900 121 | } 122 | 123 | ``` 124 | 125 | ## Configuration file: 126 | 127 | The configuration file is normal YAML. The included sample config has more detail but here is an example config with 4 sensors. 128 | 129 | ``` 130 | mqtt_server_url: "tcp://172.148.5.11:1883" 131 | mqtt_base_topic: "homeassistant/sensor/ble-temp/" 132 | 133 | mqtt_username: "mosquitto" 134 | mqtt_password: "mosquitto_pass" 135 | 136 | bluetooth_adapter: 0 137 | scan_type: 1 138 | scan_window: 100 139 | scan_interval: 1000 140 | logging_level: 3 141 | 142 | publish_type: 1 143 | auto_configure: 1 144 | auto_conf_stats: 1 145 | auto_conf_tempc: 1 146 | auto_conf_tempf: 0 147 | auto_conf_hum: 1 148 | auto_conf_battery: 1 149 | auto_conf_voltage: 0 150 | auto_conf_signal: 1 151 | 152 | sensors: 153 | - name: "Living Room Temp/Hum" 154 | unique: "th_living_room" 155 | location: "Living Room" 156 | type: 1 157 | mac: "DD:C1:38:70:0C:24" 158 | 159 | - name: "Shared Bathroom Temp/Hum" 160 | unique: "th_bathroom" 161 | location: "Shared Bathroom" 162 | type: 3 163 | mac: "DD:C1:38:AC:77:44" 164 | 165 | - name: "Attic Temp/Hum" 166 | unique: "th_attic" 167 | location: "Attic" 168 | type: 3 169 | mac: "DD:12:1D:22:80:77" 170 | 171 | - name: "LYWSD03MMC test" 172 | unique: "th_test" 173 | location: "Garage" 174 | type: 99 175 | mac: "DD:C1:38:AC:28:A2" 176 | 177 | ``` 178 | 179 | ## Use auto device configuration with Home Assistant 180 | There is full support for Home Assintant's MQTT Discovery features (https://www.home-assistant.io/docs/mqtt/discovery). This will allow auto creation of all configured entities in HA as well as grouping them together properly into Devices (which doesn't seem possible to do currently without using auto discovery). Make sure the MQTT integration is enabled either via YAML or the UI. Make sure both publish_type & auto_configure are set to 1 and then pick which entities you'd like created for each sensor from the auto_conf_* options. Enabling auto_conf_battery will integrate with HA's battery function for devices (auto_conf_voltage will only be informational). 181 | 182 | 183 | ## Example Home Assistant manual MQTT sensor configuration: 184 | ``` 185 | - platform: mqtt 186 | name: "BLE Temperature Reading Hourly Stats" 187 | state_topic: "homeassistant/sensor/ble-temp/$SYS/hour-stats" 188 | value_template: "{{ value_json.total_adv_packets }}" 189 | unit_of_measurement: "Pkts" 190 | json_attributes_topic: "homeassistant/sensor/ble-temp/$SYS/hour-stats" 191 | 192 | - platform: mqtt 193 | name: "Backyard ATC_MI Temperature" 194 | state_topic: "homeassistant/sensor/ble-temp/A4:C1:38:DD:10:20" 195 | value_template: "{{ value_json.temperature }}" 196 | unit_of_measurement: "°F" 197 | json_attributes_topic: "homeassistant/sensor/ble-temp/A4:C1:38:DD:10:20" 198 | 199 | - platform: mqtt 200 | name: "Refrigerator Govee Humidity" 201 | state_topic: "homeassistant/sensor/ble-temp/3F:46:0D:31:70:28" 202 | value_template: "{{ value_json.humidity }}" 203 | unit_of_measurement: "%" 204 | json_attributes_topic: "homeassistant/sensor/ble-temp/3F:46:0D:31:70:28" 205 | 206 | ``` 207 | 208 | ## Finding your sensor's MAC address: 209 | 210 | Considering how important this unique address is, especially when you have multiple units that all look identical, finding this number is a pain at times. Most of the sensors do NOT have the MAC address listed physically on them. 211 | 212 | Keep a list of your known sensors MAC address. I write the address with a Sharpie on my units. 213 | 214 | I do a two step process, you can find a name of the unit, sometimes with the last 2 or 3 digit pairs of the MAC address using a bluetooth low energy scanning tool like 'Light Blue', 'BLE Scanner' on iOS or Android. Or 'BlueSee' or 'Bluetooth Explorer' on Mac OS. Basically you are looking for the 'new' guy. Unplug the sensors battery, clear the scanning list. Start the scanner, plug the battery in to the sensor and watch for a new unit to appear. You are looking for this 'short' name that the unit broadcasts. Yes a pain. 215 | 216 | With this short name in hand, you will now use another tool to find the full MAC address. On the Linux machine where you will run the scanning program use the 'hcitool' BLE command as follows to find the full MAC address: 217 | 218 | examples: 219 | ``` 220 | sudo hcitool -i hci0 lescan | grep "MJ_HT_V1" 221 | sudo hcitool -i hci0 lescan | grep "80:27" 222 | sudo hcitool -i hci0 lescan | grep "ATC_71CC86" 223 | sudo hcitool -i hci0 lescan | grep "Govee_H5074_B0A7" 224 | ``` 225 | 226 | this will return a line with the full MAC address of the unit, similar to one of the ones shown below. Record this MAC address: 227 | 228 | ``` 229 | 58:2D:34:3B:72:56 MJ_HT_V1 230 | A4:C1:38:71:CC:86 ATC_71CC86 231 | E0:12:1D:22:B0:A7 Govee_H5074_B0A7 232 | ``` 233 | 234 | if you run the program without the pipe to the grep command, you can see all the Bluetooth LE devices that are visible and advertising: 235 | 236 | ``` 237 | sudo hcitool -i hci0 lescan 238 | ``` 239 | 240 | ## Dumping raw advertising packets to console: 241 | 242 | If you add the MAC address of a BLE device to the configuration file and give it a type of '99', the program will display the raw type 0 and 4 advertising packet data to the console. Useful to help figure out the data format of a new temperature and humidity sensor. 243 | 244 | Example dump: 245 | 246 | ``` 247 | ========= 248 | Current local time and date: Sun Dec 6 13:55:55 2020 249 | mac address = E0:12:1D:33:82:11 location = H5074 test unit device type = 99 advertising_packet_type = 000 250 | ==>0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 251 | ==>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 252 | ==> 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 253 | ==> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 254 | ==>043E29020100002780221D12E01D02010607030A18F5FE88EC1109476F7665655F48353037345F38303237BC 255 | ==>__________ad________________________mmmmmmmmmmmmtttthhbbzbzbccrr 256 | rssi = -68 257 | ========= 258 | Current local time and date: Sun Dec 6 13:55:55 2020 259 | mac address = E0:12:1D:33:82:11 location = H5074 test unit device type = 99 advertising_packet_type = 004 260 | ==>0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 261 | ==>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 262 | ==> 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 263 | ==> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 264 | ==>043E17020104002780221D12E00B0AFF88EC005806D0106402C0 265 | ==>__________ad________________________mmmmmmmmmmmmtttthhbbzbzbccrr 266 | rssi = -64 267 | ========= 268 | ``` 269 | 270 | 271 | ## Steps to set up raspberry pi as bluetooth sensor MQTT collector 272 | 273 | imaged with: 274 | 2020-08-20-raspios-buster-armhf-full.img 275 | 276 | ``` 277 | sudo apt-get update 278 | sudo apt-get full-upgrade 279 | 280 | reboot 281 | uname -a 282 | Linux pi-ble-02 5.4.79-v7+ #1373 SMP Mon Nov 23 13:22:33 GMT 2020 armv7l GNU/Linux 283 | Pi Model 2B V1.1 284 | Revision : a21041 285 | SoC : BCM2836 286 | RAM : 1024Mb 287 | 288 | git clone https://github.com/deepcoder/bluetooth-temperature-sensors.git 289 | 290 | # install libs if not already installed 291 | sudo apt-get install libssl-dev 292 | 293 | sudo apt-get install libbluetooth-dev 294 | 295 | sudo apt-get install libyaml-dev 296 | 297 | git clone https://github.com/eclipse/paho.mqtt.c.git 298 | cd paho.mqtt.c/ 299 | make 300 | sudo make install 301 | 302 | cd /home/pi/bluetooth-temperature-sensors 303 | make 304 | sudo make install 305 | 306 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ lsusb 307 | Bus 001 Device 005: ID 0a5c:21e8 Broadcom Corp. BCM20702A0 Bluetooth 4.0 308 | 309 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ hciconfig 310 | hci0: Type: Primary Bus: USB 311 | BD Address: 00:02:72:DC:31:2F ACL MTU: 1021:8 SCO MTU: 64:1 312 | UP RUNNING 313 | RX bytes:980 acl:0 sco:0 events:51 errors:0 314 | TX bytes:2446 acl:0 sco:0 commands:51 errors:0 315 | 316 | # Edit config file 317 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ sudo nano /etc/ble_sensor_mqtt_pub.yaml 318 | 319 | # Run in the foreground 320 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ sudo /usr/bin/ble_sensor_mqtt_pub /etc/ble_sensor_mqtt_pub.yaml 321 | 322 | # Start the service 323 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ sudo systemctl start ble_sensor_mqtt_pub 324 | 325 | # Check status of the service 326 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ sudo systemctl status ble_sensor_mqtt_pub 327 | 328 | # Follow the log file, ctrl-c to exit 329 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ sudo journalctl -efu ble_sensor_mqtt_pub 330 | 331 | # Enable service to run at boot 332 | pi@pi-ble-02:~/bluetooth-temperature-sensors $ sudo systemctl enable ble_sensor_mqtt_pub 333 | 334 | ``` 335 | ## Comparison of number of sensor reading 336 | There is not much that can be done to control the number of sensor reading taken and then collected for each of the BLE devices. These graphs show a comparison of some of the sensors over a 24 hour period. Some sensors take readings often, others much less often. The Govee 5074 appears to takes both temperature and humidity readings several times per minute, where as sensors like the Govee 5075 go multiple minutes between readings. It is difficult to gauge the specific sampling rate. Note that some sensors seems to sample temperature and humidity at different intervals, for example the Xiaomi LYWSD03MMC w/ custom firmware does this. In addition to sampling rate of the sensor, you have to account for how many of the BLE advertising packets you are collecting. If a sensor has a poor RF signal, even if it is collecting and transmitting samples at one rate, your BLE collecting device might only be capturing a subset of the packets. In addition to RF signal considerations, the BLE parameters for scan window and scan interval will effect the number of advertising packets and therefor the number of samples you receive. The table below shows that for the test sensors, with BLE scan window of 125 ms and scan interval of 312.5 ms, the collector Raspberry PI captured on the order of 300 to 500 advertising packets per hour. Again, it is difficult to deduce the number of samples per hour each sensor was taking. 337 | 338 | ![alt text](https://github.com/deepcoder/bluetooth-temperature-sensors/blob/main/sensor-temperature-24h.png?raw=true) 339 | 340 | ![alt text](https://github.com/deepcoder/bluetooth-temperature-sensors/blob/main/sensor-humidity-24h.png?raw=true) 341 | 342 | ![alt text](https://github.com/deepcoder/bluetooth-temperature-sensors/blob/main/sensor-readings-per-hour-24h.png?raw=true) 343 | 344 | 345 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /ble_sensor_mqtt_pub.c: -------------------------------------------------------------------------------- 1 | // ble_sensor_mqtt_pub.c 2 | // gcc -o ble_sensor_mqtt_pub ble_sensor_mqtt_pub.c -l bluetooth -l paho-mqtt3c 3 | // 202102030607 4 | // 5 | // decode BLE temperature sensor temperature and humidity data from BLE advertising packets 6 | // and publish to MQTT 7 | // sensors supported: 8 | // 1 = Xiaomi LYWSD03MMC-ATC https://github.com/atc1441/ATC_MiThermometer 9 | // 2 = Govee H5052 10 | // 3 = Govee H5072 11 | // 4 = Govee H5102 12 | // 5 = Govee H5075 13 | // 6 = Govee H5074 14 | // 15 | // based on work by: 16 | // Intel Edison Playground 17 | // Copyright (c) 2015 Damian Kołakowski. All rights reserved. 18 | // 19 | // YAML config parsing based on: 20 | // https://github.com/smavros/yaml-to-struct 21 | // 22 | 23 | #define VERSION_MAJOR 3 24 | #define VERSION_MINOR 0 25 | // why is it so hard to get the base name of the program withOUT the .c extension!!!!!!! 26 | 27 | #define PROGRAM_NAME "ble_sensor_mqtt_pub" 28 | // program configuration file, 29 | // holds list of BLE sensors to track 30 | #define CONFIGURATION_FILE "/etc/ble_sensor_mqtt_pub.yaml" 31 | 32 | #define MAX_SENSORS 64 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | #include "MQTTClient.h" 55 | 56 | // logging setup 57 | // LOG_EMERG 58 | // A panic condition was reported to all processes. 59 | // LOG_ALERT 60 | // A condition that should be corrected immediately. 61 | // LOG_CRIT 62 | // A critical condition. 63 | // LOG_ERR 64 | // An error message. 65 | // LOG_WARNING 66 | // A warning message. 67 | // LOG_NOTICE 68 | // A condition requiring special handling. 69 | // LOG_INFO 70 | // A general information message. 71 | // LOG_DEBUG 72 | // A message useful for debugging programs. 73 | 74 | // int logging_level = LOG_INFO; 75 | // int logging_level = LOG_ERR; 76 | int logging_level = LOG_DEBUG; 77 | 78 | #define RSYSLOG_ADDRESS "192.168.2.5" 79 | #define LOGMESSAGESIZE 512 80 | char log_message[LOGMESSAGESIZE]; 81 | 82 | // Paho MQTT setup 83 | //#define ADDRESS "tcp://192.168.2.242:1883" 84 | char mqtt_server_address[128]; 85 | // #define CLIENTID PROGRAM_NAME 86 | #define MQTTCLIENTIDSIZE 128 87 | char z_client_id_mqtt[MQTTCLIENTIDSIZE]; 88 | 89 | #define QOS 1 90 | #define TIMEOUT 10000L 91 | 92 | // MONITOR THIS AS YOU ADD MORE UNITS!!!!!!!!!!!!!!!!! 93 | #define MAXIMUM_JSON_MESSAGE 2048 94 | 95 | // MQTT topic definitions 96 | // code to publish topic will append mac address of unit to this base 97 | // base topic: 98 | // each sensor with publish it's data under this base, example: 99 | // homeassistant/sensor/ble-temp/A4:C1:38:DB:64:96 100 | //char topic_base[128]; 101 | //const char topic_base[] = "homeassistant/sensor/ble-temp/"; 102 | // under the base topic, this sub topic will publish statistics 103 | // topic for hourly statistics 104 | const char topic_statistics[] = "$SYS/hour-stats"; 105 | 106 | struct hci_request ble_hci_request(uint16_t ocf, int clen, void *status, void *cparam) 107 | { 108 | struct hci_request rq; 109 | memset(&rq, 0, sizeof(rq)); 110 | rq.ogf = OGF_LE_CTL; 111 | rq.ocf = ocf; 112 | rq.cparam = cparam; 113 | rq.clen = clen; 114 | rq.rparam = status; 115 | rq.rlen = 1; 116 | return rq; 117 | } 118 | 119 | typedef struct 120 | { 121 | int type; 122 | char mac[19]; 123 | char location[64]; 124 | char name[64]; 125 | char unique[64]; 126 | char my_id[64]; 127 | char make[64]; 128 | char model[64]; 129 | int readings_per_hour; 130 | } sensor_t; 131 | 132 | typedef struct 133 | { 134 | char mqtt_server_url[128]; 135 | char mqtt_base_topic[128]; 136 | char mqtt_username[64]; 137 | char mqtt_password[64]; 138 | int bluetooth_adapter; 139 | int scan_type; 140 | int scan_window; 141 | int scan_interval; 142 | int publish_type; 143 | int auto_configure; 144 | int auto_conf_stats; 145 | int auto_conf_tempf; 146 | int auto_conf_tempc; 147 | int auto_conf_hum; 148 | int auto_conf_battery; 149 | int auto_conf_voltage; 150 | int auto_conf_signal; 151 | char syslog_address[64]; 152 | int logging_level; 153 | sensor_t sensors[MAX_SENSORS]; 154 | } config_t; 155 | 156 | /* Global parser */ 157 | unsigned int parser(config_t *config, char **argv); 158 | 159 | /* Parser utilities */ 160 | void init_prs(FILE *fp, yaml_parser_t *parser); 161 | void parse_next(yaml_parser_t *parser, yaml_event_t *event); 162 | void clean_prs(FILE *fp, yaml_parser_t *parser, yaml_event_t *event); 163 | 164 | /* Parser actions */ 165 | void event_switch(bool *seq_status, unsigned int *map_seq, config_t *config, 166 | yaml_parser_t *parser, yaml_event_t *event, FILE *fp); 167 | void to_data(bool *seq_status, unsigned int *map_seq, config_t *config, 168 | yaml_parser_t *parser, yaml_event_t *event, FILE *fp); 169 | void to_data_from_map(char *buf, unsigned int *map_seq, config_t *config, 170 | yaml_parser_t *parser, yaml_event_t *event, FILE *fp); 171 | 172 | /* Post parsing utilities */ 173 | void print_data(unsigned int sensor_count, config_t *config); 174 | 175 | // returns a structure with info about each bluetooth adapter found on system and returns number of adapters found 176 | static int hci_devlist(struct hci_dev_info **di, int *num) 177 | { 178 | int i; 179 | 180 | if ((*di = malloc(HCI_MAX_DEV * sizeof(**di))) == NULL) 181 | { 182 | printf("Couldn't allocated memory for hci_devlist: %s", strerror(errno)); 183 | exit(1); 184 | } 185 | 186 | for (i = *num = 0; i < HCI_MAX_DEV; i++) 187 | if (hci_devinfo(i, &(*di)[*num]) == 0) 188 | (*num)++; 189 | 190 | return 0; 191 | } 192 | 193 | char advertising_packet_type_desc[9][30] = 194 | { 195 | "ADV_IND 0 (0000)", 196 | "ADV_DIRECT_IND 1 (0001)", 197 | "ADV_NONCONN_IND 2 (0010)", 198 | "SCAN_REQ 3 (0011)", 199 | "SCAN_RSP 4 (0100)", 200 | "CONNECT_REQ 5 (0101)", 201 | "ADV_SCAN_IND 6 (0110)", 202 | "ADV_EXT_IND 7 (0111)", 203 | "AUX_CONNECT_RSP 8 (1000)"}; 204 | 205 | // used for printing packet info during debugging 206 | // https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format 207 | #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" 208 | #define BYTE_TO_BINARY(byte) \ 209 | (byte & 0x80 ? '1' : '0'), \ 210 | (byte & 0x40 ? '1' : '0'), \ 211 | (byte & 0x20 ? '1' : '0'), \ 212 | (byte & 0x10 ? '1' : '0'), \ 213 | (byte & 0x08 ? '1' : '0'), \ 214 | (byte & 0x04 ? '1' : '0'), \ 215 | (byte & 0x02 ? '1' : '0'), \ 216 | (byte & 0x01 ? '1' : '0') 217 | 218 | // this function sends a log message to a remote syslog server 219 | // call with: 220 | // log level 221 | // hostname of logging server 222 | // program name that is sending log message 223 | // message 224 | 225 | void send_remote_syslog_message(int log_level, char *hostname, char *program_name, char *message) 226 | { 227 | int sockfd, n; 228 | int serverlen; 229 | int message_length; 230 | struct sockaddr_in serveraddr; 231 | struct hostent *server; 232 | #define LOGBUFFERSIZE 1024 233 | char syslogbuf[LOGBUFFERSIZE]; 234 | #define RSYSLOGPORT 514 235 | 236 | // socket: create the socket 237 | sockfd = socket(AF_INET, SOCK_DGRAM, 0); 238 | if (sockfd < 0) 239 | { 240 | fprintf(stderr, "ERROR opening socket for remote syslog write"); 241 | exit(1); 242 | } 243 | 244 | // gethostbyname: get the server's DNS entry 245 | server = gethostbyname(hostname); 246 | if (server == NULL) 247 | { 248 | fprintf(stderr, "ERROR, no such host as %s for remote syslog write\n", hostname); 249 | exit(1); 250 | } 251 | 252 | // build the server's Internet address 253 | bzero((char *)&serveraddr, sizeof(serveraddr)); 254 | serveraddr.sin_family = AF_INET; 255 | bcopy((char *)server->h_addr, 256 | (char *)&serveraddr.sin_addr.s_addr, server->h_length); 257 | serveraddr.sin_port = htons(RSYSLOGPORT); 258 | 259 | // build the syslog message 260 | message_length = snprintf(syslogbuf, LOGBUFFERSIZE, "<%d>%s %s", LOG_USER + log_level, program_name, message); 261 | 262 | // fprintf(stdout, "%s\n", syslogbuf); 263 | 264 | // send the message to the server 265 | serverlen = sizeof(serveraddr); 266 | n = sendto(sockfd, syslogbuf, strlen(syslogbuf), 0, (struct sockaddr *)&serveraddr, serverlen); 267 | if (n < 0) 268 | { 269 | fprintf(stderr, "ERROR in sendto for remote syslog write\n"); 270 | exit(1); 271 | } 272 | 273 | return; 274 | } 275 | 276 | // catch -c to exit program 277 | static volatile bool keep_running = true; 278 | 279 | void intHandler(int dummy) 280 | { 281 | keep_running = false; 282 | } 283 | 284 | // MQTT async routines 285 | 286 | volatile MQTTClient_deliveryToken deliveredtoken; 287 | 288 | void delivered(void *context, MQTTClient_deliveryToken dt) 289 | { 290 | // printf("Message with token value %d delivery confirmed\n", dt); 291 | deliveredtoken = dt; 292 | } 293 | 294 | // MQTT received message handler 295 | int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) 296 | { 297 | int i; 298 | char *payloadptr; 299 | fprintf(stdout, "Message arrived\n"); 300 | fprintf(stdout, " topic: %s\n", topicName); 301 | fprintf(stdout, " message: "); 302 | payloadptr = message->payload; 303 | for (i = 0; i < message->payloadlen; i++) 304 | { 305 | putc(*payloadptr++, stdout); 306 | } 307 | fprintf(stdout, "\n"); 308 | MQTTClient_freeMessage(&message); 309 | MQTTClient_free(topicName); 310 | return 1; 311 | } 312 | 313 | // MQTT connection to server lost handler 314 | void connlost(void *context, char *cause) 315 | { 316 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d MQTT Server Connection lost", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 317 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 318 | syslog(LOG_ERR, "%s", log_message); 319 | fprintf(stderr, "MQTT Server Connection lost, cause: %s\n", cause); 320 | exit(1); 321 | } 322 | 323 | // for reading configuration file 324 | // read a field from the input line 325 | char *getfield(char *line, int num) 326 | { 327 | char *tok; 328 | for (tok = strtok(line, ","); 329 | tok && *tok; 330 | tok = strtok(NULL, ",\n")) 331 | { 332 | if (!--num) 333 | return tok; 334 | } 335 | return NULL; 336 | } 337 | 338 | // trim leading and trailing white space from a character string 339 | // https://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way 340 | char *trim(char *str) 341 | { 342 | int isspace(int); 343 | size_t len = 0; 344 | char *frontp = str; 345 | char *endp = NULL; 346 | 347 | if (str == NULL) 348 | { 349 | return NULL; 350 | } 351 | if (str[0] == '\0') 352 | { 353 | return str; 354 | } 355 | 356 | len = strlen(str); 357 | endp = str + len; 358 | 359 | // Move the front and back pointers to address the first non-whitespace 360 | // characters from each end. 361 | while (isspace((unsigned char)*frontp)) 362 | { 363 | ++frontp; 364 | } 365 | if (endp != frontp) 366 | { 367 | while (isspace((unsigned char)*(--endp)) && endp != frontp) 368 | { 369 | } 370 | } 371 | 372 | if (frontp != str && endp == frontp) 373 | *str = '\0'; 374 | else if (str + len - 1 != endp) 375 | *(endp + 1) = '\0'; 376 | 377 | // Shift the string so that it starts at str so that if it's dynamically 378 | // allocated, we can still free it on the returned pointer. Note the reuse 379 | // of endp to mean the front of the string buffer now. 380 | endp = str; 381 | if (frontp != str) 382 | { 383 | while (*frontp) 384 | { 385 | *endp++ = *frontp++; 386 | } 387 | *endp = '\0'; 388 | } 389 | 390 | return str; 391 | } 392 | 393 | int main(int argc, char *argv[]) 394 | { 395 | 396 | // startup 397 | fprintf(stdout, "%s v%2d.%02d\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 398 | 399 | // handle signals, SIGINT 400 | struct sigaction act; 401 | act.sa_handler = intHandler; 402 | sigaction(SIGINT, &act, NULL); 403 | 404 | if (argc != 2) 405 | { 406 | 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); 407 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 408 | syslog(LOG_ERR, "%s", log_message); 409 | fprintf(stderr, "Start program with a single argument pointing to yaml config file\n"); 410 | exit(1); 411 | } 412 | 413 | config_t config; 414 | 415 | int sensor_count; 416 | sensor_count = parser(&config, argv); 417 | 418 | int x; 419 | for (x = 0; x < sensor_count; x++) 420 | { 421 | if (config.publish_type) 422 | { 423 | strcpy(config.sensors[x].my_id, config.sensors[x].unique); 424 | } 425 | else 426 | { 427 | strcpy(config.sensors[x].my_id, config.sensors[x].mac); 428 | } 429 | switch (config.sensors[x].type) 430 | { 431 | case 1: 432 | strcpy(config.sensors[x].make, "Xiaomi"); 433 | strcpy(config.sensors[x].model, "LYWSD03MMC-ATC"); 434 | break; 435 | case 2: 436 | strcpy(config.sensors[x].make, "Govee"); 437 | strcpy(config.sensors[x].model, "H5052"); 438 | break; 439 | case 3: 440 | strcpy(config.sensors[x].make, "Govee"); 441 | strcpy(config.sensors[x].model, "H5072"); 442 | break; 443 | case 4: 444 | strcpy(config.sensors[x].make, "Govee"); 445 | strcpy(config.sensors[x].model, "H5102"); 446 | break; 447 | case 5: 448 | strcpy(config.sensors[x].make, "Govee"); 449 | strcpy(config.sensors[x].model, "H5075"); 450 | break; 451 | case 6: 452 | strcpy(config.sensors[x].make, "Govee"); 453 | strcpy(config.sensors[x].model, "H5074"); 454 | break; 455 | default: 456 | strcpy(config.sensors[x].make, ""); 457 | strcpy(config.sensors[x].model, ""); 458 | } 459 | } 460 | logging_level = config.logging_level; 461 | 462 | if (logging_level > LOG_NOTICE) 463 | { 464 | print_data(sensor_count, &config); 465 | } 466 | 467 | int hci_devs_num; 468 | struct hci_dev_info *hci_devs; 469 | 470 | int ret, status; 471 | 472 | // bluetooth adapter mac address 473 | char bluetooth_adapter_mac[19]; 474 | // adapter number 475 | int bluetooth_adapter_number; 476 | 477 | // get the info about each of the bluetooth adapters in system 478 | if (hci_devlist(&hci_devs, &hci_devs_num)) 479 | { 480 | 481 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Couldn't enumerate HCI devices: %s", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, strerror(errno)); 482 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 483 | syslog(LOG_ERR, "%s", log_message); 484 | fprintf(stderr, "Couldn't enumerate HCI devices: %s", strerror(errno)); 485 | exit(1); 486 | } 487 | else 488 | { 489 | fprintf(stdout, "%u Bluetooth adapter(s) in system.\n", hci_devs_num); 490 | } 491 | 492 | // get requested adapter number from command line 493 | bluetooth_adapter_number = config.bluetooth_adapter; 494 | 495 | int ble_scan_type; // 0 = passive, 1 = active scan 496 | 497 | ble_scan_type = config.scan_type; 498 | 499 | if (ble_scan_type != 1) 500 | { 501 | ble_scan_type = 0; 502 | } 503 | 504 | //int ble_scan_interval = 65; // value * 0.625 ms, scan every 41 milliseconds 505 | //int ble_scan_window = 750; // value * 0.625 ms, window 469 milliseconds 506 | int ble_scan_window = 48; // value * 0.625 ms, window 30 milliseconds 507 | int ble_scan_interval = 1500; // value * 0.625 ms, scan every 975 milliseconds 508 | 509 | ble_scan_window = config.scan_window; 510 | 511 | if (ble_scan_window == 0) 512 | { 513 | ble_scan_window = 48; 514 | } 515 | 516 | ble_scan_interval = config.scan_interval; 517 | 518 | if (ble_scan_interval == 0) 519 | { 520 | ble_scan_interval = 1500; 521 | } 522 | 523 | if (bluetooth_adapter_number < 0 || bluetooth_adapter_number > hci_devs_num - 1) 524 | { 525 | 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); 526 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 527 | syslog(LOG_ERR, "%s", log_message); 528 | fprintf(stderr, "Enter bluetooth adapter number between 0 and %u !!\n", hci_devs_num - 1); 529 | exit(1); 530 | } 531 | 532 | // get MAC address for adapter selected 533 | strcpy(bluetooth_adapter_mac, batostr(&hci_devs[bluetooth_adapter_number].bdaddr)); 534 | 535 | // log startup of program 536 | // strcpy(log_message, "test message *****"); 537 | setlogmask(LOG_UPTO(LOG_INFO)); 538 | openlog(PROGRAM_NAME, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); 539 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Starting.", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 540 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 541 | syslog(LOG_INFO, "%s", log_message); 542 | 543 | // maximum number of sensors 544 | // #define MAXIMUM_UNITS 40 545 | // number of devices read from configuration file 546 | int mac_total; 547 | 548 | int sensor_data_start; 549 | 550 | // total number of devices read from configuration file 551 | mac_total = sensor_count; 552 | 553 | fprintf(stdout, "Total devices in configuration file : %d\n", mac_total); 554 | 555 | // // create the MQTT topic from the base topic string and the MAC address of sensor 556 | // int topic_length; 557 | // char topic_buffer[200]; 558 | // int topic_buffer_size = 200; 559 | 560 | // initialize MQTT 561 | MQTTClient client; 562 | MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; 563 | MQTTClient_message pubmsg = MQTTClient_message_initializer; 564 | MQTTClient_deliveryToken token; 565 | int rc; 566 | 567 | // set MQTT client ID to program name plus bluetooth mac address, to allow multiple instances on one machine 568 | snprintf(z_client_id_mqtt, MQTTCLIENTIDSIZE, "%s-%s", PROGRAM_NAME, bluetooth_adapter_mac); 569 | fprintf(stdout, "MQTT client name : %s\n", z_client_id_mqtt); 570 | MQTTClient_create(&client, config.mqtt_server_url, z_client_id_mqtt, MQTTCLIENT_PERSISTENCE_NONE, NULL); 571 | // MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); 572 | conn_opts.keepAliveInterval = 20; 573 | conn_opts.cleansession = 1; 574 | conn_opts.username = config.mqtt_username; 575 | conn_opts.password = config.mqtt_password; 576 | MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered); 577 | if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) 578 | { 579 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d failed to connect to MQTT server", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 580 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 581 | syslog(LOG_ERR, "%s", log_message); 582 | fprintf(stderr, "Failed to connect to MQTT server, return code %d\n", rc); 583 | exit(1); 584 | } 585 | 586 | // Get HCI device. 587 | 588 | const int bluetooth_device = hci_open_dev(hci_get_route(&hci_devs[bluetooth_adapter_number].bdaddr)); 589 | 590 | 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); 591 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 592 | syslog(LOG_INFO, "%s", log_message); 593 | fprintf(stdout, "Bluetooth Adapter : %u has MAC address : %s\n", bluetooth_adapter_number, bluetooth_adapter_mac); 594 | 595 | if (bluetooth_device < 0) 596 | { 597 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d failed to open HCI device", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 598 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 599 | syslog(LOG_ERR, "%s", log_message); 600 | fprintf(stderr, "Failed to open HCI device, return code %d\n", bluetooth_device); 601 | exit(1); 602 | } 603 | 604 | // Set BLE scan parameters 605 | 606 | 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); 607 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 608 | syslog(LOG_INFO, "%s", log_message); 609 | fprintf(stdout, "Advertising scan type (0=passive, 1=active): %u\n", ble_scan_type); 610 | 611 | 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); 612 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 613 | syslog(LOG_INFO, "%s", log_message); 614 | fprintf(stdout, "Advertising scan window : %4u, %4.1f ms\n", ble_scan_window, ble_scan_window * 0.625); 615 | 616 | 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); 617 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 618 | syslog(LOG_INFO, "%s", log_message); 619 | fprintf(stdout, "Advertising scan interval : %4u, %4.1f ms\n", ble_scan_interval, ble_scan_interval * 0.625); 620 | 621 | le_set_scan_parameters_cp scan_params_cp; 622 | memset(&scan_params_cp, 0, sizeof(scan_params_cp)); 623 | // BLE PASSIVE OR ACTIVE SCAN *************************************************************************************** 624 | scan_params_cp.type = ble_scan_type; // 0x00 for passive scan, 0x01 for active scan (to get scan response packets) 625 | scan_params_cp.interval = htobs(ble_scan_interval); 626 | scan_params_cp.window = htobs(ble_scan_window); 627 | // scan_params_cp.interval = htobs(0x0010); 628 | // scan_params_cp.window = htobs(0x0010); 629 | scan_params_cp.own_bdaddr_type = 0x00; // Public Device Address (default). 630 | scan_params_cp.filter = 0x00; // Accept all. 631 | 632 | struct hci_request scan_params_rq = ble_hci_request(OCF_LE_SET_SCAN_PARAMETERS, LE_SET_SCAN_PARAMETERS_CP_SIZE, &status, &scan_params_cp); 633 | 634 | ret = hci_send_req(bluetooth_device, &scan_params_rq, 1000); 635 | if (ret < 0) 636 | { 637 | hci_close_dev(bluetooth_device); 638 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to set scan parameters data", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 639 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 640 | syslog(LOG_ERR, "%s", log_message); 641 | fprintf(stderr, "Failed to set scan parameters data, you must run this program as ROOT, return code %d\n", ret); 642 | exit(1); 643 | } 644 | 645 | // Set BLE events report mask. 646 | 647 | le_set_event_mask_cp event_mask_cp; 648 | memset(&event_mask_cp, 0, sizeof(le_set_event_mask_cp)); 649 | int i = 0; 650 | for (i = 0; i < 8; i++) 651 | event_mask_cp.mask[i] = 0xFF; 652 | 653 | struct hci_request set_mask_rq = ble_hci_request(OCF_LE_SET_EVENT_MASK, LE_SET_EVENT_MASK_CP_SIZE, &status, &event_mask_cp); 654 | ret = hci_send_req(bluetooth_device, &set_mask_rq, 1000); 655 | if (ret < 0) 656 | { 657 | hci_close_dev(bluetooth_device); 658 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to set event mask", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 659 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 660 | syslog(LOG_ERR, "%s", log_message); 661 | fprintf(stderr, "Failed to set event mask, return code %d\n", ret); 662 | exit(1); 663 | } 664 | 665 | // Enable scanning. 666 | 667 | le_set_scan_enable_cp scan_cp; 668 | memset(&scan_cp, 0, sizeof(scan_cp)); 669 | scan_cp.enable = 0x01; // Enable flag. 670 | scan_cp.filter_dup = 0x00; // Filtering disabled. 671 | 672 | struct hci_request enable_adv_rq = ble_hci_request(OCF_LE_SET_SCAN_ENABLE, LE_SET_SCAN_ENABLE_CP_SIZE, &status, &scan_cp); 673 | 674 | ret = hci_send_req(bluetooth_device, &enable_adv_rq, 1000); 675 | if (ret < 0) 676 | { 677 | hci_close_dev(bluetooth_device); 678 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to enable scan", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 679 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 680 | syslog(LOG_ERR, "%s", log_message); 681 | fprintf(stderr, "Failed to enable scan, return code %d\n", ret); 682 | exit(1); 683 | } 684 | 685 | // Get Results. 686 | 687 | struct hci_filter nf; 688 | hci_filter_clear(&nf); 689 | hci_filter_set_ptype(HCI_EVENT_PKT, &nf); 690 | hci_filter_set_event(EVT_LE_META_EVENT, &nf); 691 | ret = setsockopt(bluetooth_device, SOL_HCI, HCI_FILTER, &nf, sizeof(nf)); 692 | if (ret < 0) 693 | { 694 | hci_close_dev(bluetooth_device); 695 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Could not set socket options", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 696 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 697 | syslog(LOG_ERR, "%s", log_message); 698 | fprintf(stderr, "Could not set socket options, return code %d\n", ret); 699 | exit(1); 700 | } 701 | 702 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Scanning....", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 703 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 704 | syslog(LOG_INFO, "%s", log_message); 705 | // fprintf(stdout, "%s v%2d.%02d\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 706 | fprintf(stdout, "Scanning....\n"); 707 | fflush(stdout); 708 | 709 | // bluetooth advertising packet buffer 710 | uint8_t ble_adv_buf[HCI_MAX_EVENT_SIZE]; 711 | evt_le_meta_event *meta_event; 712 | le_advertising_info *adv_info; 713 | int bluetooth_adv_packet_length; 714 | 715 | // create the MQTT topic from the base topic string and the MAC address of sensor 716 | int topic_length; 717 | char topic_buffer[200]; 718 | int topic_buffer_size = 200; 719 | 720 | // MQTT payload buffer 721 | int payload_length; 722 | char payload_buffer[MAXIMUM_JSON_MESSAGE]; 723 | 724 | // int payload_buff_size = 300; 725 | 726 | // holds current time of current advertising packet that is received 727 | time_t rawtime = time(NULL); 728 | struct tm tm = *gmtime(&rawtime); 729 | struct tm *time_packet_received; 730 | 731 | // get the current hour, keep track every time we roll over to a new hour 732 | int hour_current; 733 | int hour_last; 734 | 735 | time_t gmt_time_now; 736 | struct tm tnp = *gmtime(&gmt_time_now); 737 | 738 | time(&gmt_time_now); 739 | tnp = *gmtime(&gmt_time_now); 740 | hour_current = tnp.tm_hour; 741 | 742 | if (hour_current == 0) 743 | { 744 | hour_last = 23; 745 | } 746 | else 747 | { 748 | hour_last = hour_current - 1; 749 | } 750 | 751 | fprintf(stdout, "current hour (GMT) = %d\n", hour_current); 752 | fprintf(stdout, "last hour (GMT) = %d\n", hour_last); 753 | 754 | if (config.auto_configure) 755 | { 756 | if (logging_level > LOG_INFO) 757 | { 758 | fprintf(stdout, "=========\n"); 759 | fprintf(stdout, "Begining auto configuration of devices\n"); 760 | } 761 | 762 | if (config.auto_conf_stats) 763 | { 764 | 765 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 766 | "{\"~\":\"%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}}\"}", 767 | config.mqtt_base_topic); 768 | 769 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 770 | // if (payload_length >= payload_buff_size) 771 | { 772 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 773 | exit(-1); 774 | } 775 | 776 | // // create the MQTT topic from the base topic string and the MAC address of sensor 777 | // int topic_length; 778 | // char topic_buffer[200]; 779 | // int topic_buffer_size = 200; 780 | 781 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%shourly-stats/config", config.mqtt_base_topic); 782 | 783 | // publish the message and wait for success 784 | pubmsg.payload = payload_buffer; 785 | pubmsg.payloadlen = payload_length; 786 | pubmsg.qos = QOS; 787 | pubmsg.retained = 1; 788 | deliveredtoken = 0; 789 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 790 | 791 | // wait for messqge to be delivered to server 792 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 793 | while (deliveredtoken != token) 794 | ; 795 | } 796 | 797 | for (x = 0; x < sensor_count; x++) 798 | { 799 | if (logging_level > LOG_INFO) 800 | { 801 | fprintf(stdout, " Configuring: %s\n", config.sensors[x].my_id); 802 | } 803 | 804 | if (config.sensors[x].type != 99) 805 | { 806 | // configure temp F sensor 807 | if (config.auto_conf_tempf) 808 | { 809 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 810 | "{\"~\":\"%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\"} }", 811 | config.mqtt_base_topic, 812 | config.sensors[x].my_id, 813 | config.sensors[x].name, 814 | config.sensors[x].my_id, 815 | config.sensors[x].name, 816 | config.sensors[x].my_id, 817 | config.sensors[x].location, 818 | config.sensors[x].mac, 819 | config.sensors[x].make, 820 | config.sensors[x].model); 821 | 822 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 823 | // if (payload_length >= payload_buff_size) 824 | { 825 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 826 | exit(-1); 827 | } 828 | 829 | // // create the MQTT topic from the base topic string and the MAC address of sensor 830 | 831 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sF/config", config.mqtt_base_topic, config.sensors[x].my_id); 832 | 833 | // publish the message and wait for success 834 | pubmsg.payload = payload_buffer; 835 | pubmsg.payloadlen = payload_length; 836 | pubmsg.qos = QOS; 837 | pubmsg.retained = 1; 838 | deliveredtoken = 0; 839 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 840 | 841 | // wait for messqge to be delivered to server 842 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 843 | while (deliveredtoken != token) 844 | ; 845 | } 846 | 847 | // configure temp C sensor 848 | if (config.auto_conf_tempc) 849 | { 850 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 851 | "{\"~\":\"%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\"} }", 852 | config.mqtt_base_topic, 853 | config.sensors[x].my_id, 854 | config.sensors[x].name, 855 | config.sensors[x].my_id, 856 | config.sensors[x].name, 857 | config.sensors[x].my_id, 858 | config.sensors[x].location, 859 | config.sensors[x].mac, 860 | config.sensors[x].make, 861 | config.sensors[x].model); 862 | 863 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 864 | // if (payload_length >= payload_buff_size) 865 | { 866 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 867 | exit(-1); 868 | } 869 | 870 | // // create the MQTT topic from the base topic string and the MAC address of sensor 871 | 872 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sT/config", config.mqtt_base_topic, config.sensors[x].my_id); 873 | 874 | // publish the message and wait for success 875 | pubmsg.payload = payload_buffer; 876 | pubmsg.payloadlen = payload_length; 877 | pubmsg.qos = QOS; 878 | pubmsg.retained = 1; 879 | deliveredtoken = 0; 880 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 881 | 882 | // wait for messqge to be delivered to server 883 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 884 | while (deliveredtoken != token) 885 | ; 886 | } 887 | 888 | // configure hum sensor 889 | if (config.auto_conf_hum) 890 | { 891 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 892 | "{\"~\":\"%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\"} }", 893 | config.mqtt_base_topic, 894 | config.sensors[x].my_id, 895 | config.sensors[x].name, 896 | config.sensors[x].my_id, 897 | config.sensors[x].name, 898 | config.sensors[x].my_id, 899 | config.sensors[x].location, 900 | config.sensors[x].mac, 901 | config.sensors[x].make, 902 | config.sensors[x].model); 903 | 904 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 905 | // if (payload_length >= payload_buff_size) 906 | { 907 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 908 | exit(-1); 909 | } 910 | 911 | // // create the MQTT topic from the base topic string and the MAC address of sensor 912 | 913 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sH/config", config.mqtt_base_topic, config.sensors[x].my_id); 914 | 915 | // publish the message and wait for success 916 | pubmsg.payload = payload_buffer; 917 | pubmsg.payloadlen = payload_length; 918 | pubmsg.qos = QOS; 919 | pubmsg.retained = 1; 920 | deliveredtoken = 0; 921 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 922 | 923 | // wait for messqge to be delivered to server 924 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 925 | while (deliveredtoken != token) 926 | ; 927 | } 928 | 929 | // configure battery sensor 930 | if (config.auto_conf_battery) 931 | { 932 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 933 | "{\"~\":\"%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\"} }", 934 | config.mqtt_base_topic, 935 | config.sensors[x].my_id, 936 | config.sensors[x].name, 937 | config.sensors[x].my_id, 938 | config.sensors[x].name, 939 | config.sensors[x].my_id, 940 | config.sensors[x].location, 941 | config.sensors[x].mac, 942 | config.sensors[x].make, 943 | config.sensors[x].model); 944 | 945 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 946 | // if (payload_length >= payload_buff_size) 947 | { 948 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 949 | exit(-1); 950 | } 951 | 952 | // // create the MQTT topic from the base topic string and the MAC address of sensor 953 | 954 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sB/config", config.mqtt_base_topic, config.sensors[x].my_id); 955 | 956 | // publish the message and wait for success 957 | pubmsg.payload = payload_buffer; 958 | pubmsg.payloadlen = payload_length; 959 | pubmsg.qos = QOS; 960 | pubmsg.retained = 1; 961 | deliveredtoken = 0; 962 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 963 | 964 | // wait for messqge to be delivered to server 965 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 966 | while (deliveredtoken != token) 967 | ; 968 | } 969 | 970 | // configure voltage sensor only an option for sensor type 1 971 | if (config.auto_conf_voltage && config.sensors[x].type == 1) 972 | { 973 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 974 | "{\"~\":\"%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\"} }", 975 | config.mqtt_base_topic, 976 | config.sensors[x].my_id, 977 | config.sensors[x].name, 978 | config.sensors[x].my_id, 979 | config.sensors[x].name, 980 | config.sensors[x].my_id, 981 | config.sensors[x].location, 982 | config.sensors[x].mac, 983 | config.sensors[x].make, 984 | config.sensors[x].model); 985 | 986 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 987 | // if (payload_length >= payload_buff_size) 988 | { 989 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 990 | exit(-1); 991 | } 992 | 993 | // // create the MQTT topic from the base topic string and the MAC address of sensor 994 | // int topic_length; 995 | // char topic_buffer[200]; 996 | // int topic_buffer_size = 200; 997 | 998 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sV/config", config.mqtt_base_topic, config.sensors[x].my_id); 999 | 1000 | // publish the message and wait for success 1001 | pubmsg.payload = payload_buffer; 1002 | pubmsg.payloadlen = payload_length; 1003 | pubmsg.qos = QOS; 1004 | pubmsg.retained = 1; 1005 | deliveredtoken = 0; 1006 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1007 | 1008 | // wait for messqge to be delivered to server 1009 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1010 | while (deliveredtoken != token) 1011 | ; 1012 | } 1013 | 1014 | // configure signal sensor 1015 | if (config.auto_conf_signal) 1016 | { 1017 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1018 | "{\"~\":\"%s%s\",\"dev_cla\":\"signal_strength\",\"name\":\"%s-S\",\"uniq_id\":\"%s-S\",\"stat_t\":\"~/state\",\"unit_of_meas\":\"dBm\",\"val_tpl\":\"{{value_json.rssi}}\",\"dev\":{\"name\":\"%s\",\"ids\":\"%s\",\"sa\":\"%s\",\"cns\":[[\"mac\", \"%s\"]],\"mf\":\"%s\",\"mdl\":\"%s\"} }", 1019 | config.mqtt_base_topic, 1020 | config.sensors[x].my_id, 1021 | config.sensors[x].name, 1022 | config.sensors[x].my_id, 1023 | config.sensors[x].name, 1024 | config.sensors[x].my_id, 1025 | config.sensors[x].location, 1026 | config.sensors[x].mac, 1027 | config.sensors[x].make, 1028 | config.sensors[x].model); 1029 | 1030 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1031 | // if (payload_length >= payload_buff_size) 1032 | { 1033 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 1034 | exit(-1); 1035 | } 1036 | 1037 | // // create the MQTT topic from the base topic string and the MAC address of sensor 1038 | // int topic_length; 1039 | // char topic_buffer[200]; 1040 | // int topic_buffer_size = 200; 1041 | 1042 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%sS/config", config.mqtt_base_topic, config.sensors[x].my_id); 1043 | 1044 | // publish the message and wait for success 1045 | pubmsg.payload = payload_buffer; 1046 | pubmsg.payloadlen = payload_length; 1047 | pubmsg.qos = QOS; 1048 | pubmsg.retained = 1; 1049 | deliveredtoken = 0; 1050 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1051 | 1052 | // wait for messqge to be delivered to server 1053 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1054 | while (deliveredtoken != token) 1055 | ; 1056 | } 1057 | } 1058 | } 1059 | if (logging_level > LOG_INFO) 1060 | { 1061 | fprintf(stdout, " Auto configuration complete\n"); 1062 | } 1063 | fflush(stdout); 1064 | } 1065 | 1066 | // loop until SIGINT received 1067 | while (keep_running) 1068 | { 1069 | 1070 | // check if we have rolled over to a new hour, if so send report of advertising packets receive in last hour 1071 | time(&gmt_time_now); 1072 | tnp = *gmtime(&gmt_time_now); 1073 | 1074 | if (hour_current != tnp.tm_hour) 1075 | { 1076 | hour_current = tnp.tm_hour; 1077 | // check if new day 1078 | if (hour_current == 0) 1079 | { 1080 | hour_last = 23; 1081 | } 1082 | else 1083 | { 1084 | hour_last = hour_current - 1; 1085 | } 1086 | 1087 | // don't publish right at top of hour, wait a few seconds 1088 | sleep(10); 1089 | 1090 | fprintf(stdout, "*********** =========\n"); 1091 | fprintf(stdout, "HOUR ROLLOVER\n"); 1092 | fprintf(stdout, "current hour (GMT) = %d\n", hour_current); 1093 | fprintf(stdout, "last hour (GMT) = %d\n", hour_last); 1094 | 1095 | time(&gmt_time_now); 1096 | tnp = *gmtime(&gmt_time_now); 1097 | 1098 | // create JSON string with timestamp, count and location for each known device 1099 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1100 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",", 1101 | tnp.tm_year + 1900, tnp.tm_mon + 1, tnp.tm_mday, tnp.tm_hour, tnp.tm_min, tnp.tm_sec); 1102 | 1103 | int count_string_length; 1104 | char count_string_buffer[MAXIMUM_JSON_MESSAGE] = ""; 1105 | int count_string_size = MAXIMUM_JSON_MESSAGE; 1106 | 1107 | // this builds a string contains the readings for each device concatenated together 1108 | int total_advertising_packets = 0; 1109 | int n; 1110 | for (n = 0; n <= mac_total - 1; n++) 1111 | { 1112 | count_string_length = snprintf(count_string_buffer, count_string_size, "\"%s\":{\"count\":%d, \"location\":\"%s\"},", config.sensors[n].mac, config.sensors[n].readings_per_hour, config.sensors[n].location); 1113 | strcat(payload_buffer, count_string_buffer); 1114 | // if ( n < mac_total - 1 ) 1115 | // strcat(payload_buffer, ","); 1116 | 1117 | fprintf(stderr, "Location : %s packets received in last hour : %d %s\n", config.sensors[n].mac, config.sensors[n].readings_per_hour, config.sensors[n].location); 1118 | total_advertising_packets = total_advertising_packets + config.sensors[n].readings_per_hour; 1119 | config.sensors[n].readings_per_hour = 0; 1120 | } 1121 | 1122 | // append the total of all advertising packets for all sensors of this type in last hour 1123 | count_string_length = snprintf(count_string_buffer, count_string_size, "\"total_adv_packets\":%d}", total_advertising_packets); 1124 | strcat(payload_buffer, count_string_buffer); 1125 | 1126 | // get length of MQTT payload after concatinating all the individual string together 1127 | payload_length = strlen(payload_buffer); 1128 | 1129 | fprintf(stdout, "payload_buffer JSON : %s\n", payload_buffer); 1130 | 1131 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1132 | { 1133 | fprintf(stderr, "MQTT payload too long: %d\n", payload_length); 1134 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d MQTT payload too long: %d\n", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR, payload_length); 1135 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 1136 | syslog(LOG_ERR, "%s", log_message); 1137 | exit(1); 1138 | } 1139 | 1140 | // publish it to a statistics topic under the root topic 1141 | topic_length = snprintf(topic_buffer, topic_buffer_size, 1142 | "%s%s", 1143 | config.mqtt_base_topic, topic_statistics); 1144 | 1145 | // publish the message and wait for success 1146 | pubmsg.payload = payload_buffer; 1147 | pubmsg.payloadlen = payload_length; 1148 | pubmsg.qos = QOS; 1149 | pubmsg.retained = 0; 1150 | deliveredtoken = 0; 1151 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1152 | 1153 | // wait for messqge to be delivered to server 1154 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1155 | while (deliveredtoken != token) 1156 | ; 1157 | } 1158 | 1159 | // get the bluetooth packet 1160 | bluetooth_adv_packet_length = read(bluetooth_device, ble_adv_buf, sizeof(ble_adv_buf)); 1161 | // apparently there can be multiple advertisement packets with the packet received 1162 | if (bluetooth_adv_packet_length >= HCI_EVENT_HDR_SIZE) 1163 | { 1164 | meta_event = (evt_le_meta_event *)(ble_adv_buf + HCI_EVENT_HDR_SIZE + 1); 1165 | if (meta_event->subevent == EVT_LE_ADVERTISING_REPORT) 1166 | { 1167 | 1168 | uint8_t reports_count = meta_event->data[0]; 1169 | void *offset = meta_event->data + 1; 1170 | while (reports_count--) 1171 | { 1172 | // this is the advertising specific data within the packet 1173 | adv_info = (le_advertising_info *)offset; 1174 | 1175 | // get the MAC address of the device that sent the advertising packet 1176 | char addr[18]; 1177 | ba2str(&(adv_info->bdaddr), addr); 1178 | 1179 | // check the MAC address of the BLE device and see if it is in out list of deies to monitor 1180 | 1181 | int mac_match = 0; 1182 | int mac_index; 1183 | int i_match; 1184 | 1185 | for (i_match = 0; i_match < mac_total; ++i_match) 1186 | { 1187 | if (strcmp(addr, config.sensors[i_match].mac) == 0) 1188 | { 1189 | mac_match = 1; 1190 | // keep a pointer to the mac address we matched 1191 | mac_index = i_match; 1192 | } 1193 | } 1194 | 1195 | // found the mac address in our list we are interested in, so decipher it's data 1196 | // if (1 == 1) 1197 | if (mac_match == 1) 1198 | { 1199 | 1200 | // different processing based on the device type, each type has different formats of advertising packets 1201 | 1202 | // 1 = Xiaomi LYWSD03MMC-ATC 1203 | if (config.sensors[mac_index].type == 1) 1204 | { 1205 | int advertising_packet_type; // type of advertising packet 1206 | //printf("=========\n"); 1207 | //get the time that we received the scan response packet 1208 | time(&rawtime); 1209 | tm = *gmtime(&rawtime); 1210 | time_packet_received = localtime(&rawtime); 1211 | 1212 | // printf ( "Current local time and date: %s", asctime (timeinfo) ); 1213 | 1214 | // printf("mac address = %s location = %s ", addr, config.sensors[mac_index].location); 1215 | 1216 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 1217 | // printf("advertising_packet_type = %03d\n", advertising_packet_type); 1218 | // length of packet and subpacket 1219 | 1220 | // printf("full packet length = %3d %02X\n", bluetooth_adv_packet_length, bluetooth_adv_packet_length); 1221 | // printf("sub packet length = %3d %02X\n", adv_info->length, adv_info->length); 1222 | 1223 | // printf("rssi = %03d %02X\n", (int8_t)adv_info->data[adv_info->length], adv_info->data[adv_info->length]); 1224 | 1225 | // handle the specific data for each advertising packet type 1226 | // The Advertising and Scan Response data is sent in advertising events. The 1227 | // Advertising Data is placed in the AdvData field of ADV_IND, 1228 | // ADV_NONCONN_IND, and ADV_SCAN_IND packets. The Scan Response 1229 | // data is sent in the ScanRspData field of SCAN_RSP packets. 1230 | // https://www.libelium.com/forum/libelium_files/bt4_core_spec_adv_data_reference.pdf 1231 | 1232 | if (advertising_packet_type == 0) 1233 | { 1234 | 1235 | int ad_length; // length of ADV_IND packet type 1236 | int ad_type; // attribute of ADV_IND packet type 1237 | 1238 | int8_t rssi_int = adv_info->data[adv_info->length]; 1239 | 1240 | if (logging_level == LOG_DEBUG) 1241 | { 1242 | fprintf(stdout, "=========\n"); 1243 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 1244 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1245 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1246 | fprintf(stdout, "rssi = %03d\n", rssi_int); 1247 | } 1248 | 1249 | // length of packet and subpacket 1250 | 1251 | //printf("full packet length = %3d %02X\n", bluetooth_adv_packet_length, bluetooth_adv_packet_length); 1252 | //printf("sub packet length = %3d %02X\n", adv_info->length, adv_info->length); 1253 | 1254 | ad_length = (unsigned int)adv_info->data[0]; 1255 | //printf("ADV_IND AD Data Length = %3d %02X\n", ad_length, ad_length); 1256 | ad_type = (unsigned int)adv_info->data[1]; 1257 | //printf("ADV_IND AD Type = %3d %02X\n", ad_type, ad_type); 1258 | 1259 | int16_t temperature_int; 1260 | double temperature_celsius; 1261 | double temperature_fahrenheit; 1262 | int16_t humidity_int; 1263 | double humidity; 1264 | uint8_t battery_pct_int; 1265 | uint16_t battery_mv_int; 1266 | uint8_t frame_int; 1267 | 1268 | // check for pvvx firmware custom format 1269 | if (bluetooth_adv_packet_length == 34) 1270 | { 1271 | if (logging_level == LOG_DEBUG) 1272 | { 1273 | fprintf(stdout, "Parsing as PVVX Firmware\n"); 1274 | } 1275 | 1276 | temperature_int = (adv_info->data[10]) | (adv_info->data[11] << 8); 1277 | temperature_celsius = (double)temperature_int / 100.0; 1278 | 1279 | temperature_fahrenheit = temperature_celsius * 9.0 / 5.0 + 32.0; 1280 | 1281 | humidity_int = (adv_info->data[12]) | (adv_info->data[13] << 8); 1282 | humidity = (double)humidity_int / 100.0; 1283 | 1284 | battery_pct_int = adv_info->data[16]; 1285 | 1286 | battery_mv_int = (adv_info->data[14]) | (adv_info->data[15] << 8); 1287 | 1288 | frame_int = adv_info->data[17]; 1289 | } 1290 | else 1291 | { 1292 | if (logging_level == LOG_DEBUG) 1293 | { 1294 | fprintf(stdout, "Parsing as ATC Firmware\n"); 1295 | } 1296 | 1297 | temperature_int = (adv_info->data[10] << 8) | adv_info->data[11]; 1298 | temperature_celsius = (double)temperature_int / 10.0; 1299 | 1300 | temperature_fahrenheit = temperature_celsius * 9.0 / 5.0 + 32.0; 1301 | 1302 | humidity_int = adv_info->data[12]; 1303 | humidity = (double)humidity_int; 1304 | 1305 | battery_pct_int = adv_info->data[13]; 1306 | 1307 | battery_mv_int = (adv_info->data[14] << 8) | adv_info->data[15]; 1308 | 1309 | frame_int = adv_info->data[16]; 1310 | } 1311 | 1312 | if (logging_level == LOG_DEBUG) 1313 | { 1314 | fprintf(stdout, "temp c = %.1f\n", temperature_celsius); 1315 | fprintf(stdout, "temp f = %.1f\n", temperature_fahrenheit); 1316 | fprintf(stdout, "humidity pct = %.1f\n", humidity); 1317 | fprintf(stdout, "battery pct = %3d\n", battery_pct_int); 1318 | fprintf(stdout, "battery mv = %4d\n", battery_mv_int); 1319 | fprintf(stdout, "frame = %3d\n", frame_int); 1320 | } 1321 | // count the number of advertising packets we get from each unit 1322 | 1323 | config.sensors[mac_index].readings_per_hour = config.sensors[mac_index].readings_per_hour + 1; 1324 | 1325 | if (config.publish_type == 1) 1326 | { 1327 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1328 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac\":\"%s\",\"rssi\":%d,\"tempf\":%#.1F,\"units\":\"F\",\"tempc\":%#.1F,\"humidity\":%#.1F,\"batterypct\":%i,\"batterymv\":%i,\"frame\":%i,\"name\":\"%s\",\"location\":\"%s\",\"type\":\"%d\"}", 1329 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1330 | addr, rssi_int, temperature_fahrenheit, 1331 | temperature_celsius, 1332 | humidity, battery_pct_int, battery_mv_int, frame_int, 1333 | config.sensors[mac_index].name, 1334 | config.sensors[mac_index].location, 1335 | config.sensors[mac_index].type); 1336 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s/state", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1337 | } 1338 | else 1339 | { 1340 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1341 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac-address\":\"%s\",\"rssi\":%d,\"temperature\":%#.1F,\"units\":\"F\",\"temperature-celsius\":%#.1F,\"humidity\":%.0F,\"battery-pct\":%i,\"battery-mv\":%i,\"frame\":%i,\"sensor-name\":\"%s\",\"location\":\"%s\",\"sensor-type\":\"%d\"}", 1342 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1343 | addr, rssi_int, temperature_fahrenheit, 1344 | temperature_celsius, 1345 | humidity, battery_pct_int, battery_mv_int, frame_int, 1346 | config.sensors[mac_index].name, 1347 | config.sensors[mac_index].location, 1348 | config.sensors[mac_index].type); 1349 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1350 | } 1351 | 1352 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1353 | // if (payload_length >= payload_buff_size) 1354 | { 1355 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 1356 | exit(-1); 1357 | } 1358 | 1359 | // publish the message and wait for success 1360 | pubmsg.payload = payload_buffer; 1361 | pubmsg.payloadlen = payload_length; 1362 | pubmsg.qos = QOS; 1363 | pubmsg.retained = 0; 1364 | deliveredtoken = 0; 1365 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1366 | 1367 | // wait for messqge to be delivered to server 1368 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1369 | while (deliveredtoken != token) 1370 | ; 1371 | } 1372 | 1373 | if (advertising_packet_type == 4) 1374 | { 1375 | } 1376 | fflush(stdout); 1377 | } 1378 | // end device type 1 1379 | 1380 | // 2 = Govee H5052 1381 | if (config.sensors[mac_index].type == 2) 1382 | { 1383 | //get the time that we received the scan response packet 1384 | time(&rawtime); 1385 | tm = *gmtime(&rawtime); 1386 | time_packet_received = localtime(&rawtime); 1387 | 1388 | int advertising_packet_type; // type of advertising packet 1389 | 1390 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 1391 | 1392 | if (advertising_packet_type == 0) 1393 | { 1394 | } 1395 | 1396 | // sensor data is broadcast in type 4 advertising message by the H5052 1397 | if (advertising_packet_type == 4) 1398 | { 1399 | // get rssi 1400 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 1401 | 1402 | if (logging_level == LOG_DEBUG) 1403 | { 1404 | fprintf(stdout, "=========\n"); 1405 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 1406 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1407 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1408 | fprintf(stdout, "rssi = %03d\n", rssi_int); 1409 | } 1410 | 1411 | // fprintf(stdout, "=========\n"); 1412 | // fprintf(stdout, "Current local time and date: %s", asctime (time_packet_received) ); 1413 | // fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].location); 1414 | // 1415 | // fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1416 | 1417 | sensor_data_start = 5; 1418 | 1419 | // get the lsb msb byte pairs for temperature and humidity and convert them to an integer value (in 100's) 1420 | // temperature is a signed 16 bit integer to allow for temperatures below and above 0 degrees celsius 1421 | signed short int temperature_int = adv_info->data[sensor_data_start + 0] | adv_info->data[sensor_data_start + 1] << 8; 1422 | int humidity_int = adv_info->data[sensor_data_start + 2] | adv_info->data[sensor_data_start + 3] << 8; 1423 | 1424 | // convert the integer * 100 value for temperature and humidity to degrees fahrenheit and celsius (for homekit) and humidity percentage 1425 | 1426 | double temperature_fahrenheit; 1427 | double temperature_celsius; 1428 | temperature_fahrenheit = (temperature_int / 100.0) * 9.0 / 5.0 + 32.0; 1429 | temperature_celsius = (temperature_int / 100.0); 1430 | 1431 | double humidity = humidity_int / 100.0; 1432 | 1433 | // get battery level percentage 1434 | int battery_precentage_int = (signed char)adv_info->data[sensor_data_start + 4]; 1435 | 1436 | if (logging_level == LOG_DEBUG) 1437 | { 1438 | fprintf(stdout, "temp c = %.1f\n", temperature_celsius); 1439 | fprintf(stdout, "temp f = %.1f\n", temperature_fahrenheit); 1440 | fprintf(stdout, "humidity pct = %.1f\n", humidity); 1441 | fprintf(stdout, "battery pct = %3d\n", battery_precentage_int); 1442 | } 1443 | 1444 | // count the number of advertising packets we get from each unit 1445 | 1446 | config.sensors[mac_index].readings_per_hour = config.sensors[mac_index].readings_per_hour + 1; 1447 | 1448 | if (config.publish_type == 1) 1449 | { 1450 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1451 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac\":\"%s\",\"rssi\":%d,\"tempf\":%#.1F,\"units\":\"F\",\"tempc\":%#.1F,\"humidity\":%#.1F,\"batterypct\":%i,\"name\":\"%s\",\"location\":\"%s\",\"type\":\"%d\"}", 1452 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1453 | addr, rssi_int, temperature_fahrenheit, 1454 | temperature_celsius, 1455 | humidity, battery_precentage_int, 1456 | config.sensors[mac_index].name, 1457 | config.sensors[mac_index].location, 1458 | config.sensors[mac_index].type); 1459 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s/state", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1460 | } 1461 | else 1462 | { 1463 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1464 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac-address\":\"%s\",\"rssi\":%d,\"temperature\":%#.1F,\"units\":\"F\",\"temperature-celsius\":%#.1F,\"humidity\":%#.1F,\"battery-pct\":%i,\"sensor-name\":\"%s\",\"location\":\"%s\",\"sensor-type\":\"%d\"}", 1465 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1466 | addr, rssi_int, temperature_fahrenheit, 1467 | temperature_celsius, 1468 | humidity, battery_precentage_int, 1469 | config.sensors[mac_index].name, 1470 | config.sensors[mac_index].location, 1471 | config.sensors[mac_index].type); 1472 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1473 | } 1474 | 1475 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1476 | // if (payload_length >= payload_buff_size) 1477 | { 1478 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 1479 | exit(-1); 1480 | } 1481 | 1482 | // publish the message and wait for success 1483 | pubmsg.payload = payload_buffer; 1484 | pubmsg.payloadlen = payload_length; 1485 | pubmsg.qos = QOS; 1486 | pubmsg.retained = 0; 1487 | deliveredtoken = 0; 1488 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1489 | 1490 | // wait for messqge to be delivered to server 1491 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1492 | while (deliveredtoken != token) 1493 | ; 1494 | } 1495 | 1496 | fflush(stdout); 1497 | } 1498 | //end device type 2 1499 | 1500 | // device type 3 = Govee H5072 1501 | if (config.sensors[mac_index].type == 3) 1502 | { 1503 | //get the time that we received the scan response packet 1504 | time(&rawtime); 1505 | tm = *gmtime(&rawtime); 1506 | time_packet_received = localtime(&rawtime); 1507 | 1508 | int advertising_packet_type; // type of advertising packet 1509 | 1510 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 1511 | 1512 | // sensor data is broadcast in type 0 advertising message by the H5072 1513 | if (advertising_packet_type == 0) 1514 | { 1515 | // get rssi 1516 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 1517 | 1518 | if (logging_level == LOG_DEBUG) 1519 | { 1520 | fprintf(stdout, "=========\n"); 1521 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 1522 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1523 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1524 | fprintf(stdout, "rssi = %03d\n", rssi_int); 1525 | } 1526 | 1527 | // fprintf(stdout, "=========\n"); 1528 | // fprintf(stdout, "Current local time and date: %s", asctime (time_packet_received) ); 1529 | // fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1530 | // 1531 | // fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1532 | 1533 | sensor_data_start = 26; 1534 | 1535 | int below_32; 1536 | int msb; 1537 | 1538 | if ((adv_info->data[sensor_data_start + 0] & (1 << 7)) != 0) 1539 | { 1540 | below_32 = 1; 1541 | msb = adv_info->data[sensor_data_start + 0]; 1542 | msb &= ~(1UL << 7); 1543 | } 1544 | else 1545 | { 1546 | below_32 = 0; 1547 | msb = adv_info->data[sensor_data_start + 0]; 1548 | } 1549 | 1550 | unsigned int sensor_data = adv_info->data[sensor_data_start + 2] | adv_info->data[sensor_data_start + 1] << 8 | msb << 16; 1551 | 1552 | signed int temperature_int = sensor_data / 10000; 1553 | 1554 | // this crap code works for values below 0 degrees C but seems to bottomout about 12.2 degrees F, display shows values lower 1555 | // but not very accurate. Manual says range is 14 degrees F to 140 degrees F 1556 | // Humidity seems accurate thru range however 1557 | if (below_32 == 1) 1558 | { 1559 | temperature_int = temperature_int * -1; 1560 | } 1561 | 1562 | unsigned int humidity_int = (sensor_data % 1000) / 10; 1563 | 1564 | int32_t answer; 1565 | answer = (((int32_t)((int8_t)adv_info->data[sensor_data_start + 0])) << 16) + (((int32_t)adv_info->data[sensor_data_start + 1]) << 8) + adv_info->data[sensor_data_start + 2]; 1566 | 1567 | // convert the integer * 100 value for temperature and humidity to degrees fahrenheit and celsius (for homekit) and humidity percentage 1568 | 1569 | double temperature_fahrenheit; 1570 | double temperature_celsius; 1571 | temperature_fahrenheit = temperature_int * 9.0 / 5.0 + 32.0; 1572 | temperature_celsius = temperature_int; 1573 | 1574 | double humidity = humidity_int; 1575 | 1576 | // get battery level percentage 1577 | int battery_precentage_int = (signed char)adv_info->data[sensor_data_start + 3]; 1578 | 1579 | if (logging_level == LOG_DEBUG) 1580 | { 1581 | fprintf(stdout, "temp c = %.1f\n", temperature_celsius); 1582 | fprintf(stdout, "temp f = %.1f\n", temperature_fahrenheit); 1583 | fprintf(stdout, "humidity pct = %.1f\n", humidity); 1584 | fprintf(stdout, "battery pct = %3d\n", battery_precentage_int); 1585 | } 1586 | 1587 | // count the number of advertising packets we get from each unit 1588 | 1589 | config.sensors[mac_index].readings_per_hour = config.sensors[mac_index].readings_per_hour + 1; 1590 | 1591 | if (config.publish_type == 1) 1592 | { 1593 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1594 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac\":\"%s\",\"rssi\":%d,\"tempf\":%#.1F,\"units\":\"F\",\"tempc\":%#.1F,\"humidity\":%#.1F,\"batterypct\":%i,\"name\":\"%s\",\"location\":\"%s\",\"type\":\"%d\"}", 1595 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1596 | addr, rssi_int, temperature_fahrenheit, 1597 | temperature_celsius, 1598 | humidity, battery_precentage_int, 1599 | config.sensors[mac_index].name, 1600 | config.sensors[mac_index].location, 1601 | config.sensors[mac_index].type); 1602 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s/state", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1603 | } 1604 | else 1605 | { 1606 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1607 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac-address\":\"%s\",\"rssi\":%d,\"temperature\":%#.1F,\"units\":\"F\",\"temperature-celsius\":%#.1F,\"humidity\":%#.1F,\"battery-pct\":%i,\"sensor-name\":\"%s\",\"location\":\"%s\",\"sensor-type\":\"%d\"}", 1608 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1609 | addr, rssi_int, temperature_fahrenheit, 1610 | temperature_celsius, 1611 | humidity, battery_precentage_int, 1612 | config.sensors[mac_index].name, 1613 | config.sensors[mac_index].location, 1614 | config.sensors[mac_index].type); 1615 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1616 | } 1617 | 1618 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1619 | // if (payload_length >= payload_buff_size) 1620 | { 1621 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 1622 | exit(-1); 1623 | } 1624 | 1625 | // publish the message and wait for success 1626 | pubmsg.payload = payload_buffer; 1627 | pubmsg.payloadlen = payload_length; 1628 | pubmsg.qos = QOS; 1629 | pubmsg.retained = 0; 1630 | deliveredtoken = 0; 1631 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1632 | 1633 | // wait for messqge to be delivered to server 1634 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1635 | while (deliveredtoken != token) 1636 | ; 1637 | } 1638 | 1639 | if (advertising_packet_type == 4) 1640 | { 1641 | } 1642 | fflush(stdout); 1643 | } 1644 | // end device type 3 1645 | 1646 | // device type 4 = Govee H5102 1647 | if (config.sensors[mac_index].type == 4) 1648 | { 1649 | //get the time that we received the scan response packet 1650 | time(&rawtime); 1651 | tm = *gmtime(&rawtime); 1652 | time_packet_received = localtime(&rawtime); 1653 | 1654 | int advertising_packet_type; // type of advertising packet 1655 | 1656 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 1657 | 1658 | // sensor data is broadcast in type 0 advertising message by the H5072 1659 | if (advertising_packet_type == 0) 1660 | { 1661 | // get rssi 1662 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 1663 | 1664 | if (logging_level == LOG_DEBUG) 1665 | { 1666 | fprintf(stdout, "=========\n"); 1667 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 1668 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1669 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1670 | fprintf(stdout, "rssi = %03d\n", rssi_int); 1671 | } 1672 | 1673 | // fprintf(stdout, "=========\n"); 1674 | // fprintf(stdout, "Current local time and date: %s", asctime (time_packet_received) ); 1675 | // fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1676 | // 1677 | // fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1678 | 1679 | sensor_data_start = 27; 1680 | 1681 | int below_32; 1682 | int msb; 1683 | 1684 | if ((adv_info->data[sensor_data_start + 0] & (1 << 7)) != 0) 1685 | { 1686 | below_32 = 1; 1687 | msb = adv_info->data[sensor_data_start + 0]; 1688 | msb &= ~(1UL << 7); 1689 | } 1690 | else 1691 | { 1692 | below_32 = 0; 1693 | msb = adv_info->data[sensor_data_start + 0]; 1694 | } 1695 | 1696 | unsigned int sensor_data = adv_info->data[sensor_data_start + 2] | adv_info->data[sensor_data_start + 1] << 8 | msb << 16; 1697 | 1698 | signed int temperature_int = sensor_data / 10000; 1699 | 1700 | // this crap code works for values below 0 degrees C but seems to bottomout about 12.2 degrees F, display shows values lower 1701 | // but not very accurate. Manual says range is 14 degrees F to 140 degrees F 1702 | // Humidity seems accurate thru range however 1703 | if (below_32 == 1) 1704 | { 1705 | temperature_int = temperature_int * -1; 1706 | } 1707 | 1708 | unsigned int humidity_int = (sensor_data % 1000) / 10; 1709 | 1710 | int32_t answer; 1711 | answer = (((int32_t)((int8_t)adv_info->data[sensor_data_start + 0])) << 16) + (((int32_t)adv_info->data[sensor_data_start + 1]) << 8) + adv_info->data[sensor_data_start + 2]; 1712 | 1713 | // convert the integer * 100 value for temperature and humidity to degrees fahrenheit and celsius (for homekit) and humidity percentage 1714 | 1715 | double temperature_fahrenheit; 1716 | double temperature_celsius; 1717 | temperature_fahrenheit = temperature_int * 9.0 / 5.0 + 32.0; 1718 | temperature_celsius = temperature_int; 1719 | 1720 | double humidity = humidity_int; 1721 | // get battery level percentage 1722 | int battery_precentage_int = (signed char)adv_info->data[sensor_data_start + 3]; 1723 | 1724 | if (logging_level == LOG_DEBUG) 1725 | { 1726 | fprintf(stdout, "temp c = %.1f\n", temperature_celsius); 1727 | fprintf(stdout, "temp f = %.1f\n", temperature_fahrenheit); 1728 | fprintf(stdout, "humidity pct = %.1f\n", humidity); 1729 | fprintf(stdout, "battery pct = %3d\n", battery_precentage_int); 1730 | } 1731 | 1732 | // count the number of advertising packets we get from each unit 1733 | 1734 | config.sensors[mac_index].readings_per_hour = config.sensors[mac_index].readings_per_hour + 1; 1735 | 1736 | if (config.publish_type == 1) 1737 | { 1738 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1739 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac\":\"%s\",\"rssi\":%d,\"tempf\":%#.1F,\"units\":\"F\",\"tempc\":%#.1F,\"humidity\":%#.1F,\"batterypct\":%i,\"name\":\"%s\",\"location\":\"%s\",\"type\":\"%d\"}", 1740 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1741 | addr, rssi_int, temperature_fahrenheit, 1742 | temperature_celsius, 1743 | humidity, battery_precentage_int, 1744 | config.sensors[mac_index].name, 1745 | config.sensors[mac_index].location, 1746 | config.sensors[mac_index].type); 1747 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s/state", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1748 | } 1749 | else 1750 | { 1751 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1752 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac-address\":\"%s\",\"rssi\":%d,\"temperature\":%#.1F,\"units\":\"F\",\"temperature-celsius\":%#.1F,\"humidity\":%#.1F,\"battery-pct\":%i,\"sensor-name\":\"%s\",\"location\":\"%s\",\"sensor-type\":\"%d\"}", 1753 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1754 | addr, rssi_int, temperature_fahrenheit, 1755 | temperature_celsius, 1756 | humidity, battery_precentage_int, 1757 | config.sensors[mac_index].name, 1758 | config.sensors[mac_index].location, 1759 | config.sensors[mac_index].type); 1760 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1761 | } 1762 | 1763 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1764 | // if (payload_length >= payload_buff_size) 1765 | { 1766 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 1767 | exit(-1); 1768 | } 1769 | 1770 | // publish the message and wait for success 1771 | pubmsg.payload = payload_buffer; 1772 | pubmsg.payloadlen = payload_length; 1773 | pubmsg.qos = QOS; 1774 | pubmsg.retained = 0; 1775 | deliveredtoken = 0; 1776 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1777 | 1778 | // wait for messqge to be delivered to server 1779 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1780 | while (deliveredtoken != token) 1781 | ; 1782 | } 1783 | 1784 | if (advertising_packet_type == 4) 1785 | { 1786 | } 1787 | fflush(stdout); 1788 | } 1789 | // end device type 4 1790 | 1791 | // device type 5 = Govee H5075 1792 | if (config.sensors[mac_index].type == 5) 1793 | { 1794 | //get the time that we received the scan response packet 1795 | time(&rawtime); 1796 | tm = *gmtime(&rawtime); 1797 | time_packet_received = localtime(&rawtime); 1798 | 1799 | int advertising_packet_type; // type of advertising packet 1800 | 1801 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 1802 | 1803 | // sensor data is broadcast in type 0 advertising message by the H5072 1804 | if (advertising_packet_type == 0) 1805 | { 1806 | // get rssi 1807 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 1808 | 1809 | if (logging_level == LOG_DEBUG) 1810 | { 1811 | fprintf(stdout, "=========\n"); 1812 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 1813 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1814 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1815 | fprintf(stdout, "rssi = %03d\n", rssi_int); 1816 | } 1817 | 1818 | // fprintf(stdout, "=========\n"); 1819 | // fprintf(stdout, "Current local time and date: %s", asctime (time_packet_received) ); 1820 | // fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1821 | // 1822 | // fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1823 | 1824 | sensor_data_start = 26; 1825 | 1826 | int below_32; 1827 | int msb; 1828 | 1829 | if ((adv_info->data[sensor_data_start + 0] & (1 << 7)) != 0) 1830 | { 1831 | below_32 = 1; 1832 | msb = adv_info->data[sensor_data_start + 0]; 1833 | msb &= ~(1UL << 7); 1834 | } 1835 | else 1836 | { 1837 | below_32 = 0; 1838 | msb = adv_info->data[sensor_data_start + 0]; 1839 | } 1840 | 1841 | unsigned int sensor_data = adv_info->data[sensor_data_start + 2] | adv_info->data[sensor_data_start + 1] << 8 | msb << 16; 1842 | 1843 | double temperature_double = sensor_data / 1000 / 10.0; 1844 | 1845 | // this crap code works for values below 0 degrees C but seems to bottomout about 12.2 degrees F, display shows values lower 1846 | // but not very accurate. Manual says range is 14 degrees F to 140 degrees F 1847 | // Humidity seems accurate thru range however 1848 | if (below_32 == 1) 1849 | { 1850 | temperature_double = temperature_double * -1; 1851 | } 1852 | 1853 | double humidity_int = (sensor_data % 1000) / 10.0; 1854 | 1855 | int32_t answer; 1856 | answer = (((int32_t)((int8_t)adv_info->data[sensor_data_start + 0])) << 16) + (((int32_t)adv_info->data[sensor_data_start + 1]) << 8) + adv_info->data[sensor_data_start + 2]; 1857 | 1858 | // convert the values for temperature and humidity to degrees fahrenheit and celsius (for homekit) and humidity percentage 1859 | 1860 | double temperature_fahrenheit; 1861 | double temperature_celsius; 1862 | temperature_fahrenheit = temperature_double * 9.0 / 5.0 + 32.0; 1863 | temperature_celsius = temperature_double; 1864 | 1865 | double humidity = humidity_int; 1866 | // get battery level percentage 1867 | int battery_precentage_int = (signed char)adv_info->data[sensor_data_start + 3]; 1868 | 1869 | if (logging_level == LOG_DEBUG) 1870 | { 1871 | fprintf(stdout, "temp c = %.1f\n", temperature_celsius); 1872 | fprintf(stdout, "temp f = %.1f\n", temperature_fahrenheit); 1873 | fprintf(stdout, "humidity pct = %.1f\n", humidity); 1874 | fprintf(stdout, "battery pct = %3d\n", battery_precentage_int); 1875 | } 1876 | 1877 | // count the number of advertising packets we get from each unit 1878 | 1879 | config.sensors[mac_index].readings_per_hour = config.sensors[mac_index].readings_per_hour + 1; 1880 | 1881 | if (config.publish_type == 1) 1882 | { 1883 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1884 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac\":\"%s\",\"rssi\":%d,\"tempf\":%#.1F,\"units\":\"F\",\"tempc\":%#.1F,\"humidity\":%#.1F,\"batterypct\":%i,\"name\":\"%s\",\"location\":\"%s\",\"type\":\"%d\"}", 1885 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1886 | addr, rssi_int, temperature_fahrenheit, 1887 | temperature_celsius, 1888 | humidity, battery_precentage_int, 1889 | config.sensors[mac_index].name, 1890 | config.sensors[mac_index].location, 1891 | config.sensors[mac_index].type); 1892 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s/state", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1893 | } 1894 | else 1895 | { 1896 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 1897 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac-address\":\"%s\",\"rssi\":%d,\"temperature\":%#.1F,\"units\":\"F\",\"temperature-celsius\":%#.1F,\"humidity\":%#.1F,\"battery-pct\":%i,\"sensor-name\":\"%s\",\"location\":\"%s\",\"sensor-type\":\"%d\"}", 1898 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1899 | addr, rssi_int, temperature_fahrenheit, 1900 | temperature_celsius, 1901 | humidity, battery_precentage_int, 1902 | config.sensors[mac_index].name, 1903 | config.sensors[mac_index].location, 1904 | config.sensors[mac_index].type); 1905 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s", config.mqtt_base_topic, config.sensors[mac_index].my_id); 1906 | } 1907 | 1908 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 1909 | // if (payload_length >= payload_buff_size) 1910 | { 1911 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 1912 | exit(-1); 1913 | } 1914 | 1915 | // publish the message and wait for success 1916 | pubmsg.payload = payload_buffer; 1917 | pubmsg.payloadlen = payload_length; 1918 | pubmsg.qos = QOS; 1919 | pubmsg.retained = 0; 1920 | deliveredtoken = 0; 1921 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 1922 | 1923 | // wait for messqge to be delivered to server 1924 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 1925 | while (deliveredtoken != token) 1926 | ; 1927 | } 1928 | 1929 | if (advertising_packet_type == 4) 1930 | { 1931 | } 1932 | fflush(stdout); 1933 | } 1934 | // end device type 5 1935 | 1936 | // device type 6 = Govee H5074 1937 | if (config.sensors[mac_index].type == 6) 1938 | { 1939 | //get the time that we received the scan response packet 1940 | time(&rawtime); 1941 | tm = *gmtime(&rawtime); 1942 | time_packet_received = localtime(&rawtime); 1943 | 1944 | int advertising_packet_type; // type of advertising packet 1945 | 1946 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 1947 | 1948 | // sensor data is broadcast in type 0 advertising message by the H5072 1949 | if (advertising_packet_type == 0) 1950 | { 1951 | } 1952 | 1953 | if (advertising_packet_type == 4) 1954 | { 1955 | // get rssi 1956 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 1957 | 1958 | // this device sends sensor data only on this type of scan response advertising packet 1959 | 1960 | if ((int8_t)adv_info->data[0] == 0x0a) 1961 | { 1962 | 1963 | if (logging_level == LOG_DEBUG) 1964 | { 1965 | fprintf(stdout, "=========\n"); 1966 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 1967 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1968 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1969 | fprintf(stdout, "rssi = %03d\n", rssi_int); 1970 | } 1971 | 1972 | // fprintf(stdout, "=========\n"); 1973 | // fprintf(stdout, "Current local time and date: %s", asctime (time_packet_received) ); 1974 | // fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 1975 | // 1976 | // fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 1977 | 1978 | sensor_data_start = 5; 1979 | 1980 | // get the lsb msb byte pairs for temperature and humidity and convert them to an integer value (in 100's) 1981 | // temperature is a signed 16 bit integer to allow for temperatures below and above 0 degrees celsius 1982 | signed short int temperature_int = adv_info->data[sensor_data_start + 0] | adv_info->data[sensor_data_start + 1] << 8; 1983 | int humidity_int = adv_info->data[sensor_data_start + 2] | adv_info->data[sensor_data_start + 3] << 8; 1984 | 1985 | // convert the integer * 100 value for temperature and humidity to degrees fahrenheit and celsius (for homekit) and humidity percentage 1986 | 1987 | double temperature_fahrenheit; 1988 | double temperature_celsius; 1989 | temperature_fahrenheit = (temperature_int / 100.0) * 9.0 / 5.0 + 32.0; 1990 | temperature_celsius = (temperature_int / 100.0); 1991 | 1992 | double humidity = humidity_int / 100.0; 1993 | 1994 | // get battery level percentage 1995 | int battery_precentage_int = (signed char)adv_info->data[sensor_data_start + 4]; 1996 | 1997 | if (logging_level == LOG_DEBUG) 1998 | { 1999 | fprintf(stdout, "temp c = %.1f\n", temperature_celsius); 2000 | fprintf(stdout, "temp f = %.1f\n", temperature_fahrenheit); 2001 | fprintf(stdout, "humidity pct = %.1f\n", humidity); 2002 | fprintf(stdout, "battery pct = %3d\n", battery_precentage_int); 2003 | } 2004 | 2005 | // count the number of advertising packets we get from each unit 2006 | 2007 | config.sensors[mac_index].readings_per_hour = config.sensors[mac_index].readings_per_hour + 1; 2008 | 2009 | if (config.publish_type == 1) 2010 | { 2011 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 2012 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac\":\"%s\",\"rssi\":%d,\"tempf\":%#.1F,\"units\":\"F\",\"tempc\":%#.1F,\"humidity\":%#.1F,\"batterypct\":%i,\"name\":\"%s\",\"location\":\"%s\",\"type\":\"%d\"}", 2013 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 2014 | addr, rssi_int, temperature_fahrenheit, 2015 | temperature_celsius, 2016 | humidity, battery_precentage_int, 2017 | config.sensors[mac_index].name, 2018 | config.sensors[mac_index].location, 2019 | config.sensors[mac_index].type); 2020 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s/state", config.mqtt_base_topic, config.sensors[mac_index].my_id); 2021 | } 2022 | else 2023 | { 2024 | payload_length = snprintf(payload_buffer, MAXIMUM_JSON_MESSAGE, 2025 | "{\"timestamp\":\"%04d%02d%02d%02d%02d%02d\",\"mac-address\":\"%s\",\"rssi\":%d,\"temperature\":%#.1F,\"units\":\"F\",\"temperature-celsius\":%#.1F,\"humidity\":%#.1F,\"battery-pct\":%i,\"sensor-name\":\"%s\",\"location\":\"%s\",\"sensor-type\":\"%d\"}", 2026 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 2027 | addr, rssi_int, temperature_fahrenheit, 2028 | temperature_celsius, 2029 | humidity, battery_precentage_int, 2030 | config.sensors[mac_index].name, 2031 | config.sensors[mac_index].location, 2032 | config.sensors[mac_index].type); 2033 | topic_length = snprintf(topic_buffer, topic_buffer_size, "%s%s", config.mqtt_base_topic, config.sensors[mac_index].my_id); 2034 | } 2035 | 2036 | if (payload_length >= MAXIMUM_JSON_MESSAGE) 2037 | // if (payload_length >= payload_buff_size) 2038 | { 2039 | fprintf(stderr, "MQTT payload too long, %d\n", payload_length); 2040 | exit(-1); 2041 | } 2042 | 2043 | // publish the message and wait for success 2044 | pubmsg.payload = payload_buffer; 2045 | pubmsg.payloadlen = payload_length; 2046 | pubmsg.qos = QOS; 2047 | pubmsg.retained = 0; 2048 | deliveredtoken = 0; 2049 | MQTTClient_publishMessage(client, topic_buffer, &pubmsg, &token); 2050 | 2051 | // wait for messqge to be delivered to server 2052 | // printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", payload_buffer, topic_buffer, z_client_id_mqtt); 2053 | while (deliveredtoken != token) 2054 | ; 2055 | } 2056 | } 2057 | fflush(stdout); 2058 | } 2059 | // end device type 6 2060 | 2061 | // device type 99 = decoding 2062 | if (config.sensors[mac_index].type == 99) 2063 | { 2064 | //get the time that we received the scan response packet 2065 | time(&rawtime); 2066 | tm = *gmtime(&rawtime); 2067 | time_packet_received = localtime(&rawtime); 2068 | 2069 | int advertising_packet_type; // type of advertising packet 2070 | 2071 | advertising_packet_type = (unsigned int)ble_adv_buf[5]; 2072 | 2073 | if (advertising_packet_type == 0) 2074 | { 2075 | // counter for printing 2076 | int n; 2077 | 2078 | // get rssi 2079 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 2080 | 2081 | if (logging_level == LOG_DEBUG) 2082 | { 2083 | fprintf(stdout, "=========\n"); 2084 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 2085 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 2086 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 2087 | // print whole packet 2088 | printf("==>0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 \n"); 2089 | printf("==>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 \n"); 2090 | printf("==> 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2\n"); 2091 | printf("==> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 \n"); 2092 | printf("==>"); 2093 | for (n = 0; n < bluetooth_adv_packet_length; n++) 2094 | printf("%02X", (unsigned char)ble_adv_buf[n]); 2095 | printf("\n"); 2096 | printf("==>__________ad________________________mmmmmmmmmmmmtttthhbbzbzbccrr\n"); 2097 | fprintf(stdout, "rssi = %03d\n", rssi_int); 2098 | } 2099 | 2100 | // fprintf(stdout, "=========\n"); 2101 | // fprintf(stdout, "Current local time and date: %s", asctime (time_packet_received) ); 2102 | // fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 2103 | // 2104 | // fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 2105 | } 2106 | 2107 | if (advertising_packet_type == 4) 2108 | { 2109 | // counter for printing 2110 | int n; 2111 | 2112 | // get rssi 2113 | int rssi_int = (signed char)(int8_t)adv_info->data[adv_info->length]; 2114 | 2115 | fprintf(stdout, "=========\n"); 2116 | fprintf(stdout, "Current local time and date: %s", asctime(time_packet_received)); 2117 | fprintf(stdout, "mac address = %s location = %s device type = %d ", addr, config.sensors[mac_index].location, config.sensors[mac_index].type); 2118 | fprintf(stdout, "advertising_packet_type = %03d\n", advertising_packet_type); 2119 | // print whole packet 2120 | printf("==>0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 \n"); 2121 | printf("==>0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 \n"); 2122 | printf("==> 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2\n"); 2123 | printf("==> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 \n"); 2124 | printf("==>"); 2125 | for (n = 0; n < bluetooth_adv_packet_length; n++) 2126 | printf("%02X", (unsigned char)ble_adv_buf[n]); 2127 | printf("\n"); 2128 | printf("==>__________ad________________________mmmmmmmmmmmmtttthhbbzbzbccrr\n"); 2129 | fprintf(stdout, "rssi = %03d\n", rssi_int); 2130 | } 2131 | fflush(stdout); 2132 | } 2133 | // end device type 99 2134 | 2135 | } // end of Matched MAC address 2136 | 2137 | // if there are multiple advertising packets loop thru them 2138 | offset = adv_info->data + adv_info->length + 2; 2139 | } 2140 | } 2141 | } 2142 | } 2143 | 2144 | // -c to exit program received 2145 | fprintf(stdout, "\n-c signal received, exiting.\n"); 2146 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d -c signal received, exiting.", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 2147 | send_remote_syslog_message(LOG_INFO, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 2148 | syslog(LOG_INFO, "%s", log_message); 2149 | 2150 | // Disable scanning. 2151 | memset(&scan_cp, 0, sizeof(scan_cp)); 2152 | scan_cp.enable = 0x00; // Disable flag. 2153 | 2154 | struct hci_request disable_adv_rq = ble_hci_request(OCF_LE_SET_SCAN_ENABLE, LE_SET_SCAN_ENABLE_CP_SIZE, &status, &scan_cp); 2155 | ret = hci_send_req(bluetooth_device, &disable_adv_rq, 1000); 2156 | if (ret < 0) 2157 | { 2158 | hci_close_dev(bluetooth_device); 2159 | snprintf(log_message, LOGMESSAGESIZE, "%s v: %d.%d Failed to disable scan", PROGRAM_NAME, VERSION_MAJOR, VERSION_MINOR); 2160 | send_remote_syslog_message(LOG_ERR, RSYSLOG_ADDRESS, PROGRAM_NAME, log_message); 2161 | syslog(LOG_ERR, "%s", log_message); 2162 | fprintf(stdout, "Failed to disable scan, return code %d\n", ret); 2163 | exit(1); 2164 | } 2165 | 2166 | hci_close_dev(bluetooth_device); 2167 | 2168 | // end MQTT session 2169 | MQTTClient_disconnect(client, 10000); 2170 | MQTTClient_destroy(&client); 2171 | 2172 | exit(0); 2173 | } 2174 | 2175 | unsigned int 2176 | parser(config_t *config, char **argv) 2177 | { 2178 | /* Open file & declare libyaml types */ 2179 | FILE *fp = fopen(argv[1], "r"); 2180 | 2181 | if (fp == NULL) 2182 | { 2183 | fprintf(stdout, "ERROR: Failed to open config file: %s\n", argv[1]); 2184 | exit(EXIT_FAILURE); 2185 | } 2186 | 2187 | yaml_parser_t parser; 2188 | yaml_event_t event; 2189 | 2190 | bool seq_status = 0; /* IN or OUT of sequence index, init to OUT */ 2191 | unsigned int map_seq = 0; /* Index of mapping inside sequence */ 2192 | 2193 | init_prs(fp, &parser); /* Initiliaze parser & open file */ 2194 | 2195 | do 2196 | { 2197 | parse_next(&parser, &event); /* Parse new event */ 2198 | 2199 | /* Decide what to do with each event */ 2200 | event_switch(&seq_status, &map_seq, config, &parser, &event, fp); 2201 | 2202 | if (event.type != YAML_STREAM_END_EVENT) 2203 | { 2204 | yaml_event_delete(&event); 2205 | } 2206 | 2207 | if (map_seq > MAX_SENSORS) 2208 | { 2209 | break; 2210 | } 2211 | 2212 | } while (event.type != YAML_STREAM_END_EVENT); 2213 | 2214 | clean_prs(fp, &parser, &event); /* clean parser & close file */ 2215 | 2216 | return map_seq; 2217 | } 2218 | 2219 | void event_switch(bool *seq_status, unsigned int *map_seq, config_t *config, 2220 | yaml_parser_t *parser, yaml_event_t *event, FILE *fp) 2221 | { 2222 | switch (event->type) 2223 | { 2224 | case YAML_STREAM_START_EVENT: 2225 | break; 2226 | case YAML_STREAM_END_EVENT: 2227 | break; 2228 | case YAML_DOCUMENT_START_EVENT: 2229 | break; 2230 | case YAML_DOCUMENT_END_EVENT: 2231 | break; 2232 | case YAML_SEQUENCE_START_EVENT: 2233 | (*seq_status) = true; 2234 | break; 2235 | case YAML_SEQUENCE_END_EVENT: 2236 | (*seq_status) = false; 2237 | break; 2238 | case YAML_MAPPING_START_EVENT: 2239 | if (*seq_status == 1) 2240 | { 2241 | (*map_seq)++; 2242 | } 2243 | break; 2244 | case YAML_MAPPING_END_EVENT: 2245 | break; 2246 | case YAML_ALIAS_EVENT: 2247 | printf(" ERROR: Got alias (anchor %s)\n", 2248 | event->data.alias.anchor); 2249 | exit(EXIT_FAILURE); 2250 | break; 2251 | case YAML_SCALAR_EVENT: 2252 | to_data(seq_status, map_seq, config, parser, event, fp); 2253 | break; 2254 | case YAML_NO_EVENT: 2255 | puts(" ERROR: No event!"); 2256 | exit(EXIT_FAILURE); 2257 | break; 2258 | } 2259 | } 2260 | 2261 | void to_data(bool *seq_status, unsigned int *map_seq, config_t *config, 2262 | yaml_parser_t *parser, yaml_event_t *event, FILE *fp) 2263 | { 2264 | char *buf = (char *)event->data.scalar.value; 2265 | 2266 | /* Dictionary */ 2267 | char *mqtt_server_url = "mqtt_server_url"; 2268 | char *mqtt_base_topic = "mqtt_base_topic"; 2269 | char *mqtt_username = "mqtt_username"; 2270 | char *mqtt_password = "mqtt_password"; 2271 | char *bluetooth_adapter = "bluetooth_adapter"; 2272 | char *scan_type = "scan_type"; 2273 | char *scan_window = "scan_window"; 2274 | char *scan_interval = "scan_interval"; 2275 | char *publish_type = "publish_type"; 2276 | char *auto_configure = "auto_configure"; 2277 | char *auto_conf_stats = "auto_conf_stats"; 2278 | char *auto_conf_tempf = "auto_conf_tempf"; 2279 | char *auto_conf_tempc = "auto_conf_tempc"; 2280 | char *auto_conf_hum = "auto_conf_hum"; 2281 | char *auto_conf_battery = "auto_conf_battery"; 2282 | char *auto_conf_voltage = "auto_conf_voltage"; 2283 | char *auto_conf_signal = "auto_conf_signal"; 2284 | char *syslog_address = "syslog_address"; 2285 | char *logging_level = "logging_level"; 2286 | char *sensors = "sensors"; 2287 | 2288 | if (!strcmp(buf, mqtt_server_url)) 2289 | { 2290 | yaml_event_delete(event); 2291 | parse_next(parser, event); 2292 | strcpy(config->mqtt_server_url, (char *)event->data.scalar.value); 2293 | } 2294 | else if (!strcmp(buf, mqtt_base_topic)) 2295 | { 2296 | yaml_event_delete(event); 2297 | parse_next(parser, event); 2298 | strcpy(config->mqtt_base_topic, (char *)event->data.scalar.value); 2299 | } 2300 | else if (!strcmp(buf, mqtt_username)) 2301 | { 2302 | yaml_event_delete(event); 2303 | parse_next(parser, event); 2304 | strcpy(config->mqtt_username, (char *)event->data.scalar.value); 2305 | } 2306 | else if (!strcmp(buf, mqtt_password)) 2307 | { 2308 | yaml_event_delete(event); 2309 | parse_next(parser, event); 2310 | strcpy(config->mqtt_password, (char *)event->data.scalar.value); 2311 | } 2312 | else if (!strcmp(buf, bluetooth_adapter)) 2313 | { 2314 | yaml_event_delete(event); 2315 | parse_next(parser, event); 2316 | config->bluetooth_adapter = strtol((char *)event->data.scalar.value, NULL, 10); 2317 | } 2318 | else if (!strcmp(buf, scan_type)) 2319 | { 2320 | yaml_event_delete(event); 2321 | parse_next(parser, event); 2322 | config->scan_type = strtol((char *)event->data.scalar.value, NULL, 10); 2323 | } 2324 | else if (!strcmp(buf, scan_window)) 2325 | { 2326 | yaml_event_delete(event); 2327 | parse_next(parser, event); 2328 | config->scan_window = strtol((char *)event->data.scalar.value, NULL, 10); 2329 | } 2330 | else if (!strcmp(buf, scan_interval)) 2331 | { 2332 | yaml_event_delete(event); 2333 | parse_next(parser, event); 2334 | config->scan_interval = strtol((char *)event->data.scalar.value, NULL, 10); 2335 | } 2336 | else if (!strcmp(buf, publish_type)) 2337 | { 2338 | yaml_event_delete(event); 2339 | parse_next(parser, event); 2340 | config->publish_type = strtol((char *)event->data.scalar.value, NULL, 10); 2341 | } 2342 | else if (!strcmp(buf, auto_configure)) 2343 | { 2344 | yaml_event_delete(event); 2345 | parse_next(parser, event); 2346 | config->auto_configure = strtol((char *)event->data.scalar.value, NULL, 10); 2347 | } 2348 | else if (!strcmp(buf, auto_conf_stats)) 2349 | { 2350 | yaml_event_delete(event); 2351 | parse_next(parser, event); 2352 | config->auto_conf_stats = strtol((char *)event->data.scalar.value, NULL, 10); 2353 | } 2354 | else if (!strcmp(buf, auto_conf_tempf)) 2355 | { 2356 | yaml_event_delete(event); 2357 | parse_next(parser, event); 2358 | config->auto_conf_tempf = strtol((char *)event->data.scalar.value, NULL, 10); 2359 | } 2360 | else if (!strcmp(buf, auto_conf_tempc)) 2361 | { 2362 | yaml_event_delete(event); 2363 | parse_next(parser, event); 2364 | config->auto_conf_tempc = strtol((char *)event->data.scalar.value, NULL, 10); 2365 | } 2366 | else if (!strcmp(buf, auto_conf_hum)) 2367 | { 2368 | yaml_event_delete(event); 2369 | parse_next(parser, event); 2370 | config->auto_conf_hum = strtol((char *)event->data.scalar.value, NULL, 10); 2371 | } 2372 | else if (!strcmp(buf, auto_conf_battery)) 2373 | { 2374 | yaml_event_delete(event); 2375 | parse_next(parser, event); 2376 | config->auto_conf_battery = strtol((char *)event->data.scalar.value, NULL, 10); 2377 | } 2378 | else if (!strcmp(buf, auto_conf_voltage)) 2379 | { 2380 | yaml_event_delete(event); 2381 | parse_next(parser, event); 2382 | config->auto_conf_voltage = strtol((char *)event->data.scalar.value, NULL, 10); 2383 | } 2384 | else if (!strcmp(buf, auto_conf_signal)) 2385 | { 2386 | yaml_event_delete(event); 2387 | parse_next(parser, event); 2388 | config->auto_conf_signal = strtol((char *)event->data.scalar.value, NULL, 10); 2389 | } 2390 | else if (!strcmp(buf, syslog_address)) 2391 | { 2392 | yaml_event_delete(event); 2393 | parse_next(parser, event); 2394 | strcpy(config->syslog_address, (char *)event->data.scalar.value); 2395 | } 2396 | else if (!strcmp(buf, logging_level)) 2397 | { 2398 | yaml_event_delete(event); 2399 | parse_next(parser, event); 2400 | config->logging_level = strtol((char *)event->data.scalar.value, NULL, 10); 2401 | } 2402 | else if ((*seq_status) == true) 2403 | { 2404 | /* Data from sequence of sensors */ 2405 | to_data_from_map(buf, map_seq, config, parser, event, fp); 2406 | } 2407 | else if (!strcmp(buf, sensors)) 2408 | { 2409 | /* Do nothing, "sensors" is just the label of mapping's sequence */ 2410 | } 2411 | else 2412 | { 2413 | printf("\n -ERROR: Unknow variable in config file: %s\n", buf); 2414 | clean_prs(fp, parser, event); 2415 | exit(EXIT_FAILURE); 2416 | } 2417 | } 2418 | 2419 | void to_data_from_map(char *buf, unsigned int *map_seq, config_t *config, 2420 | yaml_parser_t *parser, yaml_event_t *event, FILE *fp) 2421 | { 2422 | /* Dictionary */ 2423 | char *name = "name"; 2424 | char *type = "type"; 2425 | char *mac = "mac"; 2426 | char *location = "location"; 2427 | char *unique = "unique"; 2428 | 2429 | if (!strcmp(buf, name)) 2430 | { 2431 | yaml_event_delete(event); 2432 | parse_next(parser, event); 2433 | strcpy(config->sensors[(*map_seq) - 1].name, 2434 | (char *)event->data.scalar.value); 2435 | } 2436 | else if (!strcmp(buf, type)) 2437 | { 2438 | yaml_event_delete(event); 2439 | parse_next(parser, event); 2440 | config->sensors[(*map_seq) - 1].type = 2441 | strtol((char *)event->data.scalar.value, NULL, 10); 2442 | } 2443 | else if (!strcmp(buf, mac)) 2444 | { 2445 | yaml_event_delete(event); 2446 | parse_next(parser, event); 2447 | config->sensors[(*map_seq) - 1].readings_per_hour = 0; 2448 | strcpy(config->sensors[(*map_seq) - 1].mac, 2449 | (char *)event->data.scalar.value); 2450 | } 2451 | else if (!strcmp(buf, location)) 2452 | { 2453 | yaml_event_delete(event); 2454 | parse_next(parser, event); 2455 | strcpy(config->sensors[(*map_seq) - 1].location, 2456 | (char *)event->data.scalar.value); 2457 | } 2458 | else if (!strcmp(buf, unique)) 2459 | { 2460 | yaml_event_delete(event); 2461 | parse_next(parser, event); 2462 | strcpy(config->sensors[(*map_seq) - 1].unique, 2463 | (char *)event->data.scalar.value); 2464 | } 2465 | else 2466 | { 2467 | printf("\n -ERROR: Unknow variable in config file: %s\n", buf); 2468 | clean_prs(fp, parser, event); 2469 | exit(EXIT_FAILURE); 2470 | } 2471 | } 2472 | 2473 | void parse_next(yaml_parser_t *parser, yaml_event_t *event) 2474 | { 2475 | /* Parse next scalar. if wrong exit with error */ 2476 | if (!yaml_parser_parse(parser, event)) 2477 | { 2478 | printf("Parser error %d\n", parser->error); 2479 | exit(EXIT_FAILURE); 2480 | } 2481 | } 2482 | 2483 | void init_prs(FILE *fp, yaml_parser_t *parser) 2484 | { 2485 | /* Parser initilization */ 2486 | if (!yaml_parser_initialize(parser)) 2487 | { 2488 | fputs("Failed to initialize parser!\n", stderr); 2489 | } 2490 | 2491 | if (fp == NULL) 2492 | { 2493 | fputs("Failed to open file!\n", stderr); 2494 | } 2495 | 2496 | yaml_parser_set_input_file(parser, fp); 2497 | } 2498 | 2499 | void clean_prs(FILE *fp, yaml_parser_t *parser, yaml_event_t *event) 2500 | { 2501 | yaml_event_delete(event); /* Delete event */ 2502 | yaml_parser_delete(parser); /* Delete parser */ 2503 | fclose(fp); /* Close file */ 2504 | } 2505 | 2506 | void print_data(unsigned int sensor_count, config_t *config) 2507 | { 2508 | puts("\n --- data structure after parsing ---"); 2509 | printf(" mqtt_server_url = %s\n", config->mqtt_server_url); 2510 | printf(" mqtt_base_topic = %s\n", config->mqtt_base_topic); 2511 | printf(" mqtt_username = %s\n", config->mqtt_username); 2512 | printf(" mqtt_password = %s\n", config->mqtt_password); 2513 | printf(" bluetooth_adapter = %i\n", config->bluetooth_adapter); 2514 | printf(" scan_type = %i\n", config->scan_type); 2515 | printf(" scan_window = %i\n", config->scan_window); 2516 | printf(" scan_interval = %i\n", config->scan_interval); 2517 | printf(" publish_type = %i\n", config->publish_type); 2518 | printf(" auto_configure = %i\n", config->auto_configure); 2519 | printf(" auto_conf_stats = %i\n", config->auto_conf_stats); 2520 | printf(" auto_conf_tempf = %i\n", config->auto_conf_tempf); 2521 | printf(" auto_conf_tempc = %i\n", config->auto_conf_tempc); 2522 | printf(" auto_conf_hum = %i\n", config->auto_conf_hum); 2523 | printf(" auto_conf_battery = %i\n", config->auto_conf_battery); 2524 | printf(" auto_conf_voltage = %i\n", config->auto_conf_voltage); 2525 | printf(" auto_conf_signal = %i\n", config->auto_conf_signal); 2526 | printf(" syslog_address = %s\n", config->syslog_address); 2527 | printf(" logging_level = %i\n", config->logging_level); 2528 | 2529 | puts(" sensor configs:"); 2530 | puts("\t -----------------"); 2531 | for (int i = 0; i < (int)sensor_count; i++) 2532 | { 2533 | printf("\t name = %s\n", config->sensors[i].name); 2534 | printf("\t unique = %s\n", config->sensors[i].unique); 2535 | printf("\t location = %s\n", config->sensors[i].location); 2536 | printf("\t type = %i\n", config->sensors[i].type); 2537 | printf("\t mac = %s\n", config->sensors[i].mac); 2538 | puts("\t -----------------"); 2539 | } 2540 | } 2541 | --------------------------------------------------------------------------------