Get battery temperature using androidhelper - qpython

I am wondering how to get battery temperature using
batteryGetTemperature()
Why do get error
And how to solve it
droid.batteryStartMonitoring()
print("Battery Percentage: " + str(droid.batteryGetLevel().result) + "%")
print("Battery Temperature: " + str(int(droid.batteryGetTemperature().result)/int(10)) + "°C")
droid.batteryStopMonitoring()

Those batteryGet… functions return None now.
I don't know why. It seems to work before.
Here's a working script I wrote long ago:
#-*-coding:utf8;-*-
#qpy:2
#qpy:console
from androidhelper import sl4a
droid=sl4a.Android()
droid.batteryStartMonitoring()
raw_input("\nBattery Data\nPress to continue…")
try:
data=droid.readBatteryData()
if data.error==None:
print "Data:"
for x in ["temperature","level","status","plugged","voltage","health","technology","battery_present"]:
print " "+x+":",data.result[x]
else:
print "ERROR!"
print data.error
except Exception as err:
print "ERROR!"
print err
finally:
droid.batteryStopMonitoring()
"""
ex.(id=0,result={"":""},error=None)
BatteryManagerFacade
batteryCheckPresent
ex.True
batteryGetHealth
1 - unknown;
2 - good;
3 - overheat;
4 - dead;
5 - over voltage;
6 - unspecified failure;
batteryGetLevel
%
batteryGetPlugType
-1 - unknown
0 - unplugged;
1 - power source is an AC charger
2 - power source is a USB port
batteryGetStatus
1 - unknown;
2 - charging;
3 - discharging;
4 - not charging;
5 - full;
batteryGetTechnology
ex.Li-ion
batteryGetTemperature
ex.310
batteryGetVoltage
ex.4248
batteryStartMonitoring
None
batteryStopMonitoring
None
readBatteryData
status
temperature
level
battery_present
plugged
health
voltage
technology
"""

Related

Radiroot package in GAP generating errors

