File size: 7,685 Bytes
ef17c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-    */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */

/*
  Author(s):  Anton Deguet
  Created on: 2024-01-25

  (C) Copyright 2024 Johns Hopkins University (JHU), All Rights Reserved.

--- begin cisst license - do not edit ---

This software is provided "as is" under an open source license, with
no warranty.  The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.

--- end cisst license ---
*/

#include <hidapi/hidapi.h>

#include <sawIntuitiveResearchKit/mtsHIDHeadSensor.h>

#include <cisstMultiTask/mtsInterfaceProvided.h>

CMN_IMPLEMENT_SERVICES_DERIVED_ONEARG(mtsHIDHeadSensor, mtsTaskContinuous, mtsTaskContinuousConstructorArg)

class mtsHIDHeadSensorData
{
public:
    hid_device * handle;
};

mtsHIDHeadSensor::mtsHIDHeadSensor(const std::string & componentName):
    mtsTaskContinuous(componentName)
{
    Init();
}

mtsHIDHeadSensor::mtsHIDHeadSensor(const mtsTaskContinuousConstructorArg & arg):
    mtsTaskContinuous(arg)
{
    Init();
}

void mtsHIDHeadSensor::Init(void)
{
    m_data = new mtsHIDHeadSensorData;

    m_interface = AddInterfaceProvided("operator_present");
    if (m_interface) {
        m_interface->AddEventWrite(m_events.operator_present,
                                   "Button", prmEventButton());
    }
}

void mtsHIDHeadSensor::EnumerateDevices(void) const
{
    struct hid_device_info *devs, *cur_dev;
    devs = hid_enumerate(0x0, 0x0);
    cur_dev = devs;
    while (cur_dev) {
        printf("Device Found\n  type: %04hx %04hx\n  path: %s\n  serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
        printf("\n");
        printf("  Manufacturer: %ls\n", cur_dev->manufacturer_string);
        printf("  Product:      %ls\n", cur_dev->product_string);
        printf("  Release:      %hx\n", cur_dev->release_number);
        printf("  Interface:    %d\n",  cur_dev->interface_number);
        printf("\n");
        cur_dev = cur_dev->next;
    }
    hid_free_enumeration(devs);
}

void mtsHIDHeadSensor::Configure(const std::string & filename)
{
    try {
        std::ifstream jsonStream;
        Json::Value jsonConfig;
        Json::Reader jsonReader;

        jsonStream.open(filename.c_str());
        if (!jsonReader.parse(jsonStream, jsonConfig)) {
            CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                     << ": failed to parse configuration file \""
                                     << filename << "\"\n"
                                     << jsonReader.getFormattedErrorMessages();
            exit(EXIT_FAILURE);
        }

        CMN_LOG_CLASS_INIT_VERBOSE << "Configure: " << this->GetName()
                                   << " using file \"" << filename << "\"" << std::endl
                                   << "----> content of configuration file: " << std::endl
                                   << jsonConfig << std::endl
                                   << "<----" << std::endl;

        // base component configuration
        mtsComponent::ConfigureJSON(jsonConfig);

        // deserialize configuration
        cmnDataJSON<mtsHIDHeadSensorConfiguration>::DeSerializeText(m_configuration, jsonConfig);

    } catch (std::exception & e) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName() << ": parsing file \""
                                 << filename << "\", got error: " << e.what() << std::endl;
        exit(EXIT_FAILURE);
    } catch (...) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName() << ": make sure the file \""
                                 << filename << "\" is in JSON format" << std::endl;
        exit(EXIT_FAILURE);
    }

    // initialize hid
    if (hid_init()) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName() << ": hid_init failed!" << std::endl;
    }

    // open the device
    m_data->handle = hid_open(std::stoul(m_configuration.id_vendor, nullptr, 16),
                              std::stoul(m_configuration.id_product, nullptr, 16),
                              NULL);

    // if the device is not found, enumerate existing ones
    if (!m_data->handle) {
        CMN_LOG_CLASS_INIT_ERROR << "Configure " << this->GetName()
                                 << ": failed to find device based on configuration: " << std::endl
                                 << m_configuration << std::endl;
        EnumerateDevices();
        exit(EXIT_FAILURE);
    } else {
        // show some information for debugging
        int res;
        const int MAX_STR = 255;
        wchar_t wstr[MAX_STR];

        // Read the Manufacturer String
        wstr[0] = 0x0000;
        res = hid_get_manufacturer_string(m_data->handle, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read manufacturer string\n");
        printf("Manufacturer String: %ls\n", wstr);

        // Read the Product String
        wstr[0] = 0x0000;
        res = hid_get_product_string(m_data->handle, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read product string\n");
        printf("Product String: %ls\n", wstr);

        // Read the Serial Number String
        wstr[0] = 0x0000;
        res = hid_get_serial_number_string(m_data->handle, wstr, MAX_STR);
        if (res < 0)
            printf("Unable to read serial number string\n");
        printf("Serial Number String: (%d) %ls", wstr[0], wstr);
        printf("\n");
    }
}


void mtsHIDHeadSensor::Startup(void)
{
}


void mtsHIDHeadSensor::Run(void)
{
    ProcessQueuedCommands();

    if (!m_data->handle) {
        return;
    }

    unsigned char buf[256];
    int res;

    // request state (cmd 0x81). The first byte is the report number (0x1).
    memset(buf,0x00,sizeof(buf));
    buf[0] = 0x1;
    buf[1] = 0x81;
    res = hid_write(m_data->handle, buf, 17);
    if (res < 0) {
        m_data->handle = nullptr;
        CMN_LOG_CLASS_RUN_ERROR << "Run " << this->GetName()
                                << ": failed to write to device: " << std::endl
                                << m_configuration << std::endl;
        return;
    }

    // read requested state
    res = 0;
    res = hid_read(m_data->handle, buf, sizeof(buf));
    if (res < 0) {
        m_data->handle = nullptr;
        CMN_LOG_CLASS_RUN_ERROR << "Run " << this->GetName()
                                << ": failed to read from device: " << std::endl
                                << m_configuration << std::endl;
        return;
    }

    bool present;

    if (m_configuration.index_data < static_cast<size_t>(res)) {
        present = buf[m_configuration.index_data];
    } else {
        m_data->handle = nullptr;
        CMN_LOG_CLASS_RUN_ERROR << "Run " << this->GetName()
                                << ": invalid data index for device: " << std::endl
                                << m_configuration << std::endl
                                << "Device returned " << res << " data elements" << std::endl;
        return;
    }

    // nothing has changed, don't do anything
    if (m_operating_present == present) {
        return;
    }

    // changed
    m_operating_present = present;
    prmEventButton payload;
    payload.SetValid(true);
    payload.SetTimestamp(StateTable.GetTic());
    if (m_operating_present) {
        payload.SetType(prmEventButton::PRESSED);
        m_events.operator_present(payload);
    } else {
        payload.SetType(prmEventButton::RELEASED);
        m_events.operator_present(payload);
    }
}


void mtsHIDHeadSensor::Cleanup(void)
{
}