Testing multiple DS18B20 sensor cables - python

I'm really new to python and coding in general so i turn here for help. At work we need to test many cables with up to five DS18B20 sensors attached to them. We got this program and we've been using it for a while now to test cables with raspberry Pi. But there are few problems with it.
The program needs to detect the number of sensors attached and see if they're working, then list them by serial number lowest>highest (so we can warm them up, see which one gets highlighted, one by one and physically number them) and repeat.
It feels generally slow and crashes pretty often.
With the cables that have 5 sensors attached to them, it can find the sensors on max 2 cables(more if lucky), and when you attach 3rd cable it won't find them anymore or it will keep saying that there's 10 sensors attached. Rebooting the Pi fixes it but it takes time. Hot-swapping the cables is probably the main culprit here, but its the fastest way.
With 3 sensor cables you can check 4-5 of them until it hangs.
Any hints where the problem could be or how i could make things more efficient and faster are welcome.
Code:
import os,sys,time
import curses
stdscr = curses.initscr()
begin_x = 5; begin_y = 5
height = 40; width = 40
def temp_raw(sensor_str):
f = open(sensor_str, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp(sensor_str):
lines = temp_raw(sensor_str)
while lines[0].strip()[-3:] != 'YES':
lines = temp_raw(sensor_str)
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
return temp_c
init = 1
timer = 0
search = 1
curses.noecho()
curses.curs_set(0)
subdirectories = []
old_nbr_of_subdirs = 1
nbr_of_subdirs = 1
old_subdirectories = []
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
while (1):
timer = timer + 1
while search == 1:
stdscr.addstr(10,30, "Searching for sensors");
subdirectories = os.listdir("/sys/bus/w1/devices/");
nbr_of_subdirs = len(subdirectories);
time.sleep(3)
if nbr_of_subdirs > old_nbr_of_subdirs:
stdscr.addstr(10,30, "Found %d new sensors " % (nbr_of_subdirs-old_nbr_of_subdirs));
stdscr.addstr(11,30, "Is this all sensors? (y/n)?");
stdscr.refresh()
c = -1;
while(c == -1):
c = stdscr.getch();
if c == ord('y'):
stdscr.addstr(10,30, " ");
stdscr.addstr(11,30, " ");
stdscr.refresh()
old_nbr_of_subdirs = nbr_of_subdirs;
init = 1;
search = 0;
timer = 0;
else:
stdscr.addstr(10,51 + timer, ". ");
timer = timer + 1;
timer = timer % 4;
stdscr.refresh()
if init == 1:
init = 0
alive_ticker = 0;
temp_list = [];
sensor_oldtemp = [0,0,0,0,0,0];
sensor_temp = [0,0,0,0,0,0];
active_sensor = [0,0,0,0,0,0];
sensors = 0;
alive_ticker = 0;
active = 2;
confirm = 0;
stdscr.addstr(17,0, "Number of subdirectories %d" % (len(subdirectories)));
removed = 0;
index = 0;
length_old_subdirs = len(old_subdirectories);
while (index < length_old_subdirs):
length_old_subdirs = len(old_subdirectories);
if old_subdirectories[index] in subdirectories:
subdirectories.remove(old_subdirectories[index]);
removed += 1;
index += 1;
else:
old_subdirectories.remove(old_subdirectories[index]);
index = 0;
stdscr.addstr(30,20, "Removed %d" % (removed))
stdscr.addstr(18,0, "Number of CUT subdirectories %d" % (len(subdirectories)));
stdscr.addstr(19,0, "Number of old_subdirectories %d" % (len(old_subdirectories)));
stdscr.addstr(13,20, "Press space to confirm active sensor!");
stdscr.addstr(14,20, "Press r to reset!");
for index in range(len(subdirectories)):
if subdirectories[index].find("28") != -1:
temp_list.append("/sys/bus/w1/devices/"+subdirectories[index]+"/w1_slave");
sensor_temp[sensors] = 0;
sensors = sensors + 1;
old_subdirectories = old_subdirectories + subdirectories;
temp_list.sort();
if confirm == 1:
stdscr.addstr(13,20, "Press space to confirm active sensor!");
stdscr.addstr(14,20, "Press r to restart!");
curses.halfdelay(1);
c = stdscr.getch();
if c == 32:
confirm = 0;
timer = 10
for z in range(sensors):
if active_sensor[z] > active:
stdscr.addstr(z+5,20, " " , curses.A_DIM)
active_sensor[z] = 100
stdscr.refresh()
elif c == ord('n'):
init = 1
continue
elif c == ord('r'):
for z in range(sensors):
active_sensor[z] = 1;
if (timer > 9):
timer = 0
nbr_active_sensors = 0
for y in range(sensors):
if 99 > active_sensor[y]:
nbr_active_sensors = nbr_active_sensors + 1;
sensor_temp[y] = read_temp(temp_list[y]);
if ((sensor_oldtemp[y] + 0.1) < sensor_temp[y]):
active_sensor[y] = active_sensor[y] + 1;
sensor_oldtemp[y] = sensor_temp[y]
stdscr.addstr(3,5, "nbr_active_sensors=%d" % (nbr_active_sensors))
stdscr.addstr(4,5, "sensors=%d" % (sensors))
if nbr_active_sensors == 0:
search = 1
timer = 0;
continue
for x in range(sensors):
if (99 > active_sensor[x] and active_sensor[x] > active):
confirm = 1
stdscr.addstr(x+5,20, "Sensor %d value %4.2f ID:%s : %d " % (x+1, sensor_temp[x], temp_list[x][20:-9], active_sensor[x]), curses.A_STANDOUT)
elif active_sensor[x] <= active:
stdscr.addstr(x+5,20, "Sensor %d value %4.2f ID:%s : %d " % (x+1, sensor_temp[x], temp_list[x][20:-9], active_sensor[x]))
stdscr.refresh()
alive_ticker = alive_ticker + 1
stdscr.addstr(2, 55, "Alive ticker: %6d" % (alive_ticker))

Question: when you insert the 3rd cable (with 2-3 temp sensor on them) it just won't find any new sensors anymore.
If I recall properly there is a Limit of 2 Cable. Have you verified your Hardware supports more Cable?
I suggest to rewrite the Code and separate the Code into UI, Sensor and Wire Parts.
For instance:
class DS18B20(object):
...
def read(self):
...
class One_Wire(object):
def search(self):
print("Searching sensors")
...
def read(self):
print('Reading sensors')
for key in self.sensors:
self.sensors[key].read()
def refresh(self):
print("Refreshing sensors")
...
def history(self, alive=True):
print('Reading History')
...
Usage:
if __name__ == '__main__':
oWire = One_Wire()
oWire.search()
print(oWire)
oWire.refresh()
print(oWire)
oWire.read()
print(oWire)
history = oWire.history()
print(history)
Output:
Searching sensors
Sensors:5, active:5
id:i2c-0 CONNECT temp:None, id:i2c-3 CONNECT temp:None, id:i2c-1 CONNECT temp:None, id:i2c-5 CONNECT temp:None, id:i2c-6 CONNECT temp:None
Refreshing sensors
NEW Sensor:i2c-2
NEW Sensor:i2c-4
Sensors:7, active:6
id:i2c-0 CONNECT temp:None, id:i2c-2 CONNECT temp:None, id:i2c-3 CONNECT temp:None, id:i2c-1 disconnect temp:None, id:i2c-5 CONNECT temp:None, id:i2c-6 CONNECT temp:None, id:i2c-4 CONNECT temp:None
Reading sensors
Reading sensors
Reading sensors
Sensors:7, active:6
id:i2c-0 CONNECT temp:19, id:i2c-2 CONNECT temp:25, id:i2c-3 CONNECT temp:26, id:i2c-1 disconnect temp:None, id:i2c-5 CONNECT temp:25, id:i2c-6 CONNECT temp:18, id:i2c-4 CONNECT temp:30
Reading History
[{'i2c-0': [20, 27, 19]}, {'i2c-2': [30, 21, 25]}, {'i2c-3': [23, 29, 26]}, {'i2c-5': [30, 18, 25]}, {'i2c-6': [30, 21, 18]}, {'i2c-4': [24, 18, 30]}]

Related

Cannot unpack noniterable bool object

I'm new to Python and posting on SO.
I'm doing a class project on trying to create an automated climate control system with a Raspberry pi(Pi4 4GB) and a DHT.
Here is my current error and code and I'm not sure what's causing the fail in the loop. It works for a while then errors out. It seems to error when it gets a bad read from the sensor, but until then it works fine.
Traceback (most recent call last):
File "/home/pi/raphael-kit/python/Climatecontrol.py", line 156, in <module>
main()
File "/home/pi/raphael-kit/python/Climatecontrol.py", line 118, in main
humidity, temperature = readDht11()
TypeError: cannot unpack non-iterable bool object
import RPi.GPIO as GPIO
import time
import LCD1602
dhtPin = 17
relayPin = 23 # Set GPIO23 as control pin
set_temp = 25 # this is the required temperature
GPIO.setmode(GPIO.BCM)
# Set relayPin's mode to output,
# and initial level to High(3.3v)
GPIO.setup(relayPin, GPIO.OUT, initial=GPIO.HIGH)
MAX_UNCHANGE_COUNT = 100
STATE_INIT_PULL_DOWN = 1
STATE_INIT_PULL_UP = 2
STATE_DATA_FIRST_PULL_DOWN = 3
STATE_DATA_PULL_UP = 4
STATE_DATA_PULL_DOWN = 5
def readDht11():
GPIO.setup(dhtPin, GPIO.OUT)
GPIO.output(dhtPin, GPIO.HIGH)
time.sleep(0.05)
GPIO.output(dhtPin, GPIO.LOW)
time.sleep(0.02)
GPIO.setup(dhtPin, GPIO.IN, GPIO.PUD_UP)
unchanged_count = 0
last = -1
data = []
while True:
current = GPIO.input(dhtPin)
data.append(current)
if last != current:
unchanged_count = 0
last = current
else:
unchanged_count += 1
if unchanged_count > MAX_UNCHANGE_COUNT:
break
state = STATE_INIT_PULL_DOWN
lengths = []
current_length = 0
for current in data:
current_length += 1
if state == STATE_INIT_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_INIT_PULL_UP
else:
continue
if state == STATE_INIT_PULL_UP:
if current == GPIO.HIGH:
state = STATE_DATA_FIRST_PULL_DOWN
else:
continue
if state == STATE_DATA_FIRST_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_DATA_PULL_UP
else:
continue
if state == STATE_DATA_PULL_UP:
if current == GPIO.HIGH:
current_length = 0
state = STATE_DATA_PULL_DOWN
else:
continue
if state == STATE_DATA_PULL_DOWN:
if current == GPIO.LOW:
lengths.append(current_length)
state = STATE_DATA_PULL_UP
else:
continue
if len(lengths) != 40:
#print ("Data not good, skip")
return False
shortest_pull_up = min(lengths)
longest_pull_up = max(lengths)
halfway = (longest_pull_up + shortest_pull_up) / 2
bits = []
the_bytes = []
byte = 0
for length in lengths:
bit = 0
if length > halfway:
bit = 1
bits.append(bit)
#print ("bits: %s, length: %d" % (bits, len(bits)))
for i in range(0, len(bits)):
byte = byte << 1
if (bits[i]):
byte = byte | 1
else:
byte = byte | 0
if ((i + 1) % 8 == 0):
the_bytes.append(byte)
byte = 0
#print (the_bytes)
checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF
#if the_bytes[4] != checksum:
#print ("Data not good, skip")
#return False
return the_bytes[0], the_bytes[2]
def main():
while True:
humidity, temperature = readDht11()
if humidity is not None and temperature is not None:
print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity))
# test for low temperature
if temperature < set_temp:
print(GPIO.output(relayPin, GPIO.LOW))
# test for high temperature
if temperature > (set_temp + 1):
print(GPIO.output(relayPin, GPIO.HIGH))
else:
print("Failed to retrieve data from humidity sensor")
time.sleep(5) #this is the time between taking readings and acting on them you can reduce it but not below 5 seconds
# Define a destroy function for clean up everything after
# the script finished
def setup():
LCD1602.init(0x27, 1) # init(slave address, background light)
LCD1602.write(0, 0, 'Temperature: %s C')
LCD1602.write(1, 1, 'humidity: %s %%')
time.sleep(2)
def destroy():
# set relay to off
GPIO.output(relayPin, GPIO.LOW)
# Release resource
GPIO.cleanup()
if __name__ == '__main__':
try:
setup()
except KeyboardInterrupt:
destroy()
as a note I haven't managed to get the LCD working in tandem but im more worried about the main functionality

