Scanning for BLE Devices from C/C++ - c

from the "Bluetooth Device Access Guide", I've read that the Bluetooth API should be accessable from C or from C++. I've found some C-headers (IOBluetoothUserLib.h, Bluetooth.h) in the IOBluetooth framework that are related to Bluetooth and contain enumerations and data structured to define search creteria but I fail to find any function that takes such enumeration or data structure as parameter. According to the documentation I would have to create a CBCentralManager but I fail to find a way to do so from C or C++.
Background: We use OS/X as a developing plattform for devlopment of BLE enabled microcontrollers. To update firmware on this microcontrollers I want to write a BLE bootloader and I want to have a commandline client to update the firmware. All of the code is written in C++ and I wouldn't like to learn objectiv-C for this small task.
Any pointers, documentation, examples?
thank you
Torsten

According to the documentation I would have to create a CBCentralManager but I fail to find a way to do so from C or C++.
The documentation you refer to is for classic Bluetooth, for which the IOBluetooth framework has some functionality. CBCentralManager is the manager from CoreBluetooth, which is for Bluetooth LE only.
For classic Bluetooth, the manager you want is the HID Manager from the IOKit framework, documentation for which can be found here. If you search around, you'll find lots of examples of C++ usage of IOKit and IOHIDManager (1, 2).
IOKit may in fact give you all the functionality you need, but IOBluetooth supplies some Bluetooth specific features. From Developing Bluetooth Applications:
Although you don’t need to use the Bluetooth API to access a HID-class device, you may choose to use functions or methods from the Bluetooth framework to enhance the user’s experience. For example, your application can provide Bluetooth-specific information that lets the user know if a device doesn’t support a particular service.

