How can I read out the NCTOPLC_AXIS_REF in TwinCAT using Ads.NET? - twincat

I'm trying to read out NCTOPLC_AXIS_REF from the PLC, but when I do a client.ReadAny(handle), it raises System.ExecutionEngineException. I've tried playing around with [StructLayout(LayoutKind.Sequential, Pack = 1)] and [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] in my struct, but so far without success.

This is the struct that works:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class NcToPlcAxisRef
{
public uint StateDWord;
public uint ErrorCode;
public uint AxisState;
public uint AxisModeConfirmation;
public uint HomingState;
public uint CoupleState;
public uint SvbEntries;
public uint SafEntries;
public uint AxisId;
public uint OpModeDWord;
public double ActPos;
public double ModuloActPos;
public ushort ActiveControlLoopIndex;
public ushort ControlLoopIndex;
public int ModuloActTurns;
public double ActVelo;
public double PosDiff;
public double SetPos;
public double SetVelo;
public double SetAcc;
public double TargetPos;
public double ModuloSetPos;
public int ModuloSetTurns;
public ushort CmdNo;
public ushort CmdState;
public double SetJerk;
public double SetTorque;
public double ActTorque;
public uint NcToPlcRefState2Value;
public uint NcToPlcRefState3Value2;
public uint TouchProbeState;
public uint TouchProbeCounter;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] CamCouplingStates = new byte[8];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public ushort[] CamCouplingTableID = new ushort[8];
public double ActTorqueDerivative;
public double SetTorqueDerivative;
public double AbsPhasingPos;
public double TorqueOffset;
public double ActPosWithoutPosCorrection;
public double ActAcc;
public uint DcTimeStamp;
}

Related

Asserion failed service testing spring

