* Open a sensor for use - the index passed as an argument refers to * the N'th sensor on the system. This index is the value which will * identify this sensor in future sensor events. * * This function returns a sensor identifier, or NULL if an error occurred. */
| 212 | * This function returns a sensor identifier, or NULL if an error occurred. |
| 213 | */ |
| 214 | SDL_Sensor * |
| 215 | SDL_SensorOpen(int device_index) |
| 216 | { |
| 217 | SDL_SensorDriver *driver; |
| 218 | SDL_SensorID instance_id; |
| 219 | SDL_Sensor *sensor; |
| 220 | SDL_Sensor *sensorlist; |
| 221 | const char *sensorname = NULL; |
| 222 | |
| 223 | SDL_LockSensors(); |
| 224 | |
| 225 | if (!SDL_GetDriverAndSensorIndex(device_index, &driver, &device_index)) { |
| 226 | SDL_UnlockSensors(); |
| 227 | return NULL; |
| 228 | } |
| 229 | |
| 230 | sensorlist = SDL_sensors; |
| 231 | /* If the sensor is already open, return it |
| 232 | * it is important that we have a single sensor * for each instance id |
| 233 | */ |
| 234 | instance_id = driver->GetDeviceInstanceID(device_index); |
| 235 | while (sensorlist) { |
| 236 | if (instance_id == sensorlist->instance_id) { |
| 237 | sensor = sensorlist; |
| 238 | ++sensor->ref_count; |
| 239 | SDL_UnlockSensors(); |
| 240 | return sensor; |
| 241 | } |
| 242 | sensorlist = sensorlist->next; |
| 243 | } |
| 244 | |
| 245 | /* Create and initialize the sensor */ |
| 246 | sensor = (SDL_Sensor *) SDL_calloc(sizeof(*sensor), 1); |
| 247 | if (sensor == NULL) { |
| 248 | SDL_OutOfMemory(); |
| 249 | SDL_UnlockSensors(); |
| 250 | return NULL; |
| 251 | } |
| 252 | sensor->driver = driver; |
| 253 | sensor->instance_id = instance_id; |
| 254 | sensor->type = driver->GetDeviceType(device_index); |
| 255 | sensor->non_portable_type = driver->GetDeviceNonPortableType(device_index); |
| 256 | |
| 257 | if (driver->Open(sensor, device_index) < 0) { |
| 258 | SDL_free(sensor); |
| 259 | SDL_UnlockSensors(); |
| 260 | return NULL; |
| 261 | } |
| 262 | |
| 263 | sensorname = driver->GetDeviceName(device_index); |
| 264 | if (sensorname) { |
| 265 | sensor->name = SDL_strdup(sensorname); |
| 266 | } else { |
| 267 | sensor->name = NULL; |
| 268 | } |
| 269 | |
| 270 | /* Add sensor to list */ |
| 271 | ++sensor->ref_count; |