Blackberry's WLANInfo.getWLANState() Doesn't Return Correct Information - blackberry

I'm working with the NetworkUtils.java class created by Sameer Nafdey in his blog post regarding accuiring a network connection within a Blackberry Application. However I recently noticed that my application was using the cell network even when a WiFi connection was available. I realized this was the case when we tested the application on a Torch with no SIM card and the app failed. After some debugging I found that:
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED){...}
was returning false despite the fact that the WiFi network was setup correctly (I was able to use web browser to visit Google). We had to return the Torch but while debugging the app in the simulator I noticed that if WiFi was on but the Data Network was turned off then this call would work correctly. However I would then get an exception (java.io.ioexception: Radio is off) when executing this block:
httpConnector = (HttpConnection)Connector.open(URL);
httpConnector.setRequestMethod(HttpConnection.GET);
httpConnector.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
in = httpConnector.openInputStream();
I've seen a lot of issues related to the Torch's WiFi connectivity problems but I'm currently concerned that this behavior may also be affecting other models. Anyone seen anything like this or have an idea of how to fix it?

You could try:
if( RadioInfo.areWAFsSupported( RadioInfo.WAF_WLAN )
&&
( RadioInfo.getActiveWAFs() & RadioInfo.WAF_WLAN ) != 0
&&
CoverageInfo.isCoverageSufficient( 1 , RadioInfo.WAF_WLAN, false) )
{ ... }
It's been working so far, on Blackberry OS 6.0 (Torch 9800). Tested on device and sim.

Related

How can we check whether connected network connection is reachable or not in iOS Swift? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
My app supports iOS12 or later and i am using latest macOS and xcode. I did several research on this topic but couldn't found any proper solutions. Yes, i know how to check whether we are connected to the network or not and can get connection types too. But the problem is: is my connected network reachable? I am communicating with an IoT device, and i have to get some data from it, also send it to different server. That device always gives me the data because it is an intranet, as i am connected to it's hotspot. I have to check whether it can send data further on it's own to another remote server(sometimes network connection doesn't work) or if not i need to switch wifi connection to my local network. I have tried several ways but couldn't get satisfactory results.
What #Joakim Danielson said above is what you should be doing. No matter what source you use, it will always give you false information at some point (about being connected to internet or not).
Make the api call.
Check for errors - is it a temporary network error?
Make the call on whether you should retry or show something else to user.
How to check if it might be a temporary network error?
You can use this extension on NSError instance that was returned from api call.
public extension NSError {
var isConnectionAborted: Bool {
return (self.domain == NSPOSIXErrorDomain && self.code == 53)
}
var isTemporaryNetworkError: Bool {
let temporaryNetworkErrorCodes = [
NSURLErrorTimedOut,
NSURLErrorCannotFindHost,
NSURLErrorCannotConnectToHost,
NSURLErrorNetworkConnectionLost,
NSURLErrorDNSLookupFailed,
NSURLErrorHTTPTooManyRedirects,
NSURLErrorResourceUnavailable,
NSURLErrorNotConnectedToInternet,
NSURLErrorRedirectToNonExistentLocation,
NSURLErrorSecureConnectionFailed,
NSURLErrorCannotLoadFromNetwork,
NSURLErrorRequestBodyStreamExhausted,
]
return (self.isConnectionAborted || temporaryNetworkErrorCodes.contains(self.code))
}
var isCancelled: Bool {
return (self.domain == NSURLErrorDomain && self.code == NSURLErrorCancelled)
}
}
I tried an api call, it failed, now I want to query whether I'm connected to ineternet or not. How to know?
Somewhere in your API code, you can add an observer for possible network changes by using NWPathMonitor like this - requires iOS 12
import Network
let monitor = NWPathMonitor()
monitor.start(queue: DispatchQueue(label: "NetworkMonitor"))
monitor.pathUpdateHandler = { (path) in
if path.status == .satisfied {
print("Connected")
} else {
print("Not Connected")
}
}
This allows more granular control as well .cellular, .wifi & .wiredEthernet etc. -
let cellMonitor = NWPathMonitor(requiredInterfaceType: .cellular)
If you still support iOS 11, you can use a 3rd party library like - Reachability
Best practice is to just try: invoke the network request and check the result. What you do if you got an error depends on your use case, if there is a user involved or if the request was made in the background.
For example, you may just output an error and let the user proceed in the app. This may require to design your screen accordingly, i.e. provide a way where the user can retry it (in the screen where you show the content, show an empty content screen and provide a pull-to-refresh or a "retry" button, etc.).
Or, you may analyse the kind of error (URL error or response error) and may apply several strategies. For example, if the network request can be performed in the background you may apply a retry when you got a 5xx HTTP status. Or, if the connection was lost (no response and you get an URLError) you may start to observe the network state and retry when the network is available.

