Transfer data between Bluetooth devices

After a while looking online for an applescript able to transfer data between Bluetooth devices in a comfortable way, i realized that nobody was able to code something useful. The solution could be very simple :

 tell application "Finder" to set the_item to item 1 of (get selection) as text
do shell script "open -a 'Bluetooth File Exchange' " & (quoted form of posix path of the_item)

…but the script evolved almost alone to my joy. You can save the following script as droplet applescript App, add a nice icon (just google for “Bluetooth icon”), i hope u find it useful. There are contributions of Macscripter and Stack overflow. Feel free to share improvements for all of us! Would be nice to read these here :stuck_out_tongue:

#Bluetooth austausch
#Bluetooth File Exchange
#0,005
#Erstellt von Joy am 10.08.17, ->12.08.17
#=====================================
#HILFE: 
# 
# 
#ZUTUN: 
# - 
# - 
# - 
#=====================================
--APPLESCRIPT
--bluetooth_powerstate(0) -- off
--bluetooth_powerstate(1) -- on
--bluetooth_powerstate(-1) -- toggle
--bluetooth_powerstate(9) -- query

property blueth_on : 0
property Osx : 4245
property _versionInteger : ""

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "IOBluetooth"
use scripting additions

on run
	my activate_bluetooth()
end run

on open transfer_files
	if blueth_on is 0 then my activate_bluetooth()
	my main(transfer_files)
end open

on reopen
	set ls to {"kill hanging OBEXAgent", "Send file", "quit"} #{"Übertragung blockiert", "Datei senden", "Beenden"}
	activate
	set ch to choose from list ls with prompt "Choose option" #"Wähle Option..."
	if ch is false then return
	set ch to ch as text
	
	if ch is "kill hanging OBEXAgent" then #"Übertragung blockiert" then
		do shell script "killall OBEXAgent"
	else if ch is "Send file" then
		my main({})
	else
		quit me
	end if
	
end reopen

on quit
	set blueth_on to 0
	#turn bluetooth OFF
	set res to my bluetooth_powerstate("0")
	continue quit
end quit

on activate_bluetooth()
	if blueth_on is 0 then
		#turn bluetooth ON
		set res to my bluetooth_powerstate("")
		if res is 0 then set res to my bluetooth_powerstate(1)
		set blueth_on to 1
	end if
	
end activate_bluetooth

on main(sel)
	set blue_device to {}
	set _versionInteger to system attribute "sysv"
	if _versionInteger > Osx then
		#"Bluetooth File Exchange"'s applescript dict is broken
		set blue_device to my get_devices()
		set lg to number of items in blue_device
		if lg > 1 then
			activate
			set ch to choose from list blue_device with prompt "Choose device" #"Wähle Gerät..."
			if ch is false then return
			set blue_device to ch as text
		else
			beep
			return
		end if
	end if
	
	if sel is {} then
		tell application "Finder"
			set frwin to (target of window 1 as text)
			activate
			set ch to choose file default location alias frwin with multiple selections allowed
			set sel to the result
			if (sel as text) is false then return
		end tell
	end if
	
	#send file
	my send_files(sel, blue_device)
	
end main

on get_devices()
	set allNames to ((current application's IOBluetoothDevice's recentDevices:0)'s valueForKey:"nameOrAddress") as list
	set pairedNames to ((current application's IOBluetoothDevice's pairedDevices())'s valueForKey:"nameOrAddress") as list
	return pairedNames
end get_devices

on send_files(sel, blue_device)
	
	set nw to ""
	repeat with a in sel
		set a to a as text
		set nw to nw & quoted form of POSIX path of a & " "
		delay 0.2
	end repeat
	
	#use shell-applescript dict is broken
	if _versionInteger > Osx then
		tell application "Bluetooth File Exchange"
			try
				send file my_file to device blue_device
			on error #decline
				return
			end try
		end tell
	else
		do shell script "open -a 'Bluetooth File Exchange' " & (nw as text)
	end if
end send_files

on bluetooth_powerstate(m)
	(*
        integer m : operation mode
            0  = off
            1  = on
            -1 = toggle
            9  = query (print current state)
        return integer : resulting state
    *)
	#if m = 9 then set m to ""
	do shell script "/usr/bin/python <<'EOF' - " & m & "
# coding: utf-8
# 
#   file:
#       bluetooth_powerstate.py
# 
#   function:
#       get or set bluetooth power state
# 
#   usaeg:
#       ./bluetooth_powerstate [mode]
#           mode :
#               0  = off
#               1  = on
#               -1 = toggle
#                  = query (print current state)
#   version:
#       0.10
# 
import sys, objc
import time
from CoreFoundation import *

IOBT_BRIDGESUPPORT = '''<?xml version=\"1.0\" standalone=\"yes\"?>
<!DOCTYPE signatures SYSTEM \"file://localhost/System/Library/DTDs/BridgeSupport.dtd\">
<signatures version=\"0.9\">
    <function name=\"IOBluetoothPreferenceGetControllerPowerState\">
        <retval type=\"i\"></retval>
    </function>
    <function name=\"IOBluetoothPreferenceSetControllerPowerState\">
        <arg type=\"i\"></arg>
        <retval type=\"i\"></retval>
    </function>
</signatures>'''

objc.initFrameworkWrapper(
    frameworkName=\"IOBluetooth\",
    frameworkIdentifier=\"com.apple.Bluetooth\",
    frameworkPath=objc.pathForFramework('/System/Library/Frameworks/IOBluetooth.framework'),
    globals=globals()
)
objc.parseBridgeSupport(
    IOBT_BRIDGESUPPORT, 
    globals(), 
    objc.pathForFramework('/System/Library/Frameworks/IOBluetooth.framework')
)

def set_ioblpstate(s):
    #   int s : 0 = off, 1 = on
    IOBluetoothPreferenceSetControllerPowerState(s)
    s1 = -1
    for i in range(50):
        s1 = get_ioblpstate()
        if s1 == s:
            break
        time.sleep(0.1)
    if s1 != s:
        sys.stderr.write('Unable to set bluetooth power state to %s\\n' % ('off' if s == 0 else 'on').encode('utf-8'))
        sys.exit(1)
    return s1

def get_ioblpstate():
    return IOBluetoothPreferenceGetControllerPowerState()

def main():
    m = [ a.decode('utf-8') for a in sys.argv[1:] ]
    if m == []:
        print '%d' % get_ioblpstate()
    elif m == ['0']:
        print '%d' % set_ioblpstate(0)
    elif m == ['1']:
        print '%d' % set_ioblpstate(1)
    elif m == ['-1']:
        print '%d' % set_ioblpstate(1 if get_ioblpstate() == 0 else 0)
    else:
        sys.stderr.write('Usage: %s [mode]\\n\\t%s, %s, %s, %s\\n' % (
            sys.argv[0], 'mode: 0 = off', '1 = on', '-1 = toggle', '(void) = query')
        )
        sys.exit(1)
    sys.exit(0)

main()
EOF"
	result + 0
end bluetooth_powerstate