Communicate with Kohler Meter in C# [closed] - c#

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I m trying to communicate with Kohler active meter. It s half duplex. I ve read all protocol. Kohler has own software to see the profiles. While it was reading the profiles, i tried to view how it is happening. Sending and recieving datas. Then i tried to write a programme in C#. To communicate in first steps baud-rate is chosen 300, and then it should be 4800.
Here is my problems:
If i try to debug my programme using F5, it is not communicating. But if i use step into mode F11, it is working? i guess it should wait some amount of time. any idea?
When i try to change baud-rate from 300 to 4800, step into mode F11 is not working. I checked in the software if it is changing or not, but it is fine. any idea what this is about?

This is a common mishap when you work with serial ports. They are very slow devices, especially at 300 baud. That's only one character per 33 milliseconds, an eternity on a modern machine. By using the debugger, you artificially slow down your program. A lot. Giving the serial port driver time to receive the full device response. When you run without single-stepping or breakpoints, the SerialPort.Read() call only returns one or a few characters at a time. You fix this by using ReadLine() with a properly set NewLine property or by storing the received bytes in a buffer until you got the full response.
You can't just change the baudrate, it must always match the rate of the device.

Before sending your requests wait for some time . When you debug with F5 you don't wait. But with F11 you wait unavoidablely. This also shows that your program works better when you wait :) Use a monitoring program like 'Free Serial Port Monitor' to find out these waiting times by first running Kohler's own program.
You can use a streamreader and streamwriter to communicate with the meter.
Like
writer = new StreamWriter(((System.IO.Ports.SerialPort)serialPort).BaseStream);
reader = new StreamReader(((System.IO.Ports.SerialPort)serialPort).BaseStream);
Don't forget to use writer.Flush() command just after you user write command.
To wait sometimes before you send your commands to the meter use System.Threading.Thread.Sleep(250); code . 250 is in msecs.
I don't recommend you to wait after sending the request. Wait before you send the new request, ACK message, etc.
If kohler's own program waits too much between commands set serialports timeout values ...
(serialport).ReadTimeout = xxx;
(serialport).WriteTimeout = xxx;

'Free Serial Port Monitor' this programme has really opened my mind. Thank you so much #ferda. and i solved the problem. it was about waiting times. First i saw the times for request and the answers using that programme. Then i also used Flush command. i watched my programme outputs using again FreeSerial Port Monitor programme. At the end i could send the datas and received datas at 4800 baud-rate. Just changing baud-rate in C# worked for Kohler. It doesn't need anything else.

Related

C#, BLE. Why does GetGattServicesAsync hang forever? Is there a work around such as turning off/on BLE?

I considered cross posting to the Super User site or similar but don't know how. As you will see this is not just a programming question.
I developed some C# code to communicate with an Onset InTemp thermometer via Bluetooth Low Energy (BLE). It works fine for a long time. I'm able to get beacons (which have the thermometer data) and also connect, get services and characteristics in case I need to get missed data or set parameters on the thermometer. However, after about 8 hours (can be as much as 24 hours) of continuously receiving beacons and connecting, getting historical data, etc., my app hangs on this line:
var gatt = await device.GetGattServicesAsync();
I put lines before and after this line and verified it's clearly hanging on this line. Again, it can be after 8 hours or 24 hours of use. It certainly chugs along just fine for quite a time. Killing and restarting the program is of no help. It hangs on the first call to:
device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
Only rebooting the PC fixes the problem. This is not surprising given the messages in the Windows Event Logs before it hangs:
The Bluetooth driver expected an HCI event with a certain size but did not receive it.
It's for this reason that I stated that this might be a SuperUser board question. No matter how badly I programmed my code :), killing the program should get BLE working again. FWIW, I did try disabling/re-enabling BLE through settings before rebooting.
I have found some links to this problem, but nothing very definitive.
I'm also working on writing a smaller, complete program to show the problem. So far, I can't get example program to fail from which I conclude that either (1) I haven't let it run long enough, or (2) I'm not fully duplicating what is going on with my full program. Perhaps I'm not putting as much pressure on the BLE drivers or I'm not listening for beacons and attempting to connect in the same ratios or with the same timing.
I should say that I see a lot of gripes about Windows implementation of the BLE Host layer and BLE drivers. Unfortunately, I'm stuck with Windows. Nordic also suggested that everything I'm reporting is a "known problem" and using their Nordic dongle will solve the problem. See for example: https://devzone.nordicsemi.com/f/nordic-q-a/65516/using-nrf52840-dongle-as-receiver-client-for-onset-thermometer.
That may well be true, but it would be a lot of work as they have libraries in C++ and Node.JS but not C#.
Any help is greatly appreciated.
Thank you!

