I'm pretty new to Android programming that's why I need your advice.
Current Situation:
I built an Android application (C#) aswell as a regular Server application (C++) which runs on a Raspberry Pi. Both programs communicate via UDP. At the moment that the Server application receives a signal it sends out a broadcast message which the Android application is listening for. Everything works just fine to the moment that the Android device falls asleep/goes idle which leads to my question.
Question:
How can I accomplish that the Android applications' listener still works, when the device falls asleep? I do not expect any solutions but any kind of advice so I don't waste time with wrong approaches.
Research:
- I read about and tried services that will keep running in the background but the service also stopped as the device went to sleep.
- I read about Broadcast Receivers which allow the application/service to get further information of the system.
- I read about WAKELOCK which allows me to keep the CPU alive, but for my purpose it should be up 'all the time' and that would drain to much energy.
Code that I would like to run in the background:
public void AsyncReceive()
{
// ...
Task.Run(() =>
{
while (this.isActive)
{
byte[] buffer = new byte[1];
DatagramPacket incoming = new DatagramPacket(buffer,
buffer.Length);
try
{
sock.Receive(incoming);
}
catch (...)
{
// Exception handling goes here...
}
// Communicate with the Android application
this.FireBroadCastReceivedEvent();
}
});
}
Edit
I also need to notice the application about incoming messages (#the 'FireBroadCastReceivedEvent()' part of the code). What would be a good way to do that?
I think you must read this link : https://developer.android.com/training/run-background-service/index.html
Hope you find what are you looking for.
Related
I got a little problem with a USB Barcode Scanner.
I am using the Scanner with the "SerialPort" class:
this._barcodeScanner = new SerialPort(comPort, 9600, Parity.None, 8, StopBits.One) { Handshake = Handshake.None, ReadTimeout = 500, WriteTimeout = 500 };
this._barcodeScanner.Open();
this._barcodeScanner.DataReceived += BarcodeScannerCallback;
If I unplug the USB Device while it´s opened via the "SerialPort" class, I can´t close the software properly and the virtual port stays open for all eternity or till I reboot the whole computer.
So my question is, is there any way to close the virtual port after I unplugged the device via C# code?
Greetings
[edit #1]
Alrighty, some more code:
This way I am checking every 10 seconds if the device is plugged in:
private bool CheckUsbDeviceAvailability()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSSerial_PortName WHERE PortName = '" + this.PortName + "'");
if (searcher.Get().Count > 0)
return true;
return false;
}
Thats the Callback-Event of the Serial Port:
void BarcodeScannerCallback(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
string data = this._barcodeScanner.ReadExisting().Replace(Convert.ToChar(2), Convert.ToChar(32)).Trim();
if (data.StartsWith("AX"))
{
string[] arrData = data.Split('\n');
this._barcodeScanner.StopAvailabilityThread();
Barcode code = new Barcode(arrData[0].Replace("\r", ""));
if (CheckIfBarcodeExists(code))
this.UpdateBarcodeNode(code);
else
this.CreateBarcodeNode(code);
BarcodeScannerCallbackEvent(sender, e, code);
this._barcodeScanner.StartAvailabilityThread();
}
this._barcodeScanner.ComDevicePluggedIn = ScannerDevice.ComAvailabilityState.Available;
}
if it doesnt answer anymore it will fire the "DeviceNotAvailableEvent()":
void BarcodeScannerDeviceNotAvailableEvent()
{
this._barcodeScanner.Close();
this._barcodeScanner.Dispose();
}
I have overriden the Dispose Event of the "SerialPort" class so that it´s going to abort the Thread:
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
this._deviceAvailableThread.Abort();
}
base.Dispose(isDisposing);
}
Serial ports date from the stone age of computing. That's where you plugged in your ASR-33 teletype to start typing in your Fortran program. The electrical interface is very simple. So is the Windows API to use a serial port from your own code. Practically any runtime environment supports them.
USB has replaced serial port hardware completely. It has a much more advanced logical interface to the machine, supporting many different type of devices. And it supports Plug and Play, allowing the operating system to detect when a device is attached or removed as well as automatically installing the device driver, etcetera.
This flexibility comes at a price however, a USB device always needs a device driver to become usable. Device drivers are not created equal. Different drivers require different ways to talk to the device. Usually done through DeviceIoControl() or Read/WriteFile() but those are very opaque API functions. In the early days of USB, device manufacturers would supply a DLL that provided a rich API to hide the implementation details.
That did not work so well, manufacturers are not very good at writing good APIs and they sure don't like to support them. So a good solution would be to support a standard API, one that's available on any machine, supported by any runtime, documented and maintained by somebody else. Like the serial port API.
That did not work so well, manufacturers are not very good at writing device drivers that emulate serial ports. The biggest hang-up with the API is that it doesn't have any support for Plug and Play. The core support for it is missing, after all serial port hardware doesn't have the logical interface to support it. There is some support for detecting that a device is attached through the DTR hardware handshake line, but no support whatsoever for detecting that the port is no longer there.
Detaching the USB device is the problem. In an ideal world, the emulator built into the device driver would simply pretend that the serial port is still there until the last handle on the device is closed. That would be the logical implementation, given that there's no way to trigger a Plug and Play event. For some strange reason that seems to be difficult to implement. Most USB drivers take the crummy shortcut, they simply make the device disappear even while it is in use.
This plays havoc on any user mode code that uses the device. Which is typically written to assume it is a real serial port and real serial ports don't suddenly disappear. At least not without drawing a bright blue spark. What goes wrong is pretty unpredictable because it depends on how the driver responds to requests on a device that's no longer there. An uncatchable exception in a worker thread started by SerialPort was a common mishap. Sounds like your driver really gets it wrong, it generates an error return code on the MJ_CLOSE driver request. Which is kind of a logical thing to do for a driver, after all the device isn't there anymore, but quite unsolvable from your end. You have a handle and you can't close it. That's up a creek with no paddle.
Every major release of .NET had a small patch to the SerialPort classes to try to minimize the misery a bit. But there's a limited amount that Microsoft can do, catching all errors and pretending they didn't happen ultimately leads to class that provides no good diagnostic anymore, even with a good driver.
So practical approaches are:
always use the Remove Hardware Safely tray icon in Windows
use the latest version of .NET
contact the vendor and ask for a driver update
ditch vendors that supply lousy drivers
tell your users that, just because it is the only thing you can do with a USB device, that unplugging it doesn't solve any problems
make closing the port easy and accessible in your UI
glue the USB connector to the port so it can't be removed
The 5th bullet is also what gets programmers in trouble. Writing serial port code isn't easy, it is heavily asynchronous and the threadpool thread that runs the DataReceived event is difficult to deal with. When you can't diagnose the software problem you tend to blame the hardware. There's very little you can do with the hardware but unplug it. Bad Idea. Now you have two problems.
This Problem Exists in .Net 2 , 3 , 3.5 you can use framework 4 (problem does not exist in .net 4)
I just started to learn ZeroMQ and want to build a distributed webcrawler as an example while learing.
My idea is to have a "server", written in PHP, which accepts a url where the crawling should start.
Workers (C# cli) will have to crawl that url, extract links, and push them back into a stack on the server. The server keeps sending urls in the stack to workers.
Perhaps a redis will keep track of all crawled urls, so we dont crawl sites multiple times and have the ability to extract statistics of the current process.
I would like to have the server to distribute tasks evenly, be aware of new/missing workers and redistribute urls when a worker doesnt respond.
Why PHP for the server: i'm just very comfortable with PHP, that is all. I dont want to make the example/testing project more complicated.
Why C# for the minions: because it runs on most windows machines. I can give the executable to various friends which can just execute it and help me test my project.
The crawling process and redis functionality are not part of my question.
My first approach was the PUSH/PULL pattern, which generally works for my scenario, but isnt aware of it's minions. I think i need a DEALER/ROUTER broker in the middle and have to handle the worker-awareness for myself.
I found this question but i'm not really sure if i understand the answer...
I'm asking for some hints how to impement the zmq stuff. Is the dealer approach correct? Is there any way to get an automatic worker-awareness? I think I need some resources/examples, or do you think that i just need to dig deeper in the zmq guide?
However, some hints towards the right direction would be great :)
Cheers
I'm building a job/task distributor that works the same as your crawler, in principal, at least. Here's a few things I've learned:
Define All Events
Communication between server and crawlers will be based on different things happening in your system, such as dispatching work from server to crawler, or a crawler sending a heartbeat message to the server. Define the system's event types; they are the use cases:
DISPATCH_WORK_TO_CRAWLER_EVENT
CRAWLER_NODE_STATUS_EVENT
...
Define a Message Standard
All communication between server and crawlers should be done using ZMsg's, so define a standard that organizes your frames, something like this:
Frame1: "Crawler v1.0" //this is a static header
Frame2: <event type> //ex: "CRAWLER_NODE_STATUS_EVENT"
Frame3: <content xml/json/binary> //content that applies to this event (if any)
Now you can create message validators to validate ZMsgs received between peers since you have a standard convention all messages must follow.
Server
Use a single ROUTER on the server for asynchrounous and bidirectional communication with the crawlers. Also, use a PUB socket for broadcasting heartbeat messages.
Don't block on the ROUTER socket, use a POLLER to loop every 5s or whatever, this allows the server to do other things periodically, like broadcast heartbeat events to the crawlers; something like this:
Socket rtr = .. //ZMQ.ROUTER
Socket pub = .. //ZMQ.PUB
ZMQ.Poller poller = new ZMQ.Poller(2)
poller.register( rtr, ZMQ.Poller.POLLIN)
poller.register( pub, ZMQ.Poller.POLLIN)
while (true) {
ZMsg msg = null
poller.poll(5000)
if( poller.pollin(0)){
//messages from crawlers
msg = ZMsg.recvMsg(rtr)
}
//send heartbeat messages
ZMsg hearbeatMsg = ...
//create message content here,
//publish to all crawlers
heartbeatMsg.send(pub)
}
To address your question about worker awareness, a simple and effective method uses a FIFO stack along with the heartbeat messages; something like this:
server maintains a simple FIFO stack in memory
server sends out heartbeats; crawlers respond with their node name; the ROUTER automatically puts the address of the node in the message as well (read up on message enveloping)
push 1 object onto the stack containing the node name and node address
when the server wants to dispatch work to a crawler, just pop the next object from the stack, create the message and address is properly (using the node address), and off it goes to that worker
dispatch more work to other crawlers the same way; when a crawler responds back to the server, just push another object with node name/address back on the stack; the other workers won't be available until they respond, so we don't bother them.
This is a simple but effective method of distributing work based on worker availability instead of blindly sending out work. Check lbbroker.php example, the concept is the same.
Crawler (Worker)
The worker should use a single DEALER socket along with a SUB. The DEALER is the main socket for async communication, and the SUB subscribes to heartbeat messages from the server. When the worker receives a heartbeat messages, it responds to the server on the DEALER socket.
Socket dlr = .. //ZMQ.DEALER
Socket sub = .. //ZMQ.SUB
ZMQ.Poller poller = new ZMQ.Poller(2)
poller.register( dlr, ZMQ.Poller.POLLIN)
poller.register( sub, ZMQ.Poller.POLLIN)
while (true) {
ZMsg msg = null
poller.poll(5000)
if( poller.pollin(0)){
//message from server
msg = ZMsg.recvMsg(dlr)
}
if( poller.pollin(1)){
//heartbeat message from server
msg = ZMsg.recvMsg(sub)
//reply back with status
ZMsg statusMsg = ...
statusMsg.send(dlr)
}
The rest you can figure out on your own. Work through the PHP examples, build stuff, break it, build more, it's the only way you'll learn!
Have fun, hope it helps!
I have a simple messaging wpf application that listens to a wcf duplex service to receive messages. I have coded it so that if the network fails (or I disconnect the LAN cable) it reconnects to the service which works well.
My problem is, when Windows goes into sleep mode it fails to try to reconnect. I suspect this is because my timer for polling the network is put to sleep and therefore the polling stops.
So, is there a way to react to a "Windows has woken up" event or similar?
I finally found what i wanted, a simple, managed code way to react to the system resume event...
Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;
private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume)
{
//Do Some processing here
}
}
The (major) benefit of this approach over p/invoke is that ir works across OS's (I need no extra handling for Windows XP & Vista) and, of course, it's rather more consice!
Have you seen http://www.codeproject.com/KB/system/OSEvents.aspx ?
It is coded in C++, but I believe it uses only Win32API, so using P/Invoke you should be able to use the code in your application. :)
I am designing a webservice interface for use between a Windows CE device and a PC. The Windows CE device is server and the PC is client.
I have decided to use the gSOAP library to implement the server and I am using .NET/C# for the client. I have followed the approach described here and everything is working well.
My question is about how to best implement an asynchronous callback/event from the server to the client. I can think of two methods:
Continuously polling the server for active events
A blocking method that keeps the connection open until an event occurs
I have currently chosen option 2 and it seems to be working well. I use an asynchronous method in the client and therefore get a callback when the method completes, i.e. when an event occurs on the Windows CE device. I then immediately call the same method again so it is ready for the next event.
Example server method (no error handling):
int ns__WaitForEvent(struct soap* soap, int *eventId)
{
WaitForSingleObject(hMyServerEvent, INFINITE);
*eventId = GetCurrentEventId();
return SOAP_OK;
}
Example client (no error handling):
private void SubscribeToServerEvents()
{
var server = new MyMethods.ServicePortTypeClient(
new BasicHttpBinding(),
new EndpointAddress(myIpAddress));
AsyncCallback cb = this.Callback;
server.BeginWaitForEvent(cb, server);
}
private void Callback(IAsyncResult ar)
{
var server = (MyMethods.ServicePortType)ar.AsyncState;
var result = server.EndWaitForEvent(ar);
// Do stuff with result
}
The server must be multi-threaded for this approach to work, and the number of clients should be limited so the server does not have a large number of threads hanging with blocking methods. In my case none of these issues are a problem - it is simple to setup a multi-threaded server using gSOAP and there will only ever be one client (which I control) attached to each server.
Are there any significant disadvantages to this approach? Can you suggest a better solution?
I suggest to turn the WinCE device into a webclient instead of a webserver and the PC into a server, that will be notified on something happens on the client. It is more natural this approach, you can still use gSoap for a soap client. On the PC you should have a web-server like Apache or IIS installed, or you could make a Windows server that will host an embedded light webserver.
I'm working on an "application system" , where I also need to make a server application. I'm working in C# (.NET 4.0). The server will mainly collect data from different POS applications / clients (which should be around 50-100, but the server should be capable of handling also around 200-300 clients). From a single client a server will probably receive around 1KB about 100x times a day. The server mainly needs to accept the data, decrypt it and store it to disk. It should also check for changes in specific directory in order to send new configurations to clients, which shouldn't be very often.
I'm quite new to C# and server programming so please bear with me. I thought about using threadpooling and async methods (there is a nice example using that in a book "C# in a nutshell"). But I spend quite some time looking for best solution and I found this. But multithreading brings more problems than benefits in my case. Thus I thought about even driven server. "A single process, handle every event (accepted connection, data available to read, can write to client, ...) on a callback." from " what is event driven web server". I find that the best solution to my problem.
But I have no idea on how to code it, I couldn't find any examples about event driven servers. As far as I understand it I should make one thread (+ 1 for GUI), then create a TCP listener and then somehow create events so that when TCP listener could accept a client the event would fire and wake up the server, also when data to read from clients would be available it would wake up the server.
Please help me out to code this, I'm totally lost. I know how I could do this using
while(true)
{
check if client wants to connect
accept client and add it to client list
iterate through client list and check if anyone is sending data ...
accept data and store it
...
}
But that is not event driven and is wasting CPU. Server will not be very active, so I'd like to make it as efficient as possible.
Some examples would really help.
Thank you for your time and answers.
p.s. Can I use just one port for all the clients?
EDIT: To clarify, I want to code an event driven server, but I don't know how to, thus I just made an example of what I know (client polling).
First, if you're new to C# and multithreading and sockets, that is a lot to bite off for your first project. I recommend learning these individually.
That said, you may find Nito.Async.Sockets helpful; it includes an event-driven server socket and handles the multithreading concerns for you.
Here is a server skeleton for what you might need. No exceptions are handled.
class Program
{
public static ManualResetEvent connected = new ManualResetEvent(false);
static void Main(string[] args)
{
string ip = "127.0.0.1";
int port = 14500;
TcpListener server = new TcpListener(IPAddress.Parse(ip), port);
server.Start();
Console.WriteLine("Server started...");
while (true)
{
connected.Reset();
server.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), server);
connected.WaitOne();
}
}
public static void AcceptCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
byte[] buffer = new byte[1024];
NetworkStream ns = client.GetStream();
if (ns.CanRead)
{
ns.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCallback), new object[] { ns, buffer });
}
connected.Set();
}
public static void ReadCallback(IAsyncResult ar)
{
NetworkStream ns = (NetworkStream)((ar.AsyncState as object[])[0]);
byte[] buffer = (byte[])((ar.AsyncState as object[])[1]);
int n = ns.EndRead(ar);
if (n > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, n));
}
ns.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCallback), new object[] { ns, buffer });
}
}
I don't know about C# frameworks, but you can have a look at Twisted, an event driven Python framework. You can find examples of servers and clients code, similar to your needs.
Here is a sample of a very simple server that echoes back to client whatever it received from it:
#!/usr/bin/env python
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
### Protocol Implementation
# This is just about the simplest possible protocol
class Echo(Protocol):
def dataReceived(self, data):
"""
As soon as any data is received, write it back.
"""
self.transport.write(data)
def main():
f = Factory()
f.protocol = Echo
reactor.listenTCP(8000, f)
reactor.run()
if __name__ == '__main__':
main()
Regarding you last question:
P.S. Can I use just one port for all the clients?
Yes, you can (whatever language/framework you use).
I would suggest to use WCF hosted as a windows service, which provide a scalable and multithread platform. It can be tailored as per protocol requirement as well. Here is an example which can be used as a reference:
http://msdn.microsoft.com/en-us/library/ms733069.aspx
Event driven doesn't exactly describe what you expect your system to work like because you describe polling your clients for data to process instead of your clients pushing their data to your service (triggering an event).
If you have very little idea about how to code a system like this you could look into existing solutions/products for your scenario.
I'd recommend checking out EAI tools like BlueIntegrator or BizTalk for integrating POS clients.
For your requirement concerning rolling out client updates you could look into BITS.
I'm a bit late to the party, but I've recently started a new job developing software to integrate with scientific instruments and am currently going through the pain of learning threading, comms, async processing, etc. I've found Joe Albahari's Threading in C# to be an excellent resource for learning about the threading side of things.