running multi-platform from an external java application - agents-jade

I am posting this after visiting all possibly related posts to my issue and could not find an exact solution.
I employing Jade in my master degree research project. That is, I would like to create several platforms from an external java application. by revising all documents in the website especially "administration" one, this would be similar to the scenario of launching several platforms using Command-line in Windows environment as the following using windows :
First platform
open a CMD
type : java jade.Boot -gui -platform-id Platform1
this will initiate a platform named Platform1, in which, its AMS would be reached in this address AMS#Platform1
Second platform
open a "new" another CMD
type : java jade.Boot -gui -platform-id Platform2 -local-port 1111
this will initiate a platform named Platform2, in which , its AMS would be reached in this address AMS#Platform2
and so on.
now this would work perfectly using the command line, as we can see different platforms with different IDs and ports can be launched such that Agents that live in them can communicate with other agents in the same platform or in remote platform.
however, I tried doing the same launching using external java application and could not succeed in doing so.
it only succeed in initiating the first platform, but it would not in the rest platforms.
this is my code
###############################################################
Profile p1 = new ProfileImpl(true);
p1.setParameter(ProfileImpl.PLATFORM_ID, "platform"+ID); // ID range from 1 to 10
p1.setParameter(Profile.LOCAL_PORT, Integer.toString(port)); // available port
Runtime.instance().setCloseVM(true)
ContainerController mc = Runtime.instance().createMainContainer(p1); // I need to have a main container for each platform
###############################################################
then I get this error
##############################################################
Aug 03, 2014 9:42:26 PM jade.imtp.leap.LEAPIMTPManager initialize
INFO: Listening for intra-platform commands on address:
- jicp://10.1.1.5:1024
- jicp://10.1.1.5:1025
Aug 03, 2014 9:42:26 PM jade.core.AgentContainerImpl joinPlatform
SEVERE: Some problem occurred while joining agent platform.
jade.core.ProfileException: Can't get a proxy to the Platform Manager - Caused by: Wrong platform name platform1. It should be platform2
at jade.core.ProfileImpl.createPlatformManager(ProfileImpl.java:529)
at jade.core.ProfileImpl.getPlatformManager(ProfileImpl.java:442)
at jade.core.ProfileImpl.getServiceManager(ProfileImpl.java:456)
at jade.core.AgentContainerImpl.init(AgentContainerImpl.java:346)
at jade.core.AgentContainerImpl.joinPlatform(AgentContainerImpl.java:492)
at jade.core.Runtime.createMainContainer(Runtime.java:166)
at intiator.intiatePlatform(intiator.java:49)
at MainLauncher.main(MainLauncher.java:69)
Nested Exception:
jade.core.IMTPException: Wrong platform name platform1. It should be platform2
at jade.imtp.leap.CommandDispatcher.setPlatformManager(CommandDispatcher.java:231)
at jade.imtp.leap.CommandDispatcher.registerSkeleton(CommandDispatcher.java:736)
at jade.imtp.leap.LEAPIMTPManager.exportPlatformManager(LEAPIMTPManager.java:198)
at jade.core.ProfileImpl.createPlatformManager(ProfileImpl.java:518)
at jade.core.ProfileImpl.getPlatformManager(ProfileImpl.java:442)
at jade.core.ProfileImpl.getServiceManager(ProfileImpl.java:456)
at jade.core.AgentContainerImpl.init(AgentContainerImpl.java:346)
at jade.core.AgentContainerImpl.joinPlatform(AgentContainerImpl.java:492)
at jade.core.Runtime.createMainContainer(Runtime.java:166)
at intiator.intiatePlatform(intiator.java:49)
at MainLauncher.main(MainLauncher.java:69)
Exception in thread "main" java.lang.NullPointerException
at intiator.intiatePlatform(intiator.java:58)
at MainLauncher.main(MainLauncher.java:69)
###############################################################
So I would like to make it successfully using code as it would be using Command-line

What you are suggesting is to create and launch two or more jade platforms in the same java program at once. This can not be possible unless you write a program that starts a single platform and increments the port and run it several time (as much as you need platforms). Otherwise I do not see any other option.
You can use this method to test if a port is available or not:
private boolean isAvailablePort(int port) {
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
}
}
}
return false;
}
Then you can use this for example:
while(!isAvailablePort(port)){
port++;
}
to automate port incrementation.

Related

Why am I getting "java.lang.NoClassDefFoundError: Could not initialize class io.mockk.impl.JvmMockKGateway" when using quarkusDev task in IntelliJ?

