Python and PSS/E - python

I am trying to have the bus loads in PSS/E to change by using python program. So I am trying to write a script in python where I could change loads to different values between two buses in PSS/E.

You can use API routine called "LOAD_CHNG_4" (search for this routin in API.pdf documentation). This routine belongs to the set of load data specification functions. It can be used to modify the data of an existing load in the working case.

Look at chapter II of the PSSE python API. It completely covers changing power flow data. Load data can be referenced with the bus number and load ID. You can change all the parameters you see in the nameplate when you manually enter in the load data itself. Use this function below to change the load:
ierr = psspy.load_chang(bus_number, load_id, intgar,realar)
See page 728 of the API manual for more info.

I wrote this class to handle loads in PSSE...It originally sent with SQL alchemy so it has some extras which I removed:
class Load():
def __init__(self,busnumber,loadID):
# Initialize the Branch Class Instance Variables to a Default 0; Except for the From,To and Circuit ID
self.bus = Bus(busnumber)
self.busI = busnumber
self.loadID = loadID
self.status = 0
self.Pload = 0.0
self.Qload = 0.0
self.errorList = []
self.init()
def init(self):
# Setup the load from the case
# Check to see if bus exists
busOk = self.bus.init()
if not busOk[0]:
return (False,self.bus.number,"The bus number %d is invalid or does not exist..." % self.bus.number)
if psspy.loddt2(self.bus.number,self.loadID,'TOTAL','ACT')[0] != 0:
return (False,False)
Scomplex = self.check(psspy.loddt2(self.bus.number,self.loadID,'TOTAL','ACT'),'loddt2','ACT') # Grab the S vector/phasor from the power flow case for the load specified at the BUS number
self.Pload = Scomplex.real
self.Qload = Scomplex.imag
self.status = self.check(psspy.lodint(self.bus.number,self.loadID,'STATUS'),'lodint','STATUS') # Grab the Status of the Load
return (True,self.bus.number)
def check(self,tuple,funName,subFun):
# Define Error Messages that should be accesable by the end-user and developer
loddt2 = {
0:'No error; P and Q or CMPVAL returned',
1:'Bus not found; P and Q or CMPVAL unchanged.',
2:'Load not found; P and Q or CMPVAL unchanged.',
3:'Bus type code is not 1, 2 or 3; P and Q or CMPVAL returned.',
4:'Load out-of-service; P and Q or CMPVAL returned.',
5:'Invalid value of STRING1 or STRING2; P and Q or CMPVAL unchanged.'
}
lodint = {
0:'No error; IVAL returned.',
1:'Bus not found; IVAL unchanged.',
2:'Load not found; IVAL unchanged.',
3:'Bus type code is not 1, 2 or 3; IVAL returned.',
4:'Load out-of-service; IVAL returned.',
5:'Invalid value of STRING; IVAL unchanged.'
}
funDic = {
'loddt2':loddt2,
'lodint':lodint
}
# Retrieve the Right Error Message
list = funDic[funName]
msg = list[tuple[0]]
if tuple[0] > 0:
logging.debug("Function Name: %s Sub Function Name: %s Error Message: %s"%(funName,subFun,msg))
return tuple[1]
def setLoad(self,loadP):
self.Pload = loadP
def updateCase(self):
# Setup Defaults
_i = psspy.getdefaultint()
_f = psspy.getdefaultreal()
cDef = psspy.getdefaultchar()
psspy.load_data_3(self.bus.number,self.loadID,[self.status,_i,_i,_i,_i],[self.Pload, self.Qload,_f,_f,_f,_f])
# To String Method
def __repr__(self):
return "%d %s %d %d" %(self.bus.number,self.loadID,self.Pload,self.Qload)
# printf Statement that Dumps information to CMD line...Homeage to C and C++
def printf(self):
print "\n Bus: %d \n Load ID: %s \n MW Value: %d \n MVAR Value: %d \n" % (self.bus.number,self.loadID,self.Pload,self.Qload)
If you call the function named, "updateCase" it will take what ever values are stored in the load object and refresh the PSSE case.

http://www.whit.com.au/blog/2011/07/run-psse-from-python-and-not-other-way/
I found this blog post about how to run Python command from PSSE. I don't think that your question has anything to do with ASP.NET though.

Related

Setting up ZKTeco ZK8500 (ZK9500) fingerprint scanner in Python