Why am i getting this error, for making gps

from machine import Pin, UART, I2C
from ssd1306 import SSD1306_I2C
#Import utime library to implement delay
import utime, time
#GPS Module UART Connection
gps_module = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))
#print gps module connection details
print(gps_module)
#Used to Store NMEA Sentences
buff = bytearray(255)
TIMEOUT = False
#store the status of satellite is fixed or not
FIX_STATUS = False
#Store GPS Coordinates
latitude = ""
longitude = ""
satellites = ""
gpsTime = ""
#function to get gps Coordinates
def getPositionData(gps_module):
global FIX_STATUS, TIMEOUT, latitude, longitude, satellites, gpsTime
#run while loop to get gps data
#or terminate while loop after 5 seconds timeout
timeout = time.time() + 8 # 8 seconds from now
while True:
gps_module.readline()
buff = str(gps_module.readline())
#parse $GPGGA term
#b'$GPGGA,094840.000,2941.8543,N,07232.5745,E,1,09,0.9,102.1,M,0.0,M,,*6C\r\n'
#print(buff)
parts = buff.split(',')
#if no gps displayed remove "and len(parts) == 15" from below if condition
if (parts[0] == "b'$GPGGA" and len(parts) == 15):
if(parts[1] and parts[2] and parts[3] and parts[4] and parts[5] and parts[6] and parts[7]):
print(buff)
#print("Message ID : " + parts[0])
#print("UTC time : " + parts[1])
#print("Latitude : " + parts[2])
#print("N/S : " + parts[3])
#print("Longitude : " + parts[4])
#print("E/W : " + parts[5])
#print("Position Fix: " + parts[6])
#print("n sat : " + parts[7])
latitude = convertToDigree(parts[2])
# parts[3] contain 'N' or 'S'
if (parts[3] == 'S'):
latitude = -latitude
longitude = convertToDigree(parts[4])
# parts[5] contain 'E' or 'W'
if (parts[5] == 'W'):
longitude = -longitude
satellites = parts[7]
gpsTime = parts[1][0:2] + ":" + parts[1][2:4] + ":" + parts[1][4:6]
FIX_STATUS = True
break
if (time.time() > timeout):
TIMEOUT = True
break
utime.sleep_ms(500)
#function to convert raw Latitude and Longitude
#to actual Latitude and Longitude
def convertToDigree(RawDegrees):
RawAsFloat = float(RawDegrees)
firstdigits = int(RawAsFloat/100) #degrees
nexttwodigits = RawAsFloat - float(firstdigits*100) #minutes
Converted = float(firstdigits + nexttwodigits/60.0)
Converted = '{0:.6f}'.format(Converted) # to 6 decimal places
return str(Converted)
while True:
getPositionData(gps_module)
#if gps data is found then print it on lcd
if(FIX_STATUS == True):
print("fix......")
print(latitude)
print(longitude)
print(satellites)
print(gpsTime)
FIX_STATUS = False
if(TIMEOUT == True):
print("Request Timeout: No GPS data is found.")
TIMEOUT = False
I am making a gps tracker and ran this code on the internet and looked good to start with then i am getting this error:
UART(1, baudrate=9600, bits=8, parity=None, stop=1, tx=4, rx=5, txbuf=256, rxbuf=256, timeout=0, timeout_char=2, invert=None)
b'$GPGGA,030203.00,3651.55112,S,17450.69721,E,1,04,1.25,21.6,M,28.1,M,,*70\r\n'
Traceback (most recent call last):
File "", line 91, in
File "", line 61, in getPositionData
TypeError: unsupported type for neg: 'str'
What am i doing wrong. I have the gps module all hooked up correctly to my raspberry pi

