Using Visual Studio Code as alternative for Arduino IDE - Setting register bit fails - visual-studio-code

Update #1
The code is working now.
Try putting those four assignments (TCCR1 to TIMSK1) inside a routine, and call it from setup. It's strange to see them treated as global variables; they aren't really. – aMike
You were right. After putting it in a routine I am able to verify and upload the code in VS Code. The result is as expected.
After the code works now I tried to improve the style of the code, so I did a little research how to make it easier to read. So it looks a bit different now.
Not that this has anything to do with your problem, but you probably don't want the semicolon in #define PRESCALE_OFFSET 3035; Also, like aMike said.
Thanks for the advice.
Although it works, VS Code still marks the relevant position as not defined as lurker mentioned. But that is how I have to do as far as I know. For example: Arduino - Port Manipulation
Thanks for your replies!
CODE Main.ino
/****************************************************************************/
/*---------------------------------Includes---------------------------------*/
/****************************************************************************/
#include <stdio.h>
#include <Arduino.h>
#include "init.h"
/****************************************************************************/
/*-------------------------Function Implementations-------------------------*/
/****************************************************************************/
void setup()
{
EnableInterrupts();
InitPeripherals();
}
void loop()
{
;
}
CODE init.h
/*---------------------------------Includes---------------------------------*/
/****************************************************************************/
#ifndef INIT_H
#define INIT_H
/****************************************************************************/
/*----------------------------Function Prototypes---------------------------*/
/****************************************************************************/
void InitPeripherals(void);
void EnableInterrupts(void);
void InitSensors(void);
void InitTimer(void);
#endif
CODE init.cpp
/****************************************************************************/
/*---------------------------------Includes---------------------------------*/
/****************************************************************************/
#include "init.h"
#include <Arduino.h>
/****************************************************************************/
/*----------------------------------Macros----------------------------------*/
/****************************************************************************/
#define PRESCALE_OFFSET 3035
/****************************************************************************/
/*-----------------------------Global Variables-----------------------------*/
/****************************************************************************/
/****************************************************************************/
/*-------------------------Function Implementations-------------------------*/
/****************************************************************************/
void EnableInterrupts(void)
{
TIMSK1 |= (1<<TOIE1); //enable interrupts on timer2 (16bit timer)
}
void InitSensors(void)
{
;
}
void InitTimer(void)
{
TCCR1A = 0; //WGM10 WGM11 normal mode for 16bit timer
TCCR1B = 0; //WGM12 WGM13 normal mode for 16bit timer
TCCR1B |= (1<<CS12); //prescaler set to 256
}
void InitPeripherals(void)
{
EnableInterrupts();
InitSensors();
InitTimer();
Serial.begin(115200);
}
/* Declare the Timer Interrupt Function*/
ISR(TIMER1_OVF_vect)
{
TCNT1 = PRESCALE_OFFSET; //let the timer start at offset
Serial.println(millis());
}
ISSUE
I am working on a small embedded project and I want to use an Arduino Uno for realization.
I don't like the Arduino IDE and want to use Visual Studio Code instead.
I managed to get everything running so far. I can compile and upload the code to the Board to get some output on the serial monitor for example.
So far so good.
Now I want to dive deeper and set some register bits to set up a timer interrupt. This code below throws an error in VS Code during verfication, but not in Arduino IDE. I uploaded via Arduino IDE and the code runs as expected.
Does anyone know how to overcome this issue in VS Code?
I am a beginner, so please don't wonder about the structre and the actual content of the code. At the moment I am trying to figure out how to use header files correctly and how to set up a useful structure.
Thanks in advance!
CODE Main.ino
#include "init.h"
#include <stdio.h>
#include <Arduino.h>
int i = 0;
void setup()
{
Serial.begin(115200);
}
void loop()
{
;
}
CODE init.h
#ifndef INIT_H
#define INIT_H
#include <Arduino.h>
#define PRESCALE_OFFSET 3035;
/*
Functions
*/
int function01(int a);
#endif
CODE init.cpp
#include "init.h"
#include <Arduino.h>
TCCR1A = 0; //WGM10 WGM11 normal mode for 16bit timer
TCCR1B = 0; //WGM12 WGM13 normal mode for 16bit timer
TCCR1B |= (1<<CS12); //prescaler set to 256
TIMSK1 |= (1<<TOIE1); //enable interrupts on timer2 (16bit timer)
ISR(TIMER1_OVF_vect)
{
TCNT1 = PRESCALE_OFFSET; //let the timer start at offset
Serial.println(millis());
}
int function01(int a)
{
a++;
return a;
}
ERROR
[Starting] Verifying sketch 'Main.ino'
[Warning] Output path is not specified. Unable to reuse previously compiled files. Build will be slower. See README.
Konfiguration wird geladen...
Pakete werden initialisiert...
Boards werden vorbereitet...
Überprüfungsvorgang...
In file included
from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:90,
from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
from c:\Users\pelzk\OneDrive\3D Prints\04 Projekte\Hydroponic\Coding\hydroponics\init.h:4,
from c:\Users\pelzk\OneDrive\3D Prints\04 Projekte\Hydroponic\Coding\hydroponics\init.cpp:5:
init.cpp:8:1: error: expected unqualified-id before 'volatile'
TCCR1A = 0; //WGM10 WGM11 normal mode for 16bit timer
^
init.cpp:8:1: error: expected ')' before 'volatile'
init.cpp:8:1: error: expected ')' before 'volatile'
init.cpp:9:1: error: expected unqualified-id before 'volatile'
TCCR1B = 0; //WGM12 WGM13 normal mode for 16bit timer
^
init.cpp:9:1: error: expected ')' before 'volatile'
init.cpp:9:1: error: expected ')' before 'volatile'
init.cpp:10:1: error: expected unqualified-id before 'volatile'
TCCR1B |= (1<<CS12); //prescaler set to 256
^
init.cpp:10:1: error: expected ')' before 'volatile'
init.cpp:10:1: error: expected ')' before 'volatile'
init.cpp:11:1: error: expected unqualified-id before 'volatile'
TIMSK1 |= (1<<TOIE1); //enable interrupts on timer2 (16bit timer)
^
init.cpp:11:1: error: expected ')' before 'volatile'
init.cpp:11:1: error: expected ')' before 'volatile'
exit status 1
DEBUG StatusLogger Stopping LoggerContext[name=1e6f5c3, org.apache.logging.log4j.core.LoggerContext#28087]
DEBUG StatusLogger Stopping LoggerContext[name=1e6f5c3, org.apache.logging.log4j.core.LoggerContext#28087]...
TRACE StatusLogger Unregistering 1 MBeans: [org.apache.logging.log4j2:type=1e6f5c3]
TRACE StatusLogger Unregistering 1 MBeans: [org.apache.logging.log4j2:type=1e6f5c3,component=StatusLogger]
TRACE StatusLogger Unregistering 1 MBeans: [org.apache.logging.log4j2:type=1e6f5c3,component=ContextSelector]
TRACE StatusLogger Unregistering 1 MBeans: [org.apache.logging.log4j2:type=1e6f5c3,component=Loggers,name=]
TRACE StatusLogger Unregistering 2 MBeans: [org.apache.logging.log4j2:type=1e6f5c3,component=Appenders,name=RollingFile, org.apache.logging.log4j2:type=1e6f5c3,component=Appenders,name=Console]
TRACE StatusLogger Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=1e6f5c3,component=AsyncAppenders,name=*'
TRACE StatusLogger Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=1e6f5c3,component=AsyncLoggerRingBuffer'
TRACE StatusLogger Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=1e6f5c3,component=Loggers,name=*,subtype=RingBuffer'
TRACE StatusLogger Stopping XmlConfiguration[location=jar:file:/C:/Program%20Files%20(x86)/Arduino/lib/pde.jar!/log4j2.xml]...
TRACE StatusLogger XmlConfiguration notified 2 ReliabilityStrategies that config will be stopped.
TRACE StatusLogger XmlConfiguration stopping 1 LoggerConfigs.
TRACE StatusLogger XmlConfiguration stopping root LoggerConfig.
TRACE StatusLogger XmlConfiguration notifying ReliabilityStrategies that appenders will be stopped.
TRACE StatusLogger XmlConfiguration stopping remaining Appenders.
DEBUG StatusLogger Shutting down RollingFileManager C:\Users\pelzk\AppData\Local\Arduino15/logs/application.log
DEBUG StatusLogger Shutting down RollingFileManager C:\Users\pelzk\AppData\Local\Arduino15/logs/application.log
DEBUG StatusLogger All asynchronous threads have terminated
DEBUG StatusLogger RollingFileManager shutdown completed with status true
DEBUG StatusLogger Shut down RollingFileManager C:\Users\pelzk\AppData\Local\Arduino15/logs/application.log, all resources released: true
DEBUG StatusLogger Appender RollingFile stopped with status true
DEBUG StatusLogger Shutting down OutputStreamManager SYSTEM_ERR.false.false
DEBUG StatusLogger Shut down OutputStreamManager SYSTEM_ERR.false.false, all resources released: true
DEBUG StatusLogger Appender Console stopped with status true
TRACE StatusLogger XmlConfiguration stopped 2 remaining Appenders.
TRACE StatusLogger XmlConfiguration cleaning Appenders from 2 LoggerConfigs.
DEBUG StatusLogger Stopped XmlConfiguration[location=jar:file:/C:/Program%20Files%20(x86)/Arduino/lib/pde.jar!/log4j2.xml] OK
DEBUG StatusLogger Stopped LoggerContext[name=1e6f5c3, org.apache.logging.log4j.core.LoggerContext#28087] with status true
IntelliSense configuration already up to date. To manually rebuild your IntelliSense configuration run "Ctrl+Alt+I"
[Error] Verifying sketch 'Main.ino': Exit with code=1

Related

Pi4J v2 SPI w/ GPIO Pin

I'm trying to use Pi4J to talk to an SPI device where the CS pin is a GPIO pin (GPIO 5) and not one of the mapped CS pins. I don't see how to configure it this way in any of the examples or javadocs. I think it would be somewhere on my SpiConfig line.
// Initialize Pi4J with an auto context
// An auto context includes AUTO-DETECT BINDINGS enabled
// which will load all detected Pi4J extension libraries
// (Platforms and Providers) in the class path
var pi4j = Pi4J.newAutoContext();
// create SPI config
SpiConfig config = Spi.newConfigBuilder(pi4j).id("thermocouple-1")
.name("Thermocouple 1").bus(SpiBus.BUS_1)
.chipSelect(SpiChipSelect.CS_0).build();
// get a SPI I/O provider from the Pi4J context
SpiProvider spiProvider = pi4j.provider("pigpio-spi");
// use try-with-resources to auto-close SPI when complete
try (Spi spi = spiProvider.create(config)) {
byte data[] = new byte[]{0, 0, 0, 0};
It looks like this is possible with v1 of the library, but it's not the same in v2.
I ended up posting on the pi4j project on GitHub and through those conversations worked out what I needed. Here is a cross post from there.
Well looking at the DAC8552 example was the key. Here is a working
version that asks the device for it's ID (register 0xD0) and gives the
correct answer for BME280 (0x60). Thanks for the assist. Here is the
working code (needs to be cleaned up, but it's a basic start).
package com.pi4j.example.spi;
import com.pi4j.Pi4J;
import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import com.pi4j.io.spi.Spi;
import com.pi4j.io.spi.SpiBus;
import com.pi4j.io.spi.SpiChipSelect;
import com.pi4j.io.spi.SpiMode;
import com.pi4j.util.Console;
import com.pi4j.util.StringUtil;
public class BmeTest {
private static final SpiBus spiBus = SpiBus.BUS_0;
public static void main(String[] args) throws Exception {
final var console = new Console();
// print program title/header
console.title("<-- The Pi4J Project -->",
"Basic SPI Communications Example");
Context pi4j = Pi4J.newAutoContext();
var spiConfig = Spi.newConfigBuilder(pi4j)
.id("SPI" + spiBus + "_BME280")
.name("BME280")
.bus(spiBus)
.chipSelect(SpiChipSelect.CS_0) // not used
.mode(SpiMode.MODE_0)
.provider("pigpio-spi")
.build();
// required all configs
var outputConfig = DigitalOutput.newConfigBuilder(pi4j)
.id("CS_GPIO5")
.name("CS GPIO5")
.address(5)
.shutdown(DigitalState.HIGH)
.initial(DigitalState.HIGH)
.provider("pigpio-digital-output");
DigitalOutput csGpio = null;
try {
csGpio = pi4j.create(outputConfig);
} catch (Exception e) {
e.printStackTrace();
console.println("create DigOut DRDY failed");
System.exit(202);
}
// use try-with-resources to auto-close SPI when complete
try (var spi = pi4j.create(spiConfig)) {
byte data[] = new byte[] { (byte) (0x80 | 0xD0), (byte) 0x00 };
csGpio.high();
csGpio.low();
spi.transfer(data, data);
csGpio.high();
// take a breath to allow time for the SPI
// data to get updated in the SPI device
Thread.sleep(100);
// read data back from the SPI channel
console.println("--------------------------------------");
console.println("SPI [READ] :");
console.println(" [BYTES] 0x" + StringUtil.toHexString(data));
console.println(" [STRING] " + new String(data));
console.println("--------------------------------------");
}
// shutdown Pi4J
console.println("ATTEMPTING TO SHUTDOWN/TERMINATE THIS PROGRAM");
pi4j.shutdown();
}
}
With the following output:
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console -
[main] INFO com.pi4j.util.Console - <-- The Pi4J Project -->
[main] INFO com.pi4j.util.Console - Basic SPI Communications Example
[main] INFO com.pi4j.util.Console -
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console -
[main] INFO com.pi4j.Pi4J - New auto context
[main] INFO com.pi4j.Pi4J - New context builder
[main] INFO com.pi4j.platform.impl.DefaultRuntimePlatforms - adding platform to managed platform map [id=raspberrypi; name=RaspberryPi Platform; priority=5; class=com.pi4j.plugin.raspberrypi.platform.RaspberryPiPlatform]
[main] INFO com.pi4j.util.Console - --------------------------------------
[main] INFO com.pi4j.util.Console - SPI [READ] :
[main] INFO com.pi4j.util.Console - [BYTES] 0xFF 60
[main] INFO com.pi4j.util.Console - [STRING] �`
[main] INFO com.pi4j.util.Console - --------------------------------------
[main] INFO com.pi4j.util.Console - ATTEMPTING TO SHUTDOWN/TERMINATE THIS PROGRAM

Emulator gives failure response: Trust anchor for certification path not found

I tried to search for this error a lot did not found any solution for it.
Details:
Made a request to API through retrofit, getting success response for the real devices but getting failure response if request is been made from android emulator.
public void loadPostsToDB() {
Call<List<Post>> call = mAPIServiceInterface.getAllPosts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
List<Post> posts = response.body();
new InsertPostAsyncTask(mDaoInterface,posts).execute();
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Log.e("Failure Reason : "," "+t.toString());
}
});
}
In above code gives response, I checked through debugging, as per it, point hits on success when ran from real device but failure function debug point got hit if ran from emulator.
Below is the log which got printed.
2020-12-01 20:57:23.647 6863-6879/reference.module.retrofit D/OkHttp: --> GET https://jsonplaceholder.typicode.com/posts
2020-12-01 20:57:23.647 6863-6879/reference.module.retrofit D/OkHttp: --> END GET
2020-12-01 20:57:23.828 6863-6882/reference.module.retrofit I/OpenGLRenderer: Initialized EGL, version 1.4
2020-12-01 20:57:23.828 6863-6882/reference.module.retrofit D/OpenGLRenderer: Swap behavior 1
2020-12-01 20:57:23.829 6863-6882/reference.module.retrofit W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-12-01 20:57:23.829 6863-6882/reference.module.retrofit D/OpenGLRenderer: Swap behavior 0
2020-12-01 20:57:23.849 6863-6882/reference.module.retrofit D/EGL_emulation: eglCreateContext: 0x9ca04240: maj 2 min 0 rcv 2
2020-12-01 20:57:23.924 6863-6882/reference.module.retrofit D/EGL_emulation: eglMakeCurrent: 0x9ca04240: ver 2 0 (tinfo 0x9ca037d0)
2020-12-01 20:57:24.135 6863-6882/reference.module.retrofit D/EGL_emulation: eglMakeCurrent: 0x9ca04240: ver 2 0 (tinfo 0x9ca037d0)
2020-12-01 20:57:24.278 6863-6879/reference.module.retrofit D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
2020-12-01 20:57:24.279 6863-6863/reference.module.retrofit E/Failure Reason :: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Any suggestion? what might be causing this behaviour?
The issue got solved,
It was required change from server side for certificates.

How to load a drools rule externally

I have a drl file and a .class file in a folder. drl contains rule which is built on class attributes. Now through a java program i want to invoke this rule on some input. I am clueless here . please look at code below
class file
import java.io.Serializable;
public class Txn754909164
implements Serializable
{
String sequenceNo;
String accountNumber;
String customerNumber;
// setter and getters
}
drl file
import Txn754909164;
import java.util.*;
dialect "mvel"
rule "rule6"
when
txn:Txn754909164(sequence == 10)
then
System.out.println( "invoking rule ***********************" );
end
client code
public KieContainer kieContainer(String packageName) {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newUrlResource("drl resource url..."));
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem,MyInputClass.getClassLoader());
KieModule kieModule = null;
try {
kieBuilder.buildAll();
kieModule = kieBuilder.getKieModule();
} catch (Exception e) {
e.printStackTrace();
}
return kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId(),cls.getClassLoader());
}
and finally
StatelessKieSession kieSession = container.getKieBase().newStatelessKieSession();
kieSession.execute(obj);
logs
11:47:34.795 [http-nio-8282-exec-4] INFO o.d.c.k.b.impl.KieRepositoryImpl - KieModule was added: MemoryKieModule[releaseId=org.default:artifact:1.0.0-SNAPSHOT]
11:47:34.803 [http-nio-8282-exec-4] TRACE org.drools.core.phreak.AddRemoveRule - Adding Rule rule6
11:47:45.994 [AsyncResolver-bootstrap-executor-0] INFO c.n.d.s.r.aws.ConfigClusterResolver - Resolving eureka endpoints via configuration
11:47:49.899 [http-nio-8282-exec-4] TRACE o.drools.core.reteoo.EntryPointNode - Insert [fact 0:1:1764329060:1764329060:1:DEFAULT:NON_TRAIT:Txn754909164:Txn754909164#69298664]
11:47:52.953 [http-nio-8282-exec-4] INFO o.k.a.e.r.DebugRuleRuntimeEventListener - ==>[ObjectInsertedEventImpl: getFactHandle()=[fact 0:1:1764329060:1764329060:1:DEFAULT:NON_TRAIT:Txn754909164:Txn754909164#69298664], getObject()=Txn754909164#69298664, getKnowledgeRuntime()=KieSession[0], getPropagationContext()=PhreakPropagationContext [entryPoint=EntryPoint::DEFAULT, factHandle=[fact 0:1:1764329060:1764329060:1:DEFAULT:NON_TRAIT:Txn754909164:Txn754909164#69298664], leftTuple=null, originOffset=-1, propagationNumber=2, rule=null, type=INSERTION]]
11:48:41.571 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was INACTIVE is now FIRING_ALL_RULES
11:48:41.572 [http-nio-8282-exec-4] TRACE org.drools.core.common.DefaultAgenda - Starting Fire All Rules
11:48:41.573 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was FIRING_ALL_RULES is now HALTING
11:48:41.573 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was HALTING is now INACTIVE
11:48:41.574 [http-nio-8282-exec-4] TRACE org.drools.core.common.DefaultAgenda - Ending Fire All Rules
11:48:41.575 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was INACTIVE is now DISPOSED
It should print statement in then clause of drl rule
above mentioned question and explanation is answer in itself. Found it working perfectly fine from next day. I guess it was just a workspace issue.

Trying to override the JUL logger used by vert.x

I'd like to use Log4j2 and am setting up my MainVerticle with system properties to do that,
public class MainVerticle extends AbstractVerticle
{
static {
System.setProperty( "vertx.logger-delegate-factory-class-name",
"io.vertx.core.logging.Log4j2LogDelegateFactory" );
System.setProperty( "log4j2.debug", "true" );
}
....
}
I then deploy my HttpVerticle from this verticle, and in the HTTP verticle, I'm trying to use parameterized statements, which aren't working. So I added a couple of logging statements to show the logger delegate in-use, as well as the system property:
public class HttpServerVerticle extends AbstractVerticle
{
private static final Logger LOGGER = LoggerFactory.getLogger( HttpServerVerticle.class );
#Override
public void start() throws Exception
{
LOGGER.info( System.getProperty( "vertx.logger-delegate-factory-class-name" ) );
LOGGER.info( LOGGER.getDelegate().getClass().getName() );
....
And below in a handler of the incoming message, I'm using this:
LOGGER.info( "Chat message received: {}" + message.body(), message.body() );
Note that I'm adding the message.body() using concatenation to prove that the message is not an empty string.
The output of these log statements are:
[INFO] Sep 24, 2018 2:46:09 AM ca.LinkEdTutoring.chat.http.HttpServerVerticle
[INFO] INFO: io.vertx.core.logging.Log4j2LogDelegateFactory
[INFO] Sep 24, 2018 2:46:09 AM ca.LinkEdTutoring.chat.http.HttpServerVerticle
[INFO] INFO: io.vertx.core.logging.JULLogDelegate
and for an incoming message of the letter "b":
[INFO] INFO: Chat message received: {}b
I've tried setting the system properties in the pom.xml file and on the command line with -D arguments.
This is with vert.x 3.5.3
Any thoughts on what I've forgotten to do?
================
EDIT: capturing the salient points from the comment thread.
cannot set system properties in a verticle, because the vert.x JUL logger gets initiated before the main verticle.
cannot set ... in the pom.xml when running the code with the vertx plugin. The mvn vertx plugin must get invoked after vertx is initialized.
only way it seems possible to override the JUL logger is the command line, using -D vargs.
do not forget that vargs are set before the -jar switch, i.e., $ java -Dx=y -jar jarname.jar
If you use the command line to start, you can configure it with -Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.Log4j2LogDelegateFactory. This is the easiest.
Of course, you can also set it directly in the code via System.setProperty, which is the same as the -D setting, but this must be done before the LoggerFactory is initialized. Obviously your code in the Verticle subclass must be executed after the Vertx initialization is successful. The LoggerFactory has already been initialized.

FactType.getFields return no fields drools KIE

I have created a fact type( CustomerFact ) with two fact fields(age and bonus) . A sample rule is also created using workbench. Now, I want to inject some test values and check whether the rules are getting fired. I used Eclipse IDE.
I am able to retrieve package name and the rule created in workbench in my java code. However, I am enable to get any fact fields. GetFields always returns an empty list whereas it should have returned 2 fields. Is there any alternative to this? I just want to set the field of the fact type and see whether the rules are getting fired. Any help is highly appreciated.
package org.demo.cityproject;
/**
* This class was automatically generated by the data modeler tool.
*/
public class CustomerFact implements java.io.Serializable
{
static final long serialVersionUID = 1L;
#org.kie.api.definition.type.Key
private int age;
#org.kie.api.definition.type.Key
private int bonus;
public CustomerFact()
{
}
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
this.age = age;
}
public int getBonus()
{
return this.bonus;
}
public void setBonus(int bonus)
{
this.bonus = bonus;
}
public CustomerFact(int age, int bonus)
{
this.age = age;
this.bonus = bonus;
}
#Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
org.demo.cityproject.CustomerFact that = (org.demo.cityproject.CustomerFact) o;
if (age != that.age)
return false;
if (bonus != that.bonus)
return false;
return true;
}
#Override
public int hashCode()
{
int result = 17;
result = 31 * result + age;
result = 31 * result + bonus;
return result;
}
}
Test Code
public static void main(String[] args)
{
String url = "http://localhost:8080/kie-drools-wb-distribution-wars-6.2.0.Final-jboss-as7/maven2/Project1/org/demo/CityProject/1.0/CityProject-1.0.jar";
ReleaseIdImpl releaseId = new ReleaseIdImpl("org.demo", "CityProject", "LATEST");
KieServices kieServices = KieServices.Factory.get();
kieServices.getResources().newUrlResource(url);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieScanner kieScanner = kieServices.newKieScanner(kieContainer);
kieScanner.scanNow();
Scanner scanner = new Scanner(System.in);
System.out.println("kieContainer.getKieBaseNames() "+kieContainer.getKieBaseNames());
KieSession newKieSession =kieContainer.newKieSession("session1");
KieBase lKieBase=newKieSession.getKieBase();
System.out.println("lPackage "+lKieBase.getKiePackages());
KiePackage lPackage=lKieBase.getKiePackage("org.demo.cityproject");
System.out.println("lPackage FactTypes: "+lPackage.getFactTypes());
for(FactType lFact:lPackage.getFactTypes())
{
System.out.println("lFacts: "+lFact.getName());
System.out.println("lFacts Fields: "+lFact.getFields());
}
}
Console o/p in eclipse
22:58:28.998 [main] DEBUG o.d.c.k.b.impl.KieRepositoryImpl - KieModule Lookup. ReleaseId org.demo:CityProject:LATEST was not in cache, checking maven repository
22:58:37.430 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:37.743 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:39.455 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:41.744 [main] DEBUG o.e.a.i.i.DefaultDependencyCollector - Dependency collection stats: {ConflictMarker.analyzeTime=0, ConflictMarker.markTime=0, ConflictMarker.nodeCount=1, ConflictIdSorter.graphTime=0, ConflictIdSorter.topsortTime=0, ConflictIdSorter.conflictIdCount=1, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=0, ConflictResolver.conflictItemCount=1, DefaultDependencyCollector.collectTime=32, DefaultDependencyCollector.transformTime=15}
22:58:42.230 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:42.230 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:42.246 [main] DEBUG o.e.a.i.i.DefaultDependencyCollector - Dependency collection stats: {ConflictMarker.analyzeTime=0, ConflictMarker.markTime=0, ConflictMarker.nodeCount=1, ConflictIdSorter.graphTime=0, ConflictIdSorter.topsortTime=0, ConflictIdSorter.conflictIdCount=0, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=0, ConflictResolver.conflictItemCount=0, DefaultDependencyCollector.collectTime=0, DefaultDependencyCollector.transformTime=0}
22:58:47.596 [main] INFO o.d.c.k.b.impl.KieRepositoryImpl - KieModule was added: ZipKieModule[releaseId=org.demo:CityProject:1.0,file=C:\Users\USER\.m2\repository\org\demo\CityProject\1.0\CityProject-1.0.jar]
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.426 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.442 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
kieContainer.getKieBaseNames() [KnowledgeBaseALL]
22:58:50.532 [main] DEBUG o.drools.core.impl.KnowledgeBaseImpl - Starting Engine in PHREAK mode
lPackage [[Package name=org.demo.cityproject]]
lPackage FactTypes: [ClassDefinition{className='org.demo.cityproject.CustomerFact', superClass='java.lang.Object', interfaces=[java.io.Serializable], definedClass=class org.demo.cityproject.CustomerFact, traitable=null, abstract=false, fields={}, annotations=null}]
lFacts: org.demo.cityproject.CustomerFact
**lFacts Fields: []**
As you can see in the output fact field is empty.
The - rather disappointing - situation is that there are two or even three kinds of FactTypes:
Fact types defined by a declare statement in a DRL file
Fact types resulting from Java classes and imported explicitly or implicitly
JDK types used as fact types
Method getFactTypes does not return #3. Method getFields returns an empty list for #2.
Finally I found an answer. Such fields can be invoked by reflection.
Here is how the rules get triggered
for(FactType lFct:lusedpackage.getFactTypes())
{
// System.out.println("Customer class "+lFct.getFactClass());
**Constructor constructor=lFct.getFactClass().getConstructor(String.class,java.math.BigInteger.class);**
**Object s1=constructor.newInstance(lcity,lcustomerID);**
//System.out.println("constructor "+constructor);
//System.out.println("Object "+s1);
**Method lCustID=lFct.getFactClass().getMethod("getCustomerID");**
System.out.println("*************************************************************");
System.out.println("Customer value before firing the rule: "+ lCustID.invoke(s1));
**Method setCity = lFct.getFactClass().getMethod("getCity");**
System.out.println("City value before firing the rule: "+ setCity.invoke(s1));
//System.out.println("method "+lCustID);
System.out.println("*************************************************************");
newKieSession.insert(s1);
newKieSession.fireAllRules();
System.out.println("Customer value after firing the rule: "+ **lCustID.invoke(s1)**);
System.out.println("City value after firing the rule: "+ setCity.invoke(s1));
System.out.println("*************************************************************");
}