We have two IR sensors interfaced with our RPi3, and we want to store the sensor data into the database.
This is the code we are trying to run.
db = MySQLdb.connect("localhost","Keerti","Keerti","test")
curs = db.cursor()
try:
print "module test"
time.sleep(2)
print "ready"
while True:
if GPIO.input(4):
print "motion detected 1"
curs.execute("INSERT INTO parktest(irname,irdata) VALUES('%f', '%f')" % (1,1))
time.sleep(1)
else:
print "no motion 1"
curs.execute("INSERT INTO parktest(irname,irdata) VALUES('%f', '%f')" % (1,0))
time.sleep(1)
if GPIO.input(14):
print "motion detected 2"
curs.execute("INSERT INTO parktest(irname, irdata) VALUES('%f','%f')" % (2,1))
time.sleep(1)
else:
print "no motion 2"
curs.execute("INSERT INTO parktest(irname, irdata) VALUES('%f','%f')" % (2,0))
time.sleep(1)
except KeyboardInterrupt:
print "quit"
GPIO.cleanup()
This, runs fine without any warnings or errors. However, it isn't storing anything in the table.
What might be the issue?
After execute(), you must use commit() to confirm all the pending changes.
Or you can use rollback() to cancel all the pendings.
Otherwise, nothing will be changed in database.
Related
Good day. I wrote an application on python that collects call logs from the Avaya PBX and writes them to the mysql database. It works well, but sometimes the PBX sends an empty string for some reason and the program fails. I attach the screen and code below. I understand that you need to wrap the function in an exception: try except, but I don’t understand how to do it. Please tell me how to do this.enter image description here
def write_db(item, *agrs):
connection = pymysql.connect(host='localhost',
user='acdr',
password='it8ejokd',
db='avaya_cdr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
DBTBL = "cdr102019"
DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"
dep_num_call = find_dep(item[3].replace(' ', ''))
name_dep_call = name_dep(dep_num_call)
dep_num_dial = find_dep(item[4].replace(' ', ''))
name_dep_dial = name_dep(dep_num_dial)
item.append(name_dep_call)
item.append(name_dep_dial)
item[1] = item[1] + "00"
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
connection.commit()
finally:
connection.close()
# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)
# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')
# Слушаем запросы и пишем в db
while True:
connection, address = server_socket.accept()
data = connection.recv(1024)
if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
str = data.decode("utf-8")
item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
print(item)
write_db(item)
connection.close()
You'll have to catch the exception, so we can cater for a few types, but just to be sure and get you up and running, you could do the following :)
try:
with connection.cursor() as cursor:
sql = (
"INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES "
"(%s,%s,%s,%s,%s,%s,%s)"
)
cursor.execute(
sql,
(item),
)
connection.commit()
except Exception as e:
print("Error occurred: %s"% e)
finally:
connection.close()
This should do the trick. I've used all four elements of try/except/else/finally here, with brief explanations of when they're executed.
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
except Exception: # If this code fails, ignore it
pass
else: # If the code inside 'try' succeeds, execute this code.
connection.commit()
finally: # Regardless of whether or not the code inside 'try' succeeds, execute this code
connection.close()
I'm trying to get data from raspberry pi 3 to Azure
The script reads data from Raspberry Pi3, which is connect via bluetooth to sensors and takes several values.
Unfortunately i am getting an error, when I run it
"local variable 'temperature' referenced before assignment"
def iothub_client_sample_run():
msgs=[]
for address, name in list(devices.items()):
try:
client = iothub_client_init()
if client.protocol == IoTHubTransportProvider.MQTT & (name == "Flower care"):
msg_txt_formatted = MSG_TXT % (
temperature,
sunlight,
moisture,
fertility)
message = IoTHubMessage(msg_txt_formatted)
# optional: assign ids
message.temperature_id = "%d" % temperature
client.send_event_async(message, send_confirmation_callback, devices.items())
print ( "IoTHubClient.send_event_async accepted message {} for transmission to IoT Hub.".format(devices.items()) )
return msgs
while 1:
msgs=iothub_client_sample_run()
for msg in msgs:
print msg['topic']
print msg['payload']
(result, mid)=mqttc.publish(msg['topic'],msg['payload'])
print ( "Send status: %s" % status )
time.sleep(10)
mqttc.disconnect()
except IoTHubError as iothub_error:
print ( "Unexpected error %s from IoTHub" % iothub_error )
return
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
print_last_message_time(client)
The error message here is pretty clear.
Remember that Python reads and executes code one line at a time so if you have a variable stated after the function that uses it then it is going to throw an error. Juggle your code around to put your variables before they are called and you shouldn't have any problems with this error again.
This script is supposed to continuously read different rfid tags once, print out the tag number and send it to the remote xbee. However, it keeps reading tags in a continuous loop. I want it to read a tag once display the result and send it to the remote xbee, then wait for a different tag and repeat the process.
def main():
ann = as3992_api.AntennaDevice()
print "Firmware info: %s\nHardware info: %s" % ann.get_system_info()
print "Activating antenna"
ann.set_antenna_state(True)
print " Reading Tags:"
while True:
try:
for epc, rssi in ann.iter_epc_rssi():
#time.sleep(1)
print "---------------------------------------"
print "Scanning Tag..."
time.sleep(1)
print "Tag code epc:" +epc.encode("HEX"),rssi
#send tag info to remote xbee
xbee.tx_long_addr(frame='0x1', dest_addr=XBEE1_ADDR_LONG, data=epc.encode("HEX"))
print "---------------------------------------"
time.sleep(1)
print "Sending tag information to XBee 1 ..."
except KeyboardInterrupt:
ann.set_antenna_state(False)
break
if __name__ == "__main__":
main()
def main():
ann = as3992_api.AntennaDevice()
print "Firmware info: %s\nHardware info: %s" % ann.get_system_info()
print "Activating antenna"
ann.set_antenna_state(True)
print " Reading Tags:"
ok=[]
while True:
try:
for epc, rssi in ann.iter_epc_rssi():
if epc+rssi not in ok:
#time.sleep(1)
print "---------------------------------------"
print "Scanning Tag..."
time.sleep(1)
print "Tag code epc:" +epc.encode("HEX"),rssi
#send tag info to remote xbee
xbee.tx_long_addr(frame='0x1', dest_addr=XBEE1_ADDR_LONG, data=epc.encode("HEX"))
print "---------------------------------------"
time.sleep(1)
print "Sending tag information to XBee 1 ..."
ok.append( epc+rssi )
except KeyboardInterrupt:
ann.set_antenna_state(False)
break
I am working on a python script to take an incoming String of data from several arduinos to read, split and insert that data into a database.
The problem is the sensor data varies in the number of values depending on what kind of sensor is used. I cannot figure out the proper way to loop through the separated pieces and insert them properly.
A '1' specifies 10HS sensor and need 1 space for the incoming value
The String comes in like this for 10HS sensors:
"Cucumber2015,Arduino01,1,20150918124200,25.3,75.5,1,12 .....
A '2' specifies 10HS sensor and need 1 space for the incoming value
"Cucumber2015,Arduino01,1,20150918124200,25.3,75.5,2,12,24,23 ......
The for loop should repeat until all the sensor values have an insert statement for their respective tables.
I have tried the code shown below and keep getting errors.
How can I accomplish this? Besides the syntax problem, am I going about this correctly?
My current error
File "serialToDbV3.py", line 50
index =index+1
^
SyntaxError: invalid syntax
Python code
#!/usr/bin/python
import serial
import MySQLdb
#establish connection to MySQL. You'll have to change this for your database.
dbConn = MySQLdb.connect("localhost","python_user","password","IrrigationDB") or die ("could not connect to database")
#open a cursor to the database
cursor = dbConn.cursor()
device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
baudrate = 9600
def getSerialData():
try:
print "Trying...",device
arduino = serial.Serial(device, baudrate)
except:
print "Failed to connect on",device
try:
print "Trying to get data"
next(arduino)
data = arduino.readline() #read the data from the Arduino
pieces = data.split(",") #split the data by the tab
print "Data: %s" % data
print "Piece 0: ProjectID %s" % pieces[0]
print "Piece 1: ArduinoID %s" % pieces[1]
print "Piece 2: Plot# %s" % pieces[2]
print "Piece 3: SQLTime %s" % pieces[3]
print "Piece 4: AirTemp %s" % pieces[4]
print "Piece 5: Humidity %s" % pieces[5]
print "Piece 6: SensType %s" % pieces[6]
print "Piece 7: SensData %s" % pieces[7]
print "Piece 8: %s" % pieces[8]
print "Piece 9: %s" % pieces[9]
print "Piece 10: %s" % pieces[10]
#Here we are going to insert the data into the Database
try:
print "Trying insertion..."
cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Project`(`idProject`)VALUES (%s)", (pieces[0]))
cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Arduino`(`idArduino`,`FK_ProjectID`)VALUES (%s,%s)", (pieces[1],pieces[0]))
cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Plot`(`idPlot`,`FK_ArduinoID`)VALUES (%s,%s)", (pieces[2],pieces[1]))
cursor.execute("INSERT INTO `IrrigationDB`.`Reading`(`DateAndTime`,`airTempC`,`relativeHumidity`,`FK_PlotID`)VALUES (%s,%s,%s,%s)", (pieces[3],pieces[4],pieces[5],pieces[2]))
startingPosition = 6
for index in xrange(startingPosition, len(pieces), step):
if pieces[6] == 1 :
cursor.execute("INSERT INTO `IrrigationDB`.`10HS_Sensor`(`id10HS_Sensor`,`DielectricPermittivity`)VALUES (%s,%s,%s)", (pieces[2],pieces[i+1])
index =index+1
if pieces[6] == 2 :
cursor.execute("INSERT INTO `IrrigationDB`.`GS3_Sensor`(`idGS3_Sensor`,`DielectricPermittivity`,`soilTempC`,`electricalConductivity`)VALUES (%s,%s,%s)", (pieces[2],pieces[i+1],pieces[i+2],pieces[i+3]))
index=index+3
except MySQLdb.IntegrityError:
print "failed to insert data"
except:
print "Failed to get data from Arduino!"
val = 0
while val == 0 :
getSerialData()
Use proper exception reporting, at least until you get to end-user land.
try:
cursor.execute("INSERT IGNORE INTO `IrrigationDB`.`Project`(`idProject`)VALUES (%s)", (pieces[0]))
except Exception, e:
print "this is sql #6", e
raise
This will tell you more clearly what is going on, which you can then post here.
I want to make a loop to be storing data from serial database. The code I have goes through the first loop but fails to execute in the next loops. Here is the code:
import serial
import MySQLdb
import time
dbConn = MySQLdb.connect("localhost","root","root","testing") or die ("could not connect to database")
cursor = dbConn.cursor()
device = '/dev/ttyACM0'
max=30
start=time.time()
while True:
try:
print "Trying...",device
arduino = serial.Serial(device, 9600)
except:
print "Failed to connect on",device
try:
data = arduino.readline()
pieces = data.split("\t")
try:
cursor.execute("INSERT INTO productCount (line,count) VALUES (%s,%s)", (pieces[0],pieces[1]))
dbConn.commit()
cursor.close()
except MySQLdb.IntegrityError:
print "failed to insert data"
#finally:
#cursor.close()
except:
print "Failed to get data from Arduino!"
time.sleep(10)
print "looping..."
remaining=max+start-time.time()
print "%s seconds remaining" % int(remaining)
if remaining<=0:
cursor.close()
break
You closed the cursor inside while loop. in try and finally.Put this in break condition of while loop
cursor.close()
Put it outside, or put this inside while loop
cursor = dbConn.cursor()