element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Merry Boxes & LEDs
  • Challenges & Projects
  • Project14
  • Merry Boxes & LEDs
  • More
  • Cancel
Merry Boxes & LEDs
Blog Holiday Lights and Music Festival With Love and Cheer: Python and Wrapping Presents/Code/Applications
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Merry Boxes & LEDs to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: ipv1
  • Date Created: 14 Jan 2019 7:02 PM Date Created
  • Views 1140 views
  • Likes 9 likes
  • Comments 2 comments
  • merryboxesledsch
  • ip_iot
  • holidayspecial19ch
Related
Recommended

Holiday Lights and Music Festival With Love and Cheer: Python and Wrapping Presents/Code/Applications

ipv1
ipv1
14 Jan 2019

The Raspberry Pi 3 comes with BLE which can be used in a number of ways. The finished project at Holiday Lights and Music Festival With Love and Cheer uses BLE connected LED Lights and though a number of other things could be connected as well.

image

 

In this small post, I am going to add some details to the BLE python code for the project and allow the users to reuse the code as much as possible.

 

Starting off with BLE and Linux in Python

 

Notwithstanding the fact that there are libraries for both NodeJS as well as python for BLE, there are some other techniques that can be used to work with the interface. Take a look at the following script.

import pexpect
import time
 
LIGHT01 = "20:C3:8F:8D:8C:9E"
VALUE = ["00000000", "FF000000", "00FF0000", "0000FF00", "000000FF", "00000000"];
 
child = pexpect.spawn("gatttool -I")
 
child.sendline("connect {0}".format(LIGHT01))
child.expect("Connection successful", timeout=5)
print ("Connected to the light!")
while True:
    for i in range(6):
        child.sendline("char-write-req 0x0031 {0}".format(VALUE[i]))
        print ("Value: ", VALUE[i])
        child.expect("Characteristic value was written successfully", timeout=5)
        time.sleep(1);
 
child.sendline("disconnect")
 
child.close()
 
print ("Light Turned OFF")

 

It uses the gatttool in linux to control the same TI BLE Light and can be modified to talk to other peripherals such as the TI Sensor TAG. It is interesting to see how python can be used to wrap exiting utilities. I did a fairly detailed blog over at https://hackaday.com/2018/08/03/beginning-ble-experiments-and-making-everything-better/ but the idea is simple and can be used for other applications as well.

 

In the current project, I use the bluepy library and the code for the package is as follows

#!/usr/python
from bluepy import btle
from bluepy.btle import Scanner, DefaultDelegate
from struct import *

ble_light1 = "20:c3:8f:8d:c2:c0"
ble_light2 = "20:c3:8f:8d:8c:9e"

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr

def scanForLights():
    result = 0; # 0=no lights, 1= light 1, 2= light 2, 3= both lights
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(3.0)
    for dev in devices:
        if dev.addr == ble_light1:
            print("Found Light 1")
            result = result | 0x01

        if dev.addr == ble_light2:
            print("Found Light 2")
            result = result | 0x02
    #     print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
    #     for (adtype, desc, value) in dev.getScanData():
    #         print "  %s = %s" % (desc, value)
    return result
    
def checkLights():
    p1 = btle.Peripheral(ble_light1)
    p2 = btle.Peripheral(ble_light2)
    
    v = pack("I", 0x00000000)
    
    svc = p1.getServiceByUUID("0000ffb0-0000-1000-8000-00805f9b34fb")
    h = svc.getCharacteristics()[4]
    p1.writeCharacteristic(h.valHandle, v, withResponse=True)
    p1.disconnect()
    
    svc = p2.getServiceByUUID("0000ffb0-0000-1000-8000-00805f9b34fb")
    h = svc.getCharacteristics()[4]
    p2.writeCharacteristic(h.valHandle, v, withResponse=True)
    p2.disconnect()

def writeLight(id, v):
    if id == 1:
        p = btle.Peripheral(ble_light1)
    elif id == 2:
        p = btle.Peripheral(ble_light2)
    
    svc = p.getServiceByUUID("0000ffb0-0000-1000-8000-00805f9b34fb")
    h = svc.getCharacteristics()[4]
    p.writeCharacteristic(h.valHandle, v, withResponse=True)
    p.disconnect()

def main():
    v = pack("I", 0x00000000)
    result = scanForLights()
    
    if result == 0:
        print("No light found")
    elif result == 1:
        writeLight(1, v)
    elif result == 2:
        writeLight(2, v)
    elif result == 3:
        writeLight(1, v)
        writeLight(2, v)

if __name__ == "__main__":
    main()

I divided the whole code into functions so that it may be reused once imported. There is a function to scan for the lights as well as connect to them and then write to them. Adding functions to read a particular characteristic should not be trivial and this code could be the base for the same.

 

If you feel like doing something with NodeJS, I encourage you to take a look at a similar writeup at https://hackaday.com/2018/08/24/how-to-mash-up-ble-nodejs-and-mqtt-to-get-internet-of-things/ . It uses the same TI LED Light though the code is structured very differently.

 

Moving to python was a personal choice since I intend to use it professionally. NodeJS is great if you are a web dev or have an Intel Board like the Edison leftover from the past.

 

Hope this is useful because it took me a while to figure out the difference between the two approaches.

 

Cheers.

  • Sign in to reply

Top Comments

  • DAB
    DAB over 6 years ago +2
    Nice post. I think that Python is quickly becoming the best first language, just like Basic was in the 1970's. It is easy to learn, but has the ability to evolve into some very sophisticated pieces of…
Parents
  • DAB
    DAB over 6 years ago

    Nice post.

     

    I think that Python is quickly becoming the best first language, just like Basic was in the 1970's.

    It is easy to learn, but has the ability to evolve into some very sophisticated pieces of software.

     

    DAB

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • More
    • Cancel
Comment
  • DAB
    DAB over 6 years ago

    Nice post.

     

    I think that Python is quickly becoming the best first language, just like Basic was in the 1970's.

    It is easy to learn, but has the ability to evolve into some very sophisticated pieces of software.

     

    DAB

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • More
    • Cancel
Children
  • ipv1
    ipv1 over 6 years ago in reply to DAB

    Python is quite beginner friendly and with the like of the BBC Micro bit using it, its hard to ignore. When NodeMCU firmware came out, it felt like a shift but microfirmware proves that it has evolved far more than the other contenders. Additionally, it is quite easy to extend and the tooling has come far though it may not be as polished as Java. I really feel like someone needs to come forth and set better standards but I guess that it would weaken its powers of flexibility.

     

    I started with python as a scripting system that works simply out of the box. Now it can be daunting for people going from beginners to intermediate because of just the shear amount of opinions around it. Pip, conda and even pipenv with virtual envs and not to mention the 2.7 vs 3.x debate. Its crazy out there but it allows you to take an opinionated approach to projects. That is not necessarily a good thing since it entails exploring and experimenting before having an opinion.

     

    That is a major reason I have decided to focus on python more this year. Lets see how THAT goes image

     

    Cheers,

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube