DHT Sensor Python script error - python

I have a sensor type DHT22 connected to a raspberry.
I have written a script in python but when I run it I get errors
#!/usr/bin/python
import MySQLdb
import subprocess
import re
import sys
import time
import datetime
import Adafruit_DHT
conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi")
while(True):
date = time.strftime("%d/%m/%Y")
clock = time.strftime("%H:%M")
#output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]);
output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
matches = re.search("Temp =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
temp = float(matches.group(1))
matches = re.search("Hum =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
humidity = float(matches.group(1))
# MYSQL DATA Processing
c = conn.cursor()
c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity))
#print "DB Loaded"
time.sleep(360)
This is the error encountered on running the script:
root#raspberrypi:/home# ./hdt.py
Traceback (most recent call last):
File "./dht.py", line 22, in <module>
matches = re.search("Temp =\s+([0-9.]+)", output)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

Adafruit_DHT.read_retry() does not return string. re.search expects string as second parameter.
Please have a look at code below (taken from Adafruit_Python_DHT/examples):
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)

Related

TypeError in Python3.10 script

I am trying to do network automation task using python but ran with type error while running the below given script.
I AM STUCK AT SAME KIND OF ERROR, CAN YOU GUYS PLEASE HELP ME OUT HOW TO FIX THIS ?*
durai#durai-virtual-machine:~/Network Automation$ python3 session_details.py
devices list: ['1.1.1.1', '2.2.2.2', '6.6.6.6', '7.7.7.7', '', '']
establishing telnet session: 1.1.1.1 cisco cisco
--- connected to: 1.1.1.1
--- getting version information
Traceback (most recent call last):
File "/home/durai/Network Automation/session_details.py", line 82, in <module>
device_version = get_version_info(session)
File "/home/durai/Network Automation/session_details.py", line 65, in get_version_info
version_output_parts = version_output_lines[1].split(',')
**TypeError: a bytes-like object is required, not 'str'**
durai#durai-virtual-machine:~/Network Automation$
THE BELOW IS THE BLOCK OF CODE WHERE I AM GETTING ERROR !
#-----------------------------------------------------------------------
def get_version_info(session):
print ('--- getting version information')
session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])
# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()
version_output_parts = version_output_lines[1].split(',')
version = version_output_parts[2].strip()
print ('--- got version: ', version)
return version
#-----------------------------------------------------------------------
FULL CODE FOR YOUR REFERENCE:
#!/usr/bin/python
import re
import pexpect
#-----------------------------------------------------------------------
def get_devices_list():
devices_list = []
file = open('devices', 'r')
for line in file:
devices_list.append( line.rstrip() )
file.close()
print ('devices list:', devices_list)
return devices_list
#-----------------------------------------------------------------------
def connect(ip_address, username, password):
print ('establishing telnet session:', ip_address, username, password)
telnet_command = 'telnet ' + ip_address
# Connect via telnet to device
session = pexpect.spawn('telnet ' + ip_address, timeout=20)
result = session.expect(['Username:', pexpect.TIMEOUT])
# Check for error, if so then print error and exit
if result != 0:
print ('!!! TELNET failed creating session for: ', ip_address)
exit()
# Enter the username, expect password prompt afterwards
session.sendline(username)
result = session.expect(['Password:', pexpect.TIMEOUT])
# Check for error, if so then print error and exit
if result != 0:
print ('!!! Username failed: ', username)
exit()
session.sendline(password)
result = session.expect(['>', pexpect.TIMEOUT])
# Check for error, if so then print error and exit
if result != 0:
print ('!!! Password failed: ', password)
exit()
print ('--- connected to: ', ip_address)
return session
#-----------------------------------------------------------------------
def get_version_info(session):
print ('--- getting version information')
session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])
# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()
version_output_parts = version_output_lines[1].split(',')
version = version_output_parts[2].strip()
print ('--- got version: ', version)
return version
#-----------------------------------------------------------------------
devices_list = get_devices_list() # Get list of devices
version_file_out = open('version-info-out', 'w')
# Loop through all the devices in the devices list
for ip_address in devices_list:
# Connect to the device via CLI and get version information
session = connect(ip_address, 'cisco', 'cisco')
device_version = get_version_info(session)
session.close() # Close the session
version_file_out.write('IP: '+ip_address+' Version: '+device_version+'\n')
# Done with all devices and writing the file, so close
version_file_out.close()
Python has two different kinds of strings. Normal strings are Unicode, where the individual characters are several bytes long, to handle Unicode characters. Many activities (like networking) need to use byte strings, which are written b"abc".
That's the problem here. The pexpect module is returning a byte string. So, in this line:
version_output_parts = version_output_lines[1].split(',')
version_output_parts is a byte string, but ',' is a Unicode string, and you can't mix them. So, you can either keep it bytes and do this:
version_output_parts = version_output_lines[1].split(b',')
or you can convert it to a Unicode string:
version_output_parts = version_output_parts.decode('utf-8')
version_output_parts = version_output_lines[1].split(b',')
It depends on how much you need to do with the parts.
It's the part where you extract the version that is bugged.
Try using print statements as demonstrated below to check the data types of your variables at each step.
This error suggests that you are using a method that is not available for the given data type e.g. calling a string method on an array or so on.
def get_version_info(session):
print ('--- getting version information')
session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])
# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()
# print(version_output_lines)
version_output_parts = version_output_lines[1].split(',')
# print(version_output_parts)
version = version_output_parts[2].strip()
# print(version)
print ('--- got version: ', version)
return version