When I run the following commands
g := UnivariatePolynomial(Rationals, [12,-5,0,0,0,1]);
RootsOfPolynomialAsRadicals(g);
I get this error
*** too many arguments: ...;,nf=nfinit([f,nfbasis(f,1)]);fac=lift(nffact
*** ^--------------------
*** at top-level: for(i=1,#fac[,1],for(j=1,fac[i,2
*** ^--------------------
*** incorrect type in _[,_] OCcompoC [not a matrix] (t_POL).
Error, List Element: <list>[1] must have an assigned value in
faktoren[1] := lcoeff * faktoren[1]; at /proc/cygdrive/C/gap486/pkg/Alnuth-3.0.0/gap/factors.gi:99 called from
FactorsPolynomialPari( AlgExtEmbeddedPol( H, poly )
) at /proc/cygdrive/C/gap486/pkg/Alnuth-3.0.0/gap/factors.gi:51 called from
FactorsPolynomialAlgExt( erw.H, poly ) at /proc/cygdrive/C/gap486/pkg/radiroot/lib/SplittField.gi:237 called from
RR_Zerfaellungskoerper( poly, rec(
roots := [ ],
degs := [ ],
coeffs := [ ],
K := FieldByMatrices( [ [ [ 1 ] ] ] ),
H := Rationals ) ) at /proc/cygdrive/C/gap486/pkg/radiroot/lib/Radicals.gi:293 called from
CallFuncList( RootsOfPolynomialAsRadicalsNC, arg
) at /proc/cygdrive/C/gap486/pkg/radiroot/lib/Radicals.gi:253 called from
<function "RootsOfPolynomialAsRadicals">( <arguments> )
called from read-eval loop at line 2 of *stdin*
you can 'return;' after assigning a value
I am using GAP 4.8.6 on windows 10, installed from the windows installer on the GAP downloads page, and PARI/GP 2.9.1 64 bit (stable installer). I've also tried manually downloading and using the latest versions of Alnuth and Radiroot but I'm still getting the same error. Does anyone know how to fix this?
This now works in GAP 4.11.0, with Alnuth 3.1.2, RadiRoot 2.8 and Pari/GP 2.9.3, under macOS:
g := UnivariatePolynomial(Rationals, [12,-5,0,0,0,1]);
RootsOfPolynomialAsRadicals(g);
starts an xdvi viewer which displays the result. It's hard to read as an image, so I am providing the LaTeX source for it, which may be more useful:
\documentclass[fleqn]{article}
\setlength{\paperwidth}{84cm}
\setlength{\textwidth}{80cm}
\setlength{\paperheight}{59.5cm}
\setlength{\textheight}{57cm}
\begin{document}
\noindent
An expression by radicals for the roots of the polynomial $x^{5} - 5x + 12$ with the $n$-th root of unity $\zeta_n$ and
\\
$\omega_1 = \sqrt[2]{ - 10}$,\\
$\omega_2 = \sqrt[5]{\left( - \frac{421}{5}\zeta_{5} - \frac{449}{5}\zeta_{5}^{2} - \frac{49}{5}\zeta_{5}^{3} + \frac{229}{5}\zeta_{5}^{4}\right) + \left( - \frac{168}{25}\zeta_{5} - \frac{849}{25}\zeta_{5}^{2} - \frac{1101}{25}\zeta_{5}^{3} - \frac{582}{25}\zeta_{5}^{4}\right)\omega_1}$,\\
\\
is:
\\
\noindent
$\left( - \frac{2}{11}\zeta_{5} - \frac{1}{11}\zeta_{5}^{2} + \frac{4}{11}\zeta_{5}^{3} - \frac{4}{11}\zeta_{5}^{4}\right)\omega_2 + \left( - \frac{42}{121}\zeta_{5} + \frac{34}{121}\zeta_{5}^{2} - \frac{92}{121}\zeta_{5}^{3} + \frac{15}{121}\zeta_{5}^{4}\right)\omega_2^2 + \left(\frac{91}{605}\zeta_{5} + \frac{7}{605}\zeta_{5}^{2} + \frac{38}{605}\zeta_{5}^{3} + \frac{149}{605}\zeta_{5}^{4}\right)\omega_1\omega_2^2 + \left(\frac{175}{1331}\zeta_{5} + \frac{302}{1331}\zeta_{5}^{2} + \frac{706}{1331}\zeta_{5}^{3} + \frac{482}{1331}\zeta_{5}^{4}\right)\omega_2^3 + \left(\frac{255}{1331}\zeta_{5} + \frac{364}{1331}\zeta_{5}^{2} + \frac{40}{1331}\zeta_{5}^{3} + \frac{246}{1331}\zeta_{5}^{4}\right)\omega_1\omega_2^3 + \left( - \frac{11480}{14641}\zeta_{5} + \frac{420}{14641}\zeta_{5}^{2} + \frac{7725}{14641}\zeta_{5}^{3} - \frac{740}{14641}\zeta_{5}^{4}\right)\omega_2^4 + \left(\frac{786}{14641}\zeta_{5} + \frac{6399}{14641}\zeta_{5}^{2} + \frac{45}{14641}\zeta_{5}^{3} + \frac{1275}{14641}\zeta_{5}^{4}\right)\omega_1\omega_2^4$
\end{document}
It's difficult to say what was the original problem, there were many changes in both packages, which are now hosted on GitHub - the source code repositories are https://github.com/gap-packages/radiroot and https://github.com/gap-packages/alnuth.

drone-kit Python is not connecting with Iris+

I'm trying to build my first dronekit python program, and I'm doing some tests with some examples but I couldn't connect to my UAV(Iris+). I plugged the usb radio(3DR 915 MHz) and I put vehicle = connect('/dev/ttyUSB0', wait_ready=True). Actually I have no idea which string I should put in. Thanks in advance guys, I need some help!
My code:
print "Start simulator (SITL)"
from dronekit_sitl import SITL
sitl = SITL()
sitl.download('copter', '3.3', verbose=True)
sitl_args = ['-I0', '--model', 'quad', '--home=-35.363261,149.165230,584,353']
sitl.launch(sitl_args, await_ready=True, restart=True)
# Import DroneKit-Python
from dronekit import connect, VehicleMode
import time
# Connect to the Vehicle.
print "Connecting to vehicle on: '/dev/ttyUSB0'"
vehicle = connect('/dev/ttyUSB0', wait_ready=True)
# Get some vehicle attributes (state)
print "Get some vehicle attribute values:"
print " GPS: %s" % vehicle.gps_0
print " Battery: %s" % vehicle.battery
print " Last Heartbeat: %s" % vehicle.last_heartbeat
print " Is Armable?: %s" % vehicle.is_armable
print " System status: %s" % vehicle.system_status.state
print " Mode: %s" % vehicle.mode.name # settable
# Close vehicle object before exiting script
vehicle.close()
# Shut down simulator
sitl.stop()
print("Completed")
Best place for getting dk support now is probably here: https://discuss.dronekit.io/c/python
In answer, I have not tried this on Linux. I suspect the connection string is correct, but you may have to also set the baud rate using baud=57600

Why I am not getting right value when pushing it to an array?

I have some data in the following format.
# AB Tests
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
abTests:
productRanking:
version: 4
groups: [
ratio:
default: 1
us: 0.90
me: 0.0
value: "LessPopularityEPC"
,
ratio:
default: 0
us: 0.1
value: "CtrEpcJob"
,
ratio:
default: 0
me: 1.0
value: "RandomPerVisitor"
]
# Routes
I want the following output as a string array:
productRanking:LessPopularityEPC
productRanking:CtrEpcJob
productRanking:RandomPerVisitor
I am using the following code which will separate the key and values from the data & store them into an array
START_REGEXP = /# AB Tests/
END_REGEXP = /# Routes/
COMMENT_EXP = /#/
#Function to fetch the key:value & store them into array
def Automate_AB_tests.store_key_value(input_file)
prev_line = ""
curr_line = ""
array = []
flag = false
IO.foreach(input_file) do |line|
prev_line = curr_line
curr_line = line
flag = true if line =~ START_REGEXP
if flag
unless line =~ COMMENT_EXP
if line.include? 'version: '
key = prev_line
puts key #productRanking: sabt:
end
if line.include? 'value: '
value = line.delete('\n').delete('"').split[1] #LessPopularityEPC CtrlEpcJob RandomPerVisitor
array << "#{key}:#{value}"
end
end
flag = false if line =~ END_REGEXP
end
end
puts array
end
It is fetching the keys but not storing those keys into stringArray. If anyone can point out what's wrong with my code then it would be really great. I am getting output as below:
productRanking:
:LessPopularityEPC
:CtrEpcJob
:RadomPerVisitor
Since for some reason you apparently can't or won't install Node.js, which would make really, really short work of this, you're stuck doing an ugly hack.
I propose an alternate ugly hack: CSON isn't all that different from YAML. Do some simple substitutions to turn it into YAML and then parse that in Ruby.
Caveat emptor: Like all ugly hacks, this is super fragile. It will probably break as soon as you try to take a vacation. Use at your own risk.
require "yaml"
data = <<END
# AB Tests
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
abTests:
productRanking:
version: 4
groups: [
ratio:
default: 1
us: 0.90
me: 0.0
value: "LessPopularityEPC"
,
ratio:
default: 0
us: 0.1
value: "CtrEpcJob"
,
ratio:
default: 0
me: 1.0
value: "RandomPerVisitor"
]
# Routes
END
AB_TESTS_SECTION_EXPR = /^( +)abTests:\n.+(?=^\1[^ ])/m
# Extract text between "# AB Tests" and "# Routes"
ab_tests = data[AB_TESTS_SECTION_EXPR]
# Turn the CSON array into a YAML array by removing the square brackets and
# commas and inserting a `-` before each "ratio:"
yaml = ab_tests.gsub(/\s+\[$/, '')
.gsub(/ ratio:\s*$/, '- ratio:')
.gsub(/^\s*[,\]]\s*$/, '')
puts yaml
This will print the following valid YAML:
abTests:
productRanking:
version: 4
groups:
- ratio:
default: 1
us: 0.90
me: 0.0
value: "LessPopularityEPC"
- ratio:
default: 0
us: 0.1
value: "CtrEpcJob"
- ratio:
default: 0
me: 1.0
value: "RandomPerVisitor"
Now we just need to parse the YAML into Ruby and extract the data we need:
hsh = YAML.load(yaml)
hsh["abTests"].each do |key, val|
val["groups"].each do |group|
puts "#{key}:#{group['value']}"
end
end
# => productRanking:LessPopularityEPC
# productRanking:CtrEpcJob
# productRanking:RandomPerVisitor

Python34 NMEA sentences put into xlsx using xlsxwriter

I'm working on an nmea sentence project where I get a txt file with nmea sentences delimited by commas. I'm trying to use xlsxwriter to write the results into excel. The results I want are having the timestamp,latitude, longitude and altitude printed in rows that correspond to each other...but I keep getting the first iteration of my 'query' written out five times before the other iterations are written into xlsx. I know there must be a simple solution to this..can you tell me where I'm going wrong?
This is the beginning of my script so you have a full picture of what is going on
import os
import csv
from csv import *
import numpy
import matplotlib
from numpy import *
from matplotlib import *
import matplotlib.pyplot as plt
from matplotlib.pylab import *
import numpy as np
#to export to excel
import xlsxwriter
from xlsxwriter.workbook import Workbook
#to get the csv converter functions
import os
import subprocess
import glob
#to get the datetime functions
import datetime
from datetime import datetime
from pytz import timezone
import time
import calendar
#creates the path needed for incoming and outgoing files
path_in = 'C:/Python34/gps_txts/'
path_out = 'C:/Python34/output_files/'
#prints all the data in the file if you want
q_show_content = input('Print list of files type y:')
if q_show_content == 'y':
for root, dirs, files in os.walk(path_in):
print(root, dirs, files)
else:
print('ok')
data = [] #empty because we will store data into it
#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
"""Reads a CSV file and return it as a list of rows."""
for row in csv.reader(open(filename)):
data.append(row)
return data
#request of what file to look at
print ("- - - - - - - - - - - - -")
data_file = input('Which file do you want to look at?')
f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)
with f as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
plots = csv.reader(csvfile, delimiter=',')
#creates the workbook
output_filename = input('output filename:')
workbook = xlsxwriter.Workbook(path_out + output_filename + '.xlsx')
worksheet = workbook.add_worksheet()
#formatting definitions
bold = workbook.add_format({'bold': True})
date_format = workbook.add_format({'num_format': "m/d/yyyy hh:mm:ss"})
#print number of rows
print ("- - - - - - - - - - - - -")
rows = len(read_it)
print (data_file, " has "+ str(rows) + " rows of data")
print ("- - - - - - - - - - - - -")
#Counts the number of times a GPS command is observed
def list_gps_commands(data):
"""Counts the number of times a GPS command is observed.
Returns a dictionary object."""
gps_cmds = dict()
for row in data:
try:
gps_cmds[row[0]] += 1
except KeyError:
gps_cmds[row[0]] = 1
return gps_cmds
print(list_gps_commands(read_it))
print ("- - - - - - - - - - - - -")
#prints all the data in the file if you want
q_show_data = input('Print data inside ' + data_file + ' type y:')
if q_show_data == 'y':
for row in read_it:
print(row)
else:
print('ok')
This is the part I'm having an issue with
#Function process_gps_data for GPS
NMI = 1852.0
def process_gps_data(data):
"""Processes GPS data, NMEA 0183 format.
Returns a tuple of arrays: latitude, longitude, velocity [km/h],
time [sec] and number of satellites.
See also: http://www.gpsinformation.org/dale/nmea.htm.
"""
latitude = []
longitude = []
altitude = []
velocity = []
timestamp = []
num_sats = []
for row in data:
if row[0] == '$GPRMC': # Valid position/time sentence
y = (float(row[3][0:2]) + float(row[3][2:])/60.0)
if row[4] == "S":
y = -y
latitude.append(y)
x = (float(row[5][0:3]) + float(row[5][3:])/60.0)
if row[6] == "W":
x = -x
longitude.append(x)
print('x,y:',x,y)
velocity.append(float(row[7])*NMI/1000.0)
gpstime = row[1][0:6] # hhmmss
gdate = row[9] # ddmmyy
gpsdate = gdate[4:6]+gdate[2:4]+gdate[0:2] # yymmdd
real_time =gpsdate + gpstime
add_date_time = datetime.strptime(real_time, "%y%m%d%H%M%S")
print(add_date_time)
timestamp.append(add_date_time)
return (array(latitude), array(longitude), array(velocity), array(timestamp))
# how to call process_gps_data()
(lati, long, v, t_stamp) = process_gps_data(data)
print ("- - - - - - - - - - - - -")
print('lati:',lati)
print ("- - - - - - - - - - - - -")
print('long:',long)
print ("- - - - - - - - - - - - -")
print('v:',v)
print ("- - - - - - - - - - - - -")
print('date:', t_stamp)
print ("- - - - - - - - - - - - -")
#sets up the header row
worksheet.write('A1','TimeStamp',bold)
worksheet.write('B1', 'Latitude',bold)
worksheet.write('C1', 'Longitude',bold)
worksheet.write('D1', 'Velocity',bold)
worksheet.autofilter('A1:D1') #dropdown menu created for filtering
# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(row):
worksheet.write_column(r,0, t_stamp, date_format)
worksheet.write_column(r,1, lati)
worksheet.write_column(r,2, long)
worksheet.write_column(r,3, v)
workbook.close()
f.close()
I am using a dummy gps cache with these lines in a txt file. Notice the GPRMC have a different year in row[9] == 01,02,03
$GPRMC,002454,A,3553.5295,N,13938.6570,E,0.0,43.1,180701,7.1,W,A*3F
$GPRMB,A,,,,,,,,,,,,A,A*0B
$GPGGA,002455,3553.5295,N,13938.6570,E,1,05,2.2,18.3,M,39.0,M,,*7F
$GPRMC,002456,A,3553.5321,N,13938.6581,E,0.0,43.1,180702,7.1,W,A*3D
$GPRMC,104715.20,A,5100.2111,N,00500.0006,E,21.7,003.0,140803,01.,W*70
My results being printed out looks the way that they are expected to...
- - - - - - - - - - - - -
garmin etrex summit.txt has 5 rows of data
- - - - - - - - - - - - -
{'$GPRMC': 3, '$GPGGA': 1, '$GPRMB': 1}
- - - - - - - - - - - - -
Print data inside garmin etrex summit.txt type y:
ok
x,y: 139.64428333333333 35.892158333333334
2000-07-18 00:24:54
x,y: 139.64430166666668 35.892201666666665
2001-07-18 00:24:56
x,y: 5.00001 51.00351833333333
2003-08-14 10:47:15
- - - - - - - - - - - - -
lati: [ 35.89215833 35.89220167 51.00351833]
- - - - - - - - - - - - -
long: [ 139.64428333 139.64430167 5.00001 ]
- - - - - - - - - - - - -
v: [ 0. 0. 40.1884]
- - - - - - - - - - - - -
date: [datetime.datetime(2000, 7, 18, 0, 24, 54)
datetime.datetime(2001, 7, 18, 0, 24, 56)
datetime.datetime(2003, 8, 14, 10, 47, 15)]
- - - - - - - - - - - - -
But when i look at my produced xlsx file, I have the first five rows looking like this:
TimeStamp Latitude Longitude Velocity
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2001 00:24:54 35.89215833 139.6442833 0
7/18/2002 00:24:56 35.89220167 139.6443017 0
8/14/2003 10:47:15 51.00351833 5.00001 40.1884
So my issue is that I get 5 of the same first 'query' and then the other 2 iteration of '$GPRMC'
Where am i going wrong?

Python 3, extract info from file problems

And again, asking for help. But, before I start, here will be a lot of text, so please sorry for that.
I have about 500~ IP addresses with devices 2x categories in .xlsx book
I want:
telnet to device. Check device (by authentication prompt) type 1 or type 2.
If device is type 1 - get it firmware version in 2x partitions
write in excel file:
column 1 - IP address
column 2 - device type
column 3 - firmware version
column 4 - firmware version in reserve partition.
If type 2 - write in excel file:
column 1 - IP address
column 2 - device type
If device is down, or device type 3(unknown) - write in excel file:
column 1 - IP address
column 2 - result (EOF, TIMEOUT)
What I have done: I'm able to telnet to device, check device type, write in excel with 2 columns (in 1 column IP addresses, in 2 column is device type, or EOF/TIMEOUT results)
And, I'm writing full logs from session to files in format IP_ADDRESS.txt to future diagnosis.
What I can't understand to do? I can't understand how to get firmware version, and put it on 3,4 columns.
I can't understand how to work with current log session in real time, so I've decided to copy logs from main file (IP_ADDRESS.txt) to temp.txt to work with it.
I can't understand how to extract information I needed.
The file output example:
Trying 10.40.81.167...
Connected to 10.40.81.167.
Escape character is '^]'.
####################################
# #
# RADIUS authorization disabled #
# Enter local login/password #
# #
####################################
bt6000 login: admin
Password:
Please, fill controller information at first time (Ctrl+C to abort):
^C
Controller information filling canceled.
^Cadmin#bt6000# firmware info
Active boot partition: 1
Partition 0 (reserved):
Firmware: Energomera-2.3.1
Version: 10117
Partition 1 (active):
Firmware: Energomera-2.3.1_01.04.15c
Version: 10404M
Kernel version: 2.6.38.8 #2 Mon Mar 2 20:41:26 MSK 2015
STM32:
Version: bt6000 10083
Part Number: BT6024
Updated: 27.04.2015 16:43:50
admin#bt6000#
I need values - after "Energomera" words, like 2.3.1 for reserved partition, and 2.3.1_01.04.15c for active partition.
I've tried to work with string numbers and excract string, but there was not any kind of good result at all.
Full code of my script below.
import pexpect
import pxssh
import sys #hz module
import re #Parser module
import os #hz module
import getopt
import glob #hz module
import xlrd #Excel read module
import xlwt #Excel write module
import telnetlib #telnet module
import shutil
#open excel book
rb = xlrd.open_workbook('/samba/allaccess/Energomera_Eltek_list.xlsx')
#select work sheet
sheet = rb.sheet_by_name('IPs')
#rows number in sheet
num_rows = sheet.nrows
#cols number in sheet
num_cols = sheet.ncols
#creating massive with IP addresses inside
ip_addr_list = [sheet.row_values(rawnum)[0] for rawnum in range(sheet.nrows)]
#create excel workbook with write permissions (xlwt module)
wb = xlwt.Workbook()
#create sheet IP LIST with cell overwrite rights
ws = wb.add_sheet('IP LIST', cell_overwrite_ok=True)
#create counter
i = 0
#authorization details
port = "23" #telnet port
user = "admin" #telnet username
password = "12345" #telnet password
#firmware ask function
def fw_info():
print('asking for firmware')
px.sendline('firmware info')
px.expect('bt6000#')
#firmware update function
def fw_send():
print('sending firmware')
px.sendline('tftp server 172.27.2.21')
px.expect('bt6000')
px.sendline('firmware download tftp firmware.ext2')
px.expect('Updating')
px.sendline('y')
px.send(chr(13))
ws.write(i, 0, host)
ws.write(i, 1, 'Energomera')
#if eltek found - skip, write result in book
def eltek_found():
print(host, "is Eltek. Skipping")
ws.write(i, 0, host)
ws.write(i, 1, 'Eltek')
#if 23 port telnet conn. refused - skip, write result in book
def conn_refuse():
print(host, "connection refused")
ws.write(i, 0, host)
ws.write(i, 1, 'Connection refused')
#auth function
def auth():
print(host, "is up! Energomera found. Starting auth process")
px.sendline(user)
px.expect('assword')
px.sendline(password)
#start working with ip addresses in ip_addr_list massive
for host in ip_addr_list:
#spawn pexpect connection
px = pexpect.spawn('telnet ' + host)
px.timeout = 35
#create log file with in IP.txt format (10.1.1.1.txt, for example)
fout = open('/samba/allaccess/Energomera_Eltek/{0}.txt'.format(host),"wb")
#push pexpect logfile_read output to log file
px.logfile_read = fout
try:
index = px.expect (['bt6000', 'sername', 'refused'])
#if device tell us bt6000 - authorize
if index == 0:
auth()
index1 = px.expect(['#', 'lease'])
#if "#" - ask fw version immediatly
if index1 == 0:
print('seems to controller ID already set')
fw_info()
#if "Please" - press 2 times Ctrl+C, then ask fw version
elif index1 == 1:
print('trying control C controller ID')
px.send(chr(3))
px.send(chr(3))
px.expect('bt6000')
fw_info()
#firmware update start (temporarily off)
# fw_send()
#Eltek found - func start
elif index == 1:
eltek_found()
#Conn refused - func start
elif index == 2:
conn_refuse()
#print output to console (test purposes)
print(px.before)
px.send(chr(13))
#Copy from current log file to temp.txt for editing
shutil.copy2('/samba/allaccess/Energomera_Eltek/{0}.txt'.format(host), '/home/bark/expect/temp.txt')
#EOF result - skip host, write result to excel
except pexpect.EOF:
print(host, "EOF")
ws.write(i, 0, host)
ws.write(i, 1, 'EOF')
#print output to console (test purposes)
print(px.before)
#Timeout result - skip host, write result to excel
except pexpect.TIMEOUT:
print(host, "TIMEOUT")
ws.write(i, 0, host)
ws.write(i, 1, 'TIMEOUT')
#print output to console (test purposes)
print(px.before)
#Copy from current log file to temp.txt for editing
shutil.copy2('/samba/allaccess/Energomera_Eltek/{0}.txt'.format(host), '/home/bark/expect/temp.txt')
#count +1 to correct output for Excel
i += 1
#workbook save
wb.save('/samba/allaccess/Energomera_Eltek_result.xls')
Have you have any suggestions or ideas, guys, how I can do this?
Any help is greatly appreciated.
You can use regular expressions
example:
>>> import re
>>>
>>> str = """
... Trying 10.40.81.167...
...
... Connected to 10.40.81.167.
...
... Escape character is '^]'.
...
...
...
... ####################################
... # #
... # RADIUS authorization disabled #
... # Enter local login/password #
... # #
... ####################################
... bt6000 login: admin
... Password:
... Please, fill controller information at first time (Ctrl+C to abort):
... ^C
... Controller information filling canceled.
... ^Cadmin#bt6000# firmware info
... Active boot partition: 1
... Partition 0 (reserved):
... Firmware: Energomera-2.3.1
... Version: 10117
... Partition 1 (active):
... Firmware: Energomera-2.3.1_01.04.15c
... Version: 10404M
... Kernel version: 2.6.38.8 #2 Mon Mar 2 20:41:26 MSK 2015
... STM32:
... Version: bt6000 10083
... Part Number: BT6024
... Updated: 27.04.2015 16:43:50
... admin#bt6000#
... """
>>> re.findall(r"Firmware:.*?([0-9].*)\s", str)
['2.3.1', '2.3.1_01.04.15c']
>>> reserved_firmware = re.search(r"reserved.*\s*Firmware:.*?([0-9].*)\s", str).group(1)
>>> reserved_firmware
'2.3.1'
>>> active_firmware = re.search(r"active.*\s*Firmware:.*?([0-9].*)\s", str).group(1)
>>> active_firmware
'2.3.1_01.04.15c'
>>>

Resources