0

So I am relatively new to python scripting and I came across this code that is supposed to configure wifi over bluetooth between a raspberry pi and smart device. Unfortunately, I keep running into the error listed in the title. I was hoping someone can copy and run the code and enlighten me why i keep running into this error. All help is greatly appreciated!

#!/usr/bin/env python

import os

from bluetooth import *

from wifi import Cell, Scheme

import subprocess

import time




wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"

sudo_mode = "sudo "


def wifi_connect(ssid, psk):

    # write wifi config to file
    f = open('wifi.conf', 'w')
    f.write('country=GB\n')
    f.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
    f.write('update_config=1\n')
    f.write('\n')
    f.write('network={\n')
    f.write('    ssid="' + ssid + '"\n')
    f.write('    psk="' + psk + '"\n')
    f.write('}\n')
    f.close()

    cmd = 'mv wifi.conf ' + wpa_supplicant_conf
    cmd_result = ""
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)


    # restart wifi adapter
    cmd = sudo_mode + 'ifdown wlan0'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    time.sleep(2)

    cmd = sudo_mode + 'ifup wlan0'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    time.sleep(10)

    cmd = 'iwconfig wlan0'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    cmd = 'ifconfig wlan0'
    cmd_result = os.system(cmd)
    print cmd + " - " + str(cmd_result)

    p = subprocess.Popen(['ifconfig', 'wlan0'], stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    out, err = p.communicate()

    ip_address = "<Not Set>"

    for l in out.split('\n'):
        if l.strip().startswith("inet addr:"):
            ip_address = l.strip().split(' ')[1].split(':')[1]

    return ip_address



def ssid_discovered():

    Cells = Cell.all('wlan0')

    wifi_info = 'Found ssid : \n'

    for current in range(len(Cells)):
        wifi_info +=  Cells[current].ssid + "\n"


    wifi_info+="!"

    print wifi_info
    return wifi_info


def handle_client(client_sock) :

    # get ssid
    client_sock.send(ssid_discovered())
    print "Waiting for SSID..."


    ssid = client_sock.recv(1024)
    if ssid == '' :
        return

    print "ssid received"
    print ssid

    # get psk
    client_sock.send("waiting-psk!")
    print "Waiting for PSK..."


    psk = client_sock.recv(1024)
    if psk == '' :
        return

    print "psk received"

    print psk

    ip_address = wifi_connect(ssid, psk)

    print "ip address: " + ip_address

    client_sock.send("ip-addres:" + ip_address + "!")

    return



try:
    while True:

        server_sock=BluetoothSocket( RFCOMM )
        server_sock,bind(("",PORT_ANY))
        server_sock.listen(1)

        port = server_sock.getsockname()[1]

        uuid = "815425a5-bfac-47bf-9321-c5ff980b5e11"

        advertise_service( server_sock, "RaspberryPiServer",
                           service_id = uuid,
                           service_classes = [ uuid, SERIAL_PORT_CLASS ],
                           profiles = [ SERIAL_PORT_PROFILE ], 
                           protocols = [ OBEX_UUID ] 
                            )

        print("Waiting for connection on RFCOMM channel %d" % port)

        client_sock, client_info = server_sock.accept()
        print "Accepted connection from ", client_info

        handle_client(client_sock)

        client_sock.close()
        server_sock.close()

        # finished config
        print 'Finished configuration\n'


except (KeyboardInterrupt, SystemExit):

    print '\nExiting\n'

This code outputs

Traceback (most recent call last):   File "test.py", line 128, in <module>
    server_sock=BluetoothSocket( RFCOMM )

NameError: name 'BluetoothSocket' is not defined
syrj2112
  • 1
  • 2
  • Thanks for that @Chris, fairly new to this so I didnt know how to format it properly. Any ideas why it is generating that error? – syrj2112 Mar 05 '17 at 02:01
  • Sorry, no. I've never done Bluetooth programming. But there's no `bluetooth` module in the standard library. You should probably [edit] your question and tell us what library you're using, and probably your OS too since Bluetooth support is probably going to be OS-specific. – ChrisGPT was on strike Mar 05 '17 at 02:53
  • It is a project involving Raspberry Pi 3 which have bluetooth libraries that can be installed. Im not quite sure of all the libraries involved with this project but they are incorporated in the top of the script. – syrj2112 Mar 05 '17 at 02:56
  • You _import_ them at the top of the script. But `from bluetooth import *` and `from wifi import Cell, Scheme` won't work out of the box with Python. Some other libraries must be installed, and without knowing what they are this question is very difficult to answer. – ChrisGPT was on strike Mar 05 '17 at 02:58
  • I thought I installed all libraries that would ever be required for my project but I'll install look around and install more libraries in the hopes that it will fix my problem. – syrj2112 Mar 05 '17 at 03:15
  • Sorry for being unclear. _You_ probably _have_ installed them. (Otherwise you'd get an error during `import`.) But _I_ don't know what they are. It's very hard to answer without knowing that. – ChrisGPT was on strike Mar 05 '17 at 11:58

1 Answers1

1

Can you show us your python version ?

Just type:

$ python --version

bluetooth lib seems to be present. But not BluetoothSocket: try to install bluez and python-bluez

$ sudo apt-get install bluez
$ sudo apt-get install python-bluez
eyllanesc
  • 235,170
  • 19
  • 170
  • 241