I am using Gradle 7.5, Quarkus 2.12.3 and mockk 1.13.3. When I try to run quarkusDev task from command line and then start continuous testing (by pressing r), then all tests pass OK.
However, when I do the same as from IntelliJ (as gradle run configuration), all tests fail with error:
java.lang.NoClassDefFoundError: Could not initialize class io.mockk.impl.JvmMockKGateway
How can I fix that?
Masked thrown exception
After much debugging I found the problem. The thrown exception actually originates in HotSpotVirtualMachine.java and is thrown during attachment of ByteBuddy as a java agent. Here is the relevant code;
// The tool should be a different VM to the target. This check will
// eventually be enforced by the target VM.
if (!ALLOW_ATTACH_SELF && (pid == 0 || pid == CURRENT_PID)) {
throw new IOException("Can not attach to current VM");
}
Turning check off
So the check can be turned off by setting ALLOW_ATTACH_SELF constant to true. The constant is set from a system property named jdk.attach.allowAttachSelf:
String s = VM.getSavedProperty("jdk.attach.allowAttachSelf");
ALLOW_ATTACH_SELF = "".equals(s) || Boolean.parseBoolean(s);
So, in my case, I simply added the following JVM argument to my gradle file and tests started to pass:
tasks.quarkusDev {
jvmArgs += "-Djdk.attach.allowAttachSelf"
}

UMDF PnP Driver creates no trace logs

