Nokia N95 and PyS60 with the sensor and xprofile modules - python

I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great.
The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it.
So my question is what is wrong with the code, and also whether I need to pass special parameters to ensymble?
import appuifw, e32, sensor, xprofile
from appuifw import *
old_profil = xprofile.get_ap()
def get_sensor_data(status):
#decide profile
def exit_key_handler():
# Disconnect from the sensor and exit
acc_sensor.disconnect()
app_lock.signal()
app_lock = e32.Ao_lock()
appuifw.app.exit_key_handler = exit_key_handler
appuifw.app.title = u"Acc Silent"
appuifw.app.menu = [(u'Close', app_lock.signal)]
appuifw.app.body = Canvas()
# Retrieve the acceleration sensor
sensor_type= sensor.sensors()['AccSensor']
# Create an acceleration sensor object
acc_sensor= sensor.Sensor(sensor_type['id'],sensor_type['category'])
# Connect to the sensor
acc_sensor.connect(get_sensor_data)
# Wait for sensor data and the exit event
app_lock.wait()
The script starts at boot, using ensymble and my developer certificate.
Thanks in advance

I often use something like that at the top of my scripts:
import os.path, sys
PY_PATH = None
for p in ['c:\\Data\\Python', 'e:\\Data\\Python','c:\\Python','e:\\Python']:
if os.path.exists(p):
PY_PATH = p
break
if PY_PATH and PY_PATH not in sys.path: sys.path.append(PY_PATH)

xprofile is not a standard library, make sure you add path to it. My guess is that when run as SIS, it doesn't find xprofile and hangs up. When releasing your SIS, either instruct that users install that separately or include inside your SIS.
Where would you have it installed, use that path. Here's python default directory as sample:
# PyS60 1.9.x and above
sys.path.append('c:\\Data\\Python')
sys.path.append('e:\\Data\\Python')
# Pys60 1.4.x or below
sys.path.append('c:\\Python')
sys.path.append('e:\\Python')
Btw make clean exit, do this:
appuifw.app.menu = [(u'Close', exit_key_handler)]

Related

How to solve pass thorugh command ignored issue when setting a signal analyser MXA N9020A

I am trying to set up the signal analyser using a simple python script. I am able to set the center and frequency and span frequency but when i am trying to turn the average on and set it to exponential mode, it gives me a pass through command ignored. The instrument is connected successfully using LAN.
import string
import pyvisa # PyVISA package for connecting to the instrument
pyvisa.log_to_screen()
# Make connection to instrument
# Open a VISA resource manager pointing to the installation folder for the Keysight Visa libraries.
rm = pyvisa.ResourceManager()
# Device addr
addr_MXA = 'TCPIP0::A-N9020A-00060::inst0::INSTR'
addr_VSA = 'TCPIP0::CASCODA500::hislip1::INSTR'
SA_device = rm.open_resource(addr_VSA)
# Preset and wait for operation to complete
SA_device.write('*rst')
SA_device.query('*opc?')
# Resume the sweeping
SA_device.write('init:cont ON')
SA_device.write('init:res')
# Measurement variables for the MeasSetup
freq = '2.44GHz'
freq_span = '5MHz'
count = 10
avermode = 'EXP'
search_len = '832us'
SA_device.write('sens:freq:cent {}'.format(freq))
SA_device.write('sens:freq:span {}'.format(freq_span))
# Average
SA_device.write('sens:aver ON')
SA_device.write('sens:mon:aver:tcon {}'.format(avermode))
SA_device.write('sens:aver:count {}'.format(count))
The SCPI log of Keysight VSA
This happens because I was trying to use SCPI commands for MXA N9020A instrument on 89600 VSA software running on the computer. This is solved by downloading Keysight Command Expert and use the commands that are tailored for different instruments and also using SCPI reference guide here.

irsend is not giving errors, but does not send signal on Raspbian