I am working on a Python project that includes using Images taken by Fingerprint scanner and processing them. I am currently using ZKTeco ZK8500(ZK9500) that is provided with C SDK library. But i have very little knowledge in C/C++ and to be honest Python is not my strongest language. I am trying to use C SDK via ctypes library in Python but i have some difficulties with that. I am currently testing on Windows, installed SDK from official site. So far my code looks like:
import ctypes
from ctypes import *
import logging
logging.basicConfig(filename='app_fp.log',
filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%d-%m-%Y %H:%M:%S',
level=logging.INFO)
lib_3 = CDLL('libzkfp.dll')
###############################
lib_3.ZKFPM_Init.restype = ctypes.c_int
lib_3.ZKFPM_Terminate.restype = ctypes.c_int
lib_3.ZKFPM_GetDeviceCount.restype = ctypes.c_int
lib_3.ZKFPM_OpenDevice.restype = ctypes.c_void_p
lib_3.ZKFPM_OpenDevice.argtypes = [ctypes.c_int]
lib_3.ZKFPM_CloseDevice.restype = ctypes.c_int
lib_3.ZKFPM_CloseDevice.argtypes = [ctypes.c_void_p]
lib_3.ZKFPM_GetParameters.restype = ctypes.c_int
lib_3.ZKFPM_GetParameters.argtypes = [ctypes.c_void_p,
ctypes.c_int,
ctypes.POINTER(ctypes.c_ubyte),
ctypes.POINTER(ctypes.c_uint),
]
paramChar = c_ubyte()
paramInt = c_uint()
################################
res_init = lib_3.ZKFPM_Init()
print("Init:", res_init)
res_getDeviceCount = lib_3.ZKFPM_GetDeviceCount()
print("Dev count:", res_getDeviceCount, type(res_getDeviceCount))
dev0_handle = lib_3.ZKFPM_OpenDevice(0)
print("Dev HANDLE:", dev0_handle)
dev0_getParam = lib_3.ZKFPM_GetParameters(dev0_handle,
1102,
byref(paramChar),
byref(paramInt))
print("Get dev name:", dev0_getParam, paramChar, sizeof(paramChar))
logging.info("DeviceHandle:" + str(dev0_handle))
res_close = lib_3.ZKFPM_CloseDevice(dev0_handle)
print("Close dev:", dev0_handle, res_close)
#
res_terminate = lib_3.ZKFPM_Terminate()
print("Terminate:", res_terminate)
Stdout looks like this:
Init: 0
Dev count: 2 <class 'int'>
Dev HANDLE: 2682398313632
Get dev name: -3 c_ubyte(0) 1
Close dev: 2682398313632 0
Terminate: 0
Check sum data is true!sum=9286, buf[val]=9286
Check sum data is true!sum=-44, buf[val]=-44
opts->Stripe_Reference_Point_X=654, opts->Stripe_Reference_Point_Y=542
Check sum data is true!sum=908, buf[val]=908
CMOS Sensor->Exposure:256, RedGain:152, GreenGain1:200, GreenGain2:187,BlueGain:112.
Main1LED:200, Main2LED:200, Side1LED:175, Side2LED:175, Anti1LED:200, Anti2LED:200.
start to set the exposure parameters
Process finished with exit code 0
Description of GetParameters function from SDK is:
5.2.7 ZKFPM_GetParameters
[Function]
int APICALL ZKFPM_GetParameters(HANDLE hDevice, int nParamCode, unsigned
char* paramValue, unsigned int* cbParamValue);
[Purpose]
This function is used to acquire fingerprint reader parameters.
[Parameter Description]
hDevice
Device operation instance handle
nParamCode
Parameter code (For details, see the parameter code list.)
paramValue [out]
Returned parameter value
cbParamValue [in/out]
[in] Memory size allocated based on nParamCode
[out]Data size of the returned parameter value
[Return Value]
0 Succeeded
Others Failed (See the Appendixes.)
Questions:
I do not understand why i can OpenDevice, can CloseDevice but get Get dev name: -3 c_ubyte(0) 1 when i try to get parameter i get -3- No device connected. Maybe something in my Python declaration or variable types?
How i can get image to file from fingerprint scanner? Code snippets if anybody knows?

How to read ASB status in python-escpos

I want to read back ASB and other status results in python-escpos. I thought the ._read() method would work but I get a "AttributeError: 'Serial' object has no attribute '_read'" error. I have verified the _read() method is there with inspect.
Any suggestion on how I can read back status's in python-escpos?
Please try specifying the GS a command as a parameter in the query_status() method and calling it.
GS a
[Name]
Enable/disable Automatic Status Back (ASB)
[Format]
ASCII GS a n
Hex 1D 61 n
Decimal 29 97 n
[Range]
n = 0 – 255
[Default]
n: different depending on the printers
Please try by specifying 0xFF for n.
query_status(mode)
Queries the printer for its status, and returns an array of integers containing it.
Parameters: mode – Integer that sets the status mode queried to the printer. - RT_STATUS_ONLINE: Printer status. - RT_STATUS_PAPER: Paper sensor.
Return type: array(integer)
def query_status(self, mode):
def query_status(self, mode):
"""
Queries the printer for its status, and returns an array of integers containing it.
:param mode: Integer that sets the status mode queried to the printer.
- RT_STATUS_ONLINE: Printer status.
- RT_STATUS_PAPER: Paper sensor.
:rtype: array(integer)
"""
self._raw(mode)
time.sleep(1)
status = self._read()
return status
def _raw(self, msg):
def _raw(self, msg):
""" Print any command sent in raw format
:param msg: arbitrary code to be printed
:type msg: bytes
"""
self.device.write(self.out_ep, msg, self.timeout)
def _read(self):
def _read(self):
""" Reads a data buffer and returns it to the caller. """
return self.device.read(self.in_ep, 16)
# Status Command
RT_STATUS = DLE + EOT
RT_STATUS_ONLINE = RT_STATUS + b'\x01'
RT_STATUS_PAPER = RT_STATUS + b'\x04'
RT_MASK_ONLINE = 8
RT_MASK_PAPER = 18
RT_MASK_LOWPAPER = 30
RT_MASK_NOPAPER = 114

