I have most of this app running smoothly I am trying to get this python code to send serial data through but I always get a 404 when I try to use python3 I get issues with the serialutil as far as basestring not being defined etc etc in the serial libraries. So I revert back to python 2.7 and am wondering if its possible to add the https into the string somewhere just to override whatever is happening that is reverting it back to http?
import serial
import time
import requests
import json
firebase_url = 'https://ourfleet.firebaseio.com'
auth_token = '0sBNZjz4uQvLteDoGSAJSKSDKSDBNASASJSDL'
#Connect to Serial Port for communication
ser = serial.Serial('/dev/tty.wchusbserial410', 9600, timeout=0)
#Setup a loop to send GPS values at fixed intervals
#in seconds
fixed_interval = 10
while 1:
try:
#GPS value obtained from Arduino + Ublox
gps_c = ser.readline()
#current time and date
time_hhmmss = time.strftime('%H:%M:%S')
date_mmddyyyy = time.strftime('%d/%m/%Y')
#current location name
gps_location = 'ourfleet'
print (gps_c + ',' + time_hhmmss + ',' + date_mmddyyyy + ',' + gps_location)
#insert record
data = {'date':date_mmddyyyy,'time':time_hhmmss,'location':gps_c}
result = requests.post('https://ourfleet.firebaseio.com' + '/' + gps_location + '/gps_c.json'+ auth_token, data=json.dumps(data))
#insert record
print ('Record inserted. Result Code = ' + str(result.status_code) + ',' + result.text)
time.sleep(fixed_interval)
except IOError:
print('Error! Something went wrong.')
time.sleep(fixed_interval)
Related
So I have a simple Client-Server.
They properly connect with command line arguments, send and receiving data.
When the server isn't up and running but the client executes: Attempt to connect, after 1 second display message that it timed out (3 times) before closing.
the closest i can come to it, is simply attempting it 3 times.
import sys
from socket import *
# Get the server hostname, port and data length as command line arguments
argv = sys.argv
host = argv[1]
port = argv[2]
count = argv[3]
# Command line argument is a string, change the port and count into integer
port = int(port)
count = int(count)
data = 'X' * count # Initialize data to be sent
# Create UDP client socket. Note the use of SOCK_DGRAM
clientsocket = socket(AF_INET, SOCK_DGRAM)
# Sending data to server
# times out after 1 second (?)
for i in range(3):
try:
print("Sending data to " + host + ", " + str(port) + ": " + data)
clientsocket.sendto(data.encode(),(host, port))
# Receive the server response
dataEcho, address = clientsocket.recvfrom(count)
# Display the server response as an output
print("Receive data from " + address[0] + ", " + str(address[1]) + ": " + dataEcho.decode())
break
except:
print("timed out")
finally:
#Close the client socket
clientsocket.close()
How would I add a timer to it? Just adding 1 second between each attempt instead of how I coded.
If you just want the program to sleep for x seconds you could import time, and then add time.sleep(num_of_seconds_to_sleep) after your clientsocket.close() line.
I am using the following script as the basis for a homebuilt energy monitoring system. The script serves as a gateway between an arduino based receiver connected to the serial port and passes it on through MQTT as well as a http POST. The script is intended to run indefinitely. However it crashes at random intervals, anywhere from an hour to a week. I cannot figure out why. Any pointers on how to determine why and how to log the error would be appreciated. Here is the script:
import time
import datetime
import requests
import paho.mqtt.publish as publish
#import csv
import logging
logging.basicConfig(level=logging.ERROR, filename='serial-read.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
data = ""
pieces = ""
while True:
while True:
try:
receiver = serial.Serial(device, 57600)
receiver.flushInput()
except serial.SerialException:
print "cannot connect. will try again..."
time.sleep(10)
else:
break
try:
data = receiver.readline()
#print (data)
#print repr(data)
#with open ("data_log.csv","a") as f:
#writer = csv.writer(f,delimiter=",")
#writer.writerow([time.time(),data])
pieces = data.split(" ")
try:
nodeid = int(pieces[0])
except ValueError:
pass
try:
data1 = int(pieces[1])
data2 = int(pieces[2])
data3 = int(pieces[3])
data4 = int(pieces[4])
except IndexError:
pass
#print nodeid
if nodeid == 6:
#print "Power:"
Irms = data3 + data4
print Irms
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
localtime = "'" + localtime + "'"
#print localtime
payload = {"timestamp" : localtime, "Irms" : Irms}
r = requests.post('http://www.********.ca/*****.php', params=payload)
#print(r.url)
publish.single("myHome/energy/power", Irms, hostname="192.168.1.120")
elif nodeid == 2:
temp = float(data1)/10
#print "temp:"
#print temp
hum = data3
publish.single("myHome/garage/temperature", temp, hostname="192.168.1.120")
publish.single("myHome/garage/humidity", hum, hostname="192.168.1.120")
temphum = str(temp) + " " + str(hum)
publish.single("myHome/garage/temphum", temphum, hostname="192.168.1.120")
#print temphum
except serial.serialutil.SerialException:
print "no device connected. Please reconnect device..."
receiver.close()
time.sleep(5)
Thank you!
Baobab
Your second try statement catches the following exception:
except serial.serialutil.SerialException:
But what if the block of code generates a different exception? The script will exit. Add a second except, as in the first try loop, to catch any other exceptions, and print them to your log.
I am trying to send temperature data over onto one of my website currently online. This code consists of measuring the temperature through a sensor(ds18b20), sending that data onto a mysql databse entitled temp_pi and specifically onto a table intitled TAB_CLASSROOM and lastly sending that data onto a webpage of mine. Everything in this code runs except for the sendDataToServer() part. I specify the error right before this particular line. I have the PHP set up on my website for this to work.
import os
import glob
import time
import MySQLdb
import datetime
import mysql.connector
from mysql.connector import Error
#define db and cur
db = MySQLdb.connect(host = "127.0.0.1", user = "root", passwd = "xB7O4fXmuMpF6M0u", db = "temp_pi")
cur = db.cursor()
#connection to the database
try:
connection = mysql.connector.connect(host='127.0.0.1',
database='temp_pi',
user='root',
password='xB7O4fXmuMpF6M0u')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL database... MySQL Server version on ",db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print ("Your connected to - ", record)
except Error as e :
print ("Error while connecting to MySQL", e)
#obtaining the temperature through the ds18b20 sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c
#Defining sendDataToServer() and trying to send this data towards my website
def sendDataToServer():
global temperature
threading.Timer(600,sendDataToServer).start()
print("Mesuring...")
read_temp()
temperature = read_temp()
print(temperature)
temp= read_temp()
urllib3.urlopen("http://francoouesttemp.tech/weather/add_data.php?temp="+temp).read()
#insertion of data into the mysql database
while True:
print("putting temperature data into temp_pi database")
i = datetime.datetime.now()
year = str(i.year)
month = str(i.month)
day = str(i.day)
date = day + "-" + month + "-" + year
hour = str(i.hour)
minute = str(i.minute)
second = str(i.second)
timestr = hour + ":" + minute + ":" + second
valT = str(read_temp())
try:
cur.execute("""INSERT INTO TAB_CLASSROOM(temp_c,T_Date,T_Time) VALUES(%s,%s,%s)""",(valT,i,timestr))
db.commit()
except:
db.rollback()
time.sleep(5)
#this is the part where my code tells me : NameError : name 'urllib3' is not defined ----- I want this part of the code to send the temperature, date and time over to my website.
sendDataToServer()
cur.close()
db.close()
import urllib
import requests
url = '....'
response = urllib.request.urlopen(url)
If you want to send requests using urllib3, you need to create a pool manager first.
Alternatively, you could use the HTTP client in the Python standard library. Its urlopen function is called urllib.request.urlopen. Depending on what you are trying to do, the requests package might also be an option, but it has certain disadvantages when it comes to certificate management for HTTPS URLs (the built-in client will automatically use the system certificate store).
Everyone, hello!
I'm currently trying to use Telnetlib (https://docs.python.org/2/library/telnetlib.html) for Python 2.7 to communicate with some external devices.
I have the basics set up:
import sys
import telnetlib
tn_ip = xxxx
tn_port = xxxx
tn_username = xxxxx
tn_password = xxxx
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn, tn, 15)
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
tn.read_until(searchfor)
print "Found it!"
except:
print "Unable to connect to Telnet server: " + tn_ip
telnet()
And I'm trying to go through all of the data it's outputting (which is quite a lot) until I catch what I need. Although it is logging in quite fine, and even finds the data I'm looking for, and prints my found it message, I'm trying for a way to keep the connection with telnet open as there might be other data (or repeated data) i would be missing if I logged off and logged back in.
Does anyone know how to do this?
Seems like you want to connect to external device once and print a message each time you see a specific string.
import sys
import telnetlib
tn_ip = "0.0.0.0"
tn_port = "23"
tn_username = "xxxxx"
tn_password = "xxxx"
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn_ip, tn_port, 15)
except:
print "Unable to connect to Telnet server: " + tn_ip
return
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
while True:
tn.read_until(searchfor)
print "Found it"
telnet()
I wanted to create a Python program that does several things. Ping all addresses in a predefined network, gather the DNS information, write a file with IP address, DNS name, ping fail or pass, date. Then run and email the resulting file to myself once a week, every Friday. I have created this program and will post my own answer. I am new to Python and was able to get this written with the help from other answers posted on this site. Thanks to all those who contributed answers on this site. Hope the answer I post will help someone else.
#!/usr/bin/python3.4
#Above statement makes sure you are using version 3.4
#when multiple versions are installed. has to be the 1st line.
# Import modules
import subprocess
import socket
import errno
import time
import datetime
import ipaddress
today = datetime.date.today()
# define DNS lookup and error handling
# return none,none,none needed otherwise if no DNS record
# the routine errors out and the program stops
def lookup(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return None, None, None
# Prompt the user to input a network address
# commented out the prompt for input so it can run unattended
# net_addr = input("Enter a network address in CIDR
format(ex.192.168.1.0/24): ")
net_addr = ('192.168.1.0/24')
# Create the network
ip_net = ipaddress.ip_network(net_addr)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
# Configure subprocess to hide the console window
# removed code due to errors not windows linux
# setup online and offline count variables
offCnt = 0
onCnt = 0
# Open file and or create if it doesn't exist.
# file to be overwritten each time the program is run.
file = open("lab-ip.doc","w")
# For each IP address in the subnet,
# run the ping command with subprocess.popen interface
# Grab the DNS information for each IP address
# Print to console add counters and write to file.
for i in range(len(all_hosts)):
output = subprocess.Popen(['ping', '-c', '2', str(all_hosts[i])],
stdout=subprocess.PIPE).communicate()[0]
name,alias,addresslist = lookup(str(all_hosts[i]))
if "Destination Host Unreachable" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
elif "Request timed out" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
else:
print(str(all_hosts[i]), " Ping Pass", str(name), today)
file.write(str(all_hosts[i]) + " Ping Pass - " + str(name) + " " + str(today) + "\n")
onCnt = onCnt + 1
print ("Pass count = ", str(onCnt))
file.write("Pass count = " + str(onCnt))
print ("Fail count = ", str(offCnt))
file.write(" Fail count = " + str(offCnt))
file.close()
# Import yagmail for the actual sending function
import yagmail
yag = yagmail.SMTP('Gmail-id', 'gmail-pswd')
yag.send('email#email.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
yag.send('email2#email2.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
#end