Attempted an Unsupported Operation Using Serial port

I am recompiling an application from Visual C++ 6.0 in Visual Studio 2015. It is using Mscomm as serial communication library. Everything gets compiled fine but when I run the program, I get "Attempted an Unsupported Operation" twice. Upon debugging I found out the culprit is the following snippet:
void CFFLSView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CFFLSView)
DDX_Control(pDX, IDC_MSCOMM1, m_comm);
DDX_Control(pDX, IDC_MSCOMM2, m_comm2);
//}}AFX_DATA_MAP
}
This calls m_comm and m_comm2 to be open COM1 and COM2. I don't have the equipment connected to my computer now, and I will have to test the compiled software at site tomorrow. I suspect that because nothing is connected to COM1 and COM2, the program cannot open port and returns that error but I am not sure that is the case, getting in the site is very difficult and I only have one opportunity to go in and test the software there. I want to make sure that this error is only given because nothing is connected to COM1 and COM2 and not any other problem. I appreciate your comments and thoughts on this. If it helps, the DDX_Control function calls the following function in debug mode:
void CMSComm::SetPortOpen(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x14, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
which is supposed to open the port.

Delphi - Is it possible to detect if the Screen monitor is ON or OFF by software? [duplicate]

Does anyone know if there is an API to get the current monitor state (on or off) in Windows (XP/Vista/2000/2003)?
All of my searches seem to indicate there is no real way of doing this.
This thread tries to use GetDevicePowerState which according to Microsoft's docs does not work for display devices.
In Vista I can listen to GUID_MONITOR_POWER_ON but I do not seem to get events when the monitor is turned off manually.
In XP I can hook into WM_SYSCOMMAND SC_MONITORPOWER, looking for status 2. This only works for situations where the system triggers the power off.
The WMI Win32_DesktopMonitor class does not seem to help out as well.
Edit: Here is a discussion on comp.os.ms-windows.programmer.win32 indicating there is no reliable way of doing this.
Anyone else have any other ideas?
GetDevicePowerState sometimes works for monitors. If it's present, you can open the \\.\LCD device. Close it immediately after you've finished with it.
Essentially, you're out of luck—there is no reliable way to detect the monitor power state, short of writing a device driver and filtering all of the power IRPs up and down the display driver chain. And that's not very reliable either.
You could hook up a webcam, point it at your screen and do some analysis on the images you receive ;)
Before doing anything based on the monitor state, just remember that users can use a machine with remote desktop of other systems that don't require a monitor connected to the machine - so don't turn off any visualization based on the monitor state.
You can't.
Look like all monitor power capabilities connected to the "power safe mode"
After searching i found here code that connecting between SC_MONITORPOWER message and system values (post number 2)
I use the code to testing if the system values is changing when i am manually switch off the monitor.
int main()
{
for(;monitorOff()!=1;)
Sleep(500);
return 0;
}//main
And the code is never stopped, no matter how long i am switch off my monitor.
There the code of monitorOff function:
int monitorOff()
{
const GUID MonitorClassGuid =
{0x4d36e96e, 0xe325, 0x11ce,
{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}};
list<DevData> monitors;
ListDeviceClassData(&MonitorClassGuid, monitors);
list<DevData>::iterator it = monitors.begin(),
it_end = monitors.end();
for (; it != it_end; ++it)
{
const char *off_msg = "";
//it->PowerData.PD_PowerStateMapping
if (it->PowerData.PD_MostRecentPowerState != PowerDeviceD0)
{
return 1;
}
}//for
return 0;
}//monitorOff
Conclusion : when you manually switch of the the monitor, you cant catch it by windows (if there is no unusual driver interface for this), because all windows capabilities is connected to "power safe mode".
In Windows XP or later you can use the IMSVidDevice Interface.
See
http://msdn.microsoft.com/en-us/library/dd376775(VS.85).aspx
(not sure if this works in Sever 2003)
With Delphi code, you can detect invalid monitor geomerty while standby in progress:
i := 0
('Monitor'+IntToStr(i)+': '+IntToStr(Screen.Monitors[i].BoundsRect.Left)+', '+
IntToStr(Screen.Monitors[i].BoundsRect.Top)+', '+
IntToStr(Screen.Monitors[i].BoundsRect.Right)+', '+
IntToStr(Screen.Monitors[i].BoundsRect.Bottom))
Results:
Monitor geometry before standby:
Monitor0: 0, 0, 1600, 900
Monitor geometry while standby in Deplhi7:
Monitor0: 1637792, 4210405, 31266576, 1637696
Monitor geometry while standby in DeplhiXE:
Monitor0: 4211194, 40, 1637668, 1637693
This is a really old post but if it can help someone, I have found a solution to detect a screen being available or not : the Connecting and Configuring Displays (CCD) API of Windows.
It's part of User32.ddl and the interesting functions are GetDisplayConfigBufferSizes and QueryDisplayConfig. It give us all informations that can be viewed in the Configuration Panel of windows.
In particular the PathInfo contains a TargetInfo property that have a targetAvailable flag. This flag seems to be correctly updated on all the configurations I have tried so far.
This allow you to know the state of every screens connected to the PC and set their configurations.
Here a CCD wrapper for .Net
If your monitor has some sort of built-in USB hub, you could try and use that to detect if the monitor is off/on.
This will of course only work if the USB hub doesn't stay connected when the monitor is consider "off".