I have a simple shampoos-warehouse api and want to test it service logic, but something going wrong.
Here's my Service Test:
RunWith(SpringRunner.class)
#SpringBootTest
class ShampooServiceTest {
public static final String SHAMPOO_NAME = "name";
public static final int SHAMPOO_CAPACITY = 1000;
public static final int SHAMPOO_QUANTITY = 30;
public static final boolean SHAMPOO_IS_HEALTHY = true;
public static final LocalDate SHAMPOO_EXPIRATION_DATE = LocalDate.parse("2022-11-11");
public static final String SHAMPOO_PARAM = "equals";
#Autowired
ShampooService shampooService;
#MockBean
ShampooRepository shampooRepository;
#Test
void getAddAndGetTotalShampoosByParams(){
shampooService.addShampoos(UUID.randomUUID(), SHAMPOO_NAME, SHAMPOO_CAPACITY, SHAMPOO_QUANTITY, SHAMPOO_IS_HEALTHY, SHAMPOO_EXPIRATION_DATE);
assertEquals(String.valueOf(SHAMPOO_QUANTITY), shampooService.getTotalShampoosByParam(SHAMPOO_NAME, SHAMPOO_CAPACITY, SHAMPOO_PARAM));
}
I have an assertion error here:
org.opentest4j.AssertionFailedError:
Expected :30
Actual :0
Here's my DTO:
public class ShampooDto {
public interface IncomeValidation{}
public interface OutcomeValidation{}
#NotNull(groups={IncomeValidation.class, OutcomeValidation.class})
private String name;
#Min(100)
#Max(5000)
#NotNull(groups={IncomeValidation.class, OutcomeValidation.class})
private int capacity;
#NotNull(groups={IncomeValidation.class, OutcomeValidation.class})
private int quantity;
#NotNull(groups={IncomeValidation.class})
private boolean healthy;
#NotNull(groups={IncomeValidation.class})
private LocalDate expiration_date;
}
And here's my service:
public String getTotalShampoosByParam(String name, int capacity, String param){
Integer totalQuantity;
switch (param){
case "less":
totalQuantity = shampooRepository.getTotalQuantityWhereCapacityLess(name, capacity);
break;
case "equals":
totalQuantity = shampooRepository.getTotalQuantityWhereCapacityEquals(name, capacity);
break;
case "more":
totalQuantity = shampooRepository.getTotalQuantityWhereCapacityMore(name, capacity);
break;
default:
totalQuantity = 0;
}
if(totalQuantity!=null){
return String.valueOf(totalQuantity);
}
else{
return "0";
}
}
public Shampoo addShampoos(UUID id, String name, int capacity, int quantity, boolean healthy, LocalDate expiration_date) throws ValidationException {
Optional<Shampoo> answer = shampooRepository.findShampooByNameAndCapacity(name, capacity);
if(answer.isPresent()){
Shampoo shampoo = answer.get();
shampoo.setQuantity(shampoo.getQuantity() + quantity);
shampooRepository.save(shampoo);
return shampoo;
}
else{
Shampoo shampoo = new Shampoo(id, name, capacity, quantity, healthy, expiration_date, LocalDate.now());
shampooRepository.save(shampoo);
return shampoo;
}
}
The problem is that when I added Shampoos and search it by requests, all works, but my test give me "0" instead of "30"

getting an error in unboxing in c# stating name does not exist in current context?

class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter id");
int id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter name");
string name = Console.ReadLine();
Console.WriteLine("price");
int price = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter quantity");
int quantity = Convert.ToInt32(Console.ReadLine());
product_demo p1 = new product_demo(id, name, price, quantity);
p1.diplay();
Console.Read();
}
}
public class product_demo
{
public int id;
public string name;
public int price;
public int quantity;
public product_demo(int id, string name, int price, int quantity)
{
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
object o1 = id;
object o2 = name;
object o3 = price;
object o4 = quantity;
}
public void diplay()
{
int j = (int)o1;
Console.WriteLine("id :");
}
}
getting an error while unboxing in display function. boxing is done in product_demo constructor. one more question ; can we define boxing outside any constructor or methods, directly in body of class.
You have created object o1 in the constructor of product_demo and therefore it exists only within that scope. You need to have your objects within the class (Similar to where you have placed your other variables such as int id, string name, etc.

IBM ODM Dependant XOM classes

HI I have two questions to ask :-
I have a XOM class like this -
package com.ibm.p2p;
import javax.xml.bind.annotation.XmlElement;
import ilog.rules.bom.annotations.BusinessName;
import ilog.rules.bom.annotations.CustomProperty;
public class PO {
#XmlElement
private int quantity;
#XmlElement
private double price;
#XmlElement
private double totalAmount;
public PO() {
}
#CustomProperty(name = "dataio.default", value = "true")
public PO(#BusinessName("price") double price, #BusinessName("quantity") int quantity, #BusinessName("totalAmount") int totalAmount) {
this();
this.price = price;
this.quantity = quantity;
this.totalAmount = totalAmount;
}
public int getPOQuantity() {
return quantity;
}
public void setPOQuantity(int quantity) {
this.quantity = quantity;
}
public double getPOPrice() {
return price;
}
public void setPOPrice(double price) {
this.price = price;
}
public double getPOTotalAmount() {
return totalAmount;
}
public void setPOTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
}
When I deploy this and run the TEST using the "OPENAPI-JSON" REST option , by default I get this input JSON (attached in this message) :-
I dont understant why does the extra "quantity", "price" and "totalAMount" comes ?? In my XOM I have defined "getPOQuanitity", "getPOTotalAMount","getPOPrice" right? So only "poquantity", "poprice", "pototalAmount" should come right? How is this OPENAPI-JSON getting formed? If anyone can help me clarifying this , it will be useful for our testing also.
) I have some Print statements in my Rule. When I run this RestAPI Test where can I find the COnsole Print statements? I dont see them in my Server logs.
maybe you can try removing this part of the class:
public PO(#BusinessName("price") double price, #BusinessName("quantity") int quantity, #BusinessName("totalAmount") int totalAmount) {
this();
this.price = price;
this.quantity = quantity;
this.totalAmount = totalAmount;
}

JPA - Get values from fields in other entities in a Controller class