I am trying to build the air conditioner control system, which will allow me to control the ac's using web app.
So far I have done same thing with Arduino and it worked for this particular air conditioner. I could send and receive signal so I don't think there is any problems with hardware.
So far irsend is not giving me any errors, but signal is not sent, although I tried some LED testing codes using python and it worked.
Here is the /etc/modules:
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
lirc_dev
lirc_rpi gpio_out_pin=22
Here is the /etc/lirc/hardware.conf:
########################################################
# /etc/lirc/hardware.conf
#
# Arguments which will be used when launching lircd
#
LIRCD_ARGS=""
#
# Don't start lircmd even if there seems to be a good config file
# START_LIRCMD=false
#
# Don't start irexec, even if a good config file seems to exist.
# START_IREXEC=false
#
# Try to load appropriate kernel modules
LOAD_MODULES="true"
# Run "lircd --driver=help" for a list of supported drivers.
DRIVER="default"
# usually /dev/lirc0 is the correct setting for systems using udev
DEVICE="/dev/lirc0"
MODULES="lirc_rpi"
# Default configuration files for your hardware if any
#changed for true
LIRCD_CONF="/etc/lirc/lircd.conf"
LIRCMD_CONF=""
########################################################
And /boot/config.txt:
# For more options and information see
# http://www.raspberrypi.org/documentation/configuration/config-txt.md
# Some settings may impact device functionality. See link above for details
# Uncomment this to enable the lirc-rpi module
dtoverlay=lirc-rpi, gpio_out_pin=22
# Additional overlays and parameters are documented /boot/overlays/README
# Enable audio (loads snd_bcm2835)
dtparam=audio=on
Can anyone have any idea as in why is signal is not sent? The connection seems to be correct, 22 gpio, but for python code used 15 to check if its working:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.OUT)
for i in range(0,10):
GPIO.output(15,True)
time.sleep(0.5)
GPIO.output(15,False)
time.sleep(0.5)
print "Done"
GPIO.cleanup()
P.S. I tried to change 22 to 15, didn't work out. :(
Found the error, Raspberry Pi was not reading my /etc/modules so when I saved the same data in /etc/modules-load.d/lirc_rpi.conf, it worked:
lirc_dev
lirc_rpi gpio_in_pin=22 gpio_out_pin=23
i2c-dev

Maximum time to wait for url response

I'm making a simple update checker function for my code that I set to run every time before the bulk of the code is executed. It notifies the user that a new version is available for download.
Here's a MWE:
import urllib
def updater(__version__):
try:
# Get latest version number from master repo at Github.
f = urllib.urlopen("https://raw.githubusercontent.com/chrisglass"
"/django_polymorphic/master/polymorphic/__version__.py")
s = f.read().split('"')
if s[-2] != __version__:
print "New version {} is available.".format(s[-2])
except:
pass
# Call function to check if new version is available.
__version__ = '0.1'
updater(__version__)
(that repo isn't mine, I'm using it in this example because I use a similar version of its __version.py__ file)
This works fine, but I'm concerned about Github eventually taking too long to respond, which would hold back the execution of the code.
Is there a way to jump out of the try block after say 5 seconds have elapsed? Is this the recommended way to go about this?
Use urllib2, its urlopen has a timeout parameter.
urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])
https://docs.python.org/2/library/urllib2.html

Python network bandwidth monitor

