Skip to content

Commit 6681c3e

Browse files
committed
lil fixes & edits
fixed problem w/ importing libraries in python...
1 parent e60b9de commit 6681c3e

File tree

11 files changed

+42
-37
lines changed

11 files changed

+42
-37
lines changed

App/app/src/main/java/isel/seaspot/bluetooth/BLE_Manager.kt

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import android.content.Context
77
import android.content.Intent
88
import android.os.Handler
99
import androidx.activity.result.ActivityResultLauncher
10+
import androidx.compose.ui.res.stringResource
11+
import androidx.core.os.postDelayed
1012
import isel.seaspot.R
1113
import isel.seaspot.utils.*
1214
import java.util.*
@@ -28,7 +30,8 @@ import kotlin.concurrent.withLock
2830
* @see bluetoothGattCallback - [8] https://medium.com/@martijn.van.welie/making-android-ble-work-part-2-47a3cdaade07#:~:text=int%20bondstate%20%3D-,device.getBondState()%3B,-The%20bond%20state
2931
* @see bluetoothGattCallback - [9] https://medium.com/@martijn.van.welie/making-android-ble-work-part-2-47a3cdaade07#:~:text=have%20to%20add%20a%201000%E2%80%931500%20ms%20delay.
3032
* @see bluetoothGattCallback - [10] https://developer.android.com/reference/android/bluetooth/BluetoothGatt#discoverServices()
31-
* @see bluetoothGattCallback - [11] https://issuetracker.google.com/issues/228984309 https://stackoverflow.com/q/32363931
33+
* @see bluetoothGattCallback - [11] https://issuetracker.google.com/issues/228984309 / https://stackoverflow.com/q/32363931
34+
* @see bluetoothGattCallback - [11.b] https://stackoverflow.com/q/41434555
3235
* @see clearServicesCache - [12] https://medium.com/@martijn.van.welie/making-android-ble-work-part-2-47a3cdaade07#:~:text=the%20services%0A...-,Caching%20of%20services,-The%20Android%20stack
3336
* @see setCharacteristicNotification - [13] https://developer.android.com/guide/topics/connectivity/bluetooth/transfer-ble-data#notification
3437
*/
@@ -173,9 +176,12 @@ class BLE_Manager(
173176
if(bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDED) { //consider [9]
174177
onConnectionSuccessful()
175178
log("BOND_BONDED")
176-
val areThereServices = gatt?.discoverServices() //[10]
177-
if(areThereServices == true) log("Started onServicesDiscovered()")
178-
else log("Couldn't call onServicesDiscovered()")
179+
180+
handler.postDelayed({ //Sometimes service discovery shouldn't be made immediately will not be called [11.b]
181+
val areThereServices = gatt?.discoverServices() //[10]
182+
if(areThereServices == true) log("Started onServicesDiscovered()")
183+
else log("Couldn't call onServicesDiscovered()")
184+
}, 1000)
179185
} else if (bondState == BluetoothDevice.BOND_BONDING) {
180186
log("waiting for bonding to complete")
181187
}
@@ -208,6 +214,7 @@ class BLE_Manager(
208214

209215
//This method sometimes will have gatt?.services empty [11]
210216
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
217+
log("onServicesDiscovered()")
211218
if (status == BluetoothGatt.GATT_SUCCESS) {
212219
log("onServicesDiscovered received -> GATT_SUCCESS, ${currThread()}")
213220
log("Services = ${gatt?.services?.map { "${it.uuid} (${AssignedNumbersService.uuidToEnum(it.uuid).name})" } }")
@@ -216,6 +223,7 @@ class BLE_Manager(
216223
onServicesDiscovered()
217224
} else {
218225
log("SERVICES NOT FOUND")
226+
//toast(R.string.servicesNotFound, ctx)
219227
}
220228
}
221229
else log("onServicesDiscovered received: $status")

App/app/src/main/java/isel/seaspot/screens/ConnectedDeviceScreen.kt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,11 +192,10 @@ fun CharacteristicDisplay(
192192
if(r_id!=null) characName = "${stringResource(r_id.characName_R_ID)}"
193193
else characName += " (ID = ${characteristic.value[0]})"
194194
}*/
195-
if (characteristic.value.decodeToString().isDigitsOnly())
196-
Text("${stringResource(R.string.value)}: ${characteristic.value[0]}")
197-
else{
198-
Text("${stringResource(R.string.value)}: ${characteristic.value.decodeToString()}")
199-
}
195+
val characValue = characteristic.value.decodeToString()
196+
log("CharacValue = $characValue") // note, even if you do characteristic.value[0] you will obtain the byte of the UTF character!!! not the 'value' itself!
197+
Text("${stringResource(R.string.value)}: $characValue")
198+
200199
} else {
201200
log("Text raw = ${characteristic.value.toList()}. String = ${characteristic.value.decodeToString()}")
202201
var text by rememberSaveable { mutableStateOf(characteristic.value.decodeToString()) }

App/app/src/main/java/isel/seaspot/screens/MainScreen.kt

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,6 @@ fun MainScreen(vm: MainViewModel, navController: NavController) {
4040
var isSnackbarOpen by remember { mutableStateOf(false) }
4141
var onSnackbarOk: () -> Unit by remember { mutableStateOf({}) }
4242

43-
var registredDevAddr by remember { mutableStateOf(readExpectedDeviceAddress(ctx)) }
44-
4543
Column {
4644
TopAppBar(
4745
title = {
@@ -88,7 +86,7 @@ fun MainScreen(vm: MainViewModel, navController: NavController) {
8886
if (vm.devicesFound.isNotEmpty()) {
8987
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
9088
items(vm.devicesFound.toList().sortedByDescending { it.second.name!=null }) {
91-
ListOfDevices({
89+
ListOfDevices({ //it -> Pair.first = deviceAddress, Pair.second = BluetoothDevice
9290
val onClick = {
9391
log("will connect to device")
9492
toast(R.string.connecting, ctx)
@@ -103,7 +101,8 @@ fun MainScreen(vm: MainViewModel, navController: NavController) {
103101
Unit
104102
}
105103

106-
if(it.first!=registredDevAddr){
104+
if(it.first!=readExpectedDeviceAddress(ctx)){
105+
log("Clicked on unregistered device")
107106
onSnackbarOk = onClick
108107
isSnackbarOpen = true
109108
} else onClick()

App/app/src/main/java/isel/seaspot/utils/appUserOptions.kt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package isel.seaspot.utils
22

3-
import android.app.Application
43
import android.content.Context
54
import androidx.appcompat.app.AppCompatActivity
65
import java.io.FileNotFoundException
76

7+
/**
8+
* Contains code related to double checking the connection to a not expected device (soft security)
9+
*/
10+
811
const val expectedDeviceAddressFile = "expectedDeviceAddress.txt"
912

1013
fun writeExpectedDeviceAddress(context: Context, address: String) { //https://developer.android.com/training/data-storage/app-specific

App/app/src/main/res/values-pt-rPT/strings.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,5 @@
3636
<string name="cancel">Cancelar</string>
3737
<string name="ok">Ok</string>
3838
<string name="note_dev_addr">Nota: O dispositivo escolhido é differente do esperado</string>
39+
<string name="servicesNotFound">Serviços não encontrados</string>
3940
</resources>

App/app/src/main/res/values/strings.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,5 @@
3535
<string name="cancel">Cancel</string>
3636
<string name="ok">Ok</string>
3737
<string name="note_dev_addr">Note: Registred device address is different than selected</string>
38+
<string name="servicesNotFound">Services not found</string>
3839
</resources>

Pycom/lib/gps_data.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
2-
from micropygps import MicropyGPS
1+
from micropyGPS import MicropyGPS
32
from machine import UART
43
import array
54
import time
65

76

87
class GPS_data():
98

10-
def __init__(self,uart_pins):
9+
def __init__(self, uart_pins):
1110
self.uart = UART(1, 9600, pins=uart_pins)
1211
time.sleep(0.5)
1312
self.gps_dev = MicropyGPS(location_formatting='dd')
File renamed without changes.

Pycom/main.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@
77
from network import LoRa
88
from network import Bluetooth
99
from machine import Timer
10-
from machine import ADC
11-
12-
import gps_data
1310

14-
import axp202
11+
from machine import ADC
1512
from machine import UART
1613

14+
from lib import gps_data
15+
from lib import axp202
1716

17+
# Note: in VSC some imports are underlined with red, this is from VSC and python extensions, but the libraries are present in the TTGO
1818

1919
def uuid2bytes(uuid):
2020
uuid = uuid.encode().replace(b'-',b'')
@@ -43,40 +43,32 @@ def receive_data(characteristicPort):
4343
joiner.send_data_bytes(bytes([1]), characteristicPort) # makes uplink, necessary to make an downlink after. Fport will be 2 by default
4444
# time.sleep(2.5)
4545
data, fport = joiner.receive_data_blocking() # receive the latest downlink that put in our applciation
46-
find_port= 0x1
4746
print('receive_data: ', data)
4847
print("received fport: {}".format(fport))
4948
if fport==ID_USERDATA_STRING:
50-
find_port=fport
5149
chr1.value(data) # https://docs.pycom.io/firmwareapi/pycom/network/bluetooth/gattscharacteristic/
5250
print('ID_USERDATA_STRING: ', chr1.value())
5351
elif fport==ID_BATTERY_ENERGY_STATUS:
54-
find_port=fport
5552
chr2.value(data)
5653
print('ID_BATTERY_ENERGY_STATUS: ', chr2.value())
57-
5854
elif fport==ID_LOCATION_LATITUDE:
59-
find_port=fport
6055
chr3.value(data)
6156
print('ID_LOCATION_LATITUDE: ', chr3.value())
6257
elif fport==ID_LOCATION_LONGITUDE:
63-
find_port=fport
6458
chr4.value(data)
6559
print('ID_LOCATION_LONGITUDE: ', chr4.value())
66-
6760
elif fport==ID_PHONE_ID:
68-
find_port=fport
6961
chr5.value(data)
7062
print('ID_PHONE_ID: ', chr5.value())
7163
elif fport==ID_BROADCAST_STRING:
72-
find_port=fport
7364
chr6.value(data)
7465
print('ID_BROADCAST_STRING: ', chr6.value())
75-
7666
else:
7767
print('Unregistered port was set upon the scheduled downlink, ignoring')
7868
# Write the fport value to the ObjectTranfer (service) -> Refresh (charac)
79-
chr7.value(find_port)
69+
fport_str = str(fport)
70+
print("fport_str for chr7: {}".format(fport_str))
71+
chr7.value(fport_str)
8072

8173

8274
def encodePayloadWithCharacIdentifier(value, id): # no longer in use, it was used to add the characteristic identifier in the payload, but now we use Fport. The identifiers were previously byte arrays like: ID_USERDATA_STRING = [0x1]
@@ -233,7 +225,7 @@ def char8_cb_handler(chr, data):
233225
chr8 = srv3.characteristic(uuid=CHARACTERISTIC_REFRESH_LOCATION, value="Default")
234226
chr7_cb = chr8.callback(trigger=Bluetooth.CHAR_READ_EVENT | Bluetooth.CHAR_WRITE_EVENT, handler=char8_cb_handler)
235227

236-
print('Start BLE Service')
228+
print('Started BLE Service')
237229

238230
"""
239231
Micropython code for TTGO T-Beam V1.0 and V1.1 to enable GPS in micropython pycom variant
@@ -248,11 +240,14 @@ def char8_cb_handler(chr, data):
248240
For T22_v1.0 20190612 and the T22_v1.1 20191212 and T22_v1.1 2021
249241
"""
250242

243+
# GPS & Battery Voltage methods
244+
gpsPins = ('G12','G34')
245+
251246
axp=axp202.PMU(address=axp202.AXP192_SLAVE_ADDRESS)
252247
axp.setLDO3Voltage(3300) # T-Beam GPS VDD 3v3
253248
axp.enablePower(axp202.AXP192_LDO3)
254249

255-
dev = UART(1, 9600, pins=('G12','G34'))
250+
dev = UART(1, 9600, pins=gpsPins)
256251
msg = b'\xb5b\x06\x00\x14\x00\x01\x00\x00\x00\xd0\x08\x00\x00\x80%\x00\x00\x07\x00\x03\x00\x00\x00\x00\x00\xa2\xb5'
257252
dev.write(msg)
258253

@@ -268,13 +263,13 @@ def updateBatteryVoltage(): # https://docs.pycom.io/tutorials/expansionboards/vb
268263
return level
269264

270265
def getGPSCoordinates():
271-
gps = gps_data.GPS_data(['G12', 'G34'])
266+
gps = gps_data.GPS_data(gpsPins) # The same pins indicaded on the side where the brick colored & shaped chip is placed at
272267
gps_array, timestamp, valid = gps.get_loc()
273268

274269
# decoded_gps = decode_gps_array(gps_array)
275270

276271
# print("decoded gps ", decoded_gps["data"])
277-
return {'gps_array': gps_array, 'timestamp':timestamp, 'valid':valid}
272+
return {'gps_array': gps_array, 'timestamp': timestamp, 'valid': valid}
278273

279274
def decode_gps_array(input):
280275
bytes = input

WebApp/data/Device.mjs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export class Device {
3030
constructor(id, deviceObj){
3131
this.id = id
3232
this.deviceObj = deviceObj
33+
this.deviceObj.setCharacteristic = new DeviceObj("", "").setCharacteristic //get the setCharacteristic method
3334
}
3435
}
3536

WebApp/data/data-elastic.mjs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,6 @@ function elasticDB(config){
186186
if(obj.found==false) throw new NotFound(errorMsgs.deviceNotFound(id))
187187

188188
const device = new Device(obj._id, obj._source)
189-
device.deviceObj.setCharacteristic = new DeviceObj("", "").setCharacteristic //get the setCharacteristic method
190189
const wasSet = device.deviceObj.setCharacteristic(characteristic, value)
191190
if(wasSet) await elasticFetx.updateDoc(ourIndexes.devices, device.id, device.deviceObj)
192191
}

0 commit comments

Comments
 (0)