I have two entities: Room and Service. I also have a method in Logic class that i want to use in ServiceController class. Other classes are irrelevant.
room.getBeds() always returns 0, default int value.
Room entity:
#Entity
public class Room {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int room_id;
private int beds;
private int number;
public Room() {
}
public Room(int beds, int number) {
this.beds = beds;
this.number = number;
}
public int getRoom_id() {
return room_id;
}
public void setRoom_id(int room_id) {
this.room_id = room_id;
}
public int getBeds() {
return beds;
}
public void setBeds(int beds) {
this.beds = beds;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
Service entity:
#Entity
public class Service {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int service_id;
#JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date arrival_at;
#JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date departure_at;
private int meals;
private int guest_id;
private double price;
public int getService_id() {
return service_id;
}
public void setService_id(int service_id) {
this.service_id = service_id;
}
public Date getArrival_at() {
return arrival_at;
}
public void setArrival_at(Date arrival_at) {
this.arrival_at = arrival_at;
}
public Date getDeparture_at() {
return departure_at;
}
public void setDeparture_at(Date departure_at) {
this.departure_at = departure_at;
}
public int getMeals() {
return meals;
}
public void setMeals(int meals) {
this.meals = meals;
}
public int getGuest_id() {
return guest_id;
}
public void setGuest_id(int guest_id) {
this.guest_id = guest_id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Service controller:
#RestController
public class ServiceController {
#Autowired
ServiceRepository serviceRepository;
private Logic logic = new Logic();
private Room room = new Room();
//CREATE
#PostMapping("/services")
public int createService(#RequestBody Service service) {
service.setPrice(logic.calculatePrice(service.getArrival_at(), service.getDeparture_at(), room.getBeds(), service.getMeals()));
return serviceRepository.save(service);
}
}
How to get the correct value from room.getBeds() getter?
Lerius you are just making a new object of Room Entity and are not populating any values from your Database to that object
that is the reason why it is taking room.getBeds(); as 0(i.e default value for int)
Try Populating DB values to your object after that you will be able to get the value of getBeds();

How to sort an arraylist based on a bean?

public List<Bean> getList() {
List<Bean> beanList = new ArrayList<Bean>();
// some code here
while(hasNext()) {
// some code here
Bean bean = new Bean();
listing(bean, beanList);
}
// sort by age bean here before returning
return beanList
}
public void listing(Bean bean, List<Bean> beanList) {
//some code here
bean.setName(var1);
bean.setAddress(var2);
bean.setAge(var3);
beanList.add(bean)
}
I need to sort the arraylist based on the age.
I tried using Collectors but I'm not sure how to implement it with those code yet.
Thank you.
You need implement Comparator interface. In this case your implemnetation would be
public class BeanAgeComparator implements Comparator<Bean> {
int compare(Bean o1,Bean o2) {
return o1.getAge() - o2.getAge();
}
}
Then you can sort the List using Collections.sort(beanList, new BeanAgeComparator());
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public class BinarySearch{
public static void main(String s[]) {
List<Bean> beanList=new BinarySearch().getList(10);
for(Bean bean:beanList){System.out.println(bean.getAge());}
}
public List<Bean> getList(int size) {
List<Bean> beanList = new ArrayList<Bean>();
int i=0;
while(i<size) {
Bean bean = new Bean();
listing(bean, beanList);
i++;
}
Comparator<Bean> c=new Comparator<Bean>(){
#Override
public int compare(Bean bean1, Bean bean2) {
return bean1.getAge()-bean2.getAge();
}};
Collections.sort(beanList,c);
return beanList;
}
Random r=new Random();
public void listing(Bean bean, List<Bean> beanList) {
bean.setName("name");
bean.setAddress("address");
bean.setAge(r.nextInt(81)+18);
beanList.add(bean);
}
}
class Bean {
String name;
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
int age;
}
Or u can implement comparable interface in your Bean class-
public class SortedList{
public static void main(String s[]) {
List<Bean> beanList=new SortedList().getList(10);
for(Bean bean:beanList){System.out.println(bean.getAge());}
}
public List<Bean> getList(int size) {
List<Bean> beanList = new ArrayList<Bean>();
int i=0;
while(i<size) {
Bean bean = new Bean();
listing(bean, beanList);
i++;
}
Collections.sort(beanList);
return beanList;
}
Random r=new Random();
public void listing(Bean bean, List<Bean> beanList) {
bean.setName("name");
bean.setAddress("address");
bean.setAge(r.nextInt(81)+18);
beanList.add(bean);
}
}
class Bean implements Comparable<Bean>{
String name;
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
int age;
#Override
public int compareTo(Bean bean) {
return this.getAge()-bean.getAge();
}
}

Resources