I am developing a program in python, and one element tells the user how much bandwidth they have used since the program has opened (not just within the program, but regular web browsing while the program has been opened). The output should be displayed in GTK
Is there anything in existence, if not can you point me in the right direction. It seems like i would have to edit an existing proxy script like pythonproxy, but i can't see how i would use it.
Thanks,
For my task I wrote very simple solution using psutil:
import time
import psutil
def main():
old_value = 0
while True:
new_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
if old_value:
send_stat(new_value - old_value)
old_value = new_value
time.sleep(1)
def convert_to_gbit(value):
return value/1024./1024./1024.*8
def send_stat(value):
print ("%0.3f" % convert_to_gbit(value))
main()
import time
def get_bytes(t, iface='wlan0'):
with open('/sys/class/net/' + iface + '/statistics/' + t + '_bytes', 'r') as f:
data = f.read();
return int(data)
while(True):
tx1 = get_bytes('tx')
rx1 = get_bytes('rx')
time.sleep(1)
tx2 = get_bytes('tx')
rx2 = get_bytes('rx')
tx_speed = round((tx2 - tx1)/1000000.0, 4)
rx_speed = round((rx2 - rx1)/1000000.0, 4)
print("TX: %fMbps RX: %fMbps") % (tx_speed, rx_speed)
should be work
Well, not quiet sure if there is something in existence (written in python) but you may want to have a look at the following.
Bandwidth Monitoring (Not really an active project but may give you an idea).
Munin Monitoring (A pearl based Network Monitoring Project)
ntop (written in C/C++, based on libpcap)
Also just to give you pointers if you are looking to do something on your own, one way could be to count and store packets using sudo cat /proc/net/dev
A proxy would only cover network applications that were configured to use it. You could set, e.g. a web browser to use a proxy, but what happens when your proxy exits?
I think the best thing to do is to hook in lower down the stack. There is a program that does this already, iftop. http://en.wikipedia.org/wiki/Iftop
You could start by reading the source code of iftop, perhaps wrap that into a Python C extension. Or rewrite iftop to log data to disk and read it from Python.
Would something like WireShark (https://wiki.wireshark.org/FrontPage) do the trick? I am tackling a similar problem now, and am inclined to use pyshark, a WireShark/TShark wrapper, for the task. That way you can get capture file info readily.

Adding testcase results to Quality Center Run from a outside Python Script

I want to try to add all the step details - Expected, Actual, Status,
etc. to a QC Run for a testcase of a TestSet from a Python Script
living outside the Quality Center.
I have come till here (code given below) and I don't know how to add
Step Expected and Step Actual Result. If anyone knows how do it,
please help me out!! Please, I don't want any QTP solutions.
Thanks,
Code-
# Script name - add_tsrun.py
# C:\Python27\python.exe
# This script lives locally on a Windows machine that has - Python 2.7, Win32 installed, IE8
# Dependencies on Windows Machine - Python 2.7, PythonWin32 installed, IE8, a QC Account, connectivity to QCServer
import win32com.client, os
tdc = win32com.client.Dispatch("TDApiOle80.TDConnection")
tdc.InitConnection('http://QCSERVER:8080/qcbin')
tdc.Login('USERNAME', 'PASSWORD')
tdc.Connect('DOMAIN_NAME', 'PROJECT')
tsFolder = tdc.TestSetTreeManager.NodeByPath('Root\\test_me\\sub_folder')
tsList = tsFolder.FindTestSets('testset1')
ts_object = tsList.Item(1)
ts_dir = os.path.dirname('testset1')
ts_name = os.path.basename('testset1')
tsFolder = tdc.TestSetTreeManager.NodeByPath(ts_dir)
tsList = tsFolder.FindTestSets(ts_name)
ts_object = tsList.Item(1)
TSTestFact = ts_object.TSTestFactory
TestSetTestsList = TSTestFact.NewList("")
ts_instance = TestSetTestsList.Item(1)
newItem = ts_instance.RunFactory.AddItem(None) # newItem == Run Object
newItem.Status = 'No Run'
newItem.Name = 'Run 03'
newItem.Post()
newItem.CopyDesignSteps() # Copy Design Steps
newItem.Post()
steps = newItem.StepFactory.NewList("")
step1 = steps[0]
step1.Status = "Not Completed"
step1.post()
## How do I change the Actual Result??
## I can access the Actual, Expected Result by doing this, but not change it
step1.Field('ST_ACTUAL') = 'My actual result' # This works in VB, not python as its a Syntax error!!
Traceback ( File "<interactive input>", line 1
SyntaxError: can't assign to function call
Hope this helps you guys out there. If you know the answer to set the
Actual Result, please help me out and let me know. Thanks,
Amit
As Ethan Furman answered in your previous question:
In Python () represent calls to functions, while [] represent indexing and mapping.
So in other words, you probably want to do step1.Field['ST_ACTUAL'] = 'My actual result'
Found the answer after a lot of Google Search :)
Simple -> Just do this:
step1.SetField("ST_ACTUAL", "my actual result") # Wohhooooo!!!!
If the above code fails to work, try to do the following:-
(OPTIONAL) Set your win32 com as follows- (Making ''Late Binding'')
# http://oreilly.com/catalog/pythonwin32/chapter/ch12.html
a. Start PythonWin, and from the Tools menu, select the item COM Makepy utility.
b. Using Windows Explorer, locate the client subdirectory (OTA COM Type Library)
under the main win32com directory and double-click the file makepy.py.
Thank you all...

Categories

Resources