Changing Mavlink Message Rate ArduPilotMega - c++

I am working on a project that uses Mavlink protocol (in c++) to communicate with the ArduPilotMega (2.6).
I am able to read messages such as ATTITUDE for example. The current message rate (for all messages) is 2Hz and I would like to increase this rate.
I found out that I should probably set MESSAGE_INTERVAL using MAV_CMD_SET_MESSAGE_INTERVAL in order to change it.
So my question is:
How do I send this command message using mavlink in c++?
I tried doing it using the code below but it did not work. I guess I have to use the command I mentioned above, but I don't know how.
mavlink_message_t command;
mavlink_message_interval_t interval;
interval.interval_us = 100000;
interval.message_id = 30;
mavlink_msg_message_interval_encode(255, 200, &command, &interval);
p_sensorsPort->write_message(command);
Update: I also tried this code below, maybe I am not giving it the right system id or component id.
mavlink_message_t command;
mavlink_command_long_t interval;
interval.param1 = MAVLINK_MSG_ID_ATTITUDE;
interval.param2 = 100000;
interval.command = MAV_CMD_SET_MESSAGE_INTERVAL;
interval.target_system = 0;
interval.target_component = 0;
mavlink_msg_command_long_encode(255, 0, &command, &interval);
p_sensorsPort->write_message(command);
Maybe I am missing something about the difference between target_system, target_component and sysid, compid. I tried few values for each but nothing worked.
Is there any ACK that will be able to tell me if it even got the command?

I guess you missed start_stop field. the below sample is working.
final msg_request_data_stream msg = new msg_request_data_stream ();
msg.req_message_rate = rate;
msg.req_stream_id = (short) streamId;
msg.target_component = (short)compID;
msg.target_system = (short)sysID;
/*
GCS_COMMON.cpp contains code that sends when value =1
and stop when value = 0
that is it.
*/
if (rate > 0) {
msg.start_stop = 1;
} else {
msg.start_stop = 0;
}

From Robotis Stack Exchange answer,
In order to change the message rate, the simplest way is to change the SR_* parameters value using Mission Planner. The maximum rate is 10Hz.
For example, in order to change the ATTITUDE message rate to be 10Hz I just had to change the SR_EXTRA1 parameter to be 10.
For more information about which parameter changes each message see GCS_Mavlink.cpp file in ArduCopter firmware.

Related

How to convert the output of boost::interprocess::winapi::get_last_bootup_time() to the unix time?

I need to get the time of the latest system boot. I'm using the following boost function:
#include <boost/interprocess/detail/win32_api.hpp>
std::string SystemLastBootTime = "";
if (boost::interprocess::winapi::get_last_bootup_time(SystemLastBootTime)) {
MessageBox(NULL, SystemLastBootTime.c_str(), "Last Boot Time", MB_OK | MB_ICONEXCLAMATION);
}
The output of SystemLastBootTime is:
AA000000_0E030000
What's exactly in this string, and how to convert it to a "normal" unix time, so I can compare and see if the system booted during the last 5 minutes or later?
The implementation is right there. There's actually different implementations:
when BOOST_INTERPROCESS_BOOTSTAMP_IS_SESSION_MANAGER_BASED is defined
when BOOST_INTERPROCESS_BOOTSTAMP_IS_EVENTLOG_BASED is defined
From Session Manager
inline bool get_last_bootup_time(std::string &stamp)
{
unsigned dword_val = 0;
std::size_t dword_size = sizeof(dword_val);
bool b_ret = get_registry_value_buffer( hkey_local_machine
, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management\\PrefetchParameters"
, "BootId", &dword_val, dword_size);
if (b_ret)
{
char dword_str[sizeof(dword_val)*2u+1];
buffer_to_narrow_str(&dword_val, dword_size, dword_str);
dword_str[sizeof(dword_val)*2] = '\0';
stamp = dword_str;
b_ret = get_registry_value_buffer( hkey_local_machine
, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Power"
, "HybridBootAnimationTime", &dword_val, dword_size);
//Old Windows versions have no HybridBootAnimationTime
if(b_ret)
{
buffer_to_narrow_str(&dword_val, dword_size, dword_str);
dword_str[sizeof(dword_val)*2] = '\0';
stamp += "_";
stamp += dword_str;
}
b_ret = true;
}
return b_ret;
}
From Event Log
This is even grittier, and way more code since apparently they chose not to use an existing library. They end up looking for event ID 6005, and then reading the
unsigned long TimeGenerated; // Seconds since 1-1-1970
from that record.
Summarizing
As you can see the whole thing is proprietary, and you might just want to implement it yourself without (ab)using implementation details from Boost Interprocess.
The "good news" is that you might be able to get some documentation from Microsoft about either the Session Manager registry key, or System event 6005.
Oh, and don't forget that defining BOOST_INTERPROCESS_BOOTSTAMP_IS_EVENTLOG_BASED could we result in a readable timestamp to begin with, since it just formats the UNIX timestamp with %u to the output.

