Skip to content

Instantly share code, notes, and snippets.

@makotokato
Created April 4, 2012 07:15
Show Gist options
  • Save makotokato/2299427 to your computer and use it in GitHub Desktop.
Save makotokato/2299427 to your computer and use it in GitHub Desktop.
Windows Sensor API test
#include <olectl.h>
#include <sensorsapi.h>
#include <sensors.h>
#include <stdio.h>
#pragma comment(lib, "sensorsapi.lib")
#pragma comment(lib, "PortableDeviceGUIDs.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "user32.lib")
class SensorEvent : public ISensorEvents {
public:
SensorEvent() : mCount(0) {
}
// IUnknown interface
STDMETHODIMP_(ULONG) AddRef() {
return InterlockedIncrement(&mCount);
}
STDMETHODIMP_(ULONG) Release() {
ULONG count = InterlockedDecrement(&mCount);
if (!count) {
delete this;
return 0;
}
return count;
}
STDMETHODIMP QueryInterface(REFIID iid, void** ppv) {
if (iid == IID_IUnknown) {
*ppv = static_cast<IUnknown*>(this);
} else if (iid == IID_ISensorEvents) {
*ppv = static_cast<ISensorEvents*>(this);
} else {
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
// ISensorEvents interface
STDMETHODIMP OnEvent(ISensor *aSensor, REFGUID aId, IPortableDeviceValues *aData) {
return S_OK;
}
STDMETHODIMP OnLeave(REFSENSOR_ID aId) {
return S_OK;
}
STDMETHODIMP OnStateChanged(ISensor *aSensor, SensorState state) {
return S_OK;
}
STDMETHODIMP OnDataUpdated(ISensor *aSensor, ISensorDataReport *aReport) {
printf("Updated\n");
return S_OK;
}
private:
ULONG mCount;
};
void sensor()
{
// Test is test. COM interface will be leak...
ISensorManager *manager;
ISensorCollection *collection;
if (FAILED(CoCreateInstance(CLSID_SensorManager, NULL, CLSCTX_INPROC_SERVER,
IID_ISensorManager, (void**)&manager)))
return;
if (FAILED(manager->GetSensorsByType(SENSOR_TYPE_ACCELEROMETER_3D,
&collection)))
return;
ULONG count = 0;
collection->GetCount(&count);
if (!count)
return;
ISensor *sensor;
collection->GetAt(0, &sensor);
if (!sensor)
return;
IPortableDeviceValues* values;
if (SUCCEEDED(CoCreateInstance(CLSID_PortableDeviceValues, NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(void**)&values))) {
if (SUCCEEDED(values->SetUnsignedIntegerValue(
SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL,
5000))) {
IPortableDeviceValues* returns;
sensor->SetProperties(values, &returns);
}
}
SensorEvent* event = new SensorEvent();
ISensorEvents *sensorEvents;
if (FAILED(event->QueryInterface(IID_ISensorEvents,
(void**)&sensorEvents))) {
printf("WWW\n");
return;
}
sensor->SetEventSink(sensorEvents);
}
int main()
{
CoInitialize(NULL);
sensor();
MSG msg;
while (true) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
CoUninitialize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment