* @brief This function will open a device. * * @param dev is the pointer of device driver structure. * * @param oflag is the flags for device open. * * @return the result, RT_EOK on successfully. */
| 220 | * @return the result, RT_EOK on successfully. |
| 221 | */ |
| 222 | rt_err_t rt_device_open(rt_device_t dev, rt_uint16_t oflag) |
| 223 | { |
| 224 | rt_err_t result = RT_EOK; |
| 225 | |
| 226 | /* parameter check */ |
| 227 | RT_ASSERT(dev != RT_NULL); |
| 228 | RT_ASSERT(rt_object_get_type(&dev->parent) == RT_Object_Class_Device); |
| 229 | |
| 230 | /* if device is not initialized, initialize it. */ |
| 231 | if (!(dev->flag & RT_DEVICE_FLAG_ACTIVATED)) |
| 232 | { |
| 233 | if (device_init != RT_NULL) |
| 234 | { |
| 235 | result = device_init(dev); |
| 236 | if (result != RT_EOK) |
| 237 | { |
| 238 | LOG_E("To initialize device:%.*s failed. The error code is %d", |
| 239 | RT_NAME_MAX, dev->parent.name, result); |
| 240 | |
| 241 | return result; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | dev->flag |= RT_DEVICE_FLAG_ACTIVATED; |
| 246 | } |
| 247 | |
| 248 | /* device is a stand alone device and opened */ |
| 249 | if ((dev->flag & RT_DEVICE_FLAG_STANDALONE) && |
| 250 | (dev->open_flag & RT_DEVICE_OFLAG_OPEN)) |
| 251 | { |
| 252 | return -RT_EBUSY; |
| 253 | } |
| 254 | |
| 255 | /* device is not opened or opened by other oflag, call device_open interface */ |
| 256 | if (!(dev->open_flag & RT_DEVICE_OFLAG_OPEN) || |
| 257 | ((dev->open_flag & RT_DEVICE_OFLAG_MASK) != ((oflag & RT_DEVICE_OFLAG_MASK) | RT_DEVICE_OFLAG_OPEN))) |
| 258 | { |
| 259 | if (device_open != RT_NULL) |
| 260 | { |
| 261 | result = device_open(dev, oflag); |
| 262 | } |
| 263 | else |
| 264 | { |
| 265 | /* set open flag */ |
| 266 | dev->open_flag = (oflag & RT_DEVICE_OFLAG_MASK); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /* set open flag */ |
| 271 | if (result == RT_EOK || result == -RT_ENOSYS) |
| 272 | { |
| 273 | dev->open_flag |= RT_DEVICE_OFLAG_OPEN; |
| 274 | |
| 275 | dev->ref_count++; |
| 276 | /* don't let bad things happen silently. If you are bitten by this assert, |
| 277 | * please set the ref_count to a bigger type. */ |
| 278 | RT_ASSERT(dev->ref_count != 0); |
| 279 | } |