Python Module snmpSessionBaseClass: Where to download

I am trying to import the snmpSessionBaseClass python module in a script I am running, but I do not have the module installed and I can't seem to find where to download it. Does anyone know the pip or yum command to download and install this module? Thanks!
import netsnmp
sys.path.insert(1, os.path.join(sys.path[0], os.pardir))
from snmpSessionBaseClass import add_common_options, get_common_options, verify_host, get_data
from pynag.Plugins import PluginHelper,ok,critical
The following code needs to be added to a file called snmpSessionBaseClass.py and that file needs to be placed in a directory that is in pythons path.
#!/usr/bin/env python
# Copyright (C) 2016 rsmuc <rsmuc#mailbox.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with health_monitoring_plugins. If not, see <http://www.gnu.org/licenses/>.
import pynag
import netsnmp
import os
import sys
dev_null = os.open(os.devnull, os.O_WRONLY)
tmp_stdout = os.dup(sys.stdout.fileno())
def dev_null_wrapper(func, *a, **kwargs):
"""
Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null.
This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases.
"""
os.dup2(dev_null, sys.stdout.fileno())
return_object = func(*a, **kwargs)
sys.stdout.flush()
os.dup2(tmp_stdout, sys.stdout.fileno())
return return_object
def add_common_options(helper):
# Define the common command line parameters
helper.parser.add_option('-H', help="Hostname or ip address", dest="hostname")
helper.parser.add_option('-C', '--community', dest='community', help='SNMP community of the SNMP service on target host.', default='public')
helper.parser.add_option('-V', '--snmpversion', dest='version', help='SNMP version. (1 or 2)', default=2, type='int')
def get_common_options(helper):
# get the common options
host = helper.options.hostname
version = helper.options.version
community = helper.options.community
return host, version, community
def verify_host(host, helper):
if host == "" or host is None:
helper.exit(summary="Hostname must be specified"
, exit_code=pynag.Plugins.unknown
, perfdata='')
netsnmp_session = dev_null_wrapper(netsnmp.Session,
DestHost=helper.options.hostname,
Community=helper.options.community,
Version=helper.options.version)
try:
# Works around lacking error handling in netsnmp package.
if netsnmp_session.sess_ptr == 0:
helper.exit(summary="SNMP connection failed"
, exit_code=pynag.Plugins.unknown
, perfdata='')
except ValueError as error:
helper.exit(summary=str(error)
, exit_code=pynag.Plugins.unknown
, perfdata='')
# make a snmp get, if it fails (or returns nothing) exit the plugin
def get_data(session, oid, helper, empty_allowed=False):
var = netsnmp.Varbind(oid)
varl = netsnmp.VarList(var)
data = session.get(varl)
value = data[0]
if value is None:
helper.exit(summary="snmpget failed - no data for host "
+ session.DestHost + " OID: " +oid
, exit_code=pynag.Plugins.unknown
, perfdata='')
if not empty_allowed and not value:
helper.exit(summary="snmpget failed - no data for host "
+ session.DestHost + " OID: " +oid
, exit_code=pynag.Plugins.unknown
, perfdata='')
return value
# make a snmp get, but do not exit the plugin, if it returns nothing
# be careful! This funciton does not exit the plugin, if snmp get fails!
def attempt_get_data(session, oid):
var = netsnmp.Varbind(oid)
varl = netsnmp.VarList(var)
data = session.get(varl)
value = data[0]
return value
# make a snmp walk, if it fails (or returns nothing) exit the plugin
def walk_data(session, oid, helper):
tag = []
var = netsnmp.Varbind(oid)
varl = netsnmp.VarList(var)
data = list(session.walk(varl))
if len(data) == 0:
helper.exit(summary="snmpwalk failed - no data for host " + session.DestHost
+ " OID: " +oid
, exit_code=pynag.Plugins.unknown
, perfdata='')
for x in range(0, len(data)):
tag.append(varl[x].tag)
return data, tag
# make a snmp walk, but do not exit the plugin, if it returns nothing
# be careful! This function does not exit the plugin, if snmp walk fails!
def attempt_walk_data(session, oid):
tag = []
var = netsnmp.Varbind(oid)
varl = netsnmp.VarList(var)
data = list(session.walk(varl))
for x in range(0, len(data)):
tag.append(varl[x].tag)
return data, tag
def state_summary(value, name, state_list, helper, ok_value = 'ok', info = None):
"""
Always add the status to the long output, and if the status is not ok (or ok_value),
we show it in the summary and set the status to critical
"""
# translate the value (integer) we receive to a human readable value (e.g. ok, critical etc.) with the given state_list
state_value = state_list[int(value)]
summary_output = ''
long_output = ''
if not info:
info = ''
if state_value != ok_value:
summary_output += ('%s status: %s %s ' % (name, state_value, info))
helper.status(pynag.Plugins.critical)
long_output += ('%s status: %s %s\n' % (name, state_value, info))
return (summary_output, long_output)
def add_output(summary_output, long_output, helper):
"""
if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report
"""
if summary_output != '':
helper.add_summary(summary_output)
helper.add_long_output(long_output)