Serial port: read a byte as soon as it arrives

I need to write an application that can seat in the middle of a serial port communication between an application (3rd party, no source) running on my pc and a serial device connected to it (say on COM1).
The application normally communicates with the device as soon as you plug the cable. What I need to do is break this communication by "installing" my app in the middle so I can control what data goes through.
The only way I can think of solving this is creating a a pair of virtual serial ports (COM5<->COM6) using com0com. Then I would redirect the app to use COM5 instead of COM1 (I can set this in the app options) and then write a program that will copy every byte received in COM6 (sent by the application) into COM1 (sent to the device) and viceversa.
The problem is that I need to do this without introducing any delays into the communication, otherwise the application and the device will go out of sync.
I tried creating a C# console app to do this, but it seems to wait for a pause in the stream before raising the datareceived event, effectively introducing several ms of delay (speed is 9600).
What I would like to try now is to rewrite the program (maybe using the win32 api?) in such a way that it relays each rx byte as soon as it arrives, so the device would not notice any delay.
Can I do this using win32? Is there a simpler solution you can recommend?
Thanks
Maybe not much of a complete answer for your question but I think this might be worth a try.
Depending on your needs (you did not explain them) you can try to use Termite together with com0com. You can see a quick example here.
There is also an open source clone but I think the very feature you need (forwarding) was never implemented.
In any case, Termite allows scripting, so it is quite likely to be able to meet your needs.

How to find network foscam from C#

I am in the process of creating a very nice C# Winforms application, for controlling and viewing my two foscams.
One of the key things i would like very much to have, is the ability to search the network for cameras!
I know of the "IP Camera Tool" thats very quickly finds the cameras, but i have not been able to recreate it at all (and don't want third-party application).
After searching for days on the internet, i have found "some" documentation, but after many hours of trial and error, i am at a loss here..
The documentation uses UDP packets, you send a command, and the cameras respond back.
First off, i used wireshark to intercept the "IP Camera Tool"s send packet, and replicated it in C#, and the cameras DO respond, but the response does not make any sense, and when i try to intercept it with my application, i only get a small portion of the response, from only the first camera to respond (udp stopped listening)
If there is anyone out there with some knowledge and/or code snippets, i would be very grateful! :)
Documentation:
http://foscam.us/forum/download/file.php?id=522 (pdf)
I had written some code to send the response, but i just had a BSOD and the whole .cs file got screwed..
it was basicly just creating a UdpClient object and send a string that was converted so it mached up with this: 4d:4f:5f:49:00:00:00:00:00:00:00:00:00:00:00:04:00:00:00:04:00:00:00:00:00:00:01
and broadcast it on port 10000.
And then! udp.recive would start right after send, and intercept (the first part of the message only) :-/
Any pointers to listen for more than just the first part of a response, would be very helpful!
I made some nice screenshots of everything for this post, but as this is my first post here, i can't add the images :-/
Thankyou :)
Please let me know if there is any info i missed :)
Kind regards
Niels
Edit:
Links to images:
Documentation (Search_Req):
http://dl.nxsoft.dk/stackpics/doc_search_req.PNG
Documentation (Search_Response):
http://dl.nxsoft.dk/stackpics/doc_search_resp.PNG
Wireshark Output (IP Camera Tool):
http://dl.nxsoft.dk/stackpics/fs_ws_ipTool.PNG
Wireshark Output (Camera Response):
http://dl.nxsoft.dk/stackpics/fs_ws_cam.PNG