I agreed with Henrik you'll need some glue. Look at RedBearLab guys work and precise to class.
ofxBLE. h/mm
// C++ interface //
// (Obj-C may be a superset of C, but this just makes interopability
// easier with oF)
class ofxBLE {
protected:
ofxBLEDelegate *btDelegate;
public:
ofxBLE();
~ofxBLE();
void scanPeripherals();
void sendPosition(uint8_t x, uint8_t y);
bool isConnected();
};
...
- (void)bleDidDisconnect {
NSLog(#"->Disconnected");
}
- (void)bleDidReceiveData:(unsigned char *)data length:(int)length {
}
#end
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// C++ class implementation
ofxBLE::ofxBLE() {
btDelegate = [[ofxBLEDelegate alloc] init];
}
ofxBLE::~ofxBLE() {
}
void ofxBLE::scanPeripherals(){
[btDelegate scanForPeripherals];
}
void ofxBLE::sendPosition(uint8_t x, uint8_t y) {
// position should be NORMALIZED to between 0 and 255 BEFORE
// passing into this method!
[btDelegate sendPositionX:x withY:y];
}

Related

Dead-band module not working properly for EPWM1 (TMS320F28335)

I am working on vector control of PMSM. I've got a problem with the dead-band module, and I don't understand what I'm actually doing wrong here. The register setting for EPWM modules 1 and 2 is given as follows:
For EPWM module 1 configuration
EPwm1Regs.TBPRD = PERIOD;// Period = TBCLK counts
EPwm1Regs.TBPHS.half.TBPHS = 0; // Set Phase register to zero
EPwm1Regs.TBCTL.bit.CTRMODE = TB_COUNT_UPDOWN; // Symmetrical mode
EPwm1Regs.TBCTL.bit.PHSEN = TB_DISABLE; // Master module
EPwm1Regs.TBCTL.bit.PRDLD = TB_SHADOW;
EPwm1Regs.TBCTL.bit.SYNCOSEL = TB_CTR_ZERO; // Sync down-stream module
EPwm1Regs.CMPCTL.bit.SHDWAMODE = CC_SHADOW;
EPwm1Regs.CMPCTL.bit.SHDWBMODE = CC_SHADOW;
EPwm1Regs.CMPCTL.bit.LOADAMODE = CC_CTR_ZERO; // load on CTR=Zero
EPwm1Regs.CMPCTL.bit.LOADBMODE = CC_CTR_ZERO; // load on CTR=Zero
EPwm1Regs.AQCTLA.bit.CAU = AQ_SET; // set actions for EPWM1A
EPwm1Regs.AQCTLA.bit.CAD = AQ_CLEAR;
EPwm1Regs.DBCTL.bit.OUT_MODE = DB_FULL_ENABLE; // enable Dead-band module
EPwm1Regs.DBCTL.bit.POLSEL = DB_ACTV_HIC; // Active Hi complementary
EPwm1Regs.DBFED = DEAD_TIME; //
EPwm1Regs.DBRED = DEAD_TIME; //
For EPWM Module 2 Configuration
EPwm2Regs.TBPRD = PERIOD; // Period = 1600 TBCLK counts
EPwm2Regs.TBPHS.half.TBPHS = 0; // Set Phase register to zero
EPwm2Regs.TBCTL.bit.CTRMODE = TB_COUNT_UPDOWN; // Symmetrical mode
EPwm2Regs.TBCTL.bit.PHSEN = TB_ENABLE; // Slave module
EPwm2Regs.TBCTL.bit.PRDLD = TB_SHADOW;
EPwm2Regs.TBCTL.bit.SYNCOSEL = TB_SYNC_IN; // sync flow-through
EPwm2Regs.CMPCTL.bit.SHDWAMODE = CC_SHADOW;
EPwm2Regs.CMPCTL.bit.SHDWBMODE = CC_SHADOW;
EPwm2Regs.CMPCTL.bit.LOADAMODE = CC_CTR_ZERO; // load on CTR=Zero
EPwm2Regs.CMPCTL.bit.LOADBMODE = CC_CTR_ZERO; // load on CTR=Zero
EPwm2Regs.AQCTLA.bit.CAU = AQ_SET; // set actions for EPWM2A
EPwm2Regs.AQCTLA.bit.CAD = AQ_CLEAR;
EPwm2Regs.DBCTL.bit.OUT_MODE = DB_FULL_ENABLE; // enable Dead-band module
EPwm2Regs.DBCTL.bit.POLSEL = DB_ACTV_HIC; // Active Hi complementary
EPwm2Regs.DBFED = DEAD_TIME; //
EPwm2Regs.DBRED = DEAD_TIME; //
I'm following an example (3.4) from the technical manual "sprug04a."
the compare values are initially initialized as
EPwm1Regs.CMPA.half.CMPA = 0; // adjust duty for output EPWM1A
EPwm2Regs.CMPA.half.CMPA = 0; // adjust duty for output EPWM2A
and compare values are updated in the code like:
EPwm1Regs.CMPA.half.CMPA = PERIOD - Sa;
EPwm2Regs.CMPA.half.CMPA = PERIOD - Sb;
where S_ab are the values obtained from modulation technique.
EPWM2 module is working well but EPWM1 isn't working. we are suppose to have EPWM1A complimentary signal across EPWM1B but EPWM1B shows same as EPWM1A. The scope is attached for better understanding. Need recommendation in this regards.EPWM1A&B EPWM2A&B reference, what should i need to check? as i checked technical manual and example codes but still i didnt get what i am doing wrong. Your suggestions will be valuable in this regards.

How can I get screenshot from all displays with X11?

I was working on writing a screenshot thing, and found this excellent topic for Mac: How can I get screenshot from all displays on MAC?
I was wondering if anyone has the equivalent for x11 library? To get all the monitors and then screenshot them all?
I had found this topic: https://stackoverflow.com/a/5293559/1828637
But the code linked from there is not as easy to follow for a novice like me.
Will RootWindow(3) get the area of all the monitors combined? Then I can go through and get the monitors dimensions then XGetImage those sections on the return of RootWindow?
I had come across this topic: How do take a screenshot correctly with xlib? But I'm not sure if it has multi-monitor support. I do this in ctypes so I cant test that code easily without going through the grueling task of writing it first. So I was wondering if this is correct or how would I modify it to handle multi mon please?
Edit
The poster there shared his code, it is seen here: https://github.com/Lalaland/ScreenCap/blob/master/src/screenCapturerImpl.cpp#L96 but it's complicated and I don't understand it. It uses functions like XFixesGetCursorImage which I can't find in the documentation, and I don't see how the multi monitors work there. Author of that topic warned he doesn't remember the code and it may not work with modern Linux.
This is not a perfect answer to the question, but the following code could be modified to get a very fast version of your desired end result:
https://github.com/Clodo76/vr-desktop-mirror/blob/master/DesktopCapture/main.cpp
The DesktopCapturePlugin_Initialize method converts all the displays into objects:
UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API DesktopCapturePlugin_Initialize()
{
DesksClean();
g_needReinit = 0;
IDXGIFactory1* factory;
CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory));
IDXGIAdapter1* adapter;
for (int i = 0; (factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND); ++i)
{
IDXGIOutput* output;
for (int j = 0; (adapter->EnumOutputs(j, &output) != DXGI_ERROR_NOT_FOUND); j++)
{
DXGI_OUTPUT_DESC outputDesc;
output->GetDesc(&outputDesc);
MONITORINFOEX monitorInfo;
monitorInfo.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(outputDesc.Monitor, &monitorInfo);
// Maybe in future add a function to identify the primary monitor.
//if (monitorInfo.dwFlags == MONITORINFOF_PRIMARY)
{
int iDesk = DeskAdd();
g_desks[iDesk].g_width = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left;
g_desks[iDesk].g_height = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top;
auto device = g_unity->Get<IUnityGraphicsD3D11>()->GetDevice();
IDXGIOutput1* output1;
output1 = reinterpret_cast<IDXGIOutput1*>(output);
output1->DuplicateOutput(device, &g_desks[iDesk].g_deskDupl);
}
output->Release();
}
adapter->Release();
}
factory->Release();
}
Then the OnRenderEvent method copies a frame from the display into a texture (provided by unity in this case):
void UNITY_INTERFACE_API OnRenderEvent(int eventId)
{
for (int iDesk = 0; iDesk < g_nDesks; iDesk++)
{
if (g_desks[iDesk].g_deskDupl == nullptr || g_desks[iDesk].g_texture == nullptr)
{
g_needReinit++;
return;
}
IDXGIResource* resource = nullptr;
const UINT timeout = 0; // ms
HRESULT resultAcquire = g_desks[iDesk].g_deskDupl->AcquireNextFrame(timeout, &g_desks[iDesk].g_frameInfo, &resource);
if (resultAcquire != S_OK)
{
g_needReinit++;
return;
}
g_desks[iDesk].g_isPointerVisible = (g_desks[iDesk].g_frameInfo.PointerPosition.Visible == TRUE);
g_desks[iDesk].g_pointerX = g_desks[iDesk].g_frameInfo.PointerPosition.Position.x;
g_desks[iDesk].g_pointerY = g_desks[iDesk].g_frameInfo.PointerPosition.Position.y;
ID3D11Texture2D* texture;
HRESULT resultQuery = resource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&texture));
resource->Release();
if (resultQuery != S_OK)
{
g_needReinit++;
return;
}
ID3D11DeviceContext* context;
auto device = g_unity->Get<IUnityGraphicsD3D11>()->GetDevice();
device->GetImmediateContext(&context);
context->CopyResource(g_desks[iDesk].g_texture, texture);
g_desks[iDesk].g_deskDupl->ReleaseFrame();
}
g_needReinit = 0;
}

