raise AttributeError(name) AttributeError: LCC_GetChannelHandle - python

I am very new in python cffi. I have to access my temprature module by using its Index or with its channel name. I am trying with both as you can see in my QmixTC class. I am getting attribute error. In other class, there is no errors. Can someone help me understand where is the problem. I am putting my code as well as error trace. Thanks.
main code with name qmix.py (importing it in to sample code):
class QmixTC (object):
"""
"""
def __init__(self, index=0, handle=None,name=''):
self.dll_dir = DLL_DIR
self.dll_file = os.path.join(self.dll_dir,
'labbCAN_Controller_API.dll')
self._ffi = FFI()
self._ffi.cdef(CONTROLLER_HEADER)
self._dll = self._ffi.dlopen(self.dll_file)
self._handle = self._ffi.new('dev_hdl *', 0)
if handle is None:
self.index = index
self._handle = self._ffi.new('dev_hdl *', 0)
self._call('LCC_GetChannelHandle', self.index, self._handle)
else:
self.index = None
self._handle = handle
self._ch_name="QmixTC_1_DO0_INA"
self._channel = self._ch_name + str(index)
self._call('LCC_LookupChanByName',
bytes(self._channel,'utf8'),
self._handle)
self.name = name
def _call(self, func_name, *args):
func = getattr(self._dll, func_name)
r = func(*args)
r = CHK(r, func_name, *args)
return r
def Setpoint_write (self, setpoint):
"""
Write setpoint value to controller device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[in] fSetPointValue The setpoint value to write
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_WriteSetPoint', self._handle[0], setpoint)
def enable_controllLoop (self, enable):
"""
Enables / disables a control loop.
If the control loop is enabled, then the output value is calculated periodically.
Parameters
ChanHdl Valid handle of a controller channel
Enable 1 = enable, 0 = disable
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_EnableControlLoop', self._handle[0], enable)
def read_temp_value (self, actualvalue):
"""
Read actual value from device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[out] pfActualValue Returns the actual controller value
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_ReadActualValue', self._handle[0], actualvalue)
if __name__ == '__main__':
import os.path as op
dll_dir = op.normpath('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = op.normpath('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_Pump\\Configurations\\QmixTC_pump')
bus = QmixBus(config_dir=config_dir)
bus.open()
bus.start()
controller_0 = QmixTC(index=0)
controller_0.enable_controllLoop(1)
sample program:
from __future__ import division, print_function
from win32api import GetSystemMetrics
import numpy as np
import os
import qmix
import pandas as pd
#%% CHANNEL INITIALIZATION
if __name__ == '__main__':
dll_dir = ('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = ('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_test1\\Configurations\\QmixTC_test1')
qmix_bus = qmix.QmixBus(config_dir=config_dir,dll_dir=dll_dir)
qmix_bus.open()
qmix_bus.start()
controller_0 = qmix.QmixTC(index=0)
controller_0.Setpoint_write(50)
error:
Traceback (most recent call last):
File "<ipython-input-5-40d4a3db9493>", line 17, in <module>
controller_0 = qmix.QmixTC(index=0)
File "qmix.py", line 921, in __init__
self._call('LCC_GetChannelHandle', self.index, self._handle)
File "qmix.py", line 937, in _call
func = getattr(self._dll, func_name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 875, in __getattr__
make_accessor(name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 870, in make_accessor
raise AttributeError(name)
AttributeError: LCC_GetChannelHandle

Related

TypeError: <lambda>() missing 1 required positional argument: 'instance' in Locust

I need to loadtest an Odoo Environment and I have written a test class with different methods in it. Currently I'm trying to test this stuff locally but I'm running in a error that I don't understand right now.
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreenlet.Greenlet.run
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/users.py", line 175, in run_user
user.run()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/users.py", line 143, in run
self._taskset_instance.run()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 365, in run
self.wait()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 443, in wait
self._sleep(self.wait_time())
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 418, in wait_time
return self.user.wait_time()
TypeError: <lambda>() missing 1 required positional argument: 'instance'
2022-10-20T11:30:13Z <Greenlet at 0x7f49e55376a0: run_user(<__main__.OdooTestCasesUser object at 0x7f49e51f46)> failed with TypeError
I have written the following test classes
class OdooTestCases(TaskSet):
weight = 10
fixed_count = 1
min_wait = 0.5
max_wait = 5.0
#task(20)
def read_partners(self):
customer_model = self.client.get_model("res.partner")
customer_ids = customer_model.search([], limit=80)
#task(10)
def read_product_template_qty(self):
customer_model = self.client.get_model("product.template")
customer_ids = customer_model.search([], limit=80)
#task(10)
def read_sale_orders(self):
so_model = self.client.get_model("sale.order")
so_ids = so_model.search([], limit=100)
#task(20)
def read_stock_pickings(self):
stock_picking_model = self.client.get_model("stock.picking")
stock_pickings = stock_picking_model.search([], limit=100)
#task(20)
def read_stock_movings(self):
stock_moving_model = self.client.get_model("stock.move")
stock_movings = stock_moving_model.search([], limit=100)
#task(30)
def read_stock_locations(self):
stock_location_model = self.client.get_model("stock.location")
stock_locations = stock_location_model.search([], limit=100)
#task(25)
def read_stock_picking_types(self):
stock_picking_type_model = self.client.get_model("stock.picking.type")
stock_picking_types = stock_picking_type_model.search([], limit=100)
def stop(self):
self.interrupt()
class OdooTestCasesUser(OdooLocustUser):
wait_time = between(0.500, 5)
host = "localhost"
database = "demo"
login = "test"
password = "test"
def __init__(self, parent):
super().__init__(parent)
self.login = "test"
self.password = "test"
self.wait_time = between(0.500, 5)
self.tasks = [OdooTestCases]
Another problem is that I don't get test results returned on my CLI.
I tried everything to fix this, what I've found on the internet, but without any success.
I would be really happy if someone could give me a guess or a solution.
Just hit me up if someone needs more information about this case.
Looks like you are using legacy style wait times:
min_wait = 0.5
max_wait = 5.0
AND new style
wait_time = ...
Maybe remove the legacy ones?

Python Curses addwstr() returned ERR when adding lines to screen

Suppose I am adding a large number of lines to a curses screen.
Minimal non-working example:
import curses
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
for i in range(0,100):
self.screen.addstr(str(i) + '\n')
self.screen.refresh()
self.screen.getch()
if __name__ == '__main__':
curses.wrapper(MyApp)
The above code returns:
Traceback (most recent call last):
File "test.py", line 17, in <module>
curses.wrapper(MyApp)
File "/usr/lib/python3.7/curses/__init__.py", line 94, in wrapper
return func(stdscr, *args, **kwds)
File "test.py", line 11, in __init__
self.screen.addstr(str(i) + '\n')
_curses.error: addwstr() returned ERR
Press ENTER to continue
1) What is this error?
2) If the error is because I am adding too many lines to the screen, how could I list those entries with curses? Perhaps with a scroll view of some sort?
It occurred to me that I could use try/except to determine the maximum number of lines that can be printed on the screen to avoid this error:
import curses
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
maximum = self.maxlines()
for i in range(maximum):
self.screen.addstr(str(i) + '\n')
self.screen.refresh()
self.screen.getch()
def maxlines(self):
n = 0
try:
for i in range(100):
self.screen.addstr(str(i) + '\n')
n += 1
except:
pass
self.screen.erase()
return n
if __name__ == '__main__':
curses.wrapper(MyApp)

how to read data by using pywinusb in python

I can't read hid data by using pywinusb in python.
I referred to this page(https://www.reddit.com/r/learnpython/comments/3z346p/reading_a_usb_data_stream_on_windows/)
and I have question.
def sample_handler(data):
print("Raw data: {0}".format(data))
sample_handler function needs to data.
but
device.set_raw_data_handler(sample_handler)
this code do not give data to sample_handler. is it not error?
and below is my code.
my code don't catch read_handler function.
how can i fix it. could you help me?
from pywinusb import hid
import time
class PIC18f:
def __init__(self, VID = 0x04D8, PID=0x003f):
filter = hid.HidDeviceFilter(vender_id = VID, product_id = PID)
self.devices = filter.get_devices()
self.device = self.devices[0]
self.device.open()
def write(self, args):
out_report = self.device.find_output_reports()
out_report[0].set_raw_data(args)
out_report[0].send()
time.sleep(1)
def read_handler(self, data):
print("Raw data: {0}".format(data))
print("done")
def I2C_Init(self):
buf = [0x00]
buf = buf + [0 for i in range(65-len(buf))]
buf[1] = 0xF1
buf[2] = 0x1D
self.write(buf)
self.device.set_raw_data_handler(read_handler)
test = PIC18f()
test.I2C_Init()
this is error.
Traceback (most recent call last):
File "d:/1. Siliconmitus/python/test2.py", line 35, in
test.I2C_Init()
File "d:/1. Siliconmitus/python/test2.py", line 32, in I2C_Init
self.device.set_raw_data_handler(read_handler)
NameError: name 'read_handler' is not defined
read_handler is not defined because the "read_handler" should be defined inside I2C_Init.
The following is an example:
from pywinusb import hid
filter = hid.HidDeviceFilter(vendor_id = 0x0001, product_id = 0x0002)
devices = filter.get_devices()
device = devices[0]
def readData(data):
print(data)
return None
device.set_raw_data_handler(readData)
device.open()

Broadcast a user defined class in Spark

I am trying to broadcast a user defined variable in a PySpark application but I always have the following error:
File "/usr/local/spark-2.1.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/worker.py", line 174, in main
process()
File "/usr/local/spark-2.1.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/worker.py", line 169, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/usr/local/spark-2.1.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/serializers.py", line 268, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/home/.../sparkbroad.py", line 29, in <lambda>
output = input_.map(lambda item: b.value.map(item))
File "/usr/local/spark-2.1.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/broadcast.py", line 106, in value
self._value = self.load(self._path)
File "/usr/local/spark-2.1.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/broadcast.py", line 97, in load
return pickle.load(f)
AttributeError: 'module' object has no attribute 'FooMap'
The code, in the module sparkbrad.py is the following:
import random
import pyspark as spark
class FooMap(object):
def __init__(self):
keys = list(range(10))
values = [2 * key for key in keys]
self._map = dict(zip(keys, values))
def map(self, value):
if value not in self._map:
return -1
return self._map[value]
class FooMapJob(object):
def __init__(self, inputs):
self._inputs = inputs
self._foomap = FooMap()
def run(self):
sc = spark.SparkContext('local', 'FooMap')
input_ = sc.parallelize(self._inputs, 4)
b = sc.broadcast(self._foomap)
output = input_.map(lambda item: b.value.map(item))
b.unpersist()
result = list(output.toLocalIterator())
sc.stop()
return result
def main():
inputs = [random.randint(0, 10) for _ in range(10)]
job = FooMapJob(inputs)
print(job.run())
if __name__ == '__main__':
main()
and I am running it via the:
:~$ spark-submit --master local[4] --py-files sparkbroad.py sparkbroad.py
where I have added the --py-files argument but it looks it doesn't change that much. Unfortunately, I could not find any example online dealing with broadcasting of complex classes (just lists or dictionaries). Any hint is appreciated. Thanks in advance.
UPDATE: placing the FooMap class in a separate module, everything seems working fine, even without the --py-files directive.
Placing the FooMap class in a separate module, everything works fine.
This is an addition to the previous answer.
You should import FooMap from another file not just define it in current file
maybe like this:
in foo_map.py:
class FooMap(object):
def __init__(self):
keys = list(range(10))
values = [2 * key for key in keys]
self._map = dict(zip(keys, values))
def map(self, value):
if value not in self._map:
return -1
return self._map[value]
then in sparkbrad.py
from foo_map import FooMap
class FooMapJob(object):
def __init__(self, inputs):
self._inputs = inputs
self._foomap = FooMap()
def run(self):
sc = spark.SparkContext('local', 'FooMap')
input_ = sc.parallelize(self._inputs, 4)
b = sc.broadcast(self._foomap)
output = input_.map(lambda item: b.value.map(item))
b.unpersist()
result = list(output.toLocalIterator())
sc.stop()
return result
def main():
inputs = [random.randint(0, 10) for _ in range(10)]
job = FooMapJob(inputs)
print(job.run())
if __name__ == '__main__':
main()

buildbot doesn't accept my MailNotifier's IEMailLookup object

A number of people in my organization have different email names from perforce names, so I need to create an IEmailLookup derivation that overrides getAddress to do my evil bidding:
(From my master.cfg)
class MyIEmailLookup:
from buildbot import interfaces
__implements__ = interfaces.IEmailLookup
def getAddresses(user):
address_dict = {"user1", "user_one#our_domain.com"}
try:
address = address_dict[user]
except KeyError:
address = user + "#our_domain.com"
return address
maillookup = MyIEmailLookup()
from buildbot.status import mail
c['status'].append(mail.MailNotifier(....
....
lookup=maillookup
))
I've tried any number of permutations, but I either get:
Traceback (most recent call last):
File "/Library/Python/2.6/site-packages/buildbot-0.8.3p1-py2.6.egg/buildbot/scripts/runner.py", line 1071, in doCheckConfig
ConfigLoader(configFileName=configFileName)
File "/Library/Python/2.6/site-packages/buildbot-0.8.3p1-py2.6.egg/buildbot/scripts/checkconfig.py", line 46, in __init__
self.loadConfig(configFile, check_synchronously_only=True)
File "/Library/Python/2.6/site-packages/buildbot-0.8.3p1-py2.6.egg/buildbot/master.py", line 727, in loadConfig
exec f in localDict
File "/Users/playbuilder/buildbot/master.cfg", line 207, in <module>
lookup=maillookup
File "/Library/Python/2.6/site-packages/buildbot-0.8.3p1-py2.6.egg/buildbot/status/mail.py", line 293, in __init__
assert interfaces.IEmailLookup.providedBy(lookup)
AssertionError
...or any other number of issues, dependant upon how I try to implement the IEmailLookup interface.
I'm using buildbot 0.8.3p1 and python 2.6.1.
I see precious few examples of how to do this, and every one of them fails in my context. What am I missing here?
I just solved this problem myself.
First you need to add (somewhere at the top of the file)
from zope.interface import implements
and then change
__implements__ = interfaces.IEmailLookup
to
if implements:
implements( interfaces.IEmailLookup )
else:
__implements__ = interfaces.IEmailLookup
If you want to fetch email from perforce user, you can use this class:
# .-----------------------.
# | Perforce Email Lookup |
# `-----------------------'
from twisted.internet import defer, utils
from buildbot.util import ComparableMixin
from buildbot.interfaces import IEmailLookup
from zope.interface import implements
import os
import re
class PerforceEmailLookup(ComparableMixin):
implements(IEmailLookup)
compare_attrs = ["p4port", "p4user", "p4passwd", "p4bin"]
env_vars = ["P4CLIENT", "P4PORT", "P4PASSWD", "P4USER",
"P4CHARSET"]
def __init__(self,
p4port = None,
p4user = None,
p4passwd = None,
p4bin = 'p4'):
self.p4port = p4port
self.p4user = p4user
self.p4passwd = p4passwd
self.p4bin = p4bin
self.email_re = re.compile(r"Email:\s+(?P<email>\S+#\S+)\s*$")
def _get_process_output(self, args):
env = dict([(e, os.environ.get(e)) for e in self.env_vars if os.environ.get(e)])
d = utils.getProcessOutput(self.p4bin, args, env)
return d
#defer.deferredGenerator
def getAddress(self, name):
if '#' in name:
yield name
return
args = []
if self.p4port:
args.extend(['-p', self.p4port])
if self.p4user:
args.extend(['-u', self.p4user])
if self.p4passwd:
args.extend(['-P', self.p4passwd])
args.extend(['user', '-o', name])
wfd = defer.waitForDeferred(self._get_process_output(args))
yield wfd
result = wfd.getResult()
for line in result.split('\n'):
line = line.strip()
if not line: continue
m = self.email_re.match(line)
if m:
yield m.group('email')
return
yield name
usage would look like:
c['status'].append(
MailNotifier(
sendToInterestedUsers = True,
mode = 'failing',
lookup = PerforceEmailLookup(
p4port = "perforce:1666",
p4user = "buildbot",
p4passwd = "buildbot")))
Try this:
from buildbot.interfaces import IEmailLookup
from buildbot.util import ComparableMixin
from zope.interface import implements
class lookup_example_email(ComparableMixin):
implements(IEmailLookup)
def getAddress(self,user):
return "%s#example.com"%(user)
...
mn = MailNotifier(..., lookup=lookup_example_email(), extraRecipients=m)
Here's the piece of code I use which works with buildbot 2.3.1 in python3.6.
from buildbot.interfaces import IEmailLookup
from buildbot.util import ComparableMixin
from zope.interface import implementer
#implementer(IEmailLookup)
class EmailMap(ComparableMixin):
def getAddress(self, name):
return f'{name}#xxxxx'

Categories

Resources