void CudaModule::staticInit(void) { if (s_inited) { return; } s_inited = true; s_available = false; checkError("cuInit", cuInit(0)); s_available = true; s_device = selectDevice(); printDeviceInfo(s_device); U32 flags = 0; flags |= CU_CTX_SCHED_SPIN; // use sync() if you want to yield #if (CUDA_VERSION >= 2030) if (getDriverVersion() >= 23) { // reduce launch overhead with large localmem flags |= CU_CTX_LMEM_RESIZE_TO_MAX; } #endif // OpenGL & window context must have been initialized ! checkError("cuGLCtxCreate", cuGLCtxCreate( &s_context, flags, s_device)); checkError("cuEventCreate", cuEventCreate(&s_startEvent, 0)); checkError("cuEventCreate", cuEventCreate(&s_endEvent, 0)); }
int VideoCaptureV4L2::printVerboseInfo() { if(!is_opened) { printf("ERROR: cannot print verbose info when no device has been opened.\n"); return 0; } return printDeviceInfo(fd); }
void printDeviceInfo(const std::vector<boost::compute::device> & devs) { for (const boost::compute::device & dev : devs) { printDeviceInfo(dev); } }
void OpenCLPrinter::printContextInfo(cl::Context context) { print("--- ContextInfo ---", ""); VECTOR_CLASS<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); print("Number of devices", devices.size()); for(int i=0; i<devices.size(); ++i) printDeviceInfo(devices[i]); }
void BrcmPatchRAM::uploadFirmware() { // signal to timer that firmware already loaded mDevice.setProperty(kFirmwareLoaded, true); // don't bother with devices that have no firmware if (!getProperty(kFirmwareKey)) return; if (!mDevice.open(this)) { AlwaysLog("uploadFirmware could not open the device!\n"); return; } //REVIEW: this block to avoid merge conflicts (remove once merged) ////if (mDevice.open(this)) { // Print out additional device information printDeviceInfo(); // Set device configuration to composite configuration index 0 // Obtain first interface if (setConfiguration(0) && findInterface(&mInterface) && mInterface.open(this)) { DebugLog("set configuration and interface opened\n"); mInterface.findPipe(&mInterruptPipe, kUSBInterrupt, kUSBIn); mInterface.findPipe(&mBulkPipe, kUSBBulk, kUSBOut); if (mInterruptPipe.getValidatedPipe() && mBulkPipe.getValidatedPipe()) { DebugLog("got pipes\n"); if (performUpgrade()) if (mDeviceState == kUpdateComplete) AlwaysLog("[%04x:%04x]: Firmware upgrade completed successfully.\n", mVendorId, mProductId); else AlwaysLog("[%04x:%04x]: Firmware upgrade not needed.\n", mVendorId, mProductId); else AlwaysLog("[%04x:%04x]: Firmware upgrade failed.\n", mVendorId, mProductId); OSSafeReleaseNULL(mReadBuffer); // mReadBuffer is allocated by performUpgrade but not released } mInterface.close(this); } // cleanup if (mInterruptPipe.getValidatedPipe()) { mInterruptPipe.abort(); mInterruptPipe.setPipe(NULL); } if (mBulkPipe.getValidatedPipe()) { mBulkPipe.abort(); mBulkPipe.setPipe(NULL); } mInterface.setInterface(NULL); mDevice.close(this); } }
void printDevices() { vector<Device> pending = deviceManager.getPendingDevices(); vector<Device> devices = deviceManager.getDevices(); cout << "\nDevices Pending: \n"; for (int i = 0; i < pending.size(); i++) { printDeviceInfo(pending[i]); cout << "\n\n"; } cout << "\nDevices Active: \n"; for (int i = 0; i < devices.size(); i++) { printDeviceInfo(devices[i]); cout << "\n\n"; } cout << "\n"; }
/** * Callback that * - displays the devices that have been inserted into and removed from the system. * - requests the firmware version of any devices that have been inserted into the system. * Implements freespace_hotplugCallback * @param event The type of event. * @param id The affected device. * @param cookie Not used for this application. */ void hotplugCallback(enum freespace_hotplugEvent event, FreespaceDeviceId id, void* cookie) { int rc; struct freespace_message message; switch (event) { case FREESPACE_HOTPLUG_INSERTION: // Get and print USB HID information about the device. printf("Device Inserted: %d\n", id); rc = printDeviceInfo(id); if (rc != FREESPACE_SUCCESS) { printf("Could not display device info: %d\n", rc); return; } // Open the device to be able to communicate with it rc = freespace_openDevice(id); if (rc != FREESPACE_SUCCESS) { printf("Error opening device.\n"); return; } // Set the handler that handles messages received from the device. freespace_setReceiveMessageCallback(id, receiveMessageCallback, NULL); // Create and send a product ID request message to the device memset(&message, 0, sizeof(message)); // Start with a clean message struct message.messageType = FREESPACE_MESSAGE_PRODUCTIDREQUEST; // Allow message.dest to have the default value of 0. This will cause the message // to go to the remote or the module rc = freespace_sendMessageAsync(id, &message, 100, NULL, 0); if (rc != FREESPACE_SUCCESS) { printf("Error sending productID request\n"); return; } // To communicate with a dongle set the dest field to 1 message.dest = 1; rc = freespace_sendMessageAsync(id, &message, 100, NULL, 0); if (rc != FREESPACE_SUCCESS) { printf("Error sending productID request\n"); return; } break; case FREESPACE_HOTPLUG_REMOVAL: printf("Device Removed: %d\n", id); break; default: printf("Unrecognized freespace_hotplugEvent.\n"); break; } }
void iqrcommon::moduleUSBVideoColorPT::init(){ // cout << "moduleUSBVideoColorPT::init()" << endl; clsPanTilt->init(); moduleUSBVideoColor::init(); ioctl(device_fd, VIDIOCPWCMPTGRANGE, &sPwc_mpt_range); fPanRange = abs(sPwc_mpt_range.pan_min - sPwc_mpt_range.pan_max); fTiltRange = abs(sPwc_mpt_range.tilt_min - sPwc_mpt_range.tilt_max); printDeviceInfo(); resetPanTilt(); }
void BrcmPatchRAM::uploadFirmware() { // get firmware here to pre-cache for eventual use on wakeup or now BrcmFirmwareStore* firmwareStore = getFirmwareStore(); OSArray* instructions = NULL; if (!firmwareStore || !firmwareStore->getFirmware(OSDynamicCast(OSString, getProperty(kFirmwareKey)))) return; if (mDevice->open(this)) { // Print out additional device information printDeviceInfo(); // Set device configuration to composite configuration index 0 // Obtain first interface if (setConfiguration(0) && (mInterface = findInterface()) && mInterface->open(this)) { mInterruptPipe = findPipe(kUSBInterrupt, kUSBIn); mBulkPipe = findPipe(kUSBBulk, kUSBOut); if (mInterruptPipe && mBulkPipe) { if (performUpgrade()) AlwaysLog("[%04x:%04x]: Firmware upgrade completed successfully.\n", mVendorId, mProductId); else AlwaysLog("[%04x:%04x]: Firmware upgrade failed.\n", mVendorId, mProductId); OSSafeReleaseNULL(mReadBuffer); // mReadBuffer is allocated by performUpgrade but not released } mInterface->close(this); } // cleanup if (mInterruptPipe) { mInterruptPipe->Abort(); mInterruptPipe->release(); // retained in findPipe mInterruptPipe = NULL; } if (mBulkPipe) { mBulkPipe->Abort(); mBulkPipe->release(); // retained in findPipe mBulkPipe = NULL; } OSSafeReleaseNULL(mInterface);// retained in findInterface mDevice->close(this); } }
void BrcmPatchRAM::uploadFirmware() { // signal to timer that firmware already loaded mDevice->setProperty(kFirmwareLoaded, true); if (mDevice->open(this)) { // Print out additional device information printDeviceInfo(); // Set device configuration to composite configuration index 0 // Obtain first interface if (setConfiguration(0) && (mInterface = findInterface()) && mInterface->open(this)) { mInterruptPipe = findPipe(kUSBInterrupt, kUSBIn); mBulkPipe = findPipe(kUSBBulk, kUSBOut); if (mInterruptPipe && mBulkPipe) { if (performUpgrade()) AlwaysLog("[%04x:%04x]: Firmware upgrade completed successfully.\n", mVendorId, mProductId); else AlwaysLog("[%04x:%04x]: Firmware upgrade failed.\n", mVendorId, mProductId); OSSafeReleaseNULL(mReadBuffer); // mReadBuffer is allocated by performUpgrade but not released } mInterface->close(this); } // cleanup if (mInterruptPipe) { mInterruptPipe->Abort(); mInterruptPipe->release(); // retained in findPipe mInterruptPipe = NULL; } if (mBulkPipe) { mBulkPipe->Abort(); mBulkPipe->release(); // retained in findPipe mBulkPipe = NULL; } OSSafeReleaseNULL(mInterface);// retained in findInterface mDevice->close(this); } }
void OpenCLPrinter::printPlatformAndDeviceInfo() { VECTOR_CLASS<cl::Platform> platforms; cl::Platform::get(&platforms); VECTOR_CLASS<cl::Device> devices; for(unsigned int i = 0; i < platforms.size(); i++) { printPlatformInfo(platforms[i]); platforms[i].getDevices(CL_DEVICE_TYPE_ALL, &devices); for(unsigned int j = 0; j < devices.size(); j++) { printDeviceInfo(devices[j]); } } print("Number of platforms", platforms.size()); print("Number of devices", devices.size()); }
// print info about the all audio devices to stdout. void printDevicesInfo( void ) { PaError err; int numDevices; messagePrintf( ( "Printing audio devices information...\n" ) ); err = Pa_Initialize(); if( err != paNoError ) { errorPrintf( ( "ERROR: Pa_Initialize returned 0x%x.\n", err ) ); goto error; } messagePrintf( ( "PortAudio version: 0X%08X\n", Pa_GetVersion() ) ); messagePrintf( ( "Version text: '%s'\n", Pa_GetVersionText() ) ); numDevices = Pa_GetDeviceCount(); if( numDevices < 0 ) { errorPrintf( ( "ERROR: Pa_GetDeviceCount returned 0x%x.\n", numDevices ) ); goto error; } messagePrintf( ( "Number of devices = %d\n", numDevices ) ); for( int i = 0; i < numDevices; i++ ) printDeviceInfo( i ); Pa_Terminate(); return; error: Pa_Terminate(); errorPrintf( ( "Error number: %d\n", err ) ); errorPrintf( ( "Error message: %s\n", Pa_GetErrorText(err) ) ); }
iqrcommon::moduleBttvVideo::moduleBttvVideo() : ClsBaseVideoItem() { #else iqrcommon::moduleBttvVideo::moduleBttvVideo() { #endif #ifdef IQRMODULE clsStateVariableVideoOutput = addOutputToGroup("videoOutput", "Video Output"); #endif iRoundCounter = 0; } #ifdef IQRMODULE moduleIcon iqrcommon::moduleBttvVideo::getIcon() { moduleIcon mi(ModuleIcon_CameraBttv_png_data, ModuleIcon_CameraBttv_png_len, 3 ,5); return mi; } #endif iqrcommon::moduleBttvVideo::~moduleBttvVideo() { cleanup(); } void iqrcommon::moduleBttvVideo::init() { cout << "moduleBttvVideo::init()" << endl; fCPS = 50; deviceID = -1; captureBuf = NULL; ClsBaseVideoItem::init(); openDevice( strDeviceName) ; // Select Y8 capture format captureFormat = V4L_FORMAT_Y8; // Initialize capture size based on window size // Initialize picture attributes to mid-range v4lFormat.width = imgWidth; v4lFormat.height = imgHeight; v4lFormat.format = captureFormat;; V4LMSetFormat(&v4lFormat); V4LMGetFormat(&v4lFormat); imgWidth = v4lFormat.width; imgHeight = v4lFormat.height; captureFrame = 0; if (V4LMCapture(deviceID, captureFrame) < 0) { #ifdef IQRMODULE throw ModuleError(string("Module \"") + label() + "\": Error: V4LMCapture: " + strerror(errno)); #else cerr << "Error: V4LMCapture: " << strerror(errno) << endl; exit(1); #endif } setPictureProperties(); if(bShowOutput) { clsXWin.createWindow(imgWidth, imgHeight); iScreenDepth = clsXWin.getScreenDepth(); if(iScreenDepth != 16 && iScreenDepth != 24) { cerr << "Cannot screen depth of " << iScreenDepth << endl; #ifdef IQRMODULE throw ModuleError(string("Module \"") + label() + "\": Error: V4LMCapture: " + strerror(errno)); #else exit(-1); #endif } } #ifdef IQRMODULE iNrCells = clsStateVariableVideoOutput->getStateArray().getWidth(); iGroupWidth = (int)(sqrt((double)iNrCells / fImageRatio)); iGroupHeight = iNrCells/iGroupWidth; iHPace = (int)ceil((double)imgWidth / (double)iGroupWidth); iVPace = (int)ceil((double)imgHeight / (double)iGroupHeight); // cout << "iHPace, iVPace: " << iHPace << ", " << iVPace << endl; // cout << "iGroupWidth, iGroupHeight: " << iGroupWidth << ", " << iGroupHeight << endl; #endif printDeviceInfo(); }
/** * main * This example uses the synchronous API to * - find a device * - open the device found * - configure the device to output motion * - read motion messages sent by the device * This example assume the device is already connected. */ int main(int argc, char* argv[]) { struct freespace_message message; FreespaceDeviceId device; int numIds; // The number of device ID found int rc; // Return code //struct MultiAxisSensor pointer; //struct MultiAxisSensor angVel; // Flag to indicate that the application should quit // Set by the control signal handler int quit = 0; printVersionInfo(argv[0]); addControlHandler(&quit); // Initialize the freespace library rc = freespace_init(); if (rc != FREESPACE_SUCCESS) { printf("Initialization error. rc=%d\n", rc); return 1; } printf("Scanning for Freespace devices...\n"); // Get the ID of the first device in the list of availble devices rc = freespace_getDeviceList(&device, 1, &numIds); if (numIds == 0) { printf("Didn't find any devices.\n"); return 1; } printf("Found a device. Trying to open it...\n"); // Prepare to communicate with the device found above rc = freespace_openDevice(device); if (rc != FREESPACE_SUCCESS) { printf("Error opening device: %d\n", rc); return 1; } // Display the device information. printDeviceInfo(device); // Make sure any old messages are cleared out of the system rc = freespace_flush(device); if (rc != FREESPACE_SUCCESS) { printf("Error flushing device: %d\n", rc); return 1; } // Cleanup when done and configure the device to output mouse packets printf("Sending message to enable mouse data.\n"); memset(&message, 0, sizeof(message)); // Init message fields to 0 message.messageType = FREESPACE_MESSAGE_DATAMODECONTROLV2REQUEST; message.dataModeControlV2Request.packetSelect = 1; // Mouse packet message.dataModeControlV2Request.mode = 0; // Set full motion rc = freespace_sendMessage(device, &message); if (rc != FREESPACE_SUCCESS) { printf("Could not send message: %d.\n", rc); } // Close communications with the device printf("Cleaning up...\n"); freespace_closeDevice(device); // Cleanup the library freespace_exit(); return 0; }
int main(int argc, char **argv) { int len, addr, page, answer, i; int done = FALSE; SMALLINT bank = 1; uchar data[552]; int portnum = 0; uchar AllSN[MAXDEVICES][8]; int NumDevices; int owd; char msg[132]; // check for required port name if (argc != 2) { sprintf(msg,"1-Wire Net name required on command line!\n" " (example: \"COM1\" (Win32 DS2480),\"/dev/cua0\" " "(Linux DS2480),\"{1,5}\" (Win32 TMEX)\n"); printf("%s\n",msg); return 0; } printf("\n1-Wire Memory utility console application Version 0.01\n"); if((portnum = owAcquireEx(argv[1])) < 0) { OWERROR_DUMP(stdout); return 0; } else { // loop to do menu do { // Main menu switch (menuSelect(MAIN_MENU,&AllSN[0][0])) { case MAIN_SELECT_DEVICE : // find all parts // loop to find all of the devices up to MAXDEVICES NumDevices = 0; do { // perform the search if (!owNext(portnum,TRUE, FALSE)) break; owSerialNum(portnum,AllSN[NumDevices], TRUE); NumDevices++; } while (NumDevices < (MAXDEVICES - 1)); /* for test devices without a serial number if(NumDevices == 0) { for(i=0;i<8;i++) AllSN[0][i] = 0x00; NumDevices++; }*/ // select a device owd = selectDevice(NumDevices,&AllSN[0]); // display device info printDeviceInfo(portnum,&AllSN[owd][0]); // select a bank bank = selectBank(bank, &AllSN[owd][0]); if((AllSN[owd][0] == 0x33) || (AllSN[owd][0] == 0xB3)) bank = optionSHAEE(bank,portnum,&AllSN[owd][0]); // display bank information displayBankInformation(bank,portnum,&AllSN[owd][0]); // loop on bank menu do { switch (menuSelect(BANK_MENU,&AllSN[owd][0])) { case BANK_INFO : // display bank information displayBankInformation(bank,portnum,&AllSN[owd][0]); break; case BANK_READ_BLOCK : // read a block printf("Enter the address to start reading: "); addr = getNumber(0, (owGetSize(bank,&AllSN[owd][0])-1)); printf("\n"); printf("Enter the length of data to read: "); len = getNumber(0, owGetSize(bank, &AllSN[owd][0])); printf("\n"); if(!dumpBankBlock(bank,portnum,&AllSN[owd][0],addr,len)) OWERROR_DUMP(stderr); break; case BANK_READ_PAGE : printf("Enter the page number to read: "); page = getNumber(0, (owGetNumberPages(bank,&AllSN[owd][0])-1)); printf("\n"); if(!dumpBankPage(bank,portnum,&AllSN[owd][0],page)) OWERROR_DUMP(stderr); break; case BANK_READ_UDP : printf("Enter the page number to read: "); page = getNumber(0, (owGetNumberPages(bank,&AllSN[owd][0])-1)); printf("\n"); if(!dumpBankPagePacket(bank,portnum,&AllSN[owd][0],page)) OWERROR_DUMP(stderr); break; case BANK_WRITE_BLOCK : // write a block printf("Enter the address to start writing: "); addr = getNumber(0, (owGetSize(bank,&AllSN[owd][0])-1)); if(menuSelect(ENTRY_MENU,&AllSN[owd][0]) == MODE_TEXT) len = getData(data,MAX_LEN,MODE_TEXT); else len = getData(data,MAX_LEN,MODE_HEX); if(!bankWriteBlock(bank,portnum,&AllSN[owd][0],addr,data,len)) { OWERROR_DUMP(stderr); break; } if(owCanRedirectPage(bank,&AllSN[owd][0])) { printf("Enter if you want to redirect page (0 no, 1 yes): "); answer = getNumber(0,1); if(answer) { printf("What page would you like to redirect:"); page = getNumber(0,255); printf("Where would you like to redirect:"); addr = getNumber(0,255); if(!redirectPage(bank,portnum,&AllSN[owd][0],page,addr)) { OWERROR_DUMP(stderr); break; } } } if(owCanLockPage(bank,&AllSN[owd][0])) { printf("Enter if you want to lock page (0 no, 1 yes):"); answer = getNumber(0,1); if(answer) { printf("What page would you like to lock?"); page = getNumber(0,255); if(!lockPage(bank,portnum,&AllSN[owd][0],page)) { OWERROR_DUMP(stderr); break; } } } if(owCanLockRedirectPage(bank,&AllSN[owd][0])) { printf("Enter if you want to lock redirected page (0 no, 1 yes):"); answer = getNumber(0,1); if(answer) { printf("Which redirected page do you want to lock:"); page = getNumber(0,255); if(!lockRedirectPage(bank,portnum,&AllSN[owd][0],page)) { OWERROR_DUMP(stderr); break; } } } break; case BANK_WRITE_UDP : printf("Enter the page number to write a UDP to: "); page = getNumber(0, (owGetNumberPages(bank,&AllSN[owd][0])-1)); if(menuSelect(ENTRY_MENU,&AllSN[owd][0]) == MODE_TEXT) len = getData(data,MAX_LEN,MODE_TEXT); else len = getData(data,MAX_LEN,MODE_HEX); if(!bankWritePacket(bank,portnum,&AllSN[owd][0],page,data,len)) OWERROR_DUMP(stderr); break; case BANK_BM_READ_PASS: printf("Enter the 8 byte read only password if less 0x00 will be filled in."); if(menuSelect(ENTRY_MENU,&AllSN[owd][0]) == MODE_TEXT) len = getData(data,8,MODE_TEXT); else len = getData(data,8,MODE_HEX); if(len != 8) { for(i=len;i<8;i++) data[i] = 0x00; } if(!owSetBMReadOnlyPassword(portnum,&AllSN[owd][0],data)) OWERROR_DUMP(stderr); break; case BANK_BM_RW_PASS: printf("Enter the 8 byte read/write password if less 0x00 will be filled in."); if(menuSelect(ENTRY_MENU,&AllSN[owd][0]) == MODE_TEXT) len = getData(data,8,MODE_TEXT); else len = getData(data,8,MODE_HEX); if(len != 8) { for(i=len;i<8;i++) data[i] = 0x00; } if(!owSetBMReadWritePassword(portnum,&AllSN[owd][0],data)) OWERROR_DUMP(stderr); break; case BANK_READ_PASS: printf("Enter the 8 byte read only password if less 0x00 will be filled in."); if(menuSelect(ENTRY_MENU,&AllSN[owd][0]) == MODE_TEXT) len = getData(data,8,MODE_TEXT); else len = getData(data,8,MODE_HEX); if(len != 8) { for(i=len;i<8;i++) data[i] = 0x00; } if(!owSetReadOnlyPassword(portnum,&AllSN[owd][0],data)) OWERROR_DUMP(stderr); break; case BANK_RW_PASS: printf("Enter the 8 byte read/write password if less 0x00 will be filled in."); if(menuSelect(ENTRY_MENU,&AllSN[owd][0]) == MODE_TEXT) len = getData(data,8,MODE_TEXT); else len = getData(data,8,MODE_HEX); if(len != 8) { for(i=len;i<8;i++) data[i] = 0x00; } if(!owSetReadWritePassword(portnum,&AllSN[owd][0],data)) OWERROR_DUMP(stderr); break; case BANK_ENABLE_PASS: if(!owSetPasswordMode(portnum,&AllSN[owd][0],ENABLE_PSW)) OWERROR_DUMP(stderr); break; case BANK_DISABLE_PASS: if(!owSetPasswordMode(portnum,&AllSN[owd][0],DISABLE_PSW)) OWERROR_DUMP(stderr); break; case BANK_NEW_BANK : // select a bank bank = selectBank(bank,&AllSN[owd][0]); if((AllSN[owd][0] == 0x33) || (AllSN[owd][0] == 0xB3)) bank = optionSHAEE(bank,portnum,&AllSN[owd][0]); // display bank information displayBankInformation(bank,portnum,&AllSN[owd][0]); break; case BANK_MAIN_MENU : done = TRUE; break; } } while (!done); done = FALSE; break; case MAIN_QUIT : done = TRUE; break; } // Main menu switch } while (!done); // loop to do menu owRelease(portnum); } // else for owAcquire return 1; }
/** * main * This example uses the synchronous API to * - find a device * - open the device found * - send a message * - look for a response * This example assumes that the device is already connected. */ int main(int argc, char* argv[]) { FreespaceDeviceId device; // Keep track of the device you are talking to struct freespace_message send; // A place to create messages to send to the device struct freespace_message receive; // A place to put a message received from the device int numIds; // Keep track of how many devices are available int rc; // Return Code int retryCount = 0; // How many times tried so far to get a response // Flag to indicate that the application should quit // Set by the control signal handler int quit = 0; printVersionInfo(argv[0]); addControlHandler(&quit); // Initialize the freespace library rc = freespace_init(); if (rc != FREESPACE_SUCCESS) { printf("Initialization error. rc=%d\n", rc); return 1; } printf("Scanning for Freespace devices...\n"); // Get the ID of the first device in the list of availble devices rc = freespace_getDeviceList(&device, 1, &numIds); if (numIds == 0) { printf("Didn't find any devices.\n"); return 1; } printf("Found a device. Trying to open it...\n"); // Prepare to communicate with the device found above rc = freespace_openDevice(device); if (rc != FREESPACE_SUCCESS) { printf("Error opening device: %d\n", rc); return 1; } // Display the device information. printDeviceInfo(device); // Make sure any old messages are cleared out of the system rc = freespace_flush(device); if (rc != FREESPACE_SUCCESS) { printf("Error flushing device: %d\n", rc); return 1; } printf("Requesting battery level messages.\n"); memset(&send, 0, sizeof(send)); // Start with a clean message struct // Populate the message fields. Two options are shown below. Uncomment one desired // and comment out the one not desired. //send.messageType = FREESPACE_MESSAGE_BATTERYLEVELREQUEST; // To send a battery level request send.messageType = FREESPACE_MESSAGE_PRODUCTIDREQUEST; // To send a product ID request while (!quit) { if (retryCount < RETRY_COUNT_LIMIT) { retryCount++; // Send the message constructed above. rc = freespace_sendMessage(device, &send); if (rc != FREESPACE_SUCCESS) { printf("Could not send message: %d.\n", rc); } // Read the response message. rc = freespace_readMessage(device, &receive, 100); if (rc == FREESPACE_SUCCESS) { // Print the received message freespace_printMessage(stdout, &receive); retryCount = 0; } else if (rc == FREESPACE_ERROR_TIMEOUT) { printf("<timeout> Try moving the Freespace device to wake it up.\n"); } else if (rc == FREESPACE_ERROR_INTERRUPTED) { printf("<interrupted>\n"); } else { printf("Error reading: %d. Quitting...\n", rc); break; } } else { printf("Did not receive response after %d trials\n", RETRY_COUNT_LIMIT); quit = 1; } SLEEP; } printf("Cleaning up...\n"); freespace_closeDevice(device); freespace_exit(); return 0; }
// Serial ray casting unsigned char* raycast_serial(unsigned char* data, unsigned char* region){ unsigned char* image = (unsigned char*)malloc(sizeof(unsigned char)*IMAGE_DIM*IMAGE_DIM); // Camera/eye position, and direction of viewing. These can be changed to look // at the volume from different angles. float3 camera = {.x=1000,.y=1000,.z=1000}; float3 forward = {.x=-1, .y=-1, .z=-1}; float3 z_axis = {.x=0, .y=0, .z = 1}; // Finding vectors aligned with the axis of the image float3 right = cross(forward, z_axis); float3 up = cross(right, forward); // Creating unity lenght vectors forward = normalize(forward); right = normalize(right); up = normalize(up); float fov = 3.14/4; float pixel_width = tan(fov/2.0)/(IMAGE_DIM/2); float step_size = 0.5; // For each pixel for(int y = -(IMAGE_DIM/2); y < (IMAGE_DIM/2); y++){ for(int x = -(IMAGE_DIM/2); x < (IMAGE_DIM/2); x++){ // Find the ray for this pixel float3 screen_center = add(camera, forward); float3 ray = add(add(screen_center, scale(right, x*pixel_width)), scale(up, y*pixel_width)); ray = add(ray, scale(camera, -1)); ray = normalize(ray); float3 pos = camera; // Move along the ray, we stop if the color becomes completely white, // or we've done 5000 iterations (5000 is a bit arbitrary, it needs // to be big enough to let rays pass through the entire volume) int i = 0; float color = 0; while(color < 255 && i < 5000){ i++; pos = add(pos, scale(ray, step_size)); // Update position int r = value_at(pos, region); // Check if we're in the region color += value_at(pos, data)*(0.01 + r) ; // Update the color based on data value, and if we're in the region } // Write final color to image image[(y+(IMAGE_DIM/2)) * IMAGE_DIM + (x+(IMAGE_DIM/2))] = color > 255 ? 255 : color; } } return image; } // Check if two values are similar, threshold can be changed. int similar(unsigned char* data, int3 a, int3 b){ unsigned char va = data[a.z * DATA_DIM*DATA_DIM + a.y*DATA_DIM + a.x]; unsigned char vb = data[b.z * DATA_DIM*DATA_DIM + b.y*DATA_DIM + b.x]; int i = abs(va-vb) < 1; return i; } // Serial region growing, same algorithm as in assignment 2 unsigned char* grow_region_serial(unsigned char* data){ unsigned char* region = (unsigned char*)calloc(sizeof(unsigned char), DATA_DIM*DATA_DIM*DATA_DIM); stack_t* stack = new_stack(); int3 seed = {.x=50, .y=300, .z=300}; push(stack, seed); region[seed.z *DATA_DIM*DATA_DIM + seed.y*DATA_DIM + seed.x] = 1; int dx[6] = {-1,1,0,0,0,0}; int dy[6] = {0,0,-1,1,0,0}; int dz[6] = {0,0,0,0,-1,1}; while(stack->size > 0){ int3 pixel = pop(stack); for(int n = 0; n < 6; n++){ int3 candidate = pixel; candidate.x += dx[n]; candidate.y += dy[n]; candidate.z += dz[n]; if(!inside_int(candidate)){ continue; } if(region[candidate.z * DATA_DIM*DATA_DIM + candidate.y*DATA_DIM + candidate.x]){ continue; } if(similar(data, pixel, candidate)){ push(stack, candidate); region[candidate.z * DATA_DIM*DATA_DIM + candidate.y*DATA_DIM + candidate.x] = 1; } } } return region; } unsigned char* grow_region_gpu(unsigned char* data){ cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_kernel kernel; cl_int err; char *source; int i; clGetPlatformIDs(1, &platform, NULL); clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL); context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); printPlatformInfo(platform); queue = clCreateCommandQueue(context, device, 0, &err); kernel = buildKernel("region.cl", "region", NULL, context, device); //Host variables unsigned char* host_region = (unsigned char*)calloc(sizeof(unsigned char), DATA_SIZE); int host_unfinished; cl_mem device_region = clCreateBuffer(context, CL_MEM_READ_WRITE, DATA_SIZE * sizeof(cl_uchar) ,NULL,&err); cl_mem device_data = clCreateBuffer(context, CL_MEM_READ_ONLY, DATA_SIZE * sizeof(cl_uchar), NULL,&err); cl_mem device_unfinished = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_int), NULL,&err); clError("Error allocating memory", err); //plant seed int3 seed = {.x=50, .y=300, .z=300}; host_region[index(seed.z, seed.y, seed.x)] = 2; //Copy data to the device clEnqueueWriteBuffer(queue, device_data , CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), data , 0, NULL, NULL); clEnqueueWriteBuffer(queue, device_region, CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), host_region, 0, NULL, NULL); //Calculate block and grid sizes size_t global[] = { 512, 512, 512 }; size_t local[] = { 8, 8, 8 }; //Run kernel untill completion do{ host_unfinished = 0; clEnqueueWriteBuffer(queue, device_unfinished, CL_FALSE, 0, sizeof(cl_int), &host_unfinished , 0, NULL, NULL); clFinish(queue); err = clSetKernelArg(kernel, 0, sizeof(device_data), (void*)&device_data); err = clSetKernelArg(kernel, 1, sizeof(device_region), (void*)&device_region); err = clSetKernelArg(kernel, 2, sizeof(device_unfinished), (void*)&device_unfinished); clError("Error setting arguments", err); //Run the kernel clEnqueueNDRangeKernel(queue, kernel, 3, NULL, &global, &local, 0, NULL, NULL); clFinish(queue); clError("Error running kernel", err); err = clEnqueueReadBuffer(queue, device_unfinished, CL_TRUE, 0, sizeof(cl_int), &host_unfinished, 0, NULL, NULL); clFinish(queue); clError("Error reading buffer 1", err); }while(host_unfinished); //Copy result to host err = clEnqueueReadBuffer(queue, device_region, CL_TRUE, 0, DATA_SIZE * sizeof(cl_uchar), host_region, 0, NULL, NULL); clFinish(queue); clError("Error reading buffer 2", err); return host_region; } unsigned char* raycast_gpu(unsigned char* data, unsigned char* region){ cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_kernel kernel; cl_int err; char *source; int i; clGetPlatformIDs(1, &platform, NULL); clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL); context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); printPlatformInfo(platform); printDeviceInfo(device); queue = clCreateCommandQueue(context, device, 0, &err); kernel = buildKernel("raycast.cl", "raycast", NULL, context, device); cl_mem device_region = clCreateBuffer(context, CL_MEM_READ_ONLY, DATA_SIZE * sizeof(cl_uchar) ,NULL,&err); cl_mem device_data = clCreateBuffer(context, CL_MEM_READ_ONLY, DATA_SIZE * sizeof(cl_uchar), NULL,&err); cl_mem device_image = clCreateBuffer(context, CL_MEM_READ_WRITE, IMAGE_SIZE * sizeof(cl_uchar),NULL,&err); clError("Error allocating memory", err); //Copy data to the device clEnqueueWriteBuffer(queue, device_data , CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), data , 0, NULL, NULL); clEnqueueWriteBuffer(queue, device_region, CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), region, 0, NULL, NULL); int grid_size = IMAGE_DIM; int block_size = IMAGE_DIM; //Set up kernel arguments err = clSetKernelArg(kernel, 0, sizeof(device_data), (void*)&device_data); err = clSetKernelArg(kernel, 1, sizeof(device_region), (void*)&device_region); err = clSetKernelArg(kernel, 2, sizeof(device_image), (void*)&device_image); clError("Error setting arguments", err); //Run the kernel const size_t globalws[2] = {IMAGE_DIM, IMAGE_DIM}; const size_t localws[2] = {8, 8}; clEnqueueNDRangeKernel(queue, kernel, 2, NULL, &globalws, &localws, 0, NULL, NULL); clFinish(queue); //Allocate memory for the result unsigned char* host_image = (unsigned char*)malloc(IMAGE_SIZE_BYTES); //Copy result from device err = clEnqueueReadBuffer(queue, device_image, CL_TRUE, 0, IMAGE_SIZE * sizeof(cl_uchar), host_image, 0, NULL, NULL); clFinish(queue); //Free device memory return host_image; } int main(int argc, char** argv){ unsigned char* data = create_data(); unsigned char* region = grow_region_gpu(data); unsigned char* image = raycast_gpu(data, region); write_bmp(image, IMAGE_DIM, IMAGE_DIM); }
void WPointGrey::initializationOnThread() { try { initialized = true; // Print application build information op::log(std::string{ "Application build date: " } + __DATE__ + " " + __TIME__, op::Priority::High); // Retrieve singleton reference to mSystemPtr object mSystemPtr = Spinnaker::System::GetInstance(); // Retrieve list of cameras from the mSystemPtr mCameraList = mSystemPtr->GetCameras(); unsigned int numCameras = mCameraList.GetSize(); op::log("Number of cameras detected: " + std::to_string(numCameras), op::Priority::High); // Finish if there are no cameras if (numCameras == 0) { // Clear camera list before releasing mSystemPtr mCameraList.Clear(); // Release mSystemPtr mSystemPtr->ReleaseInstance(); op::log("Not enough cameras!\nPress Enter to exit...", op::Priority::High); getchar(); op::error("No cameras detected.", __LINE__, __FUNCTION__, __FILE__); } op::log("Camera system initialized...", op::Priority::High); // // Retrieve transport layer nodemaps and print device information for // each camera // // *** NOTES *** // This example retrieves information from the transport layer nodemap // twice: once to print device information and once to grab the device // serial number. Rather than caching the nodemap, each nodemap is // retrieved both times as needed. // op::log("\n*** DEVICE INFORMATION ***\n", op::Priority::High); for (int i = 0; i < mCameraList.GetSize(); i++) { // Select camera auto cameraPtr = mCameraList.GetByIndex(i); // Retrieve TL device nodemap auto& iNodeMapTLDevice = cameraPtr->GetTLDeviceNodeMap(); // Print device information auto result = printDeviceInfo(iNodeMapTLDevice, i); if (result < 0) op::error("Result > 0, error " + std::to_string(result) + " occurred...", __LINE__, __FUNCTION__, __FILE__); } for (auto i = 0; i < mCameraList.GetSize(); i++) { // Select camera auto cameraPtr = mCameraList.GetByIndex(i); // Initialize each camera // You may notice that the steps in this function have more loops with // less steps per loop; this contrasts the acquireImages() function // which has less loops but more steps per loop. This is done for // demonstrative purposes as both work equally well. // Later: Each camera needs to be deinitialized once all images have been // acquired. cameraPtr->Init(); // Retrieve GenICam nodemap // auto& iNodeMap = cameraPtr->GetNodeMap(); // // Configure trigger // result = configureTrigger(iNodeMap); // if (result < 0) // op::error("Result > 0, error " + std::to_string(result) + " occurred...", __LINE__, __FUNCTION__, __FILE__); // // Configure chunk data // result = configureChunkData(iNodeMap); // if (result < 0) // return result; // Remove buffer --> Always get newest frame Spinnaker::GenApi::INodeMap& snodeMap = cameraPtr->GetTLStreamNodeMap(); Spinnaker::GenApi::CEnumerationPtr ptrBufferHandlingMode = snodeMap.GetNode("StreamBufferHandlingMode"); if (!Spinnaker::GenApi::IsAvailable(ptrBufferHandlingMode) || !Spinnaker::GenApi::IsWritable(ptrBufferHandlingMode)) op::error("Unable to change buffer handling mode", __LINE__, __FUNCTION__, __FILE__); Spinnaker::GenApi::CEnumEntryPtr ptrBufferHandlingModeNewest = ptrBufferHandlingMode->GetEntryByName("NewestFirstOverwrite"); if (!Spinnaker::GenApi::IsAvailable(ptrBufferHandlingModeNewest) || !IsReadable(ptrBufferHandlingModeNewest)) op::error("Unable to set buffer handling mode to newest (entry 'NewestFirstOverwrite' retrieval). Aborting...", __LINE__, __FUNCTION__, __FILE__); int64_t bufferHandlingModeNewest = ptrBufferHandlingModeNewest->GetValue(); ptrBufferHandlingMode->SetIntValue(bufferHandlingModeNewest); } // Prepare each camera to acquire images // // *** NOTES *** // For pseudo-simultaneous streaming, each camera is prepared as if it // were just one, but in a loop. Notice that cameras are selected with // an index. We demonstrate pseduo-simultaneous streaming because true // simultaneous streaming would require multiple process or threads, // which is too complex for an example. // // Serial numbers are the only persistent objects we gather in this // example, which is why a std::vector is created. std::vector<Spinnaker::GenICam::gcstring> strSerialNumbers(mCameraList.GetSize()); for (auto i = 0u; i < strSerialNumbers.size(); i++) { // Select camera auto cameraPtr = mCameraList.GetByIndex(i); // Set acquisition mode to continuous Spinnaker::GenApi::CEnumerationPtr ptrAcquisitionMode = cameraPtr->GetNodeMap().GetNode("AcquisitionMode"); if (!Spinnaker::GenApi::IsAvailable(ptrAcquisitionMode) || !Spinnaker::GenApi::IsWritable(ptrAcquisitionMode)) op::error("Unable to set acquisition mode to continuous (node retrieval; camera " + std::to_string(i) + "). Aborting...", __LINE__, __FUNCTION__, __FILE__); Spinnaker::GenApi::CEnumEntryPtr ptrAcquisitionModeContinuous = ptrAcquisitionMode->GetEntryByName("Continuous"); if (!Spinnaker::GenApi::IsAvailable(ptrAcquisitionModeContinuous) || !Spinnaker::GenApi::IsReadable(ptrAcquisitionModeContinuous)) op::error("Unable to set acquisition mode to continuous (entry 'continuous' retrieval " + std::to_string(i) + "). Aborting...", __LINE__, __FUNCTION__, __FILE__); int64_t acquisitionModeContinuous = ptrAcquisitionModeContinuous->GetValue(); ptrAcquisitionMode->SetIntValue(acquisitionModeContinuous); op::log("Camera " + std::to_string(i) + " acquisition mode set to continuous...", op::Priority::High); // Begin acquiring images cameraPtr->BeginAcquisition(); op::log("Camera " + std::to_string(i) + " started acquiring images...", op::Priority::High); // Retrieve device serial number for filename strSerialNumbers[i] = ""; Spinnaker::GenApi::CStringPtr ptrStringSerial = cameraPtr->GetTLDeviceNodeMap().GetNode("DeviceSerialNumber"); if (Spinnaker::GenApi::IsAvailable(ptrStringSerial) && Spinnaker::GenApi::IsReadable(ptrStringSerial)) { strSerialNumbers[i] = ptrStringSerial->GetValue(); op::log("Camera " + std::to_string(i) + " serial number set to " + strSerialNumbers[i].c_str() + "...", op::Priority::High); } op::log(" ", op::Priority::High); } op::log("\nRunning for all cameras...\n\n*** IMAGE ACQUISITION ***\n", op::Priority::High); } catch (const Spinnaker::Exception& e) { op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); } catch (const std::exception& e) { op::error(e.what(), __LINE__, __FUNCTION__, __FILE__); } }
int main(int argc, const char** argv) { int retval = 0; boost::program_options::options_description general_options_description("Options", 140, 60); boost::program_options::variables_map vm; std::string colorArg, deviceArg; try { std::set<Nebula::HAL::Device*> devices; std::mutex devicesMutex; installSignalHandlers(); general_options_description.add_options() (Options::kDevice, boost::program_options::value<std::string>(), "specify device") (Options::kChannel, boost::program_options::value<RT::s4>()->default_value(0), "specify LED strip channel") (Options::kNumberOfLeds, boost::program_options::value<RT::s4>()->default_value(0), "set number of leds") ("nn", boost::program_options::value<RT::s4>()->default_value(100), "set running light increment") ("size,s", boost::program_options::value<RT::s4>()->default_value(100), "Ambilight sensing zones size") (Options::kFrequency, boost::program_options::value<float>()->default_value(24.0f), "set number of LEDs color updates per second") (Options::kColor, boost::program_options::value<std::string>()->default_value(std::string("255,255,255")), "set LEDs color") (Options::kBrightness, boost::program_options::value<float>()->default_value(0.5f), "set LEDs brightness") (Options::kRate, boost::program_options::value<float>()->default_value(1.0f), "set dynamic lighting effect rate") //(Options::kStrobe, "run in stroboscope mode") (Options::kDebug, boost::program_options::value<RT::u4>()->default_value(0), "stroboscope mode"); if (argc < 2) optionsError("mode was not specified\n"); auto mode = determineMode(argv[1]); if (mode == Mode::none) optionsError("invalid mode was specified\n"); boost::program_options::store(boost::program_options::command_line_parser(argc - 1, argv + 1).options(general_options_description).run(), vm, true); boost::program_options::notify(vm); switch (mode) { case Mode::help: print_usage(general_options_description); exit(0); case Mode::version: std::cout << VERSION_STRING(VERSION, __DATE__, __TIME__) << std::endl; exit(0); default: break; } auto onDeviceAddition = [&](Nebula::HAL::Device* device) -> void { std::lock_guard<std::mutex> lock(devicesMutex); devices.insert(device); }; auto onDeviceRemoval = [&](Nebula::HAL::Device* device) -> void { std::lock_guard<std::mutex> lock(devicesMutex); devices.erase(device); }; std::unique_ptr<Nebula::HAL::Context> nebula(Nebula::HAL::createContext(onDeviceAddition, onDeviceRemoval)); if (mode == Mode::list) { std::lock_guard<std::mutex> lock(devicesMutex); for (auto device : devices) printDeviceInfo(device); } else { auto firstDeviceIterator = devices.begin(); if (firstDeviceIterator != devices.end()) { auto device = *firstDeviceIterator; auto channel = vm["channel"].as<RT::s4>(); auto numberOfLeds = vm["nleds"].as<RT::s4>(); auto frequency = vm["freq"].as<float>(); auto brightness = vm["brightness"].as<float>(); bool animate = false; if (channel < 0) optionsError("channel should be >= 0\n"); if (numberOfLeds <= 0) optionsError("number of LEDs should be > 0\n"); if (frequency <= 0.0f) optionsError("frequency should be > 0\n"); if (brightness < 0.0f) optionsError("brightness should be >= 0\n"); std::unique_ptr<Nebula::Color::RGB<RT::u1>> colors(new Nebula::Color::RGB<RT::u1>[numberOfLeds]); std::mutex colorsMutex; Nebula::HAL::Device::IoctlParameters::SetNumberOfLeds setNumberOfLedsIoctlParameters(channel, numberOfLeds); Nebula::HAL::Device::IoctlParameters::Colors colorsIoctlParameters(channel, colors.get(), numberOfLeds); device->controlIn(Nebula::HAL::Device::Request::setNumberOfLeds, &setNumberOfLedsIoctlParameters, sizeof(setNumberOfLedsIoctlParameters)); switch (mode) { case Mode::continuous: { RT::u4 r, g, b; sscanf(vm["color"].as<std::string>().c_str(), "%u,%u,%u", &r, &g, &b); r *= brightness; g *= brightness; b *= brightness; for (auto i = 0; i < numberOfLeds; i++) colors.get()[convertLedNumber(i)].set(r, g, b); device->controlIn(Nebula::HAL::Device::Request::setColors, &colorsIoctlParameters, sizeof(colorsIoctlParameters)); } break; case Mode::rainbow: case Mode::ambilight: case Mode::run: animate = true; break; default: break; } if (animate) { std::unique_ptr<Nebula::Generator> generator(createGenerator(mode, vm)); std::unique_ptr<Nebula::Transformation> transformation(new Reorder(numberOfLeds, 3)); TimerCallbackParameters timerCallbackParameters(device, &colorsIoctlParameters, &colorsMutex); std::thread pluginThread([&]() -> void { std::unique_ptr<Nebula::Color::RGB<RT::u1>> localColors(new Nebula::Color::RGB<RT::u1>[numberOfLeds]); time_t t1, t2; RT::u8 count = 0; time(&t1); while (!doTerminate) { generator->generate(localColors.get()); transformation->transformInPlace(localColors.get()); guardedMemcpy(localColors.get(), colors.get(), numberOfLeds * sizeof(Nebula::Color::RGB<RT::u1>), &colorsMutex); count++; } time(&t2); if (count > 0) printf("updates per second = %f\n", float(count) / float(t2 - t1)); }); try { runLoop(&timerCallbackParameters, frequency); } catch(...) { pluginThread.join(); throw; } pluginThread.join(); } } else printf("No device found\n"); } } catch (RT::u4 ID) { printf("Error 0x%x\n", ID); } catch (OptionsError e) { printf("Invalid program invocation: %s", e.getMessage()); print_usage(general_options_description); retval = -1; } catch (...) { printf("Exception occured\n"); } return retval; }