def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write(b'Hello world!\r\n') print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def BLE(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write('Hello world!\r\n') print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def ble_main(): global msg ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_devices() print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() # Connect to first device print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) print('Connected') client.loop_background() while True: received = uart.read(3) if received is not None: # Received data, print it out. print('UART received: {0} Writing RED to MQTT'.format(received)) client.publish(FEED_PUB, 'RED') #uart.write('GREEN\r\n') # else: # print('UART got nothing') if msg is not None: print('MQTT received: {0} Writing RED to UART'.format(msg)) uart.write('RED\r\n') msg = None # else: # print('MQTT got nothing') finally: # Make sure device is disconnected on exit. device.disconnect()
def mainBluetooth(): global sendCommand global confirmation # Clear any cached data ble.clear_cached_data() # Get first available adapter and make sure it is powered on adapter = ble.get_default_adapter() adapter.power_on() print("Using adapter: {0}".format(adapter.name)) # Disconnect any currently connected devices print("Disconnecting any connected UART devices...") UART.disconnect_devices() # Scan for UART devices print("Searching for UART device...") try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError("Failed to find UART device!") finally: adapter.stop_scan() print("Connecting to device...") device.connect() try: print("Discovering services...") UART.discover(device) # Create instance to interact with uart = UART(device) sendCommand = sendCommand.encode() uart.write(b"%b" % (sendCommand)) received = uart.read(timeout_sec=10) if received is not None: print("Received: {0}".format(received)) confirmation = "Received: " + received else: print("Received no data!") confirmation = "Received no data!" finally: device.disconnect()
def main(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) device = None packet_source = PacketSource(config) UART.disconnect_devices() while True: try: print('Connecting to device...') adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') device.connect() UART.discover(device) uart = UART(device) for packet in packet_source.read_packets(): debug('Sending packet: value={0}, metric={1}, timestamp={2}'. format(packet.value, packet.metric, packet.timestamp)) uart.write(packet.to_bytes()) print('Going to sleep for {0} seconds...'.format( config.poll_interval)) sleep(config.poll_interval) print('Disconnecting devices before restarting main loop...') device.disconnect() adapter.stop_scan() except Exception as e: print('Caught exception of type {0} in main loop: {1}'.format( sys.exc_info()[0], str(e))) sleep(5) # bleccchh
def app(list_joysticks, list_bluetooth, joy, device): if list_joysticks: joystick.init() print('Joysticks:') for i in range(joystick.get_count()): j = joystick.Joystick(i) print(j.get_id(), j.get_name()) if list_bluetooth: ble = Adafruit_BluefruitLE.get_provider() ble.initialize() ble.run_mainloop_with(lambda: list_bluetooth_devices(ble)) if device is not None: ble = Adafruit_BluefruitLE.get_provider() ble.initialize() ble.run_mainloop_with(lambda: get_device(ble, device)) return bluetooth = get_device(ble, device) bluetooth.connect() atexit.register(bluetooth.disconnect) UART.discover(bluetooth) uart = UART(bluetooth) if joy is not None: os.environ['SDL_VIDEODRIVER'] = 'dummy' pygame.init() joystick.init() j = joystick.Joystick(joy) j.init() print('Axes:', j.get_numaxes()) while True: pygame.event.get() for i in range(j.get_numaxes()): if bluetooth and uart: uart.write('{}{}\n'.format(i, j.get_axis(i))) print(' '.join( [str(j.get_axis(i)) for i in range(j.get_numaxes())]), end='\r') time.sleep(0.05)
def main(): ble.clear_cached_data() adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) print('Disconnecting any connected UART devices...') UART.disconnect_devices() print('Searching for UART device...') try: adapter.start_scan() device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: adapter.stop_scan() print('Connecting to device...') device.connect() try: print('Discovering services...') UART.discover(device) uart = UART(device) while(True): n = randbyte(0, LEDCOUNT) r = randbyte(0, 256) g = randbyte(0, 256) b = randbyte(0, 256) s = b'n'+n+b'r'+r+b'g'+g+b'b'+b+b'\r'+b'\n' print(s) uart.write(s) sleep(1) print('Waiting up to 60 seconds to receive data from the device...') finally: device.disconnect()
def main(): device = initBle() initDrone() # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. global uart uart = UART(device) print(uart) # Write a string to the TX characteristic. uart.write(b'Hello world!\r\n') #print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. while True: #print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') continue sendCommandDrone(received) #sendCommandDrone("state?") finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) adapter.start_scan() atexit.register(adapter.stop_scan) device_found = False device = None print('Searching for UART devices...') while not device_found: found = set(UART.find_devices()) for d in found: print('Found UART: {0} [{1}]'.format(d.name, d.id)) if d.name == args.name: device = d device_found = True break time.sleep(1) if device_found: print('connecting to: {0} [{1}]'.format(device.name, device.id)) device.connect() try: print('UART connecting...') UART.discover(device) uart = UART(device) print('Creating speech recognizer...') recognizer = speech.create_recognizer() while True: phrase = speech.listen_and_recognize(recognizer) for word in phrase.split(): word = word.strip() word = word.lower() print("word: ", word) if word in blue_words: uart.write(b'blue\r\n') elif word in orange_words: uart.write(b'orange\r\n') elif word in off_words: uart.write(b'off\r\n') finally: device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. #ble.clear_cached_data() #enabling this will means any BLE devices get disconnected from computer # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. # print('Disconnecting any connected UART devices...') # UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') connect_to = "yourUniqueName" try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() # make sure we connect to the device we want if device.name == connect_to: print('Connecting to device...' + device.name) device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # packets are documented here https://learn.adafruit.com/bluefruit-le-connect/controller # color_packet_blue = b'!C\x00I\xffS' # color_packet_red = b'!C\xff\x02\x08\x92' light_value = 0 while True: # build a random color if light_value > 10000: print("BRIGHT " + str(light_value)) color_packet = ColorPacket((255, 0, 0)) else: print("DIM " + str(light_value)) color_packet = ColorPacket( (randint(0, 255), randint(0, 255), 255)) uart.write(color_packet.to_bytes()) print("Sent color packet to the device.") time.sleep(0.2) print( 'Waiting up to 4 seconds to receive data from the device...' ) received = uart.read(timeout_sec=4) if received is not None: # Received data, print it out. light_value = int(received) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect() else: print("Not connecting to first device found: " + device.name)
def main(): # Grab lock before doing anything grab_lock() # get the default adapter adapter = ble.get_default_adapter() # start the adapter adapter.power_on() # clear cached data ble.clear_cached_data() # disconnect previous connections UART.disconnect_devices() # start scanning adapter.start_scan() print("Started Scanning") # keep track of known_devices known_devices = set() while True: # get the devices found found = set(UART.find_devices()) # get difference between current and known new = found - known_devices # add new to known devices known_devices.update(new) # for each new device for device in new: print("Found {0} - {1}".format(device.name, device.id)) # check if the id is the adafruit if device.id == "DE:85:BD:07:6F:29": # if it matches stop scanning adapter.stop_scan() # connect to the device device.connect() # check if it has UART capabilities UART.discover(device) # initialize uart object to talk to the device uart = UART(device) # send the servo command if sys.argv[1] == 'open': # if response received uart.write('cmd:open') if sys.argv[1] == 'close': # if response received uart.write('cmd:close') # read response received = uart.read(timeout_sec=60) if received is not None: # print response print('Received: {0}'.format(received)) # disconnect from device UART.disconnect_devices() # device.disconnect() # power down adpater adapter.power_off() # remove lock file os.remove(LOCK_FILE) # sleep time.sleep(60) return
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. mysock = MySocket() if DEBUG: print("Connecting ips socket") # mysock.connect() # mysock.mysend() # i = 0 # while True: # mysock.mysend(str(i)) # i += 1 ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() if DEBUG: print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. if DEBUG: print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. if DEBUG: print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print("Connecting to Device") device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). if DEBUG: print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. while True: uart.write('T ') # print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. if (received[0] is 'T'): bin_array = map(bin,bytearray(received)) # print(bin_array) if DEBUG: print("Probe 1: " + str(((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) / 100.0) + "\tProbe 2: " + str(((int(bin_array[3], 2) << 8) + int(bin_array[4], 2)) / 100.0)) mysock.mysend(str((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) + "," + str((int(bin_array[3], 2) << 8) + int(bin_array[4], 2))) else: # Timeout waiting for data, None is returned. if DEBUG: print('Received no data!') # sleep(1) finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print(device.name) print('Connecting to device...') # how do I connect to a specific device (out of my two?) device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') while True: # Write a string to the TX characteristic. message_string = create_packet() # we send a regular VESC packet of bytes over the BLE UART uart.write(message_string) print('write complete') time.sleep(4.0) finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. print("Motor control test start") with raw_mode(sys.stdin): try: status = 0 while True: ch = sys.stdin.read(1) if not ch or ch == chr(4): break if ch == 'w': print("FORWARD!!!") uart.write('!B51') status = 1 if ch == 's': print("FALL BACK!!!") uart.write('!B61') status = -1 if ch == 'a': print("Turn Left!") uart.write('!B71') status = 2 if ch == 'd': print("Turn Right!") uart.write('!B81') status = 2 if ch == ' ': print("HALT!!") if status == 1: uart.write('!B50') elif status == -1: uart.write('!B60') elif status == 2: uart.write('!B70') elif status == 3: uart.write('!B80') if ch == 'c': break except (KeyboardInterrupt, EOFError): pass print("Motor control test concluded") finally: # Make sure device is disconnected on exit. device.disconnect() print("Device disconnected")
def main(): # create excel spreads # book = xlwt.Workbook(encoding="utf-8") # sheet1 = book.add_sheet("Sheet 1") # for n in range(0,12) : # sheet1.write(2, n, n + 1) serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) serverSocket.bind(('localhost', 10000)) # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) print('PC should decide speed mode first.') print('you can type ' r' whenever you want to reset.') print(" type '1': regular mode") print(" type '2': slow mode") print(" type '3': fast mode") speed = raw_input('-> ') # print "you type ",speed if speed == '1' or speed == '2' or speed == '3': uart.write(speed) sleep(1) while speed != '1': if speed == '2': print "enter slow mode" elif speed == '3': print "enter fast mode" else: print "Error: you type wrong value" speed = raw_input('-> ') if speed == '1' or speed == '2' or speed == '3': uart.write(speed) print "enter regular mode" # continue sweeping uart.write('y') state = 0 currVal = [0] * 12 maxCurrPath = 0 i = 3 while true: # for n in range(0, 400) : current_path = uart.read(timeout_sec=60) currPath = ord(current_path) - ASCII_A # stdin = sys.stdin.read() # if ("\n" in stdin or "\r" in stdin): # idx = 0 # firstSweep = 0 # flag after the first sweep # pathChange = 0 # flag when found the best path # initial_value = [0] * 12 # reset = 0 # flag after the first # break # file.read(2) read the first two characters and return it as a string # if (idx == len(lines)): # idx = 0 # Listen for data from UDP # print("Waiting for packet...") data, addr = serverSocket.recvfrom(2048) print("Packet received!") txInfoJSON = json.loads(data.decode("utf-8")) txPowerLevel = txInfoJSON["txPowerLevel"] txVoltage = txInfoJSON["txVoltage"] txCurrent = txInfoJSON["txCurrent"] txPower = txInfoJSON["txPower"] print " current_path : ", currPath print " txCurrent : ", txCurrent # currVal #test print " " # swipe and store state if state == 0: currVal[currPath - 1] = txCurrent # sheet1.write(i, currPath - 1, txCurrent) #saving in excel file # if (currPath == 11): #print currVal #test # if currPath == 1 and currVal[currPath - 1] >= 0.53 and currVal[currPath - 1] <= 0.56 : # maxCurrPath = currPath # print "path 1 detected!" # state = 1 # elif currPath == 2 and currVal[currPath - 1] >= 0.53 and currVal[currPath - 1] <= 0.58 : # print "path 2 detected" # maxCurrPath = currPath # state = 1 # # elif currPath == 3 and currVal[currPath - 1] <= 0.52 and currVal[currPath - 1] >= 0.48 : # # print "path 3 detected" # # maxCurrPath = currPath # # state = 1 # elif currPath == 4 and currVal[currPath - 1] >= 0.42 and currVal[currPath - 1] <= 0.47 : # print "path 4 detected" # maxCurrPath = currPath # state = 1 # elif currPath == 5 and currVal[currPath - 1] >= 0.5 and currVal[currPath - 1] <= 0.56 : # print "path 5 detected" # maxCurrPath = currPath # state = 1 # elif currPath == 6 and currVal[currPath - 1] >= 0.45 and currVal[currPath - 1] <= 0.51 : # print "path 6 detected" # maxCurrPath = currPath # state = 1 # elif currPath == 7 and currVal[currPath - 1] >= 0.51 and currVal[currPath - 1] <= 0.56 : # print "path 7 detected" # maxCurrPath = currPath # state = 1 if currPath == 12: i = i + 1 elif state == 1: uart.write('x') sleep(1) # chr(ord('a') + 5) uart.write(chr(ASCII_A + maxCurrPath)) print("enter x state, max path : ", maxCurrPath) #test state = 2 # pause state elif state == 2: # print ("old current : ", currVal[currPath - 1], "new current : ", txCurrent) #test # if currVal[currPath - 1] > txCurrent + 0.2 : # print "value got changed!" # state = 3 print "max path : ", maxCurrPath, "txCurrent : ", txCurrent #test if maxCurrPath == 1 and txCurrent <= 0.45: print "path 1 detected!" state = 3 elif maxCurrPath == 2 and txCurrent <= 0.43: print "path 2 detected" state = 3 elif maxCurrPath == 3 and txCurrent >= 0.57: print "path 3 detected" state = 3 elif maxCurrPath == 4 and txCurrent <= 0.4: print "path 4 detected" state = 3 elif maxCurrPath == 5 and txCurrent <= 0.44: print "path 5 detected" state = 3 elif maxCurrPath == 6 and txCurrent <= 0.43: print "path 6 detected" state = 3 elif maxCurrPath == 7 and txCurrent <= 0.48: print "path 7 detected" state = 3 elif state == 3: print "value got changed!" uart.write('y') sleep(2) print("enter y state, current : ", txCurrent, "current path : ", currPath) #test state = 0 # idx += 1 # F.truncate() # F.close() # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') # received = uart.read(timeout_sec=60) # if received is not None: # # Received data, print it out. # print('Received: {0}'.format(received)) # else: # # Timeout waiting for data, None is returned. # print('Received no data!') finally: # book.save("path1-twopath.xls") # saving in excel # Make sure device is disconnected on exit. device.disconnect()
def bluetoothDaemon(): # Grab lock before doing anything grab_lock() # get the default adapter adapter = ble.get_default_adapter() # start the adapter adapter.power_on() # clear cached data ble.clear_cached_data() # disconnect previous connections UART.disconnect_devices() # start scanning adapter.start_scan() print("Started Scanning") # keep track of known_devices known_devices = set() while True: # get the devices found found = set(UART.find_devices()) # get difference between current and known new = found - known_devices # add new to known devices known_devices.update(new) # for each new device for device in new: print("Found {0} - {1}".format(device.name, device.id)) # check if the id is the adafruit if device.id == "DE:85:BD:07:6F:29": # if it matches stop scanning adapter.stop_scan() # connect to the device device.connect() # check if it has UART capabilities UART.discover(device) # initialize uart object to talk to the device uart = UART(device) # send the temp command uart.write('cmd:temp') # read response received = uart.read(timeout_sec=60) # if response received if received is not None: # print response print('Received: {0}'.format(received)) # output to file outfile = open('current.temp', 'w') outfile.write(received.split(':')[1]) outfile.write('\n') outfile.write(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())) outfile.close() # disconnect from device UART.disconnect_devices() #device.disconnect() # power down adpater adapter.power_off() # remove lock file os.remove(LOCK_FILE) lock_file_created = False # sleep time.sleep(60) return
def collectSensorData(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART devices...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). #find all sensing devices devices = set() for i in range(10): found = set(UART.find_devices()) #remove non-bluefruit devices found_filtered = set( filter(lambda x: 'Bluefruit52' in x.name, found)) #found_filtered = found new = found_filtered - devices devices.update(new) sleep(1) print("Found the following devices:") for device in devices: print(device.name, device.id) if devices is None: raise RuntimeError('Failed to find UART device!') except: adapter.stop_scan() return False finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() #collect sensor data every dt interval for device in devices: print('Connecting to device:', device.id) device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Now wait up to one minute to receive data from the device. print( 'Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. with open('sensordata', 'a') as sd: sd.write(strftime("%Y-%m-%d %H:%M:%S ") + received + '\n') print('Received: {0}'.format(received)) print(strftime("%Y-%m-%d %H:%M:%S ")) uart.write('good') print('Sent good') else: # Timeout waiting for data, None is returned. print('Received no data!') except: device.disconnect() return False finally: print('done') # Make sure device is disconnected on exit. device.disconnect() return True
def main(): target_device_name = u'RN4871-1444' target_device = None # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Start scanning with the bluetooth adapter. adapter.start_scan() # Use atexit.register to call the adapter stop_scan function before quiting. # This is good practice for calling cleanup code in this main function as # a try/finally block might not be called since this is a background thread. atexit.register(adapter.stop_scan) print('Searching for devices...') print('Press Ctrl-C to quit (will take ~30 seconds on OSX).') # Enter a loop and print out whenever a new device is found, and break when target is found. known_uarts = set() while type(target_device) == type(None): # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(DeviceInformation.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for device in new: if (device.name != None and device.id != None): dev_name = unicode(device.name).encode('ascii', 'xmlcharrefreplace') dev_id = unicode(device.id).encode('ascii', 'xmlcharrefreplace') print('Found Device: {0} [{1}]'.format(dev_name, dev_id)) if (dev_name == target_device_name): target_device = device print('Found Target Device!') known_uarts.update(new) if (type(target_device) != type(None)): break # Sleep for a half second and see if new devices have appeared. time.sleep(0.2) print('Connecting to device...') target_device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. # try: print('Discovering services...') UART.discover(target_device) print('Service discovery complete') articulate_board = UART(target_device) time.sleep(1.0) print('Starting a comm test...') # comm test parameters NUM_TRIALS = 20 HEADER_VAL = chr(253) PACKET_SIZE = 40 OVERHEAD = 2 DATA_SIZE = PACKET_SIZE - OVERHEAD MAX_NUM_ERRORS = 10 tripTimes = [] successes = 0 failures = 0 for i in range(0,NUM_TRIALS): print('Trial', i) # generate random string # randomString = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(DATA_SIZE)]) randomString = chr(i+ord('0'))*30+'AAAAAAAA' reversedString = randomString[::-1] # get sum of character values checksum = chr(sum([ord(x) for x in randomString]) % 256) # start timer startTime = time.time() # send bytes articulate_board.write(HEADER_VAL) articulate_board.write(randomString) articulate_board.write(checksum) # wait for reception msg = '' error = 0 while((len(msg) < PACKET_SIZE) and (error < MAX_NUM_ERRORS)): received = articulate_board.read(timeout_sec=1) if received is not None: msg = msg + (received) else: error=error+1 # stop timer endTime = time.time() roundTripTime = endTime - startTime expectedResponse = (HEADER_VAL + reversedString + checksum) success = len(msg) == PACKET_SIZE and msg == expectedResponse successes = successes + (1 if success else 0) failures = failures + (0 if success else 1) if(success): tripTimes.append(roundTripTime) print("Exact success") elif(len(msg) == PACKET_SIZE): print("Received a full packet, but it was invalid.") print("Expected: " + (expectedResponse.decode('cp437'))) print("Received: " + (msg.decode('cp437'))) elif(msg == ''): print("Error: received nothing in " + str(roundTripTime) + " seconds. Checksum was: " + str(ord(checksum))) else: print("Error: didn't receive full packet in time") if(len(tripTimes) > 0): averageTime = sum(tripTimes) / len(tripTimes) else: averageTime = -1 print("Average round trip time was: " + str(averageTime) + " seconds") print("Success rate: " + str(successes) + "/" + str(successes+failures)) # except Exception, e: # print('Failed with Exception: \'{}\''.format(e)) # finally: # Make sure device is disconnected on exit. target_device.disconnect()
def main(): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) serverSocket.bind(('localhost', 10000)) # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. # uart.write('3') # print("Sent '3' to the device (high speed).") # # print("delay for 5 second...") # sleep(5) # Delay for 1 minute (60 seconds). # # uart.write('2') # print("Sent '2' to the device (low speed).") # # print("delay for 5 second...") # sleep(5) # Delay for 1 minute (60 seconds). # # uart.write('1') # print("Sent '1' to the device (pause).") # print("delay for 5 second...") # sleep(5) # print("done") print('PC should decide speed mode first.') print('you can type 'r' whenever you want to reset.') print(" type '1': regular mode") print(" type '2': slow mode") print(" type '3': fast mode") speed = raw_input('-> ') print('you type ',speed) uart.write(speed) sleep(1) # send "y" when have not yet found the best path uart.write('y') # # # open the file # # try: # # F = open("/Users/cloelee/Documents/Capstone-LVAD/PathFinder/dummyFile.txt", "r+") # # except IOError: # # print "Could not read file:" # # sys.exit() # # # # fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) # # fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK) # # # # lines = F.readlines() # idx = 0 firstSweep = 0 # flag after the first sweep pathChange = 0 # flag when found the best path initial_value = [0] * 12 reset = 0 # flag after the first while True: current_path = uart.read(timeout_sec = 60) # stdin = sys.stdin.read() # if ("\n" in stdin or "\r" in stdin): # idx = 0 # firstSweep = 0 # flag after the first sweep # pathChange = 0 # flag when found the best path # initial_value = [0] * 12 # reset = 0 # flag after the first # break # file.read(2) read the first two characters and return it as a string # if (idx == len(lines)): # idx = 0 # Listen for data from UDP print("Waiting for packet...") data, addr = serverSocket.recvfrom(2048) print("Packet received!") txInfoJSON = json.loads(data.decode("utf-8")) txPowerLevel = txInfoJSON["txPowerLevel"] txVoltage = txInfoJSON["txVoltage"] txCurrent = txInfoJSON["txCurrent"] txPower = txInfoJSON["txPower"] # print(" current_path : ", current_path, ord(current_path) - ASCII_A) # if ((pathChange != 0) & (txCurrent > 0.5)): # uart.write('x') # uart.write(current_path) # print("enter x step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A) # pathChange = 1 # sleep(5) # # First time running the program to get the initial values # if ((ord(current_path) <= (ASCII_A + 12)) & (firstSweep == 0)): # print("enter first loop") # initial_value[ord(current_path) - 1 - ASCII_A] = txCurrent # # if (ord(current_path) == (ASCII_A + 12)): # firstSweep = 1 # reset = 1 # print(initial_value) # # # if (firstSweep == 1 and reset == 0): # if (txCurrent > initial_value[ord(current_path) - 1 - ASCII_A] + 0.3): # #(receivedVoltage > initial_value[ord(current_path) - 1 - ASCII_A] - 2)): # #initial_value[current_path - 1 - 'a'] = receiveVoltage # if (pathChange != 1): # pathChange = 1; # uart.write('x') # print("enter x step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A) # #sleep(5) # uart.write(current_path) # sleep(5) # # elif (pathChange == 1): # print("enter y step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A) # uart.write('y') # pathChange = 0 # firstSweep = 0 # else: # reset = 0 # idx += 1 # F.truncate() # F.close() # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') # received = uart.read(timeout_sec=60) # if received is not None: # # Received data, print it out. # print('Received: {0}'.format(received)) # else: # # Timeout waiting for data, None is returned. # print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write('Hello world!\r\n') print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: print received hexd = received.decode("hex") bytearray = array.array('B', hexd) magnetometerX = struct.unpack('>H', bytearray[0:2]) magnetometerY = struct.unpack('>H', bytearray[2:4]) magnetometerZ = struct.unpack('>H', bytearray[4:6]) accX = struct.unpack('<H', bytearray[6:8]) accY = struct.unpack('<H', bytearray[8:10]) accZ = struct.unpack('<H', bytearray[10:12]) gyroX = struct.unpack('>H', bytearray[12:14]) gyroY = struct.unpack('>H', bytearray[14:16]) gyroZ = struct.unpack('>H', bytearray[16:18]) print "MAG: " + str(magnetometerX[0]) + "," + str( magnetometerY[0]) + "," + str(magnetometerZ[0]) print "ACCEL: " + str(accX[0]) + "," + str(accY[0]) + "," + str( accZ[0]) print "GYRO: " + str(gyroX[0]) + "," + str(gyroY[0]) + "," + str( gyroZ[0]) print "-----------------" else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. print("Motor control test start") print("FORWARD!!!") # Press forward button uart.write('!B51') time.sleep(5) print("HALT!!!") # Release forward button uart.write('!B50') time.sleep(5) print("FALL BACK!!!") # Press backward button uart.write('!B61') time.sleep(5) print("HALT!!!") # Release forward button uart.write('!B60') time.sleep(5) print("TURN LEFT!!!") # Press left button uart.write('!B71') time.sleep(5) print("HALT!!!") # Release left button uart.write('!B70') time.sleep(5) print("TURN RIGHT!!!") # Press right button uart.write('!B81') time.sleep(5) print("HALT!!!") # Release right button uart.write('!B80') time.sleep(5) print("Motor control test concluded") finally: # Make sure device is disconnected on exit. device.disconnect() print("Device disconnected")
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write('Hello world!\r\n') print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: print received hexd = received.decode("hex") bytearray = array.array('B', hexd) magnetometerX = struct.unpack( '>H', bytearray[0:2] ) magnetometerY = struct.unpack( '>H', bytearray[2:4] ) magnetometerZ = struct.unpack( '>H', bytearray[4:6] ) accX = struct.unpack( '<H', bytearray[6:8] ) accY = struct.unpack( '<H', bytearray[8:10] ) accZ = struct.unpack( '<H', bytearray[10:12] ) gyroX = struct.unpack( '>H', bytearray[12:14] ) gyroY = struct.unpack( '>H', bytearray[14:16] ) gyroZ = struct.unpack( '>H', bytearray[16:18] ) print "MAG: " + str(magnetometerX[0]) + "," + str(magnetometerY[0]) + "," + str(magnetometerZ[0]) print "ACCEL: " + str(accX[0]) + "," + str(accY[0]) + "," + str(accZ[0]) print "GYRO: " + str(gyroX[0]) + "," + str(gyroY[0]) + "," + str(gyroZ[0]) print "-----------------" else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. #signal.pause() # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write(b'Hello world!\r\n') print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') print(datetime.datetime.now()) start_ms = int(round(time.time() * 1000)) buffer = '' suffix = '\r\n' finished = False while finished != True: # read data from BLE device received = uart.read(timeout_sec=30) # if nothing has been received after timeout then close the session if (received == None): finished = True else: buffer += received.decode('UTF-8') if (buffer.endswith(suffix)): now_ms = str(int(round(time.time() * 1000))) line = now_ms + ',' + buffer myfile.write(line) myfile.flush() buffer = '' finally: # Make sure device is disconnected on exit. device.disconnect() myfile.close()
def main(): # Clear any cached data ble.clear_cached_data() # Get the first available BLE network adapter adapter = ble.get_default_adapter() # Make sure the BLE network adapter is powered on adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) quit_program = False # Main loop to get user choice while not quit_program: # Get command choice from user cmd = user_input.get_cmd() if cmd == '7': # User chose to quit program quit_program = True print("Exiting program") else: cmd_string = user_input.input_to_cmd(cmd) if cmd == '5' or cmd == '6': # Get additional arguments for command '5' (blink the internal LED) # or for command '6' (switch on the RGB LED) cmd_string = user_input.get_cmd_to_send(cmd_string) # Send the command to the UART uart.write(cmd_string) print("Sent cmd '" + cmd_string + "' to the device.") # Wait up to 40 seconds to receive data from the device. print('Waiting up to 40 seconds to receive data from the device...') received = uart.read(timeout_sec=40) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. print("Disconnecting from UART") device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect( ) # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. # uart.write('3') # print("Sent '3' to the device (high speed).") # # print("delay for 5 second...") # sleep(5) # Delay for 1 minute (60 seconds). # # uart.write('2') # print("Sent '2' to the device (low speed).") # # print("delay for 5 second...") # sleep(5) # Delay for 1 minute (60 seconds). # # uart.write('1') # print("Sent '1' to the device (pause).") # print("delay for 5 second...") # sleep(5) # print("done") print('PC should decide speed mode first.') print(" type '1': regular mode") print(" type '2': slow mode") print(" type '3': slow mode") speed = raw_input('-> ') print('you type ', speed) uart.write(speed) sleep(1) uart.write('y') firstSweep = 0 pathChange = 0 initial_value = [0] * 12 while True: F = open( "C:\\Users\\thaol\\capstoneLVAD\\BLE_PCtoBrd_Python\\receiver.txt", "r+") current_path = uart.read(timeout_sec=60) if current_path is not None: # Received data, print it out. print('Received: {0}'.format(current_path)) else: # Timeout waiting for data, None is returned. print('Received no data!') break # file.read(2) read the first two characters and return it as a string receivedVoltage = F.read() # First time running the program if (current_path <= ('a' + 12) and firstSweep == 0): initial_value[current_path - 1 - 'a'] = receivedVoltage if (current_path == ('a' + 12)): firstSweep = 1 if (firstSweep == 1): if (receiveVoltage > initial_value[current_path - 1 - 'a'] + 2 or receiveVoltage < initial_value[current_path - 1 - 'a'] - 2): # initial_value[current_path - 1 - 'a'] = receiveVoltage pathChange = 1 uart.write('x') print("already found the best path") sleep(5) uart.write(current_path) print("The best path to deliver power is: ", current_path) sleep(5) elif (pathChange == 1): uart.write('y') pathChange = 0 firstSweep = 0 F.truncate() F.close() # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') # received = uart.read(timeout_sec=60) # if received is not None: # # Received data, print it out. # print('Received: {0}'.format(received)) # else: # # Timeout waiting for data, None is returned. # print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): import os f = open('data.txt', 'a', os.O_NONBLOCK) # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write('Hello world!\r\n') print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') wtr = "" while 1: received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. inputString = format(received) newData = inputString.strip().split(',') g = open('value.txt', 'r', os.O_NONBLOCK) gLines = g.readlines() if newData[0] == 'A': if len(newData) == 5: wrt = newData[1] + "," + newData[2] + "," + newData[3] + "," + newData[4] + "," #f.write(wrt) #f.flush() elif newData[0] == 'B': if len(newData) == 4: wrt = wtr + newData[1] + "," + newData[2] + "," + newData[3] + "\n" f.write(wrt) f.flush() gLines[0] = wrt g = open('value.txt', 'w') g.writelines(gLines) g.close() print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') break finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. # uart.write('3') # print("Sent '3' to the device (high speed).") # # print("delay for 5 second...") # sleep(5) # Delay for 1 minute (60 seconds). # # uart.write('2') # print("Sent '2' to the device (low speed).") # # print("delay for 5 second...") # sleep(5) # Delay for 1 minute (60 seconds). # # uart.write('1') # print("Sent '1' to the device (pause).") # print("delay for 5 second...") # sleep(5) # print("done") print('PC should decide speed mode first.') print(" type '1': regular mode") print(" type '2': slow mode") print(" type '3': slow mode") speed = raw_input('-> ') print('you type ',speed) uart.write(speed) sleep(1) uart.write('y') # # open the file # try: # F = open("/Users/cloelee/Documents/Capstone-LVAD/PathFinder/dummyFile.txt", "r+") # except IOError: # print "Could not read file:" # sys.exit() # # lines = F.readlines() idx = 0 firstSweep = 0 pathChange = 0 initial_value = [0] * 12 # receivedVoltage = 0 while True: current_path = uart.read(timeout_sec=60) # file.read(2) read the first two characters and return it as a string # if (idx == len(lines)): # idx = 0 # Listen for data from UDP print("Waiting for packet...") data, addr = serverSocket.recvfrom(2048) print("Packet received!") txInfoJSON = json.loads(data.decode("utf-8")) txPowerLevel = txInfoJSON["txPowerLevel"] txVoltage = txInfoJSON["txVoltage"] txCurrent = txInfoJSON["txCurrent"] txPower = txInfoJSON["txPower"] print(" current_path : ", current_path, ord(current_path) - ASCII_A) if ((pathChange != 0) & (txCurrent > 0.5)): uart.write('x') uart.write(current_path) print("enter x step, receive V : ", txCurrent, "current path : ", ord(current_path) - ASCII_A) pathChange = 1 sleep(5) # # idx+=1 # label .end # F.truncate() # F.close() print(" current_path : ", current_path, ord(current_path) - ASCII_A) # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') # received = uart.read(timeout_sec=60) # if received is not None: # # Received data, print it out. # print('Received: {0}'.format(received)) # else: # # Timeout waiting for data, None is returned. # print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Found UART: {0} [{1}]'.format(device.name, device.id)) print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) #print("DEVICE FOUND IS 1->"+uart.CHARACTERISTICS) #print("DEVICE FOUND IS 2->" + uart.ADVERTISED) #print("DEVICE FOUND IS 3->" + uart.SERVICES) colors = ['hello','r','g','b','r','g','b','r','g','b','a'] for x in colors: # Write a string to the TX characteristic. uart.write('hello') print("sent--->hello") #print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=10) time.sleep(10) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) #establish connectivity and get an ACK to continue communication print("SENT -->"+x) uart.write(x) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). condition = True; known_uarts = set() while condition: # Call UART.find_devices to get a list of any UART devices that # have been found. This call will quickly return results and does # not wait for devices to appear. found = set(UART.find_devices()) # Check for new devices that haven't been seen yet and print out # their name and ID (MAC address on Linux, GUID on OSX). new = found - known_uarts for device in new: print('Found UART: {0} [{1}]'.format(device.name, device.id)) known_uarts.update(new) # Sleep for a second and see if new devices have appeared. if len(known_uarts) >= 2: condition = False; time.sleep(1.0) if len(known_uarts) >= 2: condition = False; print(condition) print('connecting to a device finally!') for device in known_uarts: print('device in set: {0} [{1}]'.format(device.name, device.id)) print(len(new)) if 'C9:79:B6:8F:0B:D4' in device.id: asuka_device = device; device = asuka_device; if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Connected to: {0} {1}'.format(device.name, device.id)) print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. uart.write('on') print("Sent 'on' to the device.") # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') finally: # Make sure device is disconnected on exit. device.disconnect()
class UartSender: def __init__(self): print("UartSender") self.uart = None self.device = None def isReadyToSend(self): return (self.uart != None) def connectAsync(self, onFinished): thread = threading.Thread(target=self.connect, args=(onFinished,)) thread.start() def connect(self, onFinished): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). self.device = UART.find_device() if self.device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print('Connecting to device...') self.device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. success = False try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). print('Discovering services...') UART.discover(self.device) # Once service discovery is complete create an instance of the service # and start interacting with it. self.uart = UART(self.device) success = True except: traceback.print_exc() self.device.disconnect() self.device = None self.uart = None finally: # Make sure device is disconnected on exit.: onFinished(success) def sendAsync(self, msg): thread = threading.Thread(target=self.send, args=(msg,)) thread.start() def send(self, msg): try: # Write a string to the TX characteristic. cmd = msg self.uart.write(cmd.encode()) print("Sent "+msg+" to the device.") except: traceback.print_exc() def recv(self): try: # Now wait up to one minute to receive data from the device. print('Waiting up to 60 seconds to receive data from the device...') received = self.uart.read(timeout_sec=1) if received is not None: # Received data, print it out. print('Received: {0}'.format(received)) else: # Timeout waiting for data, None is returned. print('Received no data!') except: traceback.print_exc() def close(): self.device.disconnect()