Arduino can NOT send JSON

I want so send data via a JSON object. All 7 variables you can see in the code should be well defined.
I get the following "error message"/incomplete JSON from Arduino monitor:
{"topic":"Statistics","DrillDuration":"1000","SpeedToDrill":"20","SpeedWithObjectBefore":"100","SpeedWithObjectAfter":"100⸮⸮
Any idea? Is the package for my JSON too small?
I tested my function on a separate Arduino, where I cut my hole program. There it runs without any problems. This function "sendSummary" runs at the end of a bigger code, maybe this could lead to some issues?
Thanks a lot for your help!
void sendSummary()
{
const size_t capacity = JSON_OBJECT_SIZE(14);
DynamicJsonDocument doc(capacity);
doc["topic"] = "Statistics";
doc["DrillDuration"] = DrillDuration;
doc["SpeedToDrill"] = SpeedToDrill;
doc["SpeedWithObjectBefore"] = SpeedWithObjectBefore;
doc["SpeedWithObjectAfter"] = SpeedWithObjectAfter;
doc["SpeedWithoutObject"] = SpeedWithoutObject;
doc["DrillSpeed"] = DrillSpeedVar;
serializeJson(doc, Serial);
Serial.write("\n");
}

Writing value to PLC tag with open62541

I am trying to write bool value to PLC Tag (turn relay on or off) using OPC UA as Client writing to OPC UA Server running on Siemens S7-1512 PLC. The client must be implemented in c/c++
I have tried a few different GUI clients with no issues.
Also, I have tried Python SDK including freeopcua. I had slight issues but was able to write value after setting an attribute in the write request. But with open62541 I can't find any solution to that (status code is good but value is not changed I am able to read values):
Python working request:
node.set_attribute(ua.AttributeIds.Value, ua.DataValue(not node.get_value()))
C not working request code below:
UA_WriteRequest request;
UA_WriteRequest_init(&request);
request.nodesToWrite = UA_WriteValue_new();
request.nodesToWriteSize = 1;
request.nodesToWrite[0].nodeId = UA_NODEID_STRING_ALLOC(3, "\"VALUE\"");
request.nodesToWrite[0].attributeId = UA_ATTRIBUTEID_VALUE;
request.nodesToWrite[0].value.hasValue = true;
request.nodesToWrite[0].value.value.type = &UA_TYPES[UA_TYPES_BOOLEAN];
request.nodesToWrite[0].value.value.storageType = UA_VARIANT_DATA_NODELETE;
request.nodesToWrite[0].value.hasServerTimestamp = true;
request.nodesToWrite[0].value.hasSourceTimestamp = true;
request.nodesToWrite[0].value.sourceTimestamp = UA_DateTime_now();
request.nodesToWrite[0].value.value.data = val;
request.requestHeader.timestamp = UA_DateTime_now();
request.requestHeader.authenticationToken = UA_NODEID_NUMERIC(0, UA_NS0ID_SESSIONAUTHENTICATIONTOKEN);
//write to client service
UA_WriteResponse wResp = UA_Client_Service_write(client, request);
I expect value for PLC tag to be changed to the opposite value or provide me with info on why it won't work.
Better use the client high level api:
UA_NodeId nodeid = UA_NODEID_STRING_ALLOC(3, "\"VALUE\"");
UA_Boolean value = true;
UA_Variant *var= UA_Variant_new();
UA_Variant_setScalarCopy(var, &value, &UA_TYPES[UA_TYPES_BOOLEAN]);
UA_StatusCode ret = UA_Client_writeValueAttribute(client, nodeid, var);
....
UA_Variant_delete(var);
The reason it is rejected, is that you trie to set the Timestamp in your write request. Most server refuse that.

Some Problems of Indy 10 IdHTTP Implementation

In regard to Indy 10 of IdHTTP, many things have been running perfectly, but there are a few things that don't work so well here. That is why, once again, I need your help.
Download button has been running perfectly. I'm using the following code :
void __fastcall TForm1::DownloadClick(TObject *Sender)
{
MyFile = SaveDialog->FileName;
TFileStream* Fist = new TFileStream(MyFile, fmCreate | fmShareDenyNone);
Download->Enabled = false;
Urlz = Edit1->Text;
Url->Caption = Urlz;
try
{
IdHTTP->Get(Edit1->Text, Fist);
IdHTTP->Connected();
IdHTTP->Response->ResponseCode = 200;
IdHTTP->ReadTimeout = 70000;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->ReuseSocket;
Fist->Position = 0;
}
__finally
{
delete Fist;
Form1->Updated();
}
}
However, a "Cancel Resume" button is still can't resume interrupted downloads. Meant, it is always sending back the entire file every time I call Get() though I've used IdHTTP->Request->Ranges property.
I use the following code:
void __fastcall TForm1::CancelResumeClick(TObject *Sender)
{
MyFile = SaveDialog->FileName;;
TFileStream* TFist = new TFileStream(MyFile, fmCreate | fmShareDenyNone);
if (IdHTTP->Connected() == true)
{
IdHTTP->Disconnect();
CancelResume->Caption = "RESUME";
IdHTTP->Response->AcceptRanges = "Bytes";
}
else
{
try {
CancelResume->Caption = "CANCEL";
// IdHTTP->Request->Ranges == "0-100";
// IdHTTP->Request->Range = Format("bytes=%d-",ARRAYOFCONST((TFist->Position)));
IdHTTP->Request->Ranges->Add()->StartPos = TFist->Position;
IdHTTP->Get(Edit1->Text, TFist);
IdHTTP->Request->Referer = Edit1->Text;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->ReadTimeout = 70000;
}
__finally {
delete TFist;
}
}
Meanwhile, by using the FormatBytes function, found here, has been able to shows only the size of download files. But still unable to determine the speed of download or transfer speed.
I'm using the following code:
void __fastcall TForm1::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
__int64 Romeo = 0;
Romeo = IdHTTP->Response->ContentStream->Position;
// Romeo = AWorkCount;
Download->Caption = FormatBytes(Romeo) + " (" + IntToStr(Romeo) + " Bytes)";
ForSpeed->Caption = FormatBytes(Romeo);
ProgressBar->Position = AWorkCount;
ProgressBar->Update();
Form1->Updated();
}
Please advise and give an example. Any help would sure be appreciated!
In your DownloadClick() method:
Calling Connected() is useless, since you don't do anything with the result. Nor is there any guarantee that the connection will remain connected, as the server could send a Connection: close response header. I don't see anything in your code that is asking for HTTP keep-alives. Let TIdHTTP manage the connection for you.
You are forcing the Response->ResponseCode to 200. Don't do that. Respect the response code that the server actually sent. The fact that no exception was raised means the response was successful whether it is 200 or 206.
You are reading the ReuseSocket property value and ignoring it.
There is no need to reset the Fist->Position property to 0 before closing the file.
Now, with that said, your CancelResumeClick() method has many issues.
You are using the fmCreate flag when opening the file. If the file already exists, you will overwrite it from scratch, thus TFist->Position will ALWAYS be 0. Use fmOpenReadWrite instead so an existing file will open as-is. And then you have to seek to the end of the file to provide the correct Position to the Ranges header.
You are relying on the socket's Connected() state to make decisions. DO NOT do that. The connection may be gone after the previous response, or may have timed out and been closed before the new request is made. The file can still be resumed either way. HTTP is stateless. It does not matter if the socket remains open between requests, or is closed in between. Every request is self-contained. Use information provided in the previous response to govern the next request. Not the socket state.
You are modifying the value of the Response->AcceptRanges property, instead of using the value provided by the previous response. The server tells you if the file supports resuming, so you have to remember that value, or query it before then attempting to resumed download.
When you actually call Get(), the server may or may not respect the requested Range, depending on whether the requested file supports byte ranges or not. If the server responds with a response code of 206, the requested range is accepted, and the server sends ONLY the requested bytes, so you need to APPEND them to your existing file. However, if the server response with a response code of 200, the server is sending the entire file from scratch, so you need to REPLACE your existing file with the new bytes. You are not taking that into account.
In your IdHTTPWork() method, in order to calculate the download/transfer speed, you have to keep track of how many bytes are actually being transferred in between each event firing. When the event is fired, save the current AWorkCount and tick count, and then the next time the event is fired, you can compare the new AWorkCount and current ticks to know how much time has elapsed and how many bytes were transferred. From those value, you can calculate the speed, and even the estimated time remaining.
As for your progress bar, you can't use AWorkCount alone to calculate a new position. That only works if you set the progress bar's Max to AWorkCountMax in the OnWorkBegin event, and that value is not always know before a download begins. You need to take into account the size of the file being downloaded, whether it is being downloaded fresh or being resumed, how many bytes are being requested during a resume, etc. So there is lot more work involved in displaying a progress bar for a HTTP download.
Now, to answer your two questions:
How to retrieve and save the download file to a disk by using its original name?
It is provided by the server in the filename parameter of the Content-Disposition header, and/or in the name parameter of the Content-Type header. If neither value is provided by the server, you can use the filename that is in the URL you are requesting. TIdHTTP has a URL property that provides the parsed version of the last requested URL.
However, since you are creating the file locally before sending your download request, you will have to create a local file using a temp filename, and then rename the local file after the download is complete. Otherwise, use TIdHTTP.Head() to determine the real filename (you can also use it to determine if resuming is supported) before creating the local file with that filename, then use TIdHTTP.Get() to download to that local file. Otherwise, download the file to memory using TMemoryStream instead of TFileStream, and then save with the desired filename when complete.
when I click http://get.videolan.org/vlc/2.2.1/win32/vlc-2.2.1-win32.exe then the server will process requests to its actual url. http://mirror.vodien.com/videolan/vlc/2.2.1/win32/vlc-2.2.1-win32.exe. The problem is that IdHTTP will not automatically grab through it.
That is because VideoLan is not using an HTTP redirect to send clients to the real URL (TIdHTTP supports HTTP redirects). VideoLan is using an HTML redirect instead (TIdHTTP does not support HTML redirects). When a webbrowser downloads the first URL, a 5 second countdown timer is displayed before the real download then begins. As such, you will have to manually detect that the server is sending you an HTML page instead of the real file (look at the TIdHTTP.Response.ContentType property for that), parse the HTML to determine the real URL, and then download it. This also means that you cannot download the first URL directly into your target local file, otherwise you will corrupt it, especially during a resume. You have to cache the server's response first, either to a temp file or to memory, so you can analyze it before deciding how to act on it. It also means you have to remember the real URL for resuming, you cannot resume the download using the original countdown URL.
Try something more like the following instead. It does not take into account for everything mentioned above (particularly speed/progress tracking, HTML redirects, etc), but should get you a little closer:
void __fastcall TForm1::DownloadClick(TObject *Sender)
{
Urlz = Edit1->Text;
Url->Caption = Urlz;
IdHTTP->Head(Urlz);
String FileName = IdHTTP->Response->RawHeaders->Params["Content-Disposition"]["filename"];
if (FileName.IsEmpty())
{
FileName = IdHTTP->Response->RawHeaders->Params["Content-Type"]["name"];
if (FileName.IsEmpty())
FileName = IdHTTP->URL->Document;
}
SaveDialog->FileName = FileName;
if (!SaveDialog->Execute()) return;
MyFile = SaveDialog->FileName;
TFileStream* Fist = new TFileStream(MyFile, fmCreate | fmShareDenyWrite);
try
{
try
{
Download->Enabled = false;
Resume->Enabled = false;
IdHTTP->Request->Clear();
//...
IdHTTP->ReadTimeout = 70000;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->Get(Urlz, Fist);
}
__finally
{
delete Fist;
Download->Enabled = true;
Updated();
}
}
catch (const EIdHTTPProtocolException &)
{
DeleteFile(MyFile);
throw;
}
}
void __fastcall TForm1::ResumeClick(TObject *Sender)
{
TFileStream* Fist = new TFileStream(MyFile, fmOpenReadWrite | fmShareDenyWrite);
try
{
Download->Enabled = false;
Resume->Enabled = false;
IdHTTP->Request->Clear();
//...
Fist->Seek(0, soEnd);
IdHTTP->Request->Ranges->Add()->StartPos = Fist->Position;
IdHTTP->Request->Referer = Edit1->Text;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->ReadTimeout = 70000;
IdHTTP->Get(Urlz, Fist);
}
__finally
{
delete Fist;
Download->Enabled = true;
Updated();
}
}
void __fastcall TForm1::IdHTTPHeadersAvailable(TObject*Sender, TIdHeaderList *AHeaders, bool &VContinue)
{
Resume->Enabled = ( ((IdHTTP->Response->ResponseCode == 200) || (IdHTTP->Response->ResponseCode == 206)) && TextIsSame(AHeaders->Values["Accept-Ranges"], "bytes") );
if ((IdHTTP->Response->ContentStream) && (IdHTTP->Request->Ranges->Count > 0) && (IdHTTP->Response->ResponseCode == 200))
IdHTTP->Response->ContentStream->Size = 0;
}
#Romeo:
Also, you can try a following function to determine the real download filename.
I've translated this to C++ based on the RRUZ'function. So far so good, I'm using it on my simple IdHTTP download program, too.
But, this translation result is of course still need value improvement input from Remy Lebeau, RRUZ, or any other master here.
String __fastcall GetRemoteFileName(const String URI)
{
String result;
try
{
TIdHTTP* HTTP = new TIdHTTP(NULL);
try
{
HTTP->Head(URI);
result = HTTP->Response->RawHeaders->Params["Content-Disposition"]["filename"];
if (result.IsEmpty())
{
result = HTTP->Response->RawHeaders->Params["Content-Type"]["name"];
if (result.IsEmpty())
result = HTTP->URL->Document;
}
}
__finally
{
delete HTTP;
}
}
catch(const Exception &ex)
{
ShowMessage(const_cast<Exception&>(ex).ToString());
}
return result;
}

TaskDialogIndirect is returning an unusual error code

I'm using TaskDialogIndirect to display prompts to the user. Normally this works just fine, but sometimes, after the program has been running for a while, it begins returning an error code that the MSDN entry does not list as being one of the error codes this function can return.
0x80040001 OLE_E_ADVF "Invalid advise flags"
I have checked all the inputs to the function against previous successful calls in the same run. Aside from differences in the string to be displayed, they are identical. (the strings are even the same length.)
// create task dialog struct
TASKDIALOGCONFIG tdc;
ZeroMemory(&tdc, sizeof(TASKDIALOGCONFIG));
tdc.cbSize = sizeof(tdc);
tdc.dwFlags = (((dwMessageBoxFlags & MB_OKCANCEL) == MB_OKCANCEL) ? TDF_ALLOW_DIALOG_CANCELLATION : 0) | TDF_POSITION_RELATIVE_TO_WINDOW;
tdc.hwndParent = hwndOwner;
tdc.hInstance = LGetHInstance();
tdc.pszContent = usrText.wsz;
tdc.pButtons = _pButtons;
tdc.cButtons = nButtons;
tdc.pszMainIcon = pszTaskDialogIcon;
tdc.pszWindowTitle = usrCaption.wsz;
tdc.nDefaultButton = nDefaultButton;
// display it now
int iButton = 0;
BOOL b = 0;
HRESULT hResult = TaskDialogIndirect(&tdc, &iButton, NULL, &b);
NEW INFORMATION
At the same time that TaskDialogIndirect stops behaving correctly, ShellExecute also stops working, as does CreateFile.
This was actually caused by an event handle leak elsewhere. When the available handles ran out, no more API calls which needed to create a handle could succeed. They did return a rather odd set of error codes though, none of which was "out of handles".