15.09.2020, 08:31
I'm trying to get the Button Presses from the Sensor via the SensorTag BLE script provided in the LM.
I'm getting Data like Humidity etc, but no matter what i tried the button values don't update on button press.
I'm getting Data like Humidity etc, but no matter what i tried the button values don't update on button press.
Code:
return {
manufacturer = 'TI',
description = 'SensorTag',
default_name = 'SensorTag',
version = 2,
objects = {
{
id = 'temp',
name = 'Temperature',
datatype = dt.temperature
},
{
id = 'hum',
name = 'Humidity',
datatype = dt.scale
},
{
id = 'button1',
name = 'Button 1',
datatype = dt.switch
},
{
id = 'button2',
name = 'Button 2',
datatype = dt.switch
}
},
init = function(device)
local objects = device.objects
if not objects.button1 and not objects.button2 then
device.profile.step = nil
end
if not objects.temp and not objects.hum then
device.profile.read = nil
end
end,
setbutton = function(device, button, value)
local key = 'button' .. button
if device[ key ] ~= value then
device.writeobject(key, value)
device[ key ] = value
end
end,
step = function(device)
local sock, res, data, err, setbutton
sock = device.sock
setbutton = device.profile.setbutton
if not sock then
sock = ble.sock()
ble.settimeout(sock, 1)
-- try connecting
res = ble.connect(sock, device.mac)
if not res then
ble.close(sock)
device.setactive(false)
os.sleep(5)
return
end
-- enable button notification
ble.sockwritecmd(sock, 0x60, 1, 0)
device.sock = sock
setbutton(device, 1, false)
setbutton(device, 2, false)
end
res, data = ble.sockreadnotify(sock, 1)
-- read ok
if res then
data = data:byte(1)
setbutton(device, 1, bit.band(data, 1) == 1)
setbutton(device, 2, bit.band(data, 2) == 2)
device.setactive(true)
-- timeout or disconnect
else
res, err = ble.check(sock)
-- disconnect
if not res or err ~= 0 then
ble.close(sock)
device.sock = nil
end
end
end,
read = function(device)
local sock, res, status, values, rssi
if device.profile.step then
sock = device.sock
res = sock
else
sock = ble.sock()
ble.settimeout(sock, 1)
res = ble.connect(sock, device.mac)
end
-- connect ok, enable sensor, wait for conversion to finish, read the result
if res then
ble.sockwritecmd(sock, 0x3C, 1)
os.sleep(0.1)
res = ble.sockreadhnd(sock, 0x38)
-- read ok
if res then
status = true
values = {}
rssi = ble.getrssi(device.mac)
-- convert temperature
tmp = bit.bor(bit.lshift(res:byte(2), 8), res:byte(1))
tmp = -46.85 + 175.72 / 65536 * tmp;
values.temp = math.floor(tmp * 10) / 10
-- convert humidity
tmp = bit.bor(bit.lshift(res:byte(4), 8), res:byte(3))
tmp = -6.0 + 125.0 / 65536 * bit.band(tmp, 0xFFFC)
values.hum = math.floor(tmp + 0.5)
end
-- disable sensor
ble.sockwritecmd(sock, 0x3C, 0)
end
if not device.profile.step then
ble.close(sock)
end
return status, values, rssi
end
}