Lidar and Servo on Raspberry pi 4

I've two separate code bases for Tf-mini(Lidar) and servo motor. I want the both code to run at the same time. I tried to combine them in to a single code, But only one code runs at a time. Please help to rewrite or edit the code.
Code for servo motor here:
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
p = GPIO.PWM(7, 100)
t = 0.007
r = 20
p.start(r)
while True:
for i in range(5,r):
p.ChangeDutyCycle(i)
print(i)
time.sleep(t)
for i in range(r,5,-1):
p.ChangeDutyCycle(i)
print(i)
time.sleep(t)`
Code for lidar here:
import time
import serial
ser = serial.Serial("/dev/ttyAMA0", 115200)
def read_data():
while True:
counter = ser.in_waiting
if counter > 8:
bytes_serial = ser.read(9)
ser.reset_input_buffer()
if bytes_serial[0] == 0x59 and bytes_serial[1] == 0x59: # this portion is for python3
print("Printing python3 portion")
distance = bytes_serial[2] + bytes_serial[3]*256 # multiplied by 256, because the binary
data is shifted by 8 to the left (equivalent to "<< 8").
# Dist_L, could simply be added resulting in 16-bit data of Dist_Total.
strength = bytes_serial[4] + bytes_serial[5]*256
temperature = bytes_serial[6] + bytes_serial[7]*256
temperature = (temperature/8) - 256
print("Distance:"+ str(distance))
print("Strength:" + str(strength))
if temperature != 0:
print("Temperature:" + str(temperature))
ser.reset_input_buffer()
if bytes_serial[0] == "Y" and bytes_serial[1] == "Y":
distL = int(bytes_serial[2].encode("hex"), 16)
distH = int(bytes_serial[3].encode("hex"), 16)
stL = int(bytes_serial[4].encode("hex"), 16)
stH = int(bytes_serial[5].encode("hex"), 16)
distance = distL + distH*256
strength = stL + stH*256
tempL = int(bytes_serial[6].encode("hex"), 16)
tempH = int(bytes_serial[7].encode("hex"), 16)
temperature = tempL + tempH*256
temperature = (temperature/8) - 256
print("Printing python2 portion")
print("Distance:"+ str(distance) + "\n")
print("Strength:" + str(strength) + "\n")
print("Temperature:" + str(temperature) + "\n")
ser.reset_input_buffer()
if __name__ == "__main__":
try:
if ser.isOpen() == False:
ser.open()
read_data()
except KeyboardInterrupt(): # ctrl + c in terminal.
if ser != None:
ser.close()
print("program interrupted by the user")
Please help me to combine these two code to run at the same time.
I think I see your problem. Both segments of code are sequentially driven and hence it will create problems. Here is what you need to do (pseudo code):
loop forever:
t1=start_time
change duty cycle #remove the wait code
poll the serial port #the ladar code
t2=end_time
if t2 - t1 < t:
wait (t - (t2-t1))
Being an old Arduino fan myself, I see the struggles of handling the servo motor. I have a simple library to do most of the dirty work for me. You are most welcome to use my library via any of the two links:
https://github.com/vikramdayal/RaspberryMotors or https://pypi.org/project/RaspberryMotors/#description

how to scan ble device based on the mac address stored in database using python

I am using for loop to get the mac address from database but the loop printed the ble mac address 17 times. I tried using if else to compare the mac address with the mac address stored in database but the output scan nothing. Is there any other way to filter out other ble mac address?
import os
import sys
import struct
import bluetooth._bluetooth as bluez
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","DB_USER","DB_PASSWORD","DB_NAME" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM Mac_address"
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
NAME = row[0]
mac_address = row[1]
time = row[2]
LE_META_EVENT = 0x3e
LE_PUBLIC_ADDRESS=0x00
LE_RANDOM_ADDRESS=0x01
LE_SET_SCAN_PARAMETERS_CP_SIZE=7
OGF_LE_CTL=0x08
OCF_LE_SET_SCAN_PARAMETERS=0x000B
OCF_LE_SET_SCAN_ENABLE=0x000C
OCF_LE_CREATE_CONN=0x000D
LE_ROLE_MASTER = 0x00
LE_ROLE_SLAVE = 0x01
# these are actually subevents of LE_META_EVENT
EVT_LE_CONN_COMPLETE=0x01
EVT_LE_ADVERTISING_REPORT=0x02
EVT_LE_CONN_UPDATE_COMPLETE=0x03
EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04
# Advertisment event types
ADV_IND=0x00
ADV_DIRECT_IND=0x01
ADV_SCAN_IND=0x02
ADV_NONCONN_IND=0x03
ADV_SCAN_RSP=0x04
def returnnumberpacket(pkt):
myInteger = 0
multiple = 256
for c in pkt:
myInteger += struct.unpack("B",c)[0] * multiple
multiple = 1
return myInteger
def returnstringpacket(pkt):
myString = "";
for c in pkt:
myString += "%02x" %struct.unpack("B",c)[0]
return myString
def printpacket(pkt):
for c in pkt:
sys.stdout.write("%02x " % struct.unpack("B",c)[0])
def get_packed_bdaddr(bdaddr_string):
packable_addr = []
addr = bdaddr_string.split(':')
addr.reverse()
for b in addr:
packable_addr.append(int(b, 16))
return struct.pack("<BBBBBB", *packable_addr)
def packed_bdaddr_to_string(bdaddr_packed):
return ':'.join('%02x'%i for i in struct.unpack("<BBBBBB", bdaddr_packed[::-1]))
def hci_enable_le_scan(sock):
hci_toggle_le_scan(sock, 0x01)
def hci_disable_le_scan(sock):
hci_toggle_le_scan(sock, 0x00)
def hci_toggle_le_scan(sock, enable)
cmd_pkt = struct.pack("<BB", enable, 0x00)
bluez.hci_send_cmd(sock, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)
def hci_le_set_scan_parameters(sock):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
SCAN_RANDOM = 0x01
OWN_TYPE = SCAN_RANDOM
SCAN_TYPE = 0x01
def parse_events(sock, loop_count=100):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# perform a device inquiry on bluetooth device #0
# The inquiry should last 8 * 1.28 = 10.24 seconds
# before the inquiry is performed, bluez should flush its cache of
# previously discovered devices
flt = bluez.hci_filter_new()
bluez.hci_filter_all_events(flt)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
done = False
results = []
myFullList = []
for i in range(0, loop_count):
pkt = sock.recv(255)
ptype, event, plen = struct.unpack("BBB", pkt[:3])
#print "--------------"
if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
i =0
elif event == bluez.EVT_NUM_COMP_PKTS:
i =0
elif event == bluez.EVT_DISCONN_COMPLETE:
i =0
elif event == LE_META_EVENT:
subevent, = struct.unpack("B", pkt[3])
pkt = pkt[4:]
if subevent == EVT_LE_CONN_COMPLETE:
le_handle_connection_complete(pkt)
elif subevent == EVT_LE_ADVERTISING_REPORT:
#print "advertising report"
num_reports = struct.unpack("B", pkt[0])[0]
report_pkt_offset = 0
for i in range(0, num_reports):
Mac = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
for Mac in row[1]:
print "-------------"
#print "\tfullpacket: ", printpacket(pkt)
print "\tMAC address: ", row[1] # commented out - don't know what this byte is. It's NOT TXPower
txpower, = struct.unpack("b", pkt[report_pkt_offset -2])
print "\t(Unknown):", txpower
rssi, = struct.unpack("b", pkt[report_pkt_offset -1])
print "\tRSSI:", rssi
break
# build the return string
Adstring = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
Adstring += ","
Adstring += returnstringpacket(pkt[report_pkt_offset -22: report_pkt_offset - 6])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -1])
#print "\tAdstring=", Adstring
myFullList.append(Adstring)
done = True
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return myFullList
db.close()
The above is save as blescan.py. I run this file below to do a ble scan.
import blescan
import sys
import bluetooth._bluetooth as bluez
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
print "ble thread started"
except:
print "error accessing bluetooth device..."
sys.exit(1)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
while True:
returnedList = blescan.parse_events(sock, 10)
print "----------"

Sockets, communication stops

I have a simple question about socket programming. I've done to implement a server and two clients as following codes, but all of sudden it stops while it communicates each other. I have no idea why it happens all the time.
Would you give me advice, hint, or help?
Thank you for your time.
Client
# simple client
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
buf = 100
s.connect((host, port))
i = 0
timestep = 0
while(1):
k = '01'#+str(timestep)
#1
s.send(k)
print 'sending message is', k
#2
v = s.recv(buf)
print v
if v == 'hold 01':
print 'timestep is', timestep#'send the previous message'
if timestep == 0:
timestep == 0
else:
timestep -= 1
else:
print 'read data'
FILE = open("datainfo1.txt", "r+")
msg = FILE.read()
FILE.close()
#3
while(1):
tmp, msg = msg[:buf], msg[buf:]
s.send(tmp)
print len(tmp)
if len(tmp) < buf:
print 'break'
break
# send file
i+=1
timestep+=1
print 'end'
s.close()
Server
import socket, sys
# set up listening socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
# bind lstn socket to this port
lstn.bind(("", port))
lstn.listen(5)
# initialize buffer size
buf = 100
# initialize concatenate string, v
v = ''
# initialize client socket list
cs = []
check = [0, 0]
# a fixed number of clients
nc = 1
count = 0
status = [0,0]
j = 0
step = [0,0]
for i in range(nc):
(clnt,ap) = lstn.accept()
clnt.setblocking(0)
cs.append(clnt)
file = open("output_analysis.txt","w+")
while (len(cs) > 0):
clnt = cs.pop(0)
cs.append(clnt)
try:
#1
k = clnt.recv(buf)
print "k=",k,"\n"#[:2]
if k == '01':
print "1st client connected", status[0]
file.write("1st\t")
if status[0] == 0:
v = 'hold 01'
check[0] = 1
elif status[0] == 1:
v = 'go 01'
# status[0] = 0
print v, "the message\n"
file.write(v)
file.write("\t")
#2
clnt.send(v)
if status[0] == 1:
FILE = open("client1.txt","w+")
print 'receive 01'
#3
while(1):
status[0] = 0
print '1st : receiving'
msg = clnt.recv(buf)
print len(msg)
if len(msg) < buf:
print 'break'
#FILE.close()
break
elif k == '02':
print "2nd client connected", status[0]
file.write("2nd\t")
if status[1] == 0:
v = 'hold 02'
check[1] = 1
elif status[1] == 1:
v = 'go 02'
# status[0] = 0
print v, "the message\n"
file.write(v)
file.write("\t")
#2
clnt.send(v)
if status[1] == 1:
FILE = open("client2.txt","w+")
print 'receive 02'
#3
while(1):
status[1] = 0
print '2nd : receiving'
msg = clnt.recv(buf)
print len(msg)
if len(msg) < buf:
print 'break'
#FILE.close()
break
if check[0] == 1:# and check[1] == 1:
print j, 'here\n'
j += 1
for i in range(2):
check[i] = 0
status[i] = 1 # which means, all clients are connected
print check, status
else:
print 'hello'
except: pass
file.close()
lstn.close()
except: pass
You're ignoring all exceptions. This is a bad idea, because it doesn't let you know when things go wrong. You'll need to remove that except handler before you can reasonably debug your code.
One problem is you are setting non-blocking mode:
clnt.setblocking(0)
But never checking that it is safe to send or recv data. It turns out that since the code is ignoring all exceptions, it isn't seeing the following error that I got when I removed the try:
Exception [Errno 10035] A non-blocking socket operation could not be completed immediately
After removing the setblocking call, the code proceeded further, but still has problems.
Describing what problem you are trying to solve would help to understand what the code is trying to do.

Categories

Resources