WinRT timeout during a webrequest to detect slow internet connections

Is there a sample code available online to get WinRT to determine if its a slow internet connection within the first second of a web-request call so that I can cancel the request and switch to a local file at the start of the program. Metro requirements expect the app to boot up under 5 seconds and I need my web-request (of 300kb) to return well before that. its usually fast on WiFi but 3G speed may vary.
You can see if you are running on a 3G or WiFi connection by using the connectioncost api.
When you are on 3G you could consider using the local file anyway and then attempt to update it on the background. Additionally you might increase your logic further by checking if the user is currently roaming or even if he or she is approaching his or her datalimit, all which might influence your decision on where to load from. All this can be done through the same API.
You are also mixing up things a little as far as the 5 seconds for your app to start go. Your app can actually take 15 seconds give or take to provide something and only 5 seconds to suspend before you are forcibly cut off. If the 15 seconds isn't enough to start with you can also replace the default splash screen .. with your own splash screen and continue loading as long as you like. Keep in mind your user might not like it.
Why not load the local file and then try to update it on the background? I am not sure about your use case.

Baud rates for stable Bluetooth serial communication

I have an Arduino mega communicating over Bluetooth (bluesmirf gold device) to a C# application that I wrote. The Arduino is constantly sending a serial signal of 32 characters, the first always being an "S" and the last an "E". Using putty I can confirm that this signal is being sent correctly 99% of the time.
Now I want to read this signal with my C# application, which I am doing with the following code:
public string receiveCommandHC()
{
string messageHC = "";
if (serialHC.IsOpen)
{
while (serialHC.ReadChar() != 'S')
{
}
messageHC = serialHC.ReadTo("E");
serialHC.DiscardInBuffer();
}
return messageHC;
}
serialHC is of the serial class.
Sometimes this works perfectly but other times I'm having problems, I cannot find out why it works sometimes but others not.
The problem that I seem to be having is that sometimes I get a rather large Lag in the data that I am reading from the arduino. I notice this because I am sending button states and they only change a few seconds after I actually press or release the button on the Arduino. I used the standard baud rate of the Bluetooth device, which is 115200, and was wondering if changing that to a much lower rate could yield better results? What if any advantage would that have? I do not need hight communication rates, even updating the state 4-5 times a second would be acceptable for my application.
Is it possible the lag is coming from my code? I think it may be from the while loop that is waiting for the incoming "S" but then I don't see why it should hang there since there are new signals always coming in at a high rate.
I'm using the DiscardInBuffer() because I do not care about outdated data and just want to skip over that. It is much more important that I am reading current up to date data and acting on that fresh data.
Thank you for your help!
Best regards,
Bender
Update:
Just found out a bit more information while debugging. The problem only seems to appear:
When connected over Bluetooth (over USB cable there is absolutely NO Lag)
When a second Bluetooth connection is established from the PC to another device (different COM port and different baud rate)
Does anybody have any experience running two different devices off the same Bluetooth dongle on the PC? I can manage to connect to both no problem but still having the lag issue mentioned before.
Thanks for any help
You are not really using a physical serial port here. The BlueTooth driver merely emulates one. This is common, the Windows API has a well defined set of api functions to talk to a serial port. Emulating one makes the interface to the driver simple, the vendor doesn't have to supply an interface DLL or document a complicated DeviceIoControl() protocol.
Which means for one thing that the actual communication settings don't matter. Baudrate is meaningless in this scenario, it is the BlueTooth radio signaling that sets the transfer rate. The driver will accept whatever you select but will otherwise ignore it. Handshake signals might be interpreted, it's up to the driver to implement them. Communication error reporting is very rarely implemented, BlueTooth has an error correcting protocol, unlike a real serial port.
No, the loss of data here is entirely self induced. Clearly the driver does implement DiscardInBuffer(). Which accomplishes nothing but throw away any data that the driver received. This goes wrong if your code runs a bit late or gets interrupted by a thread context switch.
Delete the DiscardInBuffer() call.

Categories

Resources