default=None,
    type=str,
    help='Optional mac filter to only show results for this mac address.')

try:
    file_path = path.dirname(path.realpath(__file__))
    [tool_config, args] = getToolConfig(file_path, parser)
except Exception as e:
    print("ERROR", e)
    quit()

# create the library instance
print(
    f'Initializing tool with bleAdapterAddress={tool_config["bleAdapterAddress"]}'
)
core = CrownstoneBle(bleAdapterAddress=tool_config["bleAdapterAddress"])

# load the encryption keys into the library
try:
    loadKeysFromConfig(core, tool_config)
except Exception as e:
    print("ERROR", e)
    quit()


# this prints a small overview of all incoming scans.
def printAdvertisements(data):
    if macFilterPassed(args.macFilter, data.address):
        print(
            f'{data.address} {data.name} {data.rssi} mode={data.operationMode}'
        )
def scanCrownstones():
    global attempts, failures, address
    # if attempts % 2 != 0:
    # 	red('attempts needs to be even!')
    # 	quit()
    for attempt in range(attempts):
        ble = CrownstoneBle()
        ble.setSettings('adminKeyForCrown', 'memberKeyForHome',
                        'basicKeyForOther', 'MyServiceDataKey',
                        'aLocalizationKey', 'MyGoodMeshAppKey',
                        'MyGoodMeshNetKey')

        devices = ble.getCrownstonesByScanning()
        for device in devices:
            address = device['address']
            blue(address, ":\t", round(device['rssi']), ":\t",
                 device['setupMode'])

            if device['setupMode']:
                cyan('In setupMode')
                try:
                    ble.setupCrownstone(
                        device['address'],
                        crownstoneId=1,
                        sphereId=1,
                        meshDeviceKey='IamTheMeshKeyJey',
                        ibeaconUUID='1843423e-e175-4af0-a2e4-31e32f729a8a',
                        ibeaconMajor=123,
                        ibeaconMinor=456)
                except bluepy.btle.BTLEDisconnectError as err:
                    red(err)
                    failures += 1
                    fails.append((attempt, bluepy.btle.BTLEDisconnectError))
                except CrownstoneBleException as err:
                    if err.type == BleError.SETUP_FAILED:
                        print(
                            red(err.type),
                            green(
                                ', checking in 2 seconds if the crownstone is in normal mode.'
                            ),
                            cyan(
                                '(We need to give the crownstone a little more time)'
                            ))
                        blue("Normal mode now:",
                             ble.isCrownstoneInNormalMode(address))

            if not device['setupMode']:
                cyan('Not in setupMode')

                if ble.isCrownstoneInNormalMode(address):
                    magenta('In Normal mode')
                else:
                    ble.connect(address)

                ble.disconnect()
                yellow('Wait 5 sec for scan')
                time.sleep(5)
                try:
                    ble.connect(device['address'])
                except bluepy.btle.BTLEDisconnectError as err:
                    red(err)
                    ble.connect(device['address'])  # Try again once
                except Exception as err:
                    print(err)
                    red("Failed to validate session nonce, is this the right Crownstone? "
                        + address)

                # yellow('Connected to crwn')
                try:
                    ble.control.commandFactoryReset()
                except CrownstoneBleException as err:
                    if err.type == BleError.CAN_NOT_FIND_SERVICE:
                        # red(err.type)
                        red('The factory reset function could not find the service!'
                            )
                        # We need to restart the crownstone!
                        input(
                            'Please restart the crownstone! Press enter when done!'
                        )
                        ble.control.commandFactoryReset()
                        failures += 1
                        fails.append((attempt, BleError.CAN_NOT_FIND_SERVICE))
                blue('Reset done')
                time.sleep(3)
                # yellow('Disconnecting from crwn')
                ble.disconnect()
                # yellow('Disconnected from crwn')

            time.sleep(5)
            print('\n')

        ble.shutDown()
Exemple #3
0
if args.action == 'upload':
    actions.add('upload')
if args.action == 'validate':
    actions.add('validate')
if args.action == 'enable':
    actions.add('enable')
if args.action == 'disable':
    actions.add('disable')
if args.action == 'add':
    actions.add('request')
    actions.add('upload')
    actions.add('validate')
    actions.add('enable')

# Initialize the Bluetooth Core.
core = CrownstoneBle(hciIndex=args.hciIndex)
core.loadSettingsFromFile(args.keyFile)

print("Connecting to", args.bleAddress)


class connectionSettings(object):
    def __init__(self, mtu):
        self.mtu = mtu


#conSettings = connectionSettings(300)
#print("Set connection MTU to", conSettings.mtu)
ret = core.connect(args.bleAddress, False)
if ret == False:
    print("Connection failed (will not disconnect anymore then)")
from Utils.UART import events
from Utils.UART import DebugLogger
from Utils.Colors.PrintColors import *
from bluepy.btle import *

# Some pre-defined variables
attempts = 1000
address = ''
failures = 0
devices = []
switchstate = 0
starttime = time.time()

# The Crownstone BLE object to communicate with Crownstones
ble = CrownstoneBle()
ble.setSettings('adminKeyForCrown', 'memberKeyForHome', 'basicKeyForOther',
                'MyServiceDataKey', 'aLocalizationKey', 'MyGoodMeshAppKey',
                'MyGoodMeshNetKey')

# Extra variables regarding file output.
uart_connected = False
output_file = ""
out_file = False


# Function to write a line to the output file.
def output_to_file(line):
    """
	This function will write a line to the output file for archival/debugging purposes.
	"""