I wrote a python script to be run on a Raspberry Pi A+ to connect with a Raspberry Pi B+ via bluetooth and send temperature data with a DS18B20 sensor. When I run the script manually from the A+, it runs perfectly fine, but when I try to set the script to run when the Pi boots up, it is unable to connect via bluetooth. Here is the script:
import socket
import time
import os
#time.sleep(10)
serverMACAddress = '00:15:83:12:1A:39'
port = 3
connected = False
while connected == False:
try:
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
connected=True
print("connected")
except Exception as e:
print('failed')
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/28-000006773191/w1_slave'
current_time = time.time()
UPDATE_THRESHOLD = 5
newTemp = False
def temp_raw():
f = open(temp_sensor,'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = temp_raw()
temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output+2:]
temp_c = float(temp_string)/1000.0
temp_f = temp_c*9.0/5.0+32.0
return temp_c
waterTemp = read_temp()
while True:
nextWaterTemp = read_temp()
current_time = time.time()
newTemp = True
if nextWaterTemp != waterTemp:
waterTemp = nextWaterTemp
try:
s.send(bytes(str(waterTemp),'UTF-8'))
time.sleep(30)
connected = True
print(waterTemp)
except Exception as e:
print("Fail")
connected = False
while connected == False:
try:
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.s.connect((serverMACAddress,port)))
s.send(bytes(str(waterTemp),'UTF-8'))
connected = True
print("Connected")
except Exception as e:
print("Fail")
time.sleep(.5)
This code also has trouble reconnecting to the B+ if the connection fails. I have to restart the code on both the B+ and the A+ to get them to connect again for some reason. But this is a different problem. I just want this code to run when it boots.
The method I used to get the script to run on boot is putting this code in the /etc/rc.local file:
/usr/bin/python /home/pi/Desktop/client.py >/tmp.client.out 2>/tmp/client.err
Any ideas?
UPDATE:
It will either always print out "failed" in the client.out file.
OR
Nothing gets logged in the client.err or the client.out files and the bluetooth icon in the top of the screen shows that it is connected but I only receive a value of 0 for the temperature it should be sending. But when I try manually running the script without running it on boot, the temperature works fine.
Found it.
/usr/bin/python /home/pi/Desktop/client.py >/tmp.client.out 2>/tmp/client.err
needs to be
/usr/bin/python3 /home/pi/Desktop/client.py >/tmp.client.out 2>/tmp/client.err
to work with the DS18B20
I feel like an idiot after searching for hours. Sorry to waste anyone's time. I'll leave this here in case some poor soul needs it for a reference.