Python script makes AssertionError when trying to MariaDB

I have this piece of code that collects data from a HAT connected to a Raspberry.
When run it gives this error:
[51.57, 22.30, 1002.01]
Traceback (most recent call last):
File "dbWriter.py", line 45, in <module>
write2DB(record)
File "dbWriter.py", line 26, in write2DB
assert len(values) == 3
AssertionError
I am by no means a programmer, i just fiddle around. It is meant to save 'record' to a database, which is then read and updated in realtime on an apache2 server. All help appreciated.
import mysql.connector
from itertools import repeat
import sys
import bme680
import time
try:
sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY)
except IOError:
sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY)
sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)
mydb = mysql.connector.connect(
host='localhost',
user='pi',
passwd='pass',
database='weatherDB'
)
mycursor = mydb.cursor()
def write2DB(values):
assert len(values) == 3
sqlText = '''INSERT INTO data(humidity, temperature, pressure) VALUES({},{}, })'''.format(values[0], values[1], values[2])
mycursor.execute(sqlText)
mydb.commit()
for _ in repeat(None):
sensor.get_sensor_data()
output_humi = '{0:.2f}'.format(
sensor.data.humidity)
output_temp = '{0:.2f}'.format(
sensor.data.temperature)
output_pres = '{0:.2f}'.format(
sensor.data.pressure)
record = []
record = ('[' + (output_humi) + ', ' + (output_temp) + ', ' + (output_pres) + ']')
print(record)
write2DB(record)
time.sleep(10)
pass
You have:
record = ('[' + (output_humi) + ', ' + (output_temp) + ', ' + (output_pres) + ']')
record evaluates to a single string, not a list of 3 elements and hence your exception.
Change the above to:
record = [output_humi, output_temp, output_pres]
You are also missing a { in your format specification. It should be:
sqlText = '''INSERT INTO data(humidity, temperature, pressure) VALUES({},{}, {})'''.format(values[0], values[1], values[2])
An alternative would be to use a prepared statement:
sqlText = 'INSERT INTO data(humidity, temperature, pressure) VALUES(%s, %s, %s)'
mycursor.execute(sqlText, values)
In the above case you will be passing actual strings as the values. I don't know how the columns are defined, but no matter. If they are defined as floating point or decimal values, the strings will be converted to the correct type.

ValueError: invalid literal for float()

I am trying to read lightware rangefinder SF11 through serial but using Raspberry, and I am not familiar with Python, but I tried this:
import time
import serial
print('Code is Running.')
# Make a connection to the com port.
serialPortName = '/dev/ttyUSB0'
serialPortBaudRate = 115200
port = serial.Serial(serialPortName, serialPortBaudRate, timeout=0.1)
port.write('www\r\n')
port.readline() # Read and ignore any unintended responses
port.write('?\r\n') # Get the product information
productInfo = port.readline()
print('Product information: ' + productInfo)
while True:
port.write('LD\r\n') # reading distance (First return, default filtering)
distanceStr = port.readline()
distanceCM = float(distanceStr) * 100 # Convert the distance string into a number
print(distanceCM)
time.sleep(0.05) # Wait for 50ms before the next reading
When I run the code it's turn this:
Traceback (most recent call last):
File "range.py", line 25, in <module>
distanceCM = float(distanceStr) * 100 # Convert the distance string into a number
ValueError: invalid literal for float(): 1.72 m 0.086 V

Python code not storing readings in a .csv file. "sequence expected" error recieved. Any idea how to fix this?

I was applying a code that reads the coordinates from a gps and fills it in a .csv file.i am new to all of this so i can't get my head around this problem. I have used the "csv" code in other programs and it has worked. But here it is giving me a hard time. The error is as follows:
Traceback (most recent call last):
File "GPScodetest2.py", line 48, in <module>
data_writer.writerow(data)
_csv.Error: sequence expected
How to fix this?
P.S the code:
from time import sleep, strftime, time
import serial
import pynmea2
import datetime
from csv import writer
#setup the serial port to which gps is connected
port = "/dev/ttyS0"
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
dataout = pynmea2.NMEAStreamReader()
counter = 0
def get_sense_data():
while True:
newdata = ser.readline()
if newdata[0:6] == '$GPGGA':
parsed_line = pynmea2.parse(newdata)
latitude_reading = parsed_line.latitude
alpha = latitude_reading
#print(newlat)
longitude_reading = parsed_line.longitude
beta = longitude_reading
#print(newlong)
#print(latitude_reading)
#print(longitude_reading)
sense_data=[]
sense_data.append(counter)
sense_data.append(datetime.datetime.now())
sense_data.append(alpha)
sense_data.append(beta)
return sense_data
with open('GPSdata.csv', 'w+') as f:
data_writer = writer(f)
data_writer.writerow(['Term No.','Date and Time','Latitude',
' Longitude'])
while True:
data = get_sense_data
data_writer.writerow(data)
counter = counter + 1
You aren't calling the function:
data = get_sense_data
Try calling it:
data = get_sense_data()

Physical Gmail Notifier Led

So I was trying to make a physical Gmail notifier . Using a 330 ohm resistor and an LED to blink when I have unread mail. This is proving to be tougher then I thought. I keep getting this output when I go to execute the python code.
raspi_gmail.py:34: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(PIN_mail, GPIO.OUT)
Traceback (most recent call last):
File "raspi_gmail.py", line 45, in <module>
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
File "/usr/local/lib/python2.7/dist-packages/feedparser.py", line 356, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'fullcount'
This is the Code I'm using , with the credentials cut out of course.
from os.path import exists
import RPi.GPIO as GPIO, feedparser
GPIO.setmode(GPIO.BCM)
file=".unreadmail.txt"
# insert your username and password
USERNAME="[USERNAME]#gmail.com"
PASSWORD="[PASSWORD]"
# if .unreadmail.txt doesn't exists the script wont work
# the following lines check if the file exists and create it if needed
if exists(file) == False:
data = open(file, 'w')
data.write("0")
data.close()
# edit these two value depending on your pin wiring
PIN_mail=6
PIN_check=18
data = open(file, 'r')
status=int(data.read())
data.close()
GPIO.setup(PIN_mail, GPIO.OUT)
GPIO.setup(PIN_check, GPIO.OUT)
GPIO.output(PIN_check, False)
if status == 0:
GPIO.output(PIN_mail, True)
else:
GPIO.output(PIN_mail, False)
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
# output on .unreadmail.txt and GPIO
data = open(file, 'w')
if newmails > 0:
GPIO.output(PIN_mail, False)
data.write("1")
else:
GPIO.output(PIN_mail, True)
data.write("0")
GPIO.output(PIN_check, True)
data.close()
Any help would be appreciated , I'm kind of a newbie to this whole aspect.

Categories

Resources