pyModBus : check if coil is True or False - pymodbus3

I am trying to learn how to introduce values to a PLC trough python ModBus module what I'm currently trying to do is just to read the value of coil 1 to check if its True or false so I am using
order_ready = client.read_coils(0, 1)
print(order_ready)
and I get this as response ReadBitResponse(8) how can I get a "True" value from reading a coil

You can access the individual coils from the response ReadCoilResponse using the bits property . More on response could be found here
order_ready = client.read_coils(0, 1)
if not order_ready.isError():
#response.bits would return a list (multiple of 8) of booleans each bit representing the output of one coils
# In your case accessing 1st element should give the actual value
order_ready = order_ready.bits[0]
else:
# Handle error

Related

How CryptoJS calculate SHA256 on hex words array?

I tried to implement sha256 without using library, so I took this code : https://github.com/dmarman/sha256algorithm/blob/main/src/classes/sha.js
It's working well, taking in input string and returning the good hash (also a string)
The problem I have is with CryptoJS library. Let's see the three following lines :
x = "00000000";
console.log(CryptoJS.SHA256(CryptoJS.enc.Hex.parse(x))+"");
console.log(sha256(x));
It gives to me two distincts results :
df3f619804a92fdb4057192dc43dd748ea778adc52bc498ce80524c014b81119
7e071fd9b023ed8f18458a73613a0834f6220bd5cc50357ba3493c6040a9ea8c
I understood that the CryptoJS.enc.Hex.parse(x) changes the result with CryptoJS, If I use x directly, I don't have difference
Another point, if you try x == CryptoJS.enc.Hex.parse(x) it gives you true, but CryptoJS.SHA256 seems to give different result following the type of the input
The problem, is that, in my exercice, I want to get the result of CryptoJS.SHA256(CryptoJS.enc.Hex.parse(x)) with my sha256 function
So I'm looking for function f such as sha256(f(x)) = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(x))+""
I know that the condition x == CryptoJS.enc.Hex.parse(x) is not always true, it's here because I took 00000000, but we case suppose the condition always satisfied for the exercise.
Do you have any explanation please ?

pytorch lightning epoch_end/validation_epoch_end

Could anybody breakdown the code and explain it to me? The part that needs help is indicated with the "#This part". I would greatly appreciate any help thanks
def validation_epoch_end(self, outputs):
batch_losses = [x["val_loss"]for x in outputs] #This part
epoch_loss = torch.stack(batch_losses).mean()
batch_accs = [x["val_acc"]for x in outputs] #This part
epoch_acc = torch.stack(batch_accs).mean()
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
def epoch_end(self, epoch, result):
print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format( epoch,result['val_loss'], result['val_acc'])) #This part
Based on the structure, I assume you are using pytorch_lightning.
validation_epoch_end() will collect outputs from validation_step(), so it's a list of dict with the length of number of batch in your validation dataloader. Thus, the first two #This part is just unwrapping the result from your validation set.
epoch_end() catch the result {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()} from validation_epoch_end().
In your provided snippet, outputs is a list containing dicts elements which seem to contain at least keys "val_loss", and "val_acc". It would be fair to assume they correspond to the validation loss and validation accuracy respectively.
Those two lines (annotated with the # This path comment) correspond to list comprehensions going over the elements inside the outputs list. The first one gathers the values of the key "val_loss" for each element in outputs. The second one does the same this time gathering the values of the "val_acc" key.
A minimal example would be:
## before
outputs = [{'val_loss': tensor(a), # element 0
'val_acc': tensor(b)},
{'val_loss': tensor(c), # element 1
'val_acc': tensor(d)}]
## after
batch_losses = [tensor(a), tensor(c)]
batch_acc = [tensor(b), tensor(d)]

change style code function VScode time optimisation while coding

my goal is change a function to a format where the return value of the function is treated :
For example ; treating a the function scanf()
Return value of scanf : The value EOF is returned if the end of input is reached before
either the first successful conversion or a matching failure occurs.
EOF is also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set to
indicate the error.
Thus
scanf("%d\n",&i);
will be change to
#define RVAL(exp) do {if ((exp) == -1) { perror (#exp); exit(1); }} while (0)
...
RVAL(scanf("%d\n",&i));
Thus I want this to be done quickly means :
so what i do is look for occurences of "scanf" and replace it with "RVAL(scanf"
but the problem is i have to add another right parentheses
Can this be done fast ? using a techniques ? or a style ? where each whenever I enter scanf(); its replaced witch rval(scanf());
If you don't have many ) in your format string you can use a regex with (scanf([^)]*)); and replace with rval(\1);
*see comment

Can pysnmp return octectstring values only

I am doing a small script to get SNMP traps with PySnmp.
I am able to get the oid = value pairs, but the value is too long with a small information in the end. How can I access the octectstring only which comes in the end of the value. Is there a way other than string manipulations? Please comment.
OID =_BindValue(componentType=NamedTypes(NamedType('value', ObjectSyntax------------------------------------------------(DELETED)-----------------(None, OctetString(b'New Alarm'))))
Is it possible to get the output like the following, as is available from another SNMP client:
.iso.org.dod.internet.private.enterprises.xxxx.1.1.2.2.14: CM_DAS Alarm Traps:
Edit - the codes are :
**for oid, val in varBinds:
print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
target.write(str(val))**
On screen, it shows short, but on file, the val is so long.
Usage of target.write( str(val[0][1][2])) does not work for all (program stops with error), but the 1st oid(time tick) gets it fine.
How can I get the value from tail as the actual value is found there for all oids.
Thanks.
SNMP transfers information in form of a sequence of OID-value pairs called variable-bindings:
variable_bindings = [[oid1, value1], [oid2, value2], ...]
Once you get the variable-bindings sequence from SNMP PDU, to access value1, for example, you might do:
variable_binding1 = variable_bindings[0]
value1 = variable_binding1[1]
To access the tail part of value1 (assuming it's a string) you could simply subscribe it:
tail_of_value1 = value1[-10:]
I guess in your question you operate on a single variable_binding, not a sequence of them.
If you want pysnmp to translate oid-value pair into a human-friendly representation (of MIB object name, MIB object value), you'd have to pass original OID-value pair to the ObjectType class and run it through MIB resolver as explained in the documentation.
Thanks...
the following codes works like somwwhat I was looking for.
if str(oid)=="1.3.6.1.2.1.1.3.0":
target.write(" = str(val[0][1]['timeticks-value']) = " +str(val[0][1]['timeticks-value'])) # time ticks
else:
target.write("= val[0][0]['string-value']= " + str(val[0][0]['string-value']))

convert string to logical expression

I use configuration file to load logical expression which will later be replace with 0 or 1 depend on the success or failure
configuration
expression=(server.ip.1&&server.ip.2)||(server.ip.3&&server.ip.4)
Later server.ip.1 will replace with 1 or 0 depend on server availability. Later part of the logical expression evaluation has below piece of code.
my $reg_expression= configurator->get_reg_expression() ;
...
$reg_expression =~ s/$values[0]/$ip_status/g;
if ($reg_expression){
$logger->debug("no failover");
}else{
$logger->debug("falling to failover mode");
}
Issue is if condition always true what ever values assign to the expression. Issue seems to be it is taken as string so it always end up in true. Any other way that I can do the same or how can transfer above variable back to state where I can successfully use inside if condition.
$reg_expression = (0&&0)||(1&&0); # diffe
$reg_expression = '(0&&0)||(1&&0)';
You can use eval to evaluate the expression:
my $reg_expression = '(0&&0)||(1&&0)';
print eval $reg_expression, "\n";