diff --git a/bluetoothControlApp.py b/bluetoothControlApp.py index c688f6da0e99c4ee0ca13d6223f5d1b1ce99609e..96edfc957745dd18f4910e8d96a576b251c30fb3 100644 --- a/bluetoothControlApp.py +++ b/bluetoothControlApp.py @@ -16,39 +16,41 @@ blue = None while True: try: - if os.path.exists("/dev/rfcomm0"): + while blue == None: blue = serialBluetooth() - while True: - try: - line = blue.read() - if(line != ""): - duration = float(line) - print(line) - print(duration) - if button0.isPressed(): - distance = tf.getDistance() - if blue.isOpen() : - blue.write("0,"+str(distance)+",0") - print("0,"+str(distance)+",0") - time.sleep(duration) - elif button1.isPressed(): - distance = tf.getDistance() - if blue.isOpen() : - blue.write("1,"+str(distance)+",0") - print("1,"+str(distance)+",0") - time.sleep(duration) - elif button2.isPressed(): - distance = tf.getDistance() - if blue.isOpen() : - blue.write("2,"+str(distance)+",0") - print("2,"+str(distance)+",0") - time.sleep(2); - except serial.serialutil.SerialException: - break; - else: - print("Not Connected") - time.sleep(10) + while True: + try: + line = blue.read() + if(line != ""): + duration = float(line) + print(line) + print(duration) + if button0.isPressed(): + distance = tf.getDistance() + if blue.isOpen() : + blue.write("0,"+str(distance)+",0") + print("0,"+str(distance)+",0") + time.sleep(duration) + elif button1.isPressed(): + distance = tf.getDistance() + if blue.isOpen() : + blue.write("1,"+str(distance)+",0") + print("1,"+str(distance)+",0") + time.sleep(duration) + elif button2.isPressed(): + distance = tf.getDistance() + if blue.isOpen() : + blue.write("2,"+str(distance)+",0") + print("2,"+str(distance)+",0") + time.sleep(2); + except Exception: + break; + print("closing connection") + blue.close() + blue = None + time.sleep(10) except KeyboardInterrupt: # Ctrl+C tf.close() + blue.close() diff --git a/piAndroidBluetooth/serialBluetooth.py b/piAndroidBluetooth/serialBluetooth.py index b3cdefeac72b12f934997ac442d939109c953919..ac0fab2affca1ac70f1357012d938e635ad24c26 100644 --- a/piAndroidBluetooth/serialBluetooth.py +++ b/piAndroidBluetooth/serialBluetooth.py @@ -1,20 +1,37 @@ import serial import time +import os class serialBluetooth: def __init__(self): - #see if i can do rfcomm watch hci0 here - #see if /dev/rfcomm0 exist - self.ser = serial.Serial('/dev/rfcomm0', timeout=0) + print("creating") + if os.path.exists("/dev/rfcomm0"): + self.ser = serial.Serial('/dev/rfcomm0', timeout=0) + else: + self.ser = None + + def open(self): + if self.ser == None: + return false + if self.isOpen() == False: + self.ser.open() + return true + def isOpen(self): - return self.ser.isOpen() + if self.ser == None: + return False + return self.ser.isOpen()==1 def write(self, message): self.ser.write(message) def read(self): return self.ser.readline() + + def close(self): + if self.isOpen() == True: + self.ser.close() if __name__ == "__main__":