C header Python

I' m trying to import a .so library into a python code to use c functions. I think using
from ctypes import *
import ctypes
lib = CDLL('./libcaenhvwrapper.so.5.56')
is working fine. I need to use some user defined types which are defined in a header file
but I cannot access them.
thank you in advance
The types are not in the .so file that the ctypes module loads.
C types don't work like that, they're declared in the header and you must have the header to use a (C) library, even from C.
You're going to have to use the various ctypes APIs to re-create the types in Python. See this part of the tutorial, for instance, for how to work with struct and union types.
Now my code works with a normal c library, but I need to use a .so library from Caen and I
get Segmentation fault. This is the code:
from ctypes import *
lib = CDLL('./libcaenhvwrapper.so.5.56')
lib.CAENHVInitSystem.restype = c_int
lib.CAENHVInitSystem.argtypes = [c_int, c_int, c_char_p, c_char_p, c_char_p]
lib.CAENHVGetError.restype = c_int
CAENHV_SYSTEM_TYPE_t = c_int
sy1527 = CAENHV_SYSTEM_TYPE_t(0)
sy2527 = CAENHV_SYSTEM_TYPE_t(1)
sy4527 = CAENHV_SYSTEM_TYPE_t(2)
sy5527 = CAENHV_SYSTEM_TYPE_t(3)
n568 = CAENHV_SYSTEM_TYPE_t(4)
v65xx = CAENHV_SYSTEM_TYPE_t(5)
n1470 = CAENHV_SYSTEM_TYPE_t(6)
v8100 = CAENHV_SYSTEM_TYPE_t(7)
link = c_int
LINKTYPE_TCPIP = link(0)
LINKTYPE_RS232 = link(1)
LINKTYPE_CAENET = link(2)
LINKTYPE_USB = link(3)
LINKTYPE_OPTLINK = link(4)
LINKTYPE_USB_VCP = link(5)
string15=c_char*15
address=string15('1','3','7','.','1','3','8','.','1','3','.','2','0','3','\0')
userName = c_char_p('user')
passwd = c_char_p('user')
ret_init = lib.CAENHVInitSystem(0, 0, address, userName, passwd)
when I try to call the function I get a segmentation fault. I think the types are correctly defined.
Below you can see a piece of code which works ok.
from ctypes import *
lib2 = CDLL('/lib64/libc.so.6')
string15=c_char*15
address=string15('1','3','7','.','1','3','8','.','1','3','.','2','0','3','\0')
address1=create_string_buffer('137.138.13.203')
address2=c_char_p('137.138.13.200')
userName = c_char_p('user')
passwd = c_char_p('user')
a= lib2.strncmp(address, userName, c_int(4))
a= lib2.strncmp(userName, address, 4)
a= lib2.strncmp(address2, address, 15)
lib2.printf('%d\n', ret_init)
lib2.printf('%s\n', address)
lib2.printf('%s\n', address1)
lib2.printf('%s\n', address2)
lib2.printf('%d\n', lib2.strlen(address))
lib2.printf('%d\n', lib2.strlen(address1))
lib2.printf('%d\n', lib2.strlen(address2))

