RaspiBT.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import os
  2. import glob
  3. import time
  4. import RPi.GPIO as GPIO
  5. from bluetooth import *
  6. os.system('modprobe w1-gpio')
  7. os.system('modprobe w1-therm')
  8. GPIO.setmode(GPIO.BCM)
  9. GPIO.setup(17, GPIO.OUT)
  10. base_dir = '/sys/bus/w1/devices/'
  11. device_file = base_dir + 'w1_slave'
  12. def read_temp_raw():
  13. f = open(device_file, 'r')
  14. lines = f.readlines()
  15. f.close()
  16. return lines
  17. def read_temp():
  18. lines = read_temp_raw()
  19. while lines[0].strip()[-3:] != 'YES':
  20. time.sleep(0.2)
  21. lines = read_temp_raw()
  22. equals_pos = lines[1].find('t=')
  23. if equals_pos != -1:
  24. temp_string = lines[1][equals_pos+2:]
  25. temp_c = float(temp_string) / 1000.0
  26. temp_f = temp_c * 9.0 / 5.0 + 32.0
  27. return temp_c
  28. #while True:
  29. # print(read_temp())
  30. # time.sleep(1)
  31. server_sock=BluetoothSocket( RFCOMM )
  32. server_sock.bind(("",PORT_ANY))
  33. server_sock.listen(1)
  34. port = server_sock.getsockname()[1]
  35. uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
  36. advertise_service( server_sock, "AquaPiServer",
  37. service_id = uuid,
  38. service_classes = [ uuid, SERIAL_PORT_CLASS ],
  39. profiles = [ SERIAL_PORT_PROFILE ]
  40. # protocols = [ OBEX_UUID ]
  41. )
  42. while True:
  43. print ("Waiting for connection on RFCOMM channel %d" % port)
  44. client_sock, client_info = server_sock.accept()
  45. print ("Accepted connection from ", client_info)
  46. try:
  47. data = client_sock.recv(1024)
  48. if len(data) == 0: break
  49. print ("received [%s]" % data)
  50. if data == 'temp':
  51. data = str(read_temp())+'!'
  52. elif data == 'lightOn':
  53. GPIO.output(17,False)
  54. data = 'light on!'
  55. elif data == 'lightOff':
  56. GPIO.output(17,True)
  57. data = 'light off!'
  58. else:
  59. data = 'WTF!'
  60. client_sock.send(data)
  61. print ("sending [%s]" % data)
  62. except IOError:
  63. pass
  64. except KeyboardInterrupt:
  65. print ("disconnected")
  66. client_sock.close()
  67. server_sock.close()
  68. print ("all done")
  69. break