Python Forum
Sending string commands from Python to a bluetooth device
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sending string commands from Python to a bluetooth device
#1
Hi everyone, I hope you all okay. Nowadays I am dealing with arduino bluetooth module(HC-05) and I have a problem which exceeds my little knowledge. I have a fully programmed arduino bluetooth module which can understand commands such as " standby, tv volume up, tv volume down, air conditioner on, air conditioner off" and it works perfectly with an android app which is "Serial Bluetooth Terminal" and I am trying to make this on windows with using Python.The thing in my mind is sending the strings to the bluetooth device with clicking on them in windows.Does anyone have any idea about how to do this ? In the forum I found some threads about coding bluetooth device with python but it doesn't helps me since I have a fully programmed bluetooth device.

   
Reply
#2
Please show your python code.
Sounds like you're not binding your button events.
this is done by adding a command argument to the button, or by creating a separate bind instruction.

Really need to see your code.
Reply
#3
Actually I didn't attach anything to the buttons so it is just a basic Tkinter code for now.
Reply
#4
Tkinter code is where the binding must occur. Please show code.
At least show one of your button commands.
Reply
#5
from tkinter import*


root = Tk()
root.title("Tryout7")

def button_add():
    return
button_1 = Button(root, text="volume up", padx=60,pady=20,command=button_add)
button_2 = Button(root, text="volume down", padx=60,pady=20,command=button_add)
button_3 = Button(root, text="channel up", padx=60,pady=20,command=button_add)
button_4 = Button(root, text="channel down", padx=60,pady=20,command=button_add)
button_5 = Button(root, text="conditioner on", padx=60,pady=20,command=button_add)
button_6 = Button(root, text="conditioner off", padx=60,pady=20,command=button_add)
button_7 = Button(root, text="raise the bed ", padx=60,pady=20,command=button_add)
button_8 = Button(root, text="lower the bed", padx=60,pady=20,command=button_add)
button_9 = Button(root, text="open television", padx=60,pady=20,command=button_add)
button_10 = Button(root, text="mute", padx=60,pady=20,command=button_add)
button_11 = Button(root, text="open curtain", padx=60,pady=20,command=button_add)
button_12 = Button(root, text="close curtain", padx=60,pady=20,command=button_add)

button_1.grid(row=1,column=2)
button_2.grid(row=2,column=2)
button_3.grid(row=1,column=1)
button_4.grid(row=2,column=1)
button_5.grid(row=0,column=4)
button_6.grid(row=1,column=4)
button_7.grid(row=0,column=3)
button_8.grid(row=1,column=3)
button_9.grid(row=0,column=1)
button_10.grid(row=0,column=2)
button_11.grid(row=2,column=3)
button_12.grid(row=2,column=4)

this is the binding code that I worked on in last 2 days 

def scan_services():

   print("Scanning for bluetooth devices: ")

   devices = bluetooth.discover_devices(lookup_names = True)

   number_of_devices = len(devices)

   print(number_of_devices, "devices found")

   for addr,name in devices:

      print("\n")

      print("Device Name: %s" % (name))

      print("Device MAC Address: %s" % (addr))

      print("Services Found:")

      services = bluetooth.find_service(address=addr)

      if len(services) <=0:

          print("zero services found on", addr)

      else:

          for serv in services:

              print(serv['name'])

      print("\n")

   return()
and this is the code that I found for scanning devices.
Like I said they are just basic codes for a new learner like me. And I think I shouldn't deal with finding the device because I found a mac adress in features tab of the device which is 00:19:08:00:30:24
Larz60+ write Aug-31-2021, 04:18 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time.
Reply
#6
Here's how I would do the buttons:
import tkinter as tk


class BtnEngine:
    # rename class as you wish
    def __init__(self, parent):
        self.parent = parent
        self.parent.title("Tryout7")
        self.parent.minsize(100, 100)

        self.btn_row = 0
        self.btn_column = 0
        self.number_of_btns = 12
        self.btns_per_row = 4
        self.btn_number = 0
        self.btns = [None] * self.number_of_btns

        self.dispatch()

    def dispatch(self):
        self.create_buttons()
    
    def create_buttons(self):
        btn_titles = ["volume up", "volume down", "channel up", "channel down", 
            "conditioner on", "conditioner off", "raise the bed ", "lower the bed",
            "open television", "mute", "open curtain", "close curtain"]

        while self.btn_number < self.number_of_btns:
            if not ((self.btn_column + 1)  % self.btns_per_row):
                self.btn_row += 1
                self.btn_column = 0

            self.btns[self.btn_number] = (tk.Button(self.parent, text=btn_titles[self.btn_number], padx=60, pady=20,
                height = 2, width = 5,
                command=lambda idx = self.btn_number, title = btn_titles[self.btn_number]: self.button_clicked(idx, title)))

            self.btns[self.btn_number].grid(row=self.btn_row, column=self.btn_column)
            self.btn_column += 1
            self.btn_number += 1

    def button_clicked(self, idx, title):
        print(f"Button {idx+1} named {title} pressed")
        # add code for specific button here


def main():
    root = tk.Tk()
    BtnEngine(root)
    root.mainloop()


if __name__ == '__main__':
    main()
   