Im trying to create trace log messages for this Idd Sample Driver. I am following this document.
I add WPP_INIT_TRACING(pDriverObject, pRegistryPath) to the DriverEntry, and WPP_CLEANUP(pDriverObject)to the EvtCleanupCallback.
_Use_decl_annotations_
void DriverContextCleanup(WDFOBJECT DriverObject)
{
UNREFERENCED_PARAMETER(DriverObject);
DoTraceMessage(MYDRIVER_ALL_INFO, "Tracing Fini Success");
WPP_CLEANUP(WdfDriverWdmGetDriverObject(DriverObject));
}
_Use_decl_annotations_
extern "C" NTSTATUS DriverEntry(
PDRIVER_OBJECT pDriverObject,
PUNICODE_STRING pRegistryPath
)
{
WDF_DRIVER_CONFIG Config;
NTSTATUS Status;
WDF_OBJECT_ATTRIBUTES Attributes;
WDF_OBJECT_ATTRIBUTES_INIT(&Attributes);
Attributes.EvtCleanupCallback = DriverContextCleanup;
WDF_DRIVER_CONFIG_INIT(&Config,
IddSampleDeviceAdd
);
WPP_INIT_TRACING(pDriverObject, pRegistryPath);
DoTraceMessage(MYDRIVER_ALL_INFO, "Tracing Init . . .");
Status = WdfDriverCreate(pDriverObject, pRegistryPath, &Attributes, &Config, WDF_NO_HANDLE);
if (!NT_SUCCESS(Status))
{
DoTraceMessage(MYDRIVER_ALL_INFO, "Tracing Init Failed");
WPP_CLEANUP(pDriverObject);
return Status;
}
DoTraceMessage(MYDRIVER_ALL_INFO, "Tracing Init Success");
return Status;
}
I add some DoTraceMessage() calls with a flag of MYDRIVER_ALL_INFO to the DriverEntry and DeviceEntry.
NTSTATUS IddSampleDeviceD0Entry(WDFDEVICE Device, WDF_POWER_DEVICE_STATE PreviousState)
{
UNREFERENCED_PARAMETER(PreviousState);
// This function is called by WDF to start the device in the fully-on power state.
DoTraceMessage(MYDRIVER_ALL_INFO, "Tracing Device Entry");
auto* pContext = WdfObjectGet_IndirectDeviceContextWrapper(Device);
pContext->pContext->InitAdapter();
return STATUS_SUCCESS;
}
I make sure WPP Tracing is set to YES in the properties of the project.
The project builds, I go into TraceView and open the IddSampleDriver.PDB file, I set the level to verbose, and check all of the flags. I verified that it has the trace stuff it needs. Since if I open the IddSampleApp.PDB file, it fails.
I install the driver after enabling TestSigning and installing with pnputil -a ./x64/Debug/IddSampleDriver/IddSampleDriver.inf, run the sample app, the driver spins up 3 virtual monitors in the Display Settings. I then exit the app, and the monitors disappear. Everything seems to be functional. The problem is there is no traces in TraceView.
I have tried using tracelog, following this. Still nothing.
I have tried using logman, following this. Still nothing.
I am at my wits end. I spent all last week on this, Trying every possible avenue to get my trace messages to appear.
Either I followed every one of these instructions with no success. Either I somehow messed up every single one of them, or I am missing something else that I need to do in order to view these traces.
Additional Info:
Trace.h was left untouched
Targeting x64, Debug. Running on build machine. Win10.
CTL file I used:
b254994f-46e6-4718-80a0-0a3aa50d6ce4 MyDriver1TraceGuid
Basic process I used (tracelog as example):
tracepdb -f .\x64\Debug\IddSampleDriver.pdb
tracelog -start TestTraceIDD -guid .\guid.ctl -f testTrace.etl -flag 0xff
pnputil -a .\x64\Debug\IddSampleDriver\IddSampleDriver.inf #install driver
.\x64\Debug\IddSampleApp.exe #create software device and attach driver to it
<exit app>
tracelog -stop TestTraceIDD
tracefmt.exe .\testTrace.etl -p . -o test.out```
pnputil -d oem20.inf -f #uninstall driver
Solved my problem. I wasnt actually installing my driver, since it was still installed from the first time I installed it, so it was always using that driver instead of my new one with WPP enabled. I was installing and uninstalling the driver with pnputil.
I was doing pnputil -d oem20.inf -f for example to uninstall the driver. This is BAD. I have learned now that force deleting a driver does nothing. The reason I was force deleting was because it wouldnt delete when i still had a device, even though i would exit the sample app.
So what you have to do in order to properly delete the driver is enumerate the devices with pnputil, remove the ones that use your driver, then delete the driver. This allows a proper fresh driver installation.

What are possible causes of Multiple ID-statement Exception in Sesame?

I would like to know what are possible causes that can rise the following Exception ?
org.openrdf.repository.config.RepositoryConfigException: Multiple ID-statements for repository ID test_3
It rises when i try to query the test_3 repository. Another fact is that after that there is two repository with the same name displayed in my web page http://localhost:8080/openrdf-workbench/repositories/NONE/repositories
any help is welcome !
EDIT
I'm using Sesame 2.7.7
EDIT 2
Providing more details about the code which cause the Exception
code
public void connectToRepository(){
RepositoryConnection connection;
RemoteRepositoryManager repositoryManager = new RemoteRepositoryManager("http://localhost:8080/openrdf-sesame/");
try {
repositoryManager.initialize();
SailImplConfig backendConfig = new NativeStoreConfig("spoc,sopc,posc,psoc,ospc,opsc");
RepositoryImplConfig repositoryTypeSpec = new SailRepositoryConfig(backendConfig);
RepositoryConfig repConfig = new RepositoryConfig(repositoryID, repositoryTypeSpec);
repositoryManager.addRepositoryConfig(repConfig);
Repository myRepository = repositoryManager.getRepository(repositoryID);
myRepository.initialize();
connection = myRepository.getConnection();
}
catch (RepositoryException | RepositoryConfigException e) {
e.printStackTrace();
}
}
The Exception is cause by the following line in the code:
repositoryManager.addRepositoryConfig(repConfig);
Here are details
log4j:WARN No appenders could be found for logger (org.openrdf.rio.DatatypeHandlerRegistry).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Custom NTriples/NQuads Parser
Custom NTriples/NQuads Parser
org.openrdf.repository.config.RepositoryConfigException: Multiple ID-statements for repository ID 10m7_m
at org.openrdf.repository.config.RepositoryConfigUtil.getIDStatement(RepositoryConfigUtil.java:269)
at org.openrdf.repository.config.RepositoryConfigUtil.hasRepositoryConfig(RepositoryConfigUtil.java:91)
at org.openrdf.repository.manager.RemoteRepositoryManager.createRepository(RemoteRepositoryManager.java:174)
at org.openrdf.repository.manager.RepositoryManager.getRepository(RepositoryManager.java:376)
at soctrace.repositories.OLDSesameRepositoryManagement.connectToRepository(OLDSesameRepositoryManagement.java:123)
at soctrace.repositories.OLDSesameRepositoryManagement.queryInRepository(OLDSesameRepositoryManagement.java:150)
at soctrace.views.Main.main(Main.java:692)
[sesame in memory] connection to repository 10m7_m done , 444, ms
Exception in thread "main" java.lang.NullPointerException
at soctrace.repositories.OLDSesameRepositoryManagement.runQuery(OLDSesameRepositoryManagement.java:250)
at soctrace.repositories.OLDSesameRepositoryManagement.queryInRepository(OLDSesameRepositoryManagement.java:155)
at soctrace.views.Main.main(Main.java:692)
Your code creates a new repository (by adding a new repository configuration to the repository manager) every time you execute the connectToRepository() method. Since you use the exact same repository configuration (including the actual id of the repository) every time, naturally this causes an error the second time you execute it: you are trying to add a repository with an id that already exists.
You should rewrite your code to make sure that it only tries to create the repository when a repository with that id doesn't exist yet - if it already exists, it should just use the existing one.

ERROR_INVALID_PRINTER_NAME returned by OpenPrinter() in Windows 8 when executed under "SYSTEM" account

My application deletes virtual printer when user uninstalls the application.
Application's installation and Uninstallation can be done using user interaction(wizard) or by setting group policy in Windows server 2003(domain admin sets the policy in server and the domain user in client PC need to update the group policy and restart the Client PC for installation or uninstallation of the application).
The follwing code in the application deletes printer and printer driver when uninstalling the application.
void CPrinterDriver::DeletePrinterIfExists()
{
// Delete old printer driver if existing
ControlSpoolService(TRUE);
HANDLE hPrinter = NULL;
PRINTER_DEFAULTS pDefaults = { NULL, NULL, PRINTER_ALL_ACCESS };
// Ignore error codes
OpenPrinter(m_driverInfo.pName, &hPrinter, &pDefaults);
if (hPrinter)
{
// deleting jobs
SetPrinter(hPrinter, 0, NULL, PRINTER_CONTROL_PURGE);
// Delete printer
DeletePrinter(hPrinter);
// Get printer driver name and delete it
DWORD dwNeeded = 0;
GetPrinter(hPrinter, 2, NULL, 0, &dwNeeded);
if (dwNeeded)
{
PRINTER_INFO_2 *pi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, sizeof(PRINTER_INFO_2)*dwNeeded);
if (pi2)
{
GetPrinter(hPrinter, 2, (LPBYTE)pi2, dwNeeded, &dwNeeded);
DeletePrinterDriver(NULL, NULL, pi2->pDriverName);
GlobalFree(pi2);
}
}
ClosePrinter(hPrinter);
}
}
The above code works well in Windows 7 in both cases(user interactive installation and using group policy) of uninstallation. In Windows 8, it works well using user interactive installation and uninstallation.
But in Windows 8 the above OpenPrinter() is returing ERROR_INVALID_PRINTER_NAME.
We found that the OpenPrinter() is called using the "SYSTEM" account.
Kindly help.
We found that during system startup, group policy is trying to uninstall the printer before the available printers list in the PC is populated (list is populated under the below registry key.If the list is not populated the below key does not exists).
"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers"
Hence we added delay of 2 minutes(not less than 2 mins) before calling openPrinter().
After the delay the registry key exists and the OpenPrinter() succeeded.
Thus we are able to uninstall the printer.
Note: Microsoft claims that Windows 8 boot time is reduced to 7 secs for certain supported hardware. But inserting delay of 2 mins degrades the boot performance of the Windows 8 PC.
For more details regarding the improvement in the boot time of Windwos 8 OS please refer the below link.
http://blogs.msdn.com/b/b8/archive/2012/05/22/designing-for-pcs-that-boot-faster-than-ever-before.aspx
Hence delay of 2 mins can be terated as a workaround.
Need to check the behaviour in the Windows 8 OS release after 10/26.
If you suffer from the issue where:
the registry key for the shared (network) printer is missing and
the API gives you the invalid printer name error
Then you can try opening the printer by its full UNC path.
So when opening MYPRINTER does not work, then open it as \\MYSERVER\MYPRINTER .
Of course this still assumes that you can already print to this printer normally from other applications!

Detecting open PC COM port from USB Virtual Com Port device

I am using an STM32F105 microcontroller with the STM32_USB-FS-Device_Lib_V3.2.1 USB library and have adapted the VCP example for our purposes (integration with RTOS and serial API).
The problem is that if the USB cable is attached, but the port is not open on the Windows host, after a few minutes the device ends up permanently re-entering the USB ISR until the port is opened and then it all starts working normally.
I have instrumented interrupt handler and can see that when the fault occurs, the ISR handler exits and then immediately re-enters. This occurs because on exit from the interrupt the IEPINT flag in OTG_FS_GINTSTS is not clear. The OTG_FS_DAINT at this time contains 0x00000002 (IEPINT1 set), while DIEPINT1 has 0x00000080 (TXFE). The line in OTGD_FS_Handle_InEP_ISR() that clears TXFE is called, but the bit either does not clear or becomes immediately reasserted. When the COM port on the host is reopened, the state of OTG_FS_GINTSTS and OTG_FS_DAINT at the end of the interrupt is always zero, and further interrupts occur at the normal rate. Note that the problem only occurs if data is being output but the host has no port open. If either the port is open or no data is output, the system runs indefinitely. I believe that the more data that is output the sooner the problem occurs, but that is anecdotal at present.
The VCP code has a state variable that takes the following enumerated values:
UNCONNECTED,
ATTACHED,
POWERED,
SUSPENDED,
ADDRESSED,
CONFIGURED
and we use the CONFIGURED state to determine whether to put data into the driver buffer for sending. However the CONFIGURED state is set when the cable is attached not when the host has the port open and an application connected. I see that when Windows does open the port, there is a burst of interrupts so it seems that some communication occurs on this event; I wonder if it is possible therefore to detect whether the host has the port open,.
I need one of two things perhaps:
To prevent the USB code from getting stuck in the ISR in the first instance
To determine whether the host has the port open from the device end, and only push data for sending when open.
Part (1) - preventing the interrupt lock-up - was facilitated by a USB library bug fix from ST support; it was not correctly clearing the TxEmpty interrupt.
After some research and assistance from ST Support, I have determined a solution to part (2) - detecting whether the host port is open. Conventionally, when a port is opened the DTR modem control line is asserted. This information is passed to a CDC class device, so I can use this to achieve my aim. It is possible for an application to change the behaviour of DTR, but this should not happen in any of the client applications that are likely to connect to this device in this case. However there is a back-up plan that implicitly assumes the port to be open if the line-coding (baud, framing) are set. In this case there is no means of detecting closure but at least it will not prevent an unconventional application from working with my device, even if it then causes it to crash when it disconnects.
Regarding ST's VCP example code specifically I have made the following changes to usb_prop.c:
1) Added the following function:
#include <stdbool.h>
static bool host_port_open = false ;
bool Virtual_Com_Port_IsHostPortOpen()
{
return bDeviceState == CONFIGURED && host_port_open ;
}
2) Modified Virtual_Com_Port_NoData_Setup() handling of SET_CONTROL_LINE_STATE thus:
else if (RequestNo == SET_CONTROL_LINE_STATE)
{
// Test DTR state to determine if host port is open
host_port_open = (pInformation->USBwValues.bw.bb0 & 0x01) != 0 ;
return USB_SUCCESS;
}
3) To allow use with applications that do not operate DTR conventionally I have also modified Virtual_Com_Port_Data_Setup() handling of SET_LINE_CODING thus:
else if (RequestNo == SET_LINE_CODING)
{
if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT))
{
CopyRoutine = Virtual_Com_Port_SetLineCoding;
// If line coding is set the port is implicitly open
// regardless of host's DTR control. Note: if this is
// the only indicator of port open, there will be no indication
// of closure, but this will at least allow applications that
// do not assert DTR to connect.
host_port_open = true ;
}
Request = SET_LINE_CODING;
}
I found another solution by adopting CDC_Transmit_FS.
It can now be used as output for printf by overwriting _write function.
First it checks the connection state, then it tries to send over USB endport in a busy loop, which repeats sending if USB is busy.
I found out if dev_state is not USBD_STATE_CONFIGURED the USB plug is disconnected. If the plug is connected but no VCP port is open via PuTTY or termite, the second check fails.
This implementation works fine for me for RTOS and CubeMX HAL application. The busy loop is not blocking low priority threads anymore.
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
{
uint8_t result = USBD_OK;
// Check if USB interface is online and VCP connection is open.
// prior to send:
if ((hUsbDevice_0->dev_state != USBD_STATE_CONFIGURED)
|| (hUsbDevice_0->ep0_state == USBD_EP0_STATUS_IN))
{
// The physical connection fails.
// Or: The phycical connection is open, but no VCP link up.
result = USBD_FAIL;
}
else
{
USBD_CDC_SetTxBuffer(hUsbDevice_0, Buf, Len);
// Busy wait if USB is busy or exit on success or disconnection happens
while(1)
{
//Check if USB went offline while retrying
if ((hUsbDevice_0->dev_state != USBD_STATE_CONFIGURED)
|| (hUsbDevice_0->ep0_state == USBD_EP0_STATUS_IN))
{
result = USBD_FAIL;
break;
}
// Try send
result = USBD_CDC_TransmitPacket(hUsbDevice_0);
if(result == USBD_OK)
{
break;
}
else if(result == USBD_BUSY)
{
// Retry until USB device free.
}
else
{
// Any other failure
result = USBD_FAIL;
break;
}
}
}
return result;
}
CDC_Transmit_FS is used by _write:
// This function is used by printf and puts.
int _write(int file, char *ptr, int len)
{
(void) file; // Ignore file descriptor
uint8_t result;
result = CDC_Transmit_FS((uint8_t*)ptr, len);
if(result == USBD_OK)
{
return (int)len;
}
else
{
return EOF;
}
}
Regards
Bernhard
After so much searching and a kind of reverse engineering I finally found the method for detecting the open terminal and also it's termination. I found that in the CDC class there is three Data nodes , one is a control node and the other two are data In and data Out nodes.Now when you open a terminal a code is sent to the control node and also when you close it. all we need to do is to get those codes and by them start and stop our data transmission tasks. the code that is sent is respectively 0x21 and 0x22 for opening and closing the terminal.In the usb_cdc_if.c there is a function that receive and interpret those codes (there is a switch case and the variable cmd is the code we are talking about).that function is CDC_Control_FS . Here we are, Now all we need to do is to expand that function so that it interpret the 0x22 and 0x21 . there you are , now you know in your application whether the port is open or not.
I need one of two things perhaps:
To prevent the USB code from getting stuck in the ISR in the first instance
To determine whether the host has the port open from the device end, and only push data for sending when open.
You should attempt to do option 1 instead of 2. On Windows and Linux, it is possible to open a COM port and use it without setting the control signals, which means there is no fool-proof, cross-platform way to detect that the COM port is open.
A well programmed device will not let itself stop functioning just because the USB host stopped polling for data; this is a normal thing that should be handled properly. For example, you might change your code so that you only queue up data to be sent to the USB host if there is buffer space available for the endpoint. If there is no free buffer space, you might have some special error handling code.
I have the same requirement to detect PC port open/close. I have seen it implemented it as follows:
Open detected by:
DTR asserted
CDC bulk transfer
Close detected by:
DTR deasserted
USB "unplugged", sleep etc
This seems to be working reasonably well, although more thorough testing will be needed to confirm it works robustly.
Disclaimer: I use code generated by Cube, and as a result it works with HAL drivers. Solutions, proposed here before, don't work for me, so I have found one. It is not good, but works for some purposes.
One of indirect sign of not opened port arises when you try to transmit packet by CDC_Transmit_FS, and then wait till TxState is set to 0. If port is not opened it never happens. So my solution is to fix some timeout:
uint16_t count = 0;
USBD_CDC_HandleTypeDef *hcdc =
(USBD_CDC_HandleTypeDef*) USBD_Device.pClassData;
while (hcdc->TxState != 0) {
if (++count > BUSY_TIMEOUT) { //number of cycles to wait till it makes decision
//here it's clear that port is not opened
}
}
The problem is also, that if one tries to open port, after device has tried to send a packet, it cant be done. Therefore whole routine I use:
uint8_t waitForTransferCompletion(void) {
uint16_t count = 0;
USBD_CDC_HandleTypeDef *hcdc =
(USBD_CDC_HandleTypeDef*) USBD_Device.pClassData;
while (hcdc->TxState != 0) {
if (++count > BUSY_TIMEOUT) { //number of cycles to wait till it makes decision
USBD_Stop(&USBD_Device); // stop and
MX_USB_DEVICE_Init(); // init device again
HAL_Delay(RESET_DELAY); // give a chance to open port
return USBD_FAIL; // return fail, to send last packet again
}
}
return USBD_OK;
}
The question is, how big timeout has to be, not to interrupt transmission while port is opened. I set BUSY_TIMEOUT to 3000, and now it works.
I fixed it by checking of a variable hUsbDeviceFS.ep0_state.
It equal 5 if connected and 4 if do not connected or was disconnected.
But. There are some issue in the HAL. It equal 5 when program started.
Next steps fixed it at the begin of a program
/* USER CODE BEGIN 2 */
HAL_Delay(500);
hUsbDeviceFS.ep0_state = 4;
...
I do not have any wishes to learn the HAL - I hope this post will be seeing by developers and they will fix the HAL.
It helped me to fix my issue.