Git Product home page Git Product logo

pylgbst's People

Contributors

antoinechauveau avatar carnage avatar cuernodegazpacho avatar elias-lange avatar emsi avatar finik avatar gbatalski avatar ijache avatar karatheodory avatar laurentchar avatar mcfletch avatar mdevel1 avatar mwasilew avatar reinder avatar rhajek avatar tsmetana avatar undera avatar vrandezo avatar ysard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pylgbst's Issues

BLE Connection problem with BLED112 on Windows

Hi guys,

I'm a complete noon to Python and this whole BLE topic. I bought a BLED112 and think I got it installed correctly as I can connect to the MoveHub using "Bluegiga BLE GUI Tool".

Now I want to run the examples from this project using the PyCharm IDE. I cloned the pylgbst repo from my own fork and started playing around. Unfortunately I get an error when I try to run the demo.py (using right click => "Run/Debug 'demo'":

python.exe C:/git/pylgbst/examples/demo.py
INFO:root:Trying get_connection_bluepy
INFO:root:Trying get_connection_bluegiga
INFO:pygatt.backends.bgapi.bgapi:Initialized new BGAPI backend
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Found BLED112 on serial port COM3
INFO:pygatt.backends.bgapi.bgapi:Resetting and reconnecting to device for a clean environment
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Found BLED112 on serial port COM3
INFO:root:Trying get_connection_gatt
INFO:root:Trying get_connection_gattool
INFO:root:Trying get_connection_gattlib
Traceback (most recent call last):
  File "C:/git/pylgbst/examples/demo.py", line 188, in <module>
    connection = DebugServerConnection()
  File "C:\git\pylgbst\pylgbst\comms\__init__.py", line 146, in __init__
    self.sock.connect(('localhost', port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/git/pylgbst/examples/demo.py", line 191, in <module>
    connection = get_connection_auto()
  File "C:\git\pylgbst\pylgbst\__init__.py", line 58, in get_connection_auto
    raise Exception("Failed to autodetect connection, make sure you have installed prerequisites")
Exception: Failed to autodetect connection, make sure you have installed prerequisites

Process finished with exit code 1

According to the output from pygatt.backends.bgapi.bgapi I would assume the Bluetooth adapter is found, but it does not search for any devices. Is there anything I missed during setup/installation?

Thanks a lot!
Michael

gattlib

HI, We'd love to use some of your code with my son on his Lego Boost. Unfortunately we're having some issues with dependencies using python 3.6. Apologies if this is not the correct forum, we're new to this and will learn quickly!

$ python3 demo.py
Traceback (most recent call last):
File "demo.py", line 4, in
from pylgbst import *
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pylgbst/init.py", line 1, in
from pylgbst.movehub import *
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pylgbst/movehub.py", line 5, in
from pylgbst.comms import BLEConnection
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pylgbst/comms.py", line 11, in
from gattlib import DiscoveryService, GATTRequester
ModuleNotFoundError: No module named 'gattlib'

WeDo 2.0 Compatibilty

Is it possible to use this library with the wedo 2 as they both use a smiler bluetooth connection?

[Discussion] async version

First of all thanks for the wonderful library and inspiring examples!

As I was fiddling with the (asynchronous) bleak library I realized that some of the commands in pylgbst are blocking even though that is technically not necessary. As far as I can see, it is not possible to e.g. blink a light and move a motor at the same time.

As the bleak library uses asyncio, I hacked together an async/await proof-pf-concept that allows much better control over simultaneous operations. Have you considered a fully async version? And/or would you be interested to work on an async fork of this library?

Alike #34, ... not dedicated class for peripheral type 0x42 on port 0x46

Hi!
Trying Your nice library! Struggled a little to get it work as I am not so very 'pythonic', but now it does.
I am using pylgbst version 1.1.2 via pip3 install pylgbst on Windows10 with BLED112 dongle and BGAPI.
Unfortunately, the motors do not react, the warning as entitled is shown on startup.
I use Vernie from examples, the hub is beeing activated but not reacting on ...motor_AB.start_power(...).
Other peripherals seem to work o.k.
MoveHub firmware (updated via original smartphone app) has reported version 2.0.00.0017.

привет
jo elegolo

bytes vs bytearray issue in messages.py

message.py asserts msg.payload is bytes. However, it's getting set to a bytearray.

Changed decode() method in my sandbox and it works (Python 3.7):
msg.payload = bytes(data)

pylgbst on RPI3 with Raspbian stretch

Hi, Thank you for your great job and very usefull to learn python to children.
Thank to S. Mack for "Lego boost roboter steuern mit python unter windows oder linux" (in german :( )

But would it be possible to do a tutorial for RPI3 dummy users like me please?
I'm facing a lot of issues...

Let's start from the beginning.
I'm using RPI3 (enhanced with bluetooth) under Raspbian stretch.
I updated with :
sudo apt-get update
sudo apt-get upgrade -y

Next i failed to install gattlib:
sudo pip install gattlib

Collecting gattlib
Using cached https://files.pythonhosted.org/packages/be/2f/5b1aecec551b42b59d8b399ad444b5672972efb590ca83d784dbe616a3e1/gattlib-0.20150805.tar.gz
Complete output from command python setup.py egg_info:
Package glib-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `glib-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'glib-2.0' found
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-RfY5iW/gattlib/setup.py", line 12, in
"pkg-config --cflags glib-2.0".split()).decode('utf-8')
File "/usr/lib/python2.7/subprocess.py", line 219, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['pkg-config', '--cflags', 'glib-2.0']' returned non-zero exit status 1

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-RfY5iW/gattlib/

This cmds didn't figure out the issue
sudo apt-get install glib-2.0
sudo pip install --upgrade setuptools --user python

The next step succeeded
pip install https://github.com/undera/pylgbst/archive/0.5.tar.gz

but it seems to be necessary to make a:
git clone https://github.com/undera/pylgbst/
to run examples?

last step failed :
python demo.py
but of course => ImportError: No module named gattlib

thank's for your help.

Connection error on Raspberry Pi 4

I am trying to run the minimal example and run into issues with all offered Bluetooth libraries. I have pasted the debug output below. In my mind it would be nice, if the auto connection would print these by default if all connection types fail with an error.

INFO:root:Trying get_connection_bluepy
DEBUG:comms-bluepy:Trying to connect client to MoveHub with MAC: None
INFO:comms-bluepy:Discovering devices...
DEBUG:root:Failed: Traceback (most recent call last):
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 53, in get_connection_auto
    return fn(controller, hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 37, in get_connection_bluepy
    return BluepyConnection(controller).connect(hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/comms/cbluepy.py", line 96, in connect
    scanner.scan(1)
  File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 852, in scan
    self.start(passive=passive)
  File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 790, in start
    self._mgmtCmd("le on")
  File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 312, in _mgmtCmd
    raise BTLEManagementError("Failed to execute management command '%s'" % (cmd), rsp)
BTLEManagementError: Failed to execute management command 'le on' (code: 20, error: Permission Denied)

INFO:root:Trying get_connection_bluegiga
WARNING: No module named pexpect
DEBUG:comms-pygatt:Trying to connect client to MoveHub with MAC: None
INFO:pygatt.backends.bgapi.bgapi:Initialized new BGAPI backend
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
DEBUG:pygatt.backends.bgapi.util:Found 1 serial USB devices
DEBUG:pygatt.backends.bgapi.util:Checking serial USB device: /dev/ttyAMA0 - ttyAMA0
DEBUG:root:Failed: Traceback (most recent call last):
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 53, in get_connection_auto
    return fn(controller, hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 13, in get_connection_bluegiga
    return BlueGigaConnection().connect(hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/comms/cpygatt.py", line 26, in connect
    adapter.start()
  File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/bgapi/bgapi.py", line 203, in start
    self._detect_device_port()
  File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/bgapi/bgapi.py", line 147, in _detect_device_port
    raise BGAPIError("Unable to auto-detect BLED112 serial port")
BGAPIError: Unable to auto-detect BLED112 serial port

INFO:root:Trying get_connection_gatt
DEBUG:comms-gatt:Starting DeviceManager...
INFO:comms-gatt:Discovering devices...
DEBUG:comms-gatt:Devices: []
INFO:comms-gatt:Discovering devices...
DEBUG:comms-gatt:Devices: [<gatt.gatt_linux.Device instance at 0xb5871fa8>, <gatt.gatt_linux.Device instance at 0xb5874f08>, <gatt.gatt_linux.Device instance at 0xb5874e18>, <gatt.gatt_linux.Device instance at 0xb58e17d8>, <gatt.gatt_linux.Device instance at 0xb58766c0>, <gatt.gatt_linux.Device instance at 0xb586eb20>, <gatt.gatt_linux.Device instance at 0xb58762b0>, <gatt.gatt_linux.Device instance at 0xb5874f58>, <gatt.gatt_linux.Device instance at 0xb5874058>, <gatt.gatt_linux.Device instance at 0xb5874eb8>, <gatt.gatt_linux.Device instance at 0xb5874c60>, <gatt.gatt_linux.Device instance at 0xb58761c0>, <gatt.gatt_linux.Device instance at 0xb6320f58>, <gatt.gatt_linux.Device instance at 0xb5874fa8>, <gatt.gatt_linux.Device instance at 0xb5876120>]
DEBUG:comms:Checking device name: 69-6D-12-F4-5F-0D, MAC: 69:6d:12:f4:5f:0d
DEBUG:root:Failed: Traceback (most recent call last):
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 53, in get_connection_auto
    return fn(controller, hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 25, in get_connection_gatt
    return GattConnection(controller).connect(hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/comms/cgatt.py", line 103, in connect
    if self._is_device_matched(address, name, hub_mac):
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/comms/__init__.py", line 52, in _is_device_matched
    if (not hub_mac and name == LEGO_MOVE_HUB) or hub_mac.lower() == address.lower():
AttributeError: 'NoneType' object has no attribute 'lower'

INFO:root:Trying get_connection_gattool
DEBUG:comms-pygatt:Trying to connect client to MoveHub with MAC: None
DEBUG:pygatt.backends.gatttool.gatttool:gatttool_cmd=gatttool -i hci0 -I
DEBUG:root:Failed: Traceback (most recent call last):
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 53, in get_connection_auto
    return fn(controller, hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 19, in get_connection_gattool
    return GattoolConnection(controller).connect(hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/comms/cpygatt.py", line 26, in connect
    adapter.start()
  File "/home/pi/.local/lib/python2.7/site-packages/pygatt/backends/gatttool/gatttool.py", line 283, in start
    self._con = pexpect.spawn(
NameError: global name 'pexpect' is not defined

INFO:root:Trying get_connection_gattlib
INFO:comms-gattlib:Discovering devices using hci0...
DEBUG:root:Failed: Traceback (most recent call last):
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 53, in get_connection_auto
    return fn(controller, hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 31, in get_connection_gattlib
    return GattLibConnection(controller).connect(hub_mac)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/comms/cgattlib.py", line 69, in connect
    devices = service.discover(1)
RuntimeError: Set scan parameters failed (are you root?)

Traceback (most recent call last):
  File "boostic3.py", line 6, in <module>
    hub = MoveHub()
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/hub.py", line 200, in __init__
    super(MoveHub, self).__init__(connection)
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/hub.py", line 46, in __init__
    connection = get_connection_auto()
  File "/home/pi/.local/lib/python2.7/site-packages/pylgbst/__init__.py", line 60, in get_connection_auto
    raise Exception("Failed to autodetect connection, make sure you have installed prerequisites")
Exception: Failed to autodetect connection, make sure you have installed prerequisites

I think there are several causes:

  • The pylgbst homepage gives examples with pip install ..., but really under Linux that should be sudo pip install..., because some of the Python bluetooth packages need root during installation.
  • To use gattool the dependency pexpect needs to be installed using sudo pip install pexpect. I would suggest to change the main page to say explicitly that users need to follow the instructions for installing the bluetooth python packages, because those might actually require a lot of system packages (via apt-get or similar).
  • A lot of the connection types need root, so how about excluding them if python is launched without sudo?
  • Last, there is a minor logic bug here:
  File "/usr/local/lib/python2.7/dist-packages/pylgbst/comms/__init__.py", line 52, in _is_device_matched
    if (not hub_mac and name == LEGO_MOVE_HUB) or hub_mac.lower() == address.lower():
AttributeError: 'NoneType' object has no attribute 'lower'

That should be:

if (not hub_mac and name == LEGO_MOVE_HUB) or **(hub_mac and** hub_mac.lower() == address.lower()):

RuntimeError: Device is not responding!

Hello,
I really like this library. I cloned it and executed it on a raspberry pi.
I start the DebugServer with DebugServer(BLEConnection().connect()).start()

Most of the time everything works fine, and I can execute commands on the movehub.
But every once in a while I get the following error:

ERROR:comms:Failed to handle cmd: Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/pylgbst/comms.py", line 197, in _handle_conn
self._handle_cmd(json.loads(line))
File "/usr/local/lib/python2.7/dist-packages/pylgbst/comms.py", line 205, in _handle_cmd
self.ble.write(cmd['handle'], unhexlify(cmd['data']))
File "/usr/local/lib/python2.7/dist-packages/pylgbst/comms.py", line 115, in write
return self.requester.write_by_handle(handle, data)
RuntimeError: Device is not responding!

In the issue before, you wrote that the battery could be an issue.
I checked the battery and even used brand new ones, but I still get the error.

Do you have any idea how to get rid of this error?

Instable Communication using BLED112 (BlueGiga) Dongle under Ubuntu 18.04 LTS

Hi Andrey,

thanks a lot for this fabulous package!
I have been using you code now for quite a while. First on Windows 7 and Raspian and now on Ubuntu 18.04 LTS.
With Ubuntu the BLED112-Dongle first did not work. It took me some time to find out, that the default reset of the dongle in pygatt.bakcends.bgapi.py in the method BGAPIBackend.start(reset=True) was the reason for the malfunction.
In my case I changed the above method in the pygatt package to BGAPIBackend.start(reset=False) and now everything works fine. Both with the BLED112 and with a tp-link UB400 (real) BLE-Dongle.
Maybe there is a way I did not see to set the flag reset=False not in the pygatt but in the pylgbst package?
By the way:

  1. Recently I had an old MoveHub with firmware 0.0.00.0223. I had to update the Lego Firmware to 2.0.00.0017 for the MoveHub to cooperate with your package.
  2. A student of mine currently uses your package for implementing ROS with Lego Boost.

Best regards and thank you again.
Stefan

Discovering devices without result

Actually this is not an issue but I am hoping for help :-)

I am very happy that I have found your library, I am sure it will bring fun to my son and me :-)

I am trying to get it running on my Raspberry 3

What I did:
sudo pip install gattlib
Following depedencies were necessary to get gattlib compiled:
sudo apt-get install libglib2.0-dev
sudo apt-get install libboost-all-dev
pip install gTTS
pip install https://github.com/undera/pylgbst/archive/0.5.tar.gz

Python version is: Python 2.7.13

Starting on of the test programs while pressing the Move Hub button leads to:

INFO:comms:Discovering devices using hci0...
INFO:comms:Discovering devices using hci0...
INFO:comms:Discovering devices using hci0...
INFO:comms:Discovering devices using hci0...

and loops infinite without finding the Move Hub.

Using the scan funtionality of the blutoothctl tool I can see the Move Hub:

[NEW] Device 90:A4:DE:F7:70:C9 Panasonic Viera
[NEW] Device E8:B1:FC:47:99:8C LENOVO
[NEW] Device 00:16:53:AC:DA:6B LEGO Move Hub

Strange thing is that when I use the command hcitool scan I do not see the Move Hub but the other BT devices:

pi@raspberrypi:~/legoboost $ hcitool scan
Scanning ...
	E8:B1:FC:47:99:8C	LENOVO
	90:A4:DE:F7:70:C9	Panasonic Viera

Is there anything I need to configure additionally to get library call hub = MoveHub(connection) finding the LEGO Move Hub?

Any advice is welcome to get the the problem on my side analyzed.

Many thanks,
Holger

Control External Motor and Motors A/B together

Is it possible to control the Motor connected to port D (or C) simultaneously with the Motors A and/or B? Did not find any such feature but in the Lego-App it appears that it is possible.

App v1.7 features: Motor-Power & Acceleration

I am using your code on some of my MOCs and get good results.
A month ago, Lego released a new APP-Version wich inlcudes programming blocks to set the motor power (e.g. the force, not the speed!) of each motor and other blocks to set the acceleration and deceleration of each motor. Both is very usefull to exactly "touch" and reference motors against objects.
Do you happen to know which command to use to do the same in python?

It doesnt work on Raspberry pi

It doesent work on my Rpi 4 model b (Thonny Python IDE).
There is just an error message (in the Demo file):

Traceback (most recent call last):
File "/home/pi/Downloads/boost/pylgbst-master/examples/demo.py", line 5, in
from pylgbst import *
ModuleNotFoundError: No module named 'pylgbst'

pyglst

and i cant install bluepy

image

Why it is so and what can i do?

Connection breaks while still instantiating Movehub()

(Thank you for this nice library!)

I'm experiencing connection issues. I believe they could stem from something in the interplay of pylgbst and my Lego Boost Hub. I would be grateful for any pointers on how to proceed.

I've had errors using Debian on some Laptop and thought I'd try again with a Raspberry, which I suspect is used by other folks with pylgbst.

  • The Lego Boost runs on firmware version 2.0.00.0017,
  • and runs fine on the app.
  • I am trying to connect using a Raspberry Pi 4
  • running the current "Raspbian Lite" [now named Raspberry Pi OS (32-bit) Lite 2020-05-27],
  • current lgbst,
  • the system Python 3 (3.8, I believe),
  • using fresh virtual environments,
  • running everything as root for now.
  • I've tried physical distances between the Raspberry 4 and Lego between 0.2 m and 3 m.

I'm trying to run this code (from a bash script that automates for a reproducible setup):

conn = get_connection_auto(hub_mac=hub_mac)
hub = MoveHub(connection=conn)
  • the call to get_connection_auto returns, the second line fails.

The actual error comes from the respective backend (bluepy (pip freeze): BTLEDisconnectError: Device disconnected, pygatt (pip freeze): No response received / pygatt.exceptions.NotificationTimeout). However it seems that the Move hub disconnects during initialization of the MoveHub instance. During the connection attempt, its light was blue for a second, and according to the logs, the initialization proceeds up to a certain point, and then fails as if the Lego Boost device was disappearing.

I have had a look at #33 , where you had to track a new firmware version. My errors might have a similar cause (but my firmware seems up to date).

Find MoveHub by name

Currently it is not documented on the main page that the name of the MoveHub needs to be "LEGO Move Hub" for it to be found by name.

Quote from "pylgbst/comms/init.py"

 def _is_device_matched(self, address, name, hub_mac):
        log.debug("Checking device name: %s, MAC: %s", name, address)
        if address != "00:00:00:00:00:00":
            if (not hub_mac and name == LEGO_MOVE_HUB) or (hub_mac and hub_mac.lower() == address.lower()):
                log.info("Found %s at %s", name, address)
                return True
        return False

Suggestion:

  • Allow to provide name also by regex (.Move Hub.)
  • Allow to pass name (and address?) directly via the Hub constructor so that the advantages of an auto connection with searching by address can be combined.

TypeError: 'NoneType' object is not iterable

Hi,
Do you have an idea how i get rid of that messages?
I did everything you wrote on your page setting up the environment but get stuck with the demo. Here the output (demo.py is taken from you page):
/usr/bin/python2.7 /root/PycharmProjects/mypy/lego/demo.py
INFO:pygatt.backends.bgapi.bgapi:Initialized new BGAPI backend
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Found BLED112 on serial port /dev/ttyACM0
INFO:pygatt.backends.bgapi.bgapi:Resetting and reconnecting to device for a clean environment
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Found BLED112 on serial port /dev/ttyACM0
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Auto-detecting serial port for BLED112
INFO:pygatt.backends.bgapi.bgapi:Found BLED112 on serial port /dev/ttyACM0
INFO:pygatt.backends.bgapi.bgapi:Running receiver
INFO:pygatt.backends.bgapi.bgapi:Disabling advertising
INFO:comms-pygatt:Discovering devices...
INFO:pygatt.backends.bgapi.bgapi:Starting an active scan
INFO:pygatt.backends.bgapi.bgapi:Pausing for 1s to allow scan to complete
INFO:pygatt.backends.bgapi.bgapi:Stopping scan
INFO:pygatt.backends.bgapi.bgapi:Discovered 1 devices: [{'rssi': -55, 'packet_data': {'scan_response_packet': {'tx_power_level': bytearray(b'\x00'), 'slave_connection_interval_range': bytearray(b'\x10\x00 \x00'), 'complete_local_name': u'LEGO Move Hub'}, 'connectable_advertisement_packet': {'complete_list_128-bit_service_class_uuids': [u'0x00:00:16:23:12:12:EF:DE:16:23:78:5F:EA:BC:D1:23'], 'flags': bytearray(b'\x06'), 'manufacturer_specific_data': bytearray(b'\x97\x03\x00@\x06\xfeA\x00')}}, 'name': u'LEGO Move Hub', 'address': u'00:16:53:A5:5A:0B'}]
INFO:root:Found LEGO Move Hub at 00:16:53:A5:5A:0B
INFO:pygatt.backends.bgapi.bgapi:Connecting to device at address 00:16:53:A5:5A:0B (timeout 5s)
INFO:pygatt.backends.bgapi.bgapi:Connection status: handle=0x0, flags=(11, 90, 165, 83, 22, 0), address=0x0b5aa5531600, connection interval=206.250000ms, timeout=830, latency=22 intervals, bonding=0x0
INFO:pygatt.backends.bgapi.bgapi:Connected to 00:16:53:A5:5A:0B
INFO:pygatt.backends.bgapi.bgapi:Fetching characteristics for connection 0
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/pygatt/backends/bgapi/bgapi.py", line 594, in _receive
packet_type, args = self._lib.decode_packet(packet)
TypeError: 'NoneType' object is not iterable

Traceback (most recent call last):
File "/root/PycharmProjects/mypy/lego/demo2.py", line 200, in
connection.disconnect()
File "/usr/local/lib/python2.7/dist-packages/pylgbst/comms/cpygatt.py", line 48, in disconnect
self._conn_hnd.disconnect()
File "/usr/local/lib/python2.7/dist-packages/pygatt/backends/bgapi/device.py", line 21, in wrapper
return func(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pygatt/backends/bgapi/device.py", line 134, in disconnect
self._backend.expect(ResponsePacketType.connection_disconnect)
File "/usr/local/lib/python2.7/dist-packages/pygatt/backends/bgapi/bgapi.py", line 532, in expect
return self.expect_any([expected], *args, **kargs)
File "/usr/local/lib/python2.7/dist-packages/pygatt/backends/bgapi/bgapi.py", line 568, in expect_any
raise exc
pygatt.backends.bgapi.exceptions.ExpectedResponseTimeout: Timed out after 1.000000s waiting for [<ResponsePacketType.connection_disconnect: 29>]

Process finished with exit code 1

I would be very happy if you can give me a hint of how to deal with that.
Thank you very much, Andreas

I can't use pylgbst with Control+ Hub

The library is working but not in a good way, i need to change this class to work with Lego Control+ Hub.
For example i need to use the TiltSensor and the gyro sensor but i can't.

"""
    Class implementing Lego Boost's MoveHub specifics
    :type led: LEDRGB
    :type tilt_sensor: TiltSensor
    :type button: Button
    :type current: Current
    :type voltage: Voltage
    :type vision_sensor: pylgbst.peripherals.VisionSensor
    :type port_C: Peripheral
    :type port_D: Peripheral
    :type motor_A: EncodedMotor
    :type motor_B: EncodedMotor
    :type motor_AB: EncodedMotor
    :type motor_external: EncodedMotor
    """

The output after running the following code is bellow:

@asyncio.coroutine
def connect_hub(mac_address, hci):
    connection = GattConnection(hci)
    connection.connect(mac_address)
    hub = MoveHub(connection)
    return hub

@asyncio.coroutine
def connection():
    print("Looking for Hubs")
    hub1 = yield from asyncio.ensure_future(connect_hub(mac_address_hub1, hci))
    hub2 = yield from asyncio.ensure_future(connect_hub(mac_address_hub2, hci))
    print("Hubs connected")
    return hub1, hub2

Output:

(Peripheral on port 0x0, Peripheral on port 0x1, Peripheral on port 0x2, Peripheral on port 0x3, LEDRGB on port 0x32, None, Current on port 0x3b, Voltage on port 0x3c)
Got only these devices: (Peripheral on port 0x0, Peripheral on port 0x1, Peripheral on port 0x2, Peripheral on port 0x3, LEDRGB on port 0x32, None, Current on port 0x3b, Voltage on port 0x3c)

Cannot read SPEED of boost motor

peripherals.py, line 242 is

speed = unpack("<b", data[0])[0]

This line returns an error when subscribing to the SPEED sensor.

Changing it to

speed = unpack("<b", data[0:4])[0]

appears to fix the problem, but I don't know if that is correct in all cases

examples demo.py reports errors

Hi,

I wanting to try your pylgbst library. I wanted to run the demo but it failed to work.
Let me know how to fix it.

Thank you.
Best Regards
Laurent

[laurent@localhost pylgbst-master]$ export PYTHONPATH=$(pwd)
[laurent@localhost pylgbst-master]$ chmod -R +x examples/
[laurent@localhost pylgbst-master]$ ./examples/demo.py
./examples/demo.py: line 3: from: command not found
./examples/demo.py: line 5: from: command not found
./examples/demo.py: line 6: from: command not found
./examples/demo.py: line 7: from: command not found
./examples/demo.py: line 9: syntax error near unexpected token (' ./examples/demo.py: line 9: log = logging.getLogger("demo")'
[laurent@localhost pylgbst-master]$

demo.py & examples fail with "Failed to obtain all builtin devices"

Hi Andrey,

first of all: thanks a lot for all the effort you put into this library & the related Youtube videos! Those got me triggered in buying a Raspi Zero W and a BLED112 (for testing on Windows) and trying to learn Python :-)

Since I'm a complete noob to Python and this whole BLE topic, I had a hard time to setup the library and its requirements. I didnt get it to work on Windows (using PyCharm), but on the Raspi I'm now at a point where I think I have everything correctly setup - but still cannot "talk" to the Lego Boost.

I'm using Python3 and installed bluepy and the pylgbst lib:

sudo pip3 install https://github.com/undera/pylgbst/archive/0.10.tar.gz
sudo pip3 install bluepy

I can use bluetoothctl to discover, pair and connect to the Boost Hub. However, when I try to run the demo.py, I get the following error:

pi@zeropi01:~/projects/pylgbst/examples $ sudo python3 demo.py
INFO:root:Trying get_connection_bluepy
INFO:comms-bluepy:Discovering devices...
INFO:comms-bluepy:Discovering devices...
INFO:comms-bluepy:Discovering devices...
INFO:comms-bluepy:Discovering devices...
INFO:root:Found LEGO Move Hub at 00:16:53:aa:7b:f2
INFO:movehub:Attached IMOTOR on port C
INFO:movehub:Attached DISTANCE_COLOR_SENSOR on port D
INFO:movehub:Attached MOTOR on port A
INFO:movehub:Attached MOTOR on port B
INFO:movehub:Attached MOTOR on port AB
INFO:movehub:Attached LED on port LED
WARNING:movehub:Got only these devices: (LED on port LED, EncodedMotor on port A, EncodedMotor on port B, EncodedMotor on port AB, None, Button on port 0, None, None)
Traceback (most recent call last):
  File "demo.py", line 194, in <module>
    hub = MoveHub(connection)
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/movehub.py", line 63, in __init__
    self._wait_for_devices()
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/movehub.py", line 83, in _wait_for_devices
    raise RuntimeError("Failed to obtain all builtin devices")
RuntimeError: Failed to obtain all builtin devices

I have all motors and the sensor connected. I also tried without any connected motors/sensors, but the error is the same.

I can launch the DebugServer as described in the readme, and that starts successfully - but running demo.py still fails:

pi@zeropi01:~/projects/pylgbst/examples $ sudo python3 demo.py
Traceback (most recent call last):
  File "demo.py", line 194, in <module>
    hub = MoveHub(connection)
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/movehub.py", line 63, in __init__
    self._wait_for_devices()
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/movehub.py", line 71, in _wait_for_devices
    self.connection.enable_notifications()
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/comms/__init__.py", line 41, in enable_notifications
    self.write(ENABLE_NOTIFICATIONS_HANDLE, ENABLE_NOTIFICATIONS_VALUE)
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/comms/__init__.py", line 163, in write
    self._send(payload)
  File "/usr/local/lib/python3.5/dist-packages/pylgbst/comms/__init__.py", line 167, in _send
    self.sock.send(json.dumps(payload) + "\n")
TypeError: a bytes-like object is required, not 'str'

Any idea what I'm doing wrong here? I also cloned your repo to the Raspi, so I'd happily try any suggested code change (if you tell me how to use the local repo instead of the installed pip3 pylgbst lib... ;-)

Furthermore I tried to run the android_remote.py but that fails with another error message:

pi@zeropi01:~/projects/pylgbst/examples $ sudo python3 vernie/android_remote.py
Traceback (most recent call last):
  File "android_remote.py", line 12, in <module>
    from . import Vernie
SystemError: Parent module '' not loaded, cannot perform relative import

What do I need to do to make that work?

Regards
Michael

I want to have multiple functions to control the Lego hub motors not Just the run() function

I want to use this library in a special way, i need your help (i use the control+ hub)
my main file is (main.py):

import curio
import train

if __name__ == '__main__':
    curio.run(train.main()) # this works
    curio.run(train.move()) # this doesn't 

The second file is train.py

from curio import sleep
from bricknil import attach, start
from bricknil.hub import CPlusHub
from bricknil.sensor.motor import CPlusLargeMotor

@attach(CPlusLargeMotor, name='motor_A')
@attach(CPlusLargeMotor, name='motor_B')
class Train(CPlusHub):

    async def run(self):
        await self.motor_A.set_speed(+100)
        await sleep(2)

    async def move_forward(self):
        await self.motor_A.set_speed(-100)
        await self.motor_B.set_speed(-100)
        await sleep(2)

async def system():
    train = Train('My train')

async def main():  
    start(system)

async def move():
    train = Train('My train')
    await train.move_forward()

RuntimeError: Device is not responding!

Hi.

I did git clone this repository and I tested like below.
(os : ubuntu 16.04 / bluez 5.43)

from pylgbst import MoveHub
import logging

logging.basicConfig(level=logging.DEBUG);

hub = MoveHub()

for device in hub.devices:
    print(device)

If I execute the code, the move hub's light goes to blue(I think it means connected to ble.), but a error occurs.

INFO:comms:Discovering devices using hci0...
DEBUG:comms:Devices: {'xx:xx:xx:xx:xx:xx': 'LEGO Move Hub'}
INFO:root:Found LEGO Move Hub at xx:xx:xx:xx:xx:xx
DEBUG:comms:Setting notification handler: <bound method MoveHub._notify of <pylgbst.movehub.MoveHub object at 0x7fa642df9450>>
DEBUG:comms:Writing to 15: 0100
DEBUG:movehub:Notification on 14: 1b0e000f0004010125000000001000000010
INFO:movehub:Attached DISTANCE_COLOR_SENSOR on port C
DEBUG:movehub:Waiting for builtin devices to appear: (None, None, None, None, None, Button on port 0, None, None)
DEBUG:movehub:Notification on 14: 1b0e000f0004020126000000001000000010
INFO:movehub:Attached IMOTOR on port D
DEBUG:movehub:Notification on 14: 1b0e000f0004370127000000001000000010
INFO:movehub:Attached MOTOR on port A
DEBUG:movehub:Notification on 14: 1b0e000f0004380127000000001000000010
INFO:movehub:Attached MOTOR on port B
DEBUG:movehub:Notification on 14: 1b0e00090004390227003738
INFO:movehub:Attached MOTOR on port AB
DEBUG:movehub:Notification on 14: 1b0e000f0004320117000000001000000010
INFO:movehub:Attached LED on port LED
DEBUG:movehub:Waiting for builtin devices to appear: (None, EncodedMotor on port A, EncodedMotor on port B, EncodedMotor on port AB, None, Button on port 0, None, None)
DEBUG:movehub:Notification on 14: 1b0e000f00043a0128000000001000000002
INFO:movehub:Attached TILT_SENSOR on port TILT_SENSOR
DEBUG:movehub:Notification on 14: 1b0e000f00043b0115000200000002000000
INFO:movehub:Attached AMPERAGE on port AMPERAGE
DEBUG:movehub:Notification on 14: 1b0e000f00043c0114000200000002000000
INFO:movehub:Attached VOLTAGE on port VOLTAGE
DEBUG:comms:Writing to 14: 0501010105
Traceback (most recent call last):
  File "b.py", line 6, in <module>
    hub = MoveHub()
  File "/usr/local/lib/python2.7/dist-packages/pylgbst/movehub.py", line 63, in __init__
    self._report_status()
  File "/usr/local/lib/python2.7/dist-packages/pylgbst/movehub.py", line 226, in _report_status
    log.info("%s by %s", self.info_get(INFO_DEVICE_NAME), self.info_get(INFO_MANUFACTURER))
  File "/usr/local/lib/python2.7/dist-packages/pylgbst/movehub.py", line 241, in info_get
    self.send(MSG_DEVICE_INFO, pack("<B", info_type) + pack("<B", INFO_ACTION_GET))
  File "/usr/local/lib/python2.7/dist-packages/pylgbst/movehub.py", line 67, in send
    self.connection.write(MOVE_HUB_HARDWARE_HANDLE, pack("<B", len(cmd) + 1) + cmd)
  File "/usr/local/lib/python2.7/dist-packages/pylgbst/comms.py", line 108, in write
    return self.requester.write_by_handle(handle, data)
RuntimeError: Device is not responding!

How can I figure out this problem?

Invalid syntax in peripherals.py?

Hello
I'm trying to get the library working with my Boost.
Just using the simple instantiate code gives me an error:

Traceback (most recent call last):
  File "demo.py", line 1, in <module>
    from pylgbst.movehub import MoveHub
  File "C:\Python37-32\lib\site-packages\pylgbst\movehub.py", line 7, in <module>
    from pylgbst.peripherals import Button, EncodedMotor, ColorDistanceSensor, LED, TiltSensor, Voltage, Peripheral, \
  File "C:\Python37-32\lib\site-packages\pylgbst\peripherals.py", line 64
    def subscribe(self, callback, mode, granularity=1, async=False):
                                                           ^
SyntaxError: invalid `syntax`

On the screen the up-arrow is pointing to the async=False parameter.
Any clues?

I'm working in Windows 10. I have Python 3.7.2. I have installed pygatt. I know the Boost is working because I can use the Windows 10 Lego Boost app.

V1.0 not connecting to the Raspberry Pi

Previously I had a working system on the Raspberry Pi 3 and Pi3+
Linux raspberrypi 4.9.80-v7+ #1098 SMP Fri Mar 9 19:11:42 GMT 2018 armv7l GNU/Linux
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=raspbian
ID_LIKE=debian

I install the latest version with
pip install https://github.com/undera/pylgbst/archive/1.1.0.tar.gz
And I also tried a pip3 install, both report a successful installation.
then I tried:-
from pylgbst.hub import MoveHub
hub = MoveHub()
for device in hub.peripherals:
print(device)

nothing is detected, and I have to use Ctrl C to get out of it. The same sort of thing happens with the other demo codes. This also happened before and after a firmware update on my boost hub.
It is the same on the very latest Buster version with python3.7 on a Pi 3 and Pi 4, but with that there could be incompatibilities with the dependencies or OS.

Program stuck when motor turning command cannot be completed

I.e. If I use Vernie.move(FORWARD), and hold the motor to stop it running, after a short while the program stuck and no new command can be sent to Boost, it shows error message like:

Pending request MsgPortOutput({'payload': b'10110cae0100001414647f03', 'needs_reply': True, 'port': 16, 'is_buffered': False, 'do_feedback': True, 'subcommand': 12, 'params': b'ae0100001414647f03'}) while trying to put MsgPortOutput({'payload': b'02110b0100000032647f03', 'needs_reply': True, 'port': 2, 'is_buffered': False, 'do_feedback': True, 'subcommand': 11, 'params': b'0100000032647f03'})

I'm using the pygatt backend on a Raspberry with Raspbian installed.
Is there any way to clear pending requests? Or it could be a backend issue?

finding MAC Adress form Lego Hub under Windows

Hi Andrey,

thanks a lot for all the infomation and stuff you published About the Lego Boost interface.

I´ve started today with installing all the Programs and have Problems with my connection to the MoveHub.

I am working with Windows and the Bluegiga hub you recommended.

Follow steps were succesfull:

  • pip install -U pylgbst
  • pip install pygatt

I am hanging here at the Moment:
"All the functions above have optional arguments to specify adapter name and MoveHub mac address. Please look function source code for details."

in the source Code of "init.py" I have to fill out "Controller" and "hub_mac"
"def get_connection_bluegiga(controller=None, hub_mac=None):"

Where do I find these?

The USB Dongle is connected to the PC, but with pushing the green button on the Hub, Nothing happens.

What am I missing here?

Thanks al lot!!

BR Dennis

Rotating A & B motors to turn wheels

First of all, Thank you very much for the wonderful repo and very gracious notes on how to get things working. I do have this setup working with a Lego boost.

I m now stuck on a problem where I have a bare-bones move-hub with wheels for motor A & B and trying to get the bot to turn right/left. I tried using the angled methods, but looks like they refer to the angle of rotation, not turning the wheel to the left or right. Lego boost app does have an operation to turn left/right on the hub, hence wondering if there is an API that I have overlooked, or if you have any insight into how else to achieve this.

Thanks
Amit

INFO:comms-gatt:Discovering devices...

The LED on my Bluetooth dongle will light up when I use bluetoothctl or gatttool (which successfully drives the Lego motors).

But when I run the example code it reports "Discovering devices..." forever and the LED on the dongle stays dark.

Maybe it's because the USB dongle has 2 Controllers, Any ideas how to make pylgbst try more than the first Controller?

(also control-c and control-d fail to be respected.)

Unable to run MoveHub() in multiple environments

On Windows:

D:\code\boost\pylgbst>pip install https://github.com/undera/pylgbst/archive/0.9.tar.gz
Collecting https://github.com/undera/pylgbst/archive/0.9.tar.gz
  Downloading https://github.com/undera/pylgbst/archive/0.9.tar.gz
     / 40kB 181kB/s
Installing collected packages: pylgbst
  Running setup.py install for pylgbst ... done
Successfully installed pylgbst-0.9
You are using pip version 9.0.1, however version 18.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

D:\code\boost\pylgbst>python
Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pylgbst.comms_gatt import GattConnection
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pylgbst.comms_gatt'
>>> from pylgbst.movehub import MoveHub
>>> hub = MoveHub()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\code\boost\pylgbst\pylgbst\movehub.py", line 41, in __init__
    connection = get_connection_auto()
  File "D:\code\boost\pylgbst\pylgbst\__init__.py", line 52, in get_connection_auto
    raise Exception("Failed to autodetect connection, make sure you have installed prerequisites")
Exception: Failed to autodetect connection, make sure you have installed prerequisites

On Windows Subsystem for Linux:


shash@PC:~$ pip3 install https://github.com/undera/pylgbst/archive/0.9.tar.gz
Collecting https://github.com/undera/pylgbst/archive/0.9.tar.gz
  Downloading https://github.com/undera/pylgbst/archive/0.9.tar.gz
     / 40kB 180kB/s
Installing collected packages: pylgbst
  Running setup.py install for pylgbst ... done
Successfully installed pylgbst-0.9
shash@PC:~$ python3
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pylgbst.movehub import MoveHub
>>> hub = MoveHub()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/shash/.local/lib/python3.6/site-packages/pylgbst/movehub.py", line 41, in __init__
    connection = get_connection_auto()
  File "/home/shash/.local/lib/python3.6/site-packages/pylgbst/__init__.py", line 52, in get_connection_auto
    raise Exception("Failed to autodetect connection, make sure you have installed prerequisites")


What are the pre-requisites as directed by the error message?
Is it OS related?

str2hex fails (Python 3.7)

Turning on logging causes str2hex to be run, and it fails. Looks like It's another bytes vs bytearray issue.

Cannot subscribe to both ANGLE and SPEED on boost motor

When trying to add a subscription to both ANGLE and SPEED for Motor_A, I get an error on the second subscription:

Code:

self.hub.motor_A.subscribe(test_speed, mode=EncodedMotor.SENSOR_SPEED)
self.hub.motor_A.subscribe(update_angle, mode=EncodedMotor.SENSOR_ANGLE)

Error:

ValueError: Port is in active mode MsgPortInputFmtSingle({'payload': bytearray(b''), 'port': 0, 'mode': 1, 'upd_delta': 1, 'upd_enabled': 1}), unsubscribe all subscribers first

I should be able to subscribe to both of these at the same time.

Video looks great and demo starts to work but...

Thanks for your effort to make this work. It took me a while to get everything installed. Is this library compatible with Python 3.x? I tried to run it as regular user, got a hint that I need admin rights. I then ran idle3 with sudo. I couldn't no longer import gattlib. With regular user, I can import it.

Went to 2.7 using sudo idle& and it works partially. Voltage and currents report results although I don't know what to expect. LED cycle works too. Then when it comes to motors_timed, it throws an error after trying 0% and 5% (no visible or audible response). Could you help me with this issue? I just bought the set and was asked by the app to update firmware. Could this be the issue? Thanks.

"Device is not responding"

If I don't run the motor demo, but directly call functions such as hub.motor_AB.timed(0.5,-1,1), the motor responds. Same for A, B, and C (it's connected to a motor).

Faulty connection/LED Raspberry Pi 4

Hello Undra,

thanks for creating and supporting the pylgbst libary!
I'm working with a new Raspberry Pi 4B and the latest raspian image and latest version of pylgbst. The system is updated.

I've problems to get the Move Hub run with the Raspi. It starts with the gattlib and bluepy libaries.
bluetooth_log.txt

In your demo.py I've allready added the mac of the hub manually, please see picture:
Move Hub mac
I'm a green horn when it comes to python and hope it's in the right place.

My problem is, that the Raspi seems to connect with the Move Hub and gets its status, but then it starts to search again for ble devices and after a while the system freezes and I have to restart it. But the hub seems still to be connected because the leds are one and it doesn't switch of. Please see the log of the demo.py:
demo_py log.txt

I hope you can help me. Thanks!

Connect to specific Bluetooth Device Address

Hey there,

so I'm looking for a way to connecto to a specific hub. I noted the Bluetooth Device Address / hub mac.

Now I'm trying to connect to the hub with the mac address. Sadly I couldn't find documentation for that.

I think I should to it this way:

connection = get_connection_auto(hub_mac='aa:bb:cc:dd')

But when I look at the code I think there are some flaws, for example at https://github.com/undera/pylgbst/blob/master/pylgbst/comms/cpygatt.py#L24:L44

I think it shouldn't be if name == LEGO_MOVE_HUB or hub_mac == address: because at that logic it will connect me to the first hub that it detects and not to the one selected.

Please add some documentation to connect to a hub with a specific mac address.

Thank you.

Feature request: Support of BlueGiga adapters

It would be really cool to additionally support BlueGiga BLED112 adpators through pygatt just like the pyb00st package. This would allow the usuage of your package for people who have only such an adaptor (like me) and enables support for Windows, where pygattlib is not available.

Probably not that complex if you analyse a bit the implementation in pyb00st. If I find some time, I'll maybe try if I can get something running (on Linux, though)

Movehub disconnects with Raspberry pi v4.19 and Bluetooth v5.50 after connecting ?

Hi, Fantastic Project! Good work!
I am using:

  • Raspberry pi v4.19
  • Bluetooth v5.50 (PyBluez)
  • Python v3.7.3
  • installed the python dependencies

When I add the (Lego boost) device and select the MoveHub from the Bluetooth list: I click on the Pair button,
and a dialog appears: Pairing request sent to the device - waiting for a response. Then I click on the Lego boost green button to turn it on. Then a new dialog appears: Paired successful but this device has no services which can be used with Raspberry pi.

I have tested my bluetooth with another device (audio speaker) and I have been able to connect to it. I have tried different commands in the shell. I haven't found anything in the /var/log/syslog and dmesg.
In the bluetoothctl, I have this output:
[CHG] Device XX:33 Connected: yes
[CHG] Device XX:33 ServicesResolved: yes
[CHG] Device XX:33 Paired: yes
[CHG] Device XX:33 ServicesResolved: no
[CHG] Device XX:33 Paired: no
[CHG] Device XX:33 Connected: no

I have tried to make the bluetooth discoverable, tried different bluetooth commands.
It seems like the lego boost disconnects as soon as the light on the device turns off.
The device probably goes into Low energy mode and Raspberry pi is unable to keep the connection.
Not sure exactly what I am doing wrong? Any help would be greatly appreciated.
I really like the project! Thank you for reading

Missing contents of pylgbst.comms?

I just installed the 0.7 release on Windows but I'm getting an error:

C:\Anaconda3\envs\boost\python.exe C:/Anaconda3/envs/boost/Lib/site-packages/pylgbst/__init__.py
Traceback (most recent call last):
  File "C:/Anaconda3/envs/boost/Lib/site-packages/pylgbst/__init__.py", line 4, in <module>
    from pylgbst.comms import DebugServer
  File "C:\Anaconda3\envs\boost\lib\site-packages\pylgbst\__init__.py", line 4, in <module>
    from pylgbst.comms import DebugServer
ImportError: cannot import name 'DebugServer'

It appears that the contents of https://github.com/undera/pylgbst/blob/master/pylgbst/comms.py is indeed empty. Did this get deleted by accident?

Excited to try out this library as a tool for teaching Python coding to my daughter. Thank you for building this and your excellent videos.

Can't call motors from movehub

Hello

my son and I are exploring your beautiful library for Lego Boost. We have a Raspberry Pi and have already managed to make a connection with Lego Boost (Vernie), and used the Color/Distance sensor and changed de LED colors. Next step: motors, but here it fails.

When we try to access the motor_AB (or any other motor), we notice that the type of the variable is NoneType instead of EncodedMotor, hence we were unable to drive the motors. I suspect de motors are not found upon connecting. We got the following warnings when we connect:

WARNING:hub:Have not dedicated class for peripheral type 0x42 on port 0x46
WARNING:hub:Have not dedicated class for peripheral type 0x42 on port 0x46
WARNING:hub:Got only these devices: (None, None, None, LEDRGB on port 0x32, TiltSensor on port 0x3a, Current on port 0x3b, Voltage on port 0x3c)

It would much appreciated if you could help us out!

Thanks!
Kris
PS: we are using the standard Vernie robot for our experiments. When using the Lego app, everything works as expected.

RuntimeError: Failed to obtain MoveHub handle

I got this error, it was working fine, i don't know what i changed in the system but now it raise this exception

Traceback (most recent call last):
  File "index.py", line 29, in <module>
    excavator.connect(mac_address_hub1, mac_address_hub2, hci1, hci2)
  File "/home/pi/codes/DI/bluetoothIO/excavator.py", line 22, in connect
    self.connectionHub1.connect(mac_address_hub1)
  File "/home/pi/codes/DI/bluetoothIO/lglib/pylgbst/comms/cgatt.py", line 110, in connect
    self._device.connect()
  File "/home/pi/codes/DI/bluetoothIO/lglib/pylgbst/comms/cgatt.py", line 31, in connect
    raise exc
RuntimeError: Failed to obtain MoveHub handle

Raspberry Pi: demo.py sometimes work, sometimes not

Hey @undera ,

I have troubles to get the demo.py example from your repo to work always. It worked multiple times (3-4 times), but most of the time the hub switches off WARNING:hub:Hub switches off, before an action can be started and the program stuck on that state. The bot turns off after 10 seconds of not interaction which is the default as far as I can tell. I've tried it on my mac, but no bluetooth backend seems to support MacOS so not test possible. For me it looks like the program on the pi is so slow (maybe wait for an event) and reach timeout before.

Hardware: raspberry pi 3 B, Lego Boost Robot
python: 3.7.3
virtual env: yes, with python3 -m venv
Bluetooth backend: bluepy 1.3.0
Firmware-Version: 2.0.00.0017

Here is the application stdout from demo.py. It extremely fast found the hub but it stuck on the line INFO:hub:Attached peripheral: LEDRGB on port 0x32 for some time, so it seems that the program is waiting for something here.

INFO:root:Trying get_connection_bluepy
INFO:comms-bluepy:Discovering devices...
INFO:comms-bluepy:Discovering devices...
INFO:comms:Found LEGO Move Hub at 00:16:53:ba:05:69
INFO:hub:Attached peripheral: EncodedMotor on port 0x0
INFO:hub:Attached peripheral: EncodedMotor on port 0x1
INFO:hub:Attached peripheral: VisionSensor on port 0x2
INFO:hub:Attached peripheral: EncodedMotor on port 0x3
INFO:hub:Attached peripheral: EncodedMotor on port 0x10
INFO:hub:Attached peripheral: LEDRGB on port 0x32 //<= stuck for multiple seconds here
INFO:hub:Attached peripheral: TiltSensor on port 0x3a
INFO:hub:Attached peripheral: Current on port 0x3b
INFO:hub:Attached peripheral: Voltage on port 0x3c
WARNING:hub:Have not dedicated class for peripheral type 0x42 on port 0x46
INFO:hub:Attached peripheral: Peripheral on port 0x46
WARNING:hub:Hub switches off

Maybe you have an idea how I can debug that problem.

Greetings

Tonka

battery value sometimes are not returned

copied battey python script, sometimes it return no values with error:
running on raspberry. Awesome work indeed!!!

pi@raspberrypi:~ $ python battery.py
WARNING: No module named pexpect
Voltage: 0.69384765625
Voltage: 0.694091796875
Voltage: 0.69384765625
Voltage: 0.694091796875
Traceback (most recent call last):
File "battery.py", line 10, in
print ("Value: " % hub.voltage.last_value)
TypeError: not all arguments converted during string formatting
pi@raspberrypi:~ $ python battery.py
WARNING: No module named pexpect
Traceback (most recent call last):
File "battery.py", line 10, in
print ("Value: " % hub.voltage.last_value)
TypeError: not all arguments converted during string formatting

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.