If you try this, here's what you get:
Output:
Button 1 named volume up pressed Button 2 named volume down pressed Button 5 named conditioner on pressed Button 12 named close curtain pressed
You can replace the print statements with the functions that you want to perform when the particular button is pressed.
You can even add the particular function you want to execute when the buttonis pressed (If you'd like to do this, I can show you how)
Rovelin likes this post
Reply
#7
Actually this is very helpful for me, and thank you for your every minute on this code. My goal is sending strings to the HC-05 with clicking on these buttons. And I think I can do this with using this code:

import bluetooth

def connect ():
    bd_addr = "00:19:08:00:30:24"
    port = 1
    sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    sock.connect((bd_addr, port))
    sock.send("standby")
    sock.close()

connect()[error]Traceback (most recent call last):
  File "C:/Users/Ulaş/AppData/Local/Programs/Python/Python39/tryout8.py", line 1, in <module>
    import bluetooth
ModuleNotFoundError: No module named 'bluetooth'[/error]
I couldn't solve this error since I'm using win10 and As I understand it is much harder than doing it on linux. Like I said I can do this process on a windows program which is " https://www.microsoft.com/store/productId/9WZDNCRDFST8 " and when I write the strings (below) the arduino executes the command with using IR and RF.(this part is about Electricity which is the part that I understand mostly) Here is a photo of the Bluetooth terminal which is on the microsoft link.( For you to see the my usage style of that program). https://ibb.co/Rjssyvh >> As you can see on this when I wrote btcheck it responses as OK and I can understand that if it my pc is connected to the module or not. https://ibb.co/Pxt7k3h On this photo you can see that how I send the string commands such as standby, mute and head up.

Here are the strings that bluetooth module understands:

For checking bluetooth connection

btcheck

For the bed

head up
head down
head fwd
head rev
head stop
level up
level down
level fwd
level rev
level stop

For TV

standby
mute
program up
program down
volume up
volume down

For curtain

roller close
roller open
roller down
roller up
roller stop

For air conditioner

ac on
ac off
Reply
#8
Here's the same code, but with individual functions associated with each button:
All you have to do is add the interface code:
import tkinter as tk


class BtnEngine:
    # rename class as you wish
    def __init__(self, parent):
        self.parent = parent
        self.parent.title("Tryout7")
        self.parent.minsize(100, 100)

        self.btn_row = 0
        self.btn_column = 0
        self.number_of_btns = 12
        self.btns_per_row = 4
        self.btn_number = 0
        self.btns = [None] * self.number_of_btns

        self.dispatch()

    def dispatch(self):
        self.create_buttons()
    
    def create_buttons(self):
        btn_titles = ["volume up", "volume down", "channel up", "channel down", 
            "conditioner on", "conditioner off", "raise the bed ", "lower the bed",
            "open television", "mute", "open curtain", "close curtain"]

        btn_actions = [self.volume_up, self.volume_down, self.channel_up, self.channel_down,
            self.conditioner_on, self.conditioner_off, self.raise_the_bed, self.lower_the_bed,
            self.open_television, self.mute, self.open_curtain, self.close_curtain]

        while self.btn_number < self.number_of_btns:
            if not ((self.btn_column + 1)  % self.btns_per_row):
                self.btn_row += 1
                self.btn_column = 0

            self.btns[self.btn_number] = (tk.Button(self.parent, text=btn_titles[self.btn_number],
                padx=60, pady=20, height = 2, width = 5,
                command=lambda idx=self.btn_number, btitle=btn_titles[self.btn_number], 
                bfunc=btn_actions[self.btn_number]: self.button_clicked(bfunc, btitle, idx)))

            self.btns[self.btn_number].grid(row=self.btn_row, column=self.btn_column)
            self.btn_column += 1
            self.btn_number += 1

    def button_clicked(self, fcntn, title, idx):
        fcntn(idx+1, title)

    def volume_up(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def volume_down(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def channel_up(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def channel_down(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def conditioner_on(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def conditioner_off(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def raise_the_bed(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def lower_the_bed(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def open_television(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def mute(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def open_curtain(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")

    def close_curtain(self, idx, title):
        print(f"Button {idx} pressed, {title} command running")


def main():
    root = tk.Tk()
    BtnEngine(root)
    root.mainloop()


if __name__ == '__main__':
    main()
Reply
#9
Instead of a list I would use a dictionary that maps button labels to commands.
commands = {
    'TV Standby':'standby',
    ...
    'Air Conditioning On': 'ac on',
    'Air Conditioning Off': 'ac off'
}
btn_titles = list(command.keys())
Then use the dictionary to get the command.
    def button_clicked(self, idx, title):
        command = commands[title]
        # send command
Reply
#10
I use both methods.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sending a text from Python sawtooth500 2 198 Apr-14-2024, 01:56 PM
Last Post: sawtooth500
  Read data via bluetooth frohr 9 3,422 Jul-10-2022, 09:51 AM
Last Post: frohr
  Connect to HC-05 Bluetooth (NOT BLE) korenron 0 1,481 Jun-26-2022, 09:06 AM
Last Post: korenron
  Read buffer from bluetooth frohr 2 2,158 Jun-01-2022, 01:31 PM
Last Post: frohr
  Scan for Bluetooth device korenron 0 2,631 Jan-10-2022, 01:06 PM
Last Post: korenron
  ModuleNotFoundError: No module named 'bluetooth' Error Rovelin 4 12,210 Aug-31-2021, 04:04 PM
Last Post: Rovelin
  Python library for win32 console commands eldiener 3 3,489 Aug-24-2021, 10:28 PM
Last Post: bowlofred
  Python BLE Scanner not detecting device alexanderDennisEnviro500 0 2,015 Aug-01-2021, 02:29 AM
Last Post: alexanderDennisEnviro500
  Possible to execute a python script before log off/shutdown with input commands? Kaltex 1 2,282 May-18-2021, 06:31 AM
Last Post: Skaperen
  Bluetooth send message after connecting? korenron 2 2,682 Apr-26-2021, 05:50 AM
Last Post: korenron

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020