Windows 10 IoT Raspberry Pi 2: DHT22/AM2302

I just wanted to start making experience with the DHT22/AM2302 (a temperature and humidity sensor), but I have no idea how to initialize and get the data of it ... I tried to use GpioPin:
gpioController = GpioController.GetDefault();
if(gpioController == null)
{
Debug.WriteLine("GpioController Initialization failed.");
return;
}
sensorPin = gpioController.OpenPin(7); //Exception throws here
sensorPin.SetDriveMode(GpioPinDriveMode.Input);
Debug.WriteLine(sensorPin.Read());
but get the exception: "A resource required for this operation is disabled."
After that I took a look at the library for the unixoids and found this:
https://github.com/technion/lol_dht22/blob/master/dht22.c
But I have no idea how to realize that in VCSharp using Windows 10, anyone an idea or experience?
Thank you very much in advance!
UPDATE:
I got the hint, that there is not GPIO-Pin 7 and this is true, so I re-tried it, but the GPIO-Output seems to be just HIGH or LOW ... So I have to use the I2C or the SPI ... According to this Project, I decided to try it out with SPI: http://microsoft.hackster.io/windowsiot/temperature-sensor-sample and making steps forward ... The difficulty now is to translate the above linked C-Library to the C-Sharp-SDK to receive the right data ...
private async void InitSPI()
{
try
{
var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
settings.ClockFrequency = 500000;
settings.Mode = SpiMode.Mode0;
string spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);
SpiDisplay = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
}
catch(Exception ex)
{
Debug.WriteLine("SPI Initialization failed: " + ex.Message);
}
}
This works not so well, to be clear: It works just once on starting up the raspberry pi2, then starting / remote debugging the application, but after exiting the application and re-start them, the SPI Initialization fails.
And now Im working on reading the data from the pin and will show some Code in a future update. Any comments, answers and or advices are still welcome.
DHT22 requires very precise timing. Although Raspberry PI/Windows 10 IoT core is extremely fast, since it's an operating system where other things need to happen unless you write some sort of low-level driver (not C#) you won't be able to generate the timings necessary to communicate with a DHT22.
What I do is use a cheap Arduino Mini Pro for about $5 with the sole purpose to generate and send the correct timings between the microcontroller and the Raspberry Pi, then setup some sort of communication channel between the Arduino Mini Pro (I2C, Serial) to pull the data from the Arduino.