Dart VM itself implement `eval` in `dart:mirrors` and developers use it. Are planned to make this method public?

Here is code that use this eval method in Dart platform.
This is done via reflection.
runtime/lib/mirrors_impl.dart
_getFieldSlow(unwrapped) {
// ..... Skipped
var atPosition = unwrapped.indexOf('#');
if (atPosition == -1) {
// Public symbol.
f = _eval('(x) => x.$unwrapped', null);
} else {
// Private symbol.
var withoutKey = unwrapped.substring(0, atPosition);
var privateKey = unwrapped.substring(atPosition);
f = _eval('(x) => x.$withoutKey', privateKey);
}
// ..... Skipped
}
static _eval(expression, privateKey)
native "Mirrors_evalInLibraryWithPrivateKey";
runtime/lib/mirrors.cc
DEFINE_NATIVE_ENTRY(Mirrors_evalInLibraryWithPrivateKey, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(String, expression, arguments->NativeArgAt(0));
GET_NATIVE_ARGUMENT(String, private_key, arguments->NativeArgAt(1));
const GrowableObjectArray& libraries =
GrowableObjectArray::Handle(isolate->object_store()->libraries());
const int num_libraries = libraries.Length();
Library& each_library = Library::Handle();
Library& ctxt_library = Library::Handle();
String& library_key = String::Handle();
if (library_key.IsNull()) {
ctxt_library = Library::CoreLibrary();
} else {
for (int i = 0; i < num_libraries; i++) {
each_library ^= libraries.At(i);
library_key = each_library.private_key();
if (library_key.Equals(private_key)) {
ctxt_library = each_library.raw();
break;
}
}
}
ASSERT(!ctxt_library.IsNull());
return ctxt_library.Evaluate(expression);
runtime/vm/bootstrap_natives.h
V(Mirrors_evalInLibraryWithPrivateKey, 2) \
P.S.
I ask question here becuase I cannot ask it at Dart mail lists.
P.S.
As we can see it static private method in mirrors_impl.dart:
static _eval(expression, privateKey) native "Mirrors_evalInLibraryWithPrivateKey";
Does anyone want that this method should be public? (this is not a question but just a thought aloud).
According to the Dart FAQ a pure string eval like that is not likely to make it into the language, even though other dynamic features will likely be added:
So, for example, Dart isn’t likely to support evaluating a string as
code in the current context, but it may support loading that code
dynamically into a new isolate. Dart isn’t likely to support adding
fields to a value, but it may (through a mirror system) support adding
fields to a class, and you can effectively add methods using
noSuchMethod(). Using these features will have a runtime cost; it’s
important to us to minimize the cost for programs that don’t use them.
This area is still under development, so we welcome your thoughts on
what you need from runtime dynamism.

Multi-language GUI setup with a string array

I am working on the Keil uv4 IDE with an ARM Cortex-M3 in a bare metal C application. I have a GUI that I created that is currently in English, but I would like to give the user the ability to go between other languages like you can on a cell phone.
I have created a structure with all the words that are used called string_table_t.
struct string_table_t
{
char *word1;
char *word2;
char *word3;
};
My thought process was to have plain text files for the different languages and the list of words used contained in each one. Then I would do a load function that would link the pointers of the string table with the actual word.
Now, my initial menu is created statically by defining it like so. It is based off of Altium software platform.
// Test structure
struct string_table_t string_table = {"Main Menu","test1","test2"};
form_t mainmenu_form =
{
.obj.x = 0,
.obj.y = 0,
.obj.width = 240,
.obj.height = 320,
.obj.draw = form_draw,
.obj.handler = mainmenu_form_handler,
.obj.parent = NULL,
.obj.agui_index = 0,
.obj.visible = __TRUE,
.obj.enabled = __TRUE,
.caption.x = 0,
.caption.y = 0,
.caption.text = "Main Menu",
.caption.font = &helveticaneueltstdltext18_2BPP,
.caption.color = RGB(230,230,230),
.caption_line_color = RGB(241,101,33),
.caption.fontstyle = FS_NONE,
.caption.align = ALIGN_CENTRE,
.captionbarcolor = RGB(88,89,91),
.children = mainmenu_children,
.n_children = 4,
.relief = RELIEF_NONE,
.color = RGB(65,64,66),
};
What I want to do is replace the "Main Menu" of the caption.text with string_table.word1. Therefore, if I load a different language set, the menu will automatically be pointing to the correct char array. Doing this currently results in a error expression must have a constant value.
Now, I can get this to work by leaving the text null in the menu component and adding:
Link_pointer_to_menu() {
mainmenu_form.caption.text = string_table.Main_menu_text;
}
This will compile and work, but I would rather not have to have 100 or so of these statements. Is there a more optimal way of doing this?
I would recommend something like that:
enum MyWords
{
msgHello,
msgOpen,
msgClose,
msgMainMenu,
num_Messages,
};
char *string_table_t[num_Messages];
You should write code that loads your language file and assigns pointers in this array. After that in your code:
.caption.text = string_table_t[msgMainMenu];
The idea is that you give each string a symbolic name that is an offset in the table of strings. After that you use this offset as an index into the table.

Resources