Skip to content

Commit

Permalink
lil fixes & edits
Browse files Browse the repository at this point in the history
fixed problem w/ importing libraries in python...
  • Loading branch information
p4ulor committed Jul 18, 2023
1 parent e60b9de commit 6681c3e
Show file tree
Hide file tree
Showing 11 changed files with 42 additions and 37 deletions.
16 changes: 12 additions & 4 deletions App/app/src/main/java/isel/seaspot/bluetooth/BLE_Manager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import android.content.Context
import android.content.Intent
import android.os.Handler
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.ui.res.stringResource
import androidx.core.os.postDelayed
import isel.seaspot.R
import isel.seaspot.utils.*
import java.util.*
Expand All @@ -28,7 +30,8 @@ import kotlin.concurrent.withLock
* @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
* @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.
* @see bluetoothGattCallback - [10] https://developer.android.com/reference/android/bluetooth/BluetoothGatt#discoverServices()
* @see bluetoothGattCallback - [11] https://issuetracker.google.com/issues/228984309 https://stackoverflow.com/q/32363931
* @see bluetoothGattCallback - [11] https://issuetracker.google.com/issues/228984309 / https://stackoverflow.com/q/32363931
* @see bluetoothGattCallback - [11.b] https://stackoverflow.com/q/41434555
* @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
* @see setCharacteristicNotification - [13] https://developer.android.com/guide/topics/connectivity/bluetooth/transfer-ble-data#notification
*/
Expand Down Expand Up @@ -173,9 +176,12 @@ class BLE_Manager(
if(bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDED) { //consider [9]
onConnectionSuccessful()
log("BOND_BONDED")
val areThereServices = gatt?.discoverServices() //[10]
if(areThereServices == true) log("Started onServicesDiscovered()")
else log("Couldn't call onServicesDiscovered()")

handler.postDelayed({ //Sometimes service discovery shouldn't be made immediately will not be called [11.b]
val areThereServices = gatt?.discoverServices() //[10]
if(areThereServices == true) log("Started onServicesDiscovered()")
else log("Couldn't call onServicesDiscovered()")
}, 1000)
} else if (bondState == BluetoothDevice.BOND_BONDING) {
log("waiting for bonding to complete")
}
Expand Down Expand Up @@ -208,6 +214,7 @@ class BLE_Manager(

//This method sometimes will have gatt?.services empty [11]
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
log("onServicesDiscovered()")
if (status == BluetoothGatt.GATT_SUCCESS) {
log("onServicesDiscovered received -> GATT_SUCCESS, ${currThread()}")
log("Services = ${gatt?.services?.map { "${it.uuid} (${AssignedNumbersService.uuidToEnum(it.uuid).name})" } }")
Expand All @@ -216,6 +223,7 @@ class BLE_Manager(
onServicesDiscovered()
} else {
log("SERVICES NOT FOUND")
//toast(R.string.servicesNotFound, ctx)
}
}
else log("onServicesDiscovered received: $status")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,10 @@ fun CharacteristicDisplay(
if(r_id!=null) characName = "${stringResource(r_id.characName_R_ID)}"
else characName += " (ID = ${characteristic.value[0]})"
}*/
if (characteristic.value.decodeToString().isDigitsOnly())
Text("${stringResource(R.string.value)}: ${characteristic.value[0]}")
else{
Text("${stringResource(R.string.value)}: ${characteristic.value.decodeToString()}")
}
val characValue = characteristic.value.decodeToString()
log("CharacValue = $characValue") // note, even if you do characteristic.value[0] you will obtain the byte of the UTF character!!! not the 'value' itself!
Text("${stringResource(R.string.value)}: $characValue")

} else {
log("Text raw = ${characteristic.value.toList()}. String = ${characteristic.value.decodeToString()}")
var text by rememberSaveable { mutableStateOf(characteristic.value.decodeToString()) }
Expand Down
7 changes: 3 additions & 4 deletions App/app/src/main/java/isel/seaspot/screens/MainScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ fun MainScreen(vm: MainViewModel, navController: NavController) {
var isSnackbarOpen by remember { mutableStateOf(false) }
var onSnackbarOk: () -> Unit by remember { mutableStateOf({}) }

var registredDevAddr by remember { mutableStateOf(readExpectedDeviceAddress(ctx)) }

Column {
TopAppBar(
title = {
Expand Down Expand Up @@ -88,7 +86,7 @@ fun MainScreen(vm: MainViewModel, navController: NavController) {
if (vm.devicesFound.isNotEmpty()) {
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(vm.devicesFound.toList().sortedByDescending { it.second.name!=null }) {
ListOfDevices({
ListOfDevices({ //it -> Pair.first = deviceAddress, Pair.second = BluetoothDevice
val onClick = {
log("will connect to device")
toast(R.string.connecting, ctx)
Expand All @@ -103,7 +101,8 @@ fun MainScreen(vm: MainViewModel, navController: NavController) {
Unit
}

if(it.first!=registredDevAddr){
if(it.first!=readExpectedDeviceAddress(ctx)){
log("Clicked on unregistered device")
onSnackbarOk = onClick
isSnackbarOpen = true
} else onClick()
Expand Down
5 changes: 4 additions & 1 deletion App/app/src/main/java/isel/seaspot/utils/appUserOptions.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package isel.seaspot.utils

import android.app.Application
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import java.io.FileNotFoundException

/**
* Contains code related to double checking the connection to a not expected device (soft security)
*/

const val expectedDeviceAddressFile = "expectedDeviceAddress.txt"

fun writeExpectedDeviceAddress(context: Context, address: String) { //https://developer.android.com/training/data-storage/app-specific
Expand Down
1 change: 1 addition & 0 deletions App/app/src/main/res/values-pt-rPT/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@
<string name="cancel">Cancelar</string>
<string name="ok">Ok</string>
<string name="note_dev_addr">Nota: O dispositivo escolhido é differente do esperado</string>
<string name="servicesNotFound">Serviços não encontrados</string>
</resources>
1 change: 1 addition & 0 deletions App/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@
<string name="cancel">Cancel</string>
<string name="ok">Ok</string>
<string name="note_dev_addr">Note: Registred device address is different than selected</string>
<string name="servicesNotFound">Services not found</string>
</resources>
5 changes: 2 additions & 3 deletions Pycom/lib/gps_data.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@

from micropygps import MicropyGPS
from micropyGPS import MicropyGPS
from machine import UART
import array
import time


class GPS_data():

def __init__(self,uart_pins):
def __init__(self, uart_pins):
self.uart = UART(1, 9600, pins=uart_pins)
time.sleep(0.5)
self.gps_dev = MicropyGPS(location_formatting='dd')
Expand Down
File renamed without changes.
33 changes: 14 additions & 19 deletions Pycom/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
from network import LoRa
from network import Bluetooth
from machine import Timer
from machine import ADC

import gps_data

import axp202
from machine import ADC
from machine import UART

from lib import gps_data
from lib import axp202

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

def uuid2bytes(uuid):
uuid = uuid.encode().replace(b'-',b'')
Expand Down Expand Up @@ -43,40 +43,32 @@ def receive_data(characteristicPort):
joiner.send_data_bytes(bytes([1]), characteristicPort) # makes uplink, necessary to make an downlink after. Fport will be 2 by default
# time.sleep(2.5)
data, fport = joiner.receive_data_blocking() # receive the latest downlink that put in our applciation
find_port= 0x1
print('receive_data: ', data)
print("received fport: {}".format(fport))
if fport==ID_USERDATA_STRING:
find_port=fport
chr1.value(data) # https://docs.pycom.io/firmwareapi/pycom/network/bluetooth/gattscharacteristic/
print('ID_USERDATA_STRING: ', chr1.value())
elif fport==ID_BATTERY_ENERGY_STATUS:
find_port=fport
chr2.value(data)
print('ID_BATTERY_ENERGY_STATUS: ', chr2.value())

elif fport==ID_LOCATION_LATITUDE:
find_port=fport
chr3.value(data)
print('ID_LOCATION_LATITUDE: ', chr3.value())
elif fport==ID_LOCATION_LONGITUDE:
find_port=fport
chr4.value(data)
print('ID_LOCATION_LONGITUDE: ', chr4.value())

elif fport==ID_PHONE_ID:
find_port=fport
chr5.value(data)
print('ID_PHONE_ID: ', chr5.value())
elif fport==ID_BROADCAST_STRING:
find_port=fport
chr6.value(data)
print('ID_BROADCAST_STRING: ', chr6.value())

else:
print('Unregistered port was set upon the scheduled downlink, ignoring')
# Write the fport value to the ObjectTranfer (service) -> Refresh (charac)
chr7.value(find_port)
fport_str = str(fport)
print("fport_str for chr7: {}".format(fport_str))
chr7.value(fport_str)


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]
Expand Down Expand Up @@ -233,7 +225,7 @@ def char8_cb_handler(chr, data):
chr8 = srv3.characteristic(uuid=CHARACTERISTIC_REFRESH_LOCATION, value="Default")
chr7_cb = chr8.callback(trigger=Bluetooth.CHAR_READ_EVENT | Bluetooth.CHAR_WRITE_EVENT, handler=char8_cb_handler)

print('Start BLE Service')
print('Started BLE Service')

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

# GPS & Battery Voltage methods
gpsPins = ('G12','G34')

axp=axp202.PMU(address=axp202.AXP192_SLAVE_ADDRESS)
axp.setLDO3Voltage(3300) # T-Beam GPS VDD 3v3
axp.enablePower(axp202.AXP192_LDO3)

dev = UART(1, 9600, pins=('G12','G34'))
dev = UART(1, 9600, pins=gpsPins)
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'
dev.write(msg)

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

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

# decoded_gps = decode_gps_array(gps_array)

# print("decoded gps ", decoded_gps["data"])
return {'gps_array': gps_array, 'timestamp':timestamp, 'valid':valid}
return {'gps_array': gps_array, 'timestamp': timestamp, 'valid': valid}

def decode_gps_array(input):
bytes = input
Expand Down
1 change: 1 addition & 0 deletions WebApp/data/Device.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export class Device {
constructor(id, deviceObj){
this.id = id
this.deviceObj = deviceObj
this.deviceObj.setCharacteristic = new DeviceObj("", "").setCharacteristic //get the setCharacteristic method
}
}

Expand Down
1 change: 0 additions & 1 deletion WebApp/data/data-elastic.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,6 @@ function elasticDB(config){
if(obj.found==false) throw new NotFound(errorMsgs.deviceNotFound(id))

const device = new Device(obj._id, obj._source)
device.deviceObj.setCharacteristic = new DeviceObj("", "").setCharacteristic //get the setCharacteristic method
const wasSet = device.deviceObj.setCharacteristic(characteristic, value)
if(wasSet) await elasticFetx.updateDoc(ourIndexes.devices, device.id, device.deviceObj)
}
Expand Down

0 comments on commit 6681c3e

Please sign in to comment.