UDPClient not receiving packets on HTC G2

I'm attempting to receive a UDP Broadcast under Mono for Android and I am seeing no data coming in. This is somewhat perplexing because it works fine on the Galaxy Tab 7 and Galaxy Tab 10 (Android v 3.2) I have, but fails on an HTC G2 (Android v2.3.4).
The code is straightforward:
public void BeginDiscover()
{
var packet = new DiscoverPacket();
lock (m_syncRoot)
{
var localEndpoint = new IPEndPoint(m_local, 0);
using (var udp = new UdpClient(localEndpoint))
{
var remoteEndpoint = new IPEndPoint(IPAddress.Broadcast, DiscoverPort);
udp.Send(packet.Data, packet.Data.Length, remoteEndpoint);
Thread.Sleep(100);
}
}
}
I have verified that the manifest includes this line:
<uses-permission android:name="android.permission.INTERNET" />
Though this is happening in Debug, so that should be implicitly set anyway.
Other very strange observations:
Again, this is working just fine on another type of device
The handler listening for UDP broadcasts (which list listening for the response) does see this outbound packet. The code for this listener is also straightforward:
[listener code]
private void Start()
{
m_discoverListener = new UdpClient(DiscoverPort);
m_discoverListener.BeginReceive(DiscoverCallback, m_discoverListener);
}
private void DiscoverCallback(IAsyncResult result)
{
try
{
var ep = new IPEndPoint(IPAddress.Any, DiscoverPort);
var data = m_discoverListener.EndReceive(result, ref ep);
// filter out what we send
var add = AddressWithoutPort(ep.Address);
if (add == m_local.ToString()) return;
// parse discover response
// [clipped for clarity]
}
finally
{
m_discoverListener.BeginReceive(DiscoverCallback, m_discoverListener);
}
}
Wireshark running on a separate PC on the same network does see the discover request packet (from above)
The "discovered" device is also seeing it, because Wireshark is also seeing the reply
The Android device UDP listener is not receiving the response packet
The only major differences between devices that I can think of (other than different OEMs implementing the platform) is that the G2 has a cellular radio built in and the Galaxy Tab does not. In my specific test case, I have no SIM card in the phone, though, so no cellular connection is being made. Note that the code above is explicitly using the local endpoint that is on the WiFi network.
Is there a known issue with UDP on the G2 specifically or generally on older implementations of the Android platform?
It took a bit of work as the UDP response in question is coming from a microcontroller on the device and I wanted to make absolutely certain that it wasn't an issue on the micro end (though I suspected it wasn't). I created a PC-based simulator for the microcontroller device that handles my Android UDP request and that sends back the exact same UDP response that the microcontroller does, then verified all of the traffic looks fine with Wireshark.
The net result is that I see he exact same behavior with the simulator. The Galaxy Tab 7 and 10 devices receive the UDP response no problem. The HTC G2 never does. This leads me to conclude that one of the following is true:
a) The HTC G2 specifically has an implementation bug preventing it from receiving (or at least passing along) UDP broadcasts on the network
or
b) The older Android build has his bug.
Until I find different hardware with the same Android version as the G2 (v2.3) I can't tell which is the case. In either event, it's a bug that makes this (and potentially other) hardware unusable for my specific solution.
I have a couple of applications on the market based on UDP communication.
I have problems with HTC phones not receiving the UDP broadcast packets sent from another device... if sent from the same device, the packets arrive.
so, I think the problem is in HTC, and I found a possible solutions online (even though I have not tried it):
http://www.flattermann.net/2010/09/fix-udp-broadcasts-on-htc-phones-running-stock-firmware/

Resources