Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

not working #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 50 additions & 20 deletions chandelier/bt_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,23 @@

from time import sleep
import sys
import re
import pexpect
from retry import retry
from .utilities import errprint, stdprint

def reset_config():
try:
hci_name = re.search('hc..', pexpect.spawn('hcitool dev').read().decode("utf-8")).group(0)
hci = pexpect.spawn("sudo hciconfig "+ hci_name +" reset")
if hci.expect(pexpect.EOF) == 0:
return True
else:
return False
except pexpect.ExceptionPexpect as exception:
errprint(exception)
return False

class BluetoothDevice:
""" Class for generic bluetooth. Can be connected, checked if connected and is disconnecting
when object remove."""
Expand All @@ -17,7 +30,7 @@ class BluetoothError(Exception):
class DeviceNotFound(Exception):
"""Raised when given device can't be found"""

def check_if_connected(self):
def is_connected(self):
try:
hci = pexpect.spawn("hcitool con")
if hci.expect([self.addr, pexpect.EOF]) == 0:
Expand All @@ -29,24 +42,30 @@ def check_if_connected(self):
return False

def __end_connection__(self):
self.__interface__.sendline("\ndisconnect")
self.__interface__.expect("diconnected", timeout=5)
print("Disconnecting!")
self.__interface__.sendline("\nremove " + self.addr)
self.__interface__.expect("Device has been removed", timeout=5)
sleep(5)

@retry(pexpect.exceptions.TIMEOUT, tries=20)
def __check_if_device_is_visible__(self):
@retry(pexpect.exceptions.TIMEOUT, tries=5, delay=3)
def __is_device_visible__(self):
try:
self.__interface__.sendline("\ndevices")
self.__interface__.expect(self.addr)
except self.DeviceNotFound as exception:
raise exception

@retry(pexpect.exceptions.TIMEOUT, tries=120)
@retry(pexpect.exceptions.TIMEOUT, tries=3, delay=5)
def __connect_to_device__(self):
if not self.check_if_connected:
self.__end_connection__()
sleep(3)
self.__interface__.sendline("\nconnect "+self.addr)
self.__interface__.expect("Connection successful", timeout=5)
sleep(2)
if not self.is_connected():
raise pexpect.exceptions.TIMEOUT

def __trust__(self):
self.__interface__.sendline("\ntrust " + self.addr)
self.__interface__.expect("trust succeeded")

def __pair__(self):
try:
Expand All @@ -66,6 +85,7 @@ def __open_interface__(self):
# enable debuging to stdout
if self.__debug_on__:
bluetoothctl.logfile = sys.stdout.buffer
sleep(3)
return bluetoothctl
except Exception as exception:
errprint(exception)
Expand All @@ -91,12 +111,16 @@ def __prepare_bluetooth__(self, __agent__):

def __connect__(self):
try:
self.__check_if_device_is_visible__()
self.__is_device_visible__()
stdprint("Device " + self.addr + " is visible")
sleep(1)
self.__trust__()
self.__pair__()
sleep(1)
stdprint("Device " + self.addr + " is paired")
self.__connect_to_device__()
stdprint("Connection to " + self.addr + " are estabilished")
sleep(1)
stdprint("Connection to " + self.addr + " is estabilished")
except self.DeviceNotFound as exception:
errprint(exception)
errprint("Rasberry couldn't find device or connect.")
Expand All @@ -111,23 +135,29 @@ def __init__(self, addr, debug=False, agent="NoInputNoOutput"):
self.addr = addr
self.__debug_on__ = debug
self.__agent__ = agent
if self.check_if_connected():
if self.is_connected():
stdprint("Device already connected.")
return None
self.__interface__ = self.__open_interface__()
self.__prepare_bluetooth__(self.__agent__)
self.__connect__()
self.__interface__.kill(15)
self.__interface__.close(force=True)
print("Interface is killed")
except Exception as exception:
print(exception)
reset_config()
self.__interface__ = self.__open_interface__()
#self.__end_connection__()
self.__end_connection__()
self.__interface__.close(force=True)
print("Interface is killed")
raise exception

#def __del__(self):
# self.__interface__ = self.__open_interface__()
# try:
# #self.__end_connection__()
# except:
# pass
# stdprint("Device " + self.addr + " is disconnected!")
# if self.__debug_on__:
# print("disconnect")
# self.__interface__ = self.__open_interface__()
# try:
# self.__end_connection__()
# except:
# pass
# stdprint("Device " + self.addr + " is disconnected!")
36 changes: 21 additions & 15 deletions chandelier/bt_devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

class BluetoothSpeaker(bt_device.BluetoothDevice):

@retry(Exception, tries=5, delay=3)
@retry(Exception, tries=3, delay=3)
def __get_pulse_audio_sink__(self):
with pulsectl.Pulse('list-sinks') as pulse:
for sink in pulse.sink_list():
if sink.proplist.get('device.string') == self.addr:
return sink.index, sink.name

def __init__(self, addr, debug=False, agent="NoInputNoOutput"):
def __init__(self, addr, debug=False, agent="NoInputNoOutput"):
super().__init__(addr, debug, agent)
sleep(3)
try:
Expand All @@ -26,17 +26,23 @@ def __init__(self, addr, debug=False, agent="NoInputNoOutput"):


class BluetoothRemote(bt_device.BluetoothDevice):
__loop = ""
remote_inputs = []
output = ""
@retry(Exception, tries=5, delay=3)

@retry(Exception, tries=3, delay=3)
def __remote_devices__(self, addr):
remote_address = addr
devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
for device in devices:
if device.phys not in remote_address:
if device.phys == '':
devices.remove(device)
if len(devices) < 2:
raise Exception
return devices

def stop_waiting_on_output(self):
self.__loop.stop()

def wait_and_get_output(self):
@asyncio.coroutine
async def print_events(device):
Expand All @@ -46,27 +52,27 @@ async def print_events(device):
asyncio.get_running_loop().stop()
return cat_event

loop = asyncio.new_event_loop()
self.__loop = asyncio.new_event_loop()

tasks = []
for device in self.remote_inputs:
tasks.append(loop.create_task(print_events(device)))
tasks.append(self.__loop.create_task(print_events(device)))

loop.run_forever()
self.__loop.run_forever()

for task in tasks:
if task.done():
return task.result()

#devs_tasks = []
#for device in inputs:
# task = asyncio.ensure_future(print_events(device))
# devs_tasks.append(task)
try:
if task.done():
return task.result()
except:
return None

def __init__(self, addr, debug=False, agent="NoInputNoOutput"):
try:
super().__init__(addr, debug, agent)
self.remote_inputs = self.__remote_devices__(addr)
except Exception as exception:
bt_device.reset_config()
utilities.errprint(exception)
self.__end_connection__()
raise exception
Loading