Python variable substitution

I have a script that calls a list of linux guests I am trying to tidy up. Here is the code:
#!/usr/bin/python
guests = ['guest1','guest2','guest3','guest*']
def serverCheck(guestList)
for g in guestList:
server = AdminControl.completeObjectName('cell=tstenvironment,node=guest1,name=uatenvironment,type=Server,*')
try:
status = AdminControl.getAttribute(server, 'state')
print g + status
except:
print "Error %s is down." % g
serverCheck(guests)
The problem lies in this line:
server = AdminControl.completeObjectName('cell=Afcutst,node=%s,name=afcuuat1,type=Server,*') % g
How do I use my list to populate the node variable while still being able to pass the info within the parentheses to the AdminControl function?
The argument string itself is the argument to the % operator, not the return value of the function call.
server = AdminControl.completeObjectName(
'cell=Afcutst,node=%s,name=afcuuat1,type=Server,*' % (g,)
)
Peeking into the crystal ball, Python 3.6 will allow you to write
server = AdminControl.completeObjectName(
f'cell=Afcutst,node={g},name=afcuuat1,type=Server,*'
)
embedding the variable directly into a special format string literal.
can you try like this
AdminControl.completeObjectName('cell=tstenvironment,node=%s,name=uatenvironment,type=Server,*'%g)
For more readability I would suggest this and also using the same way to format strings from variables (here I chose str.format)
guests = ['guest1','guest2','guest3','guest*']
def serverCheck(guestList)
name_tpl = 'cell=tstenvironment,node={},name=uatenvironment,type=Server,*'
for g in guestList:
obj_name = name_tpl.format(g)
server = AdminControl.completeObjectName(obj_name)
try:
status = AdminControl.getAttribute(server, 'state')
print '{}: {}'.format(g, status)
except:
print 'Error {} is down'.format(g)
serverCheck(guests)

How to get parameter values of a callback function?

I am trying to make call for a callback function in python.
I have a dll present at a path say 'dllpath'.
This dll have a callback function stated below:
Function prototype:
ULONG SetByteTotalsCallback(tFNByteTotals pCallback,BYTE interval);
Parameter discription:
tFNByteTotals pCallback: mode-IN, Callback function pointer
BYTE interval:mode-IN, Interval in seconds
Callback Prototype:
void ByteTotalsCallback(ULONGLONG txTotalBytes, ULONGLONG rxTotalBytes );
I want to call the function SetByteTotalsCallback and I want to print the values of txTotalBytes and rxTotalBytes.
I tried with following code:
from ctypes import *
filepath = r"<path to dll>"
gdll = WinDLL(filepath)
tx = c_longlong
rx = c_longlong
pCallback = CFUNCTYPE(tx, rx)
def ByteTotalsCallback(t, r):
try:
print 'Printing tx and rx: '
#print 'Transmitted bytes: ',t[0]
#print 'Received bytes: ',r[0]
#return 0
except:
print 'Error...'
byteTotal_func =pCallback(ByteTotalsCallback)
SetByteTotalsCallback = gdll.SetByteTotalsCallback
try:
print 'Return of SetByteTotals: ',SetByteTotalsCallback(pCallback(ByteTotalsCallback), c_byte(128))
except:
print 'Error found: '
After executing the above code, I observe that the function ByteTotalsCallback is not getting called but SetByteTotalsCallback(pCallback(ByteTotalsCallback), c_byte(128))
got called and returned back successfully.
Can someone help me?
Thanks in advance.
Regards,
Geet

Categories

Resources