int SerialPort::Initialize() { if (initialized_) return DEVICE_OK; // do not initialize if this port has been blacklisted std::vector<std::string>::iterator it = g_BlackListedPorts.begin(); while (it < g_BlackListedPorts.end()) { if( portName_ == (*it)) return ERR_PORT_BLACKLISTED; it++; } long sb; int ret = GetPropertyData(MM::g_Keyword_StopBits, stopBits_.c_str(), sb); assert(ret == DEVICE_OK); long parity; ret = GetPropertyData(MM::g_Keyword_Parity, parity_.c_str(), parity); long baud; ret = GetCurrentPropertyData(MM::g_Keyword_BaudRate, baud); assert(ret == DEVICE_OK); long handshake; ret = GetCurrentPropertyData(MM::g_Keyword_Handshaking, handshake); assert(ret == DEVICE_OK); pService_ = new boost::asio::io_service(); try { pPort_ = new AsioClient (*pService_, boost::lexical_cast<unsigned int>(baud), this->portName_, boost::asio::serial_port_base::flow_control::type(handshake), boost::asio::serial_port_base::parity::type(parity), boost::asio::serial_port_base::stop_bits::type(sb), this ); } catch( std::exception& what) { LogMessage(what.what(),false); return DEVICE_ERR; } try { pThread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, pService_)); } catch(std::exception& what) { LogMessage(what.what(), false); return DEVICE_ERR; } ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; }
//***************************************************************************** // // This is the generic callback from host stack. // // pvData is actually a pointer to a tEventInfo structure. // // This function will be called to inform the application when a USB event has // occurred that is outside those related to the keyboard device. At this // point this is used to detect unsupported devices being inserted and removed. // It is also used to inform the application when a power fault has occurred. // This function is required when the g_USBGenericEventDriver is included in // the host controller driver array that is passed in to the // USBHCDRegisterDrivers() function. // //***************************************************************************** void USBHCDEvents(void *pvData) { tEventInfo *pEventInfo; // // Cast this pointer to its actual type. // pEventInfo = (tEventInfo *)pvData; switch(pEventInfo->ui32Event) { // // New keyboard detected. // case USB_EVENT_CONNECTED: { // // See if this is a HID Keyboard. // if((USBHCDDevClass(pEventInfo->ui32Instance, 0) == USB_CLASS_HID) && (USBHCDDevProtocol(pEventInfo->ui32Instance, 0) == USB_HID_PROTOCOL_KEYB)) { // // Indicate that the keyboard has been detected. // UARTprintf("Keyboard Connected\n"); // // Proceed to the STATE_KEYBOARD_INIT state so that the main // loop can finish initialized the mouse since // USBHKeyboardInit() cannot be called from within a callback. // g_eUSBState = STATE_KEYBOARD_INIT; } break; } // // Unsupported device detected. // case USB_EVENT_UNKNOWN_CONNECTED: { UARTprintf("Unsupported Device Class (0x%02x) Connected.\n", pEventInfo->ui32Instance); // // An unknown device was detected. // g_eUSBState = STATE_UNKNOWN_DEVICE; UpdateStatus(); break; } // // Device has been unplugged. // case USB_EVENT_DISCONNECTED: { // // Indicate that the device has been disconnected. // UARTprintf("Device Disconnected\n"); // // Change the state so that the main loop knows that the device // is no longer present. // g_eUSBState = STATE_NO_DEVICE; // // Update the screen. // UpdateStatus(); break; } // // Power Fault occurred. // case USB_EVENT_POWER_FAULT: { UARTprintf("Power Fault\n"); // // No power means no device is present. // g_eUSBState = STATE_POWER_FAULT; UpdateStatus(); break; } default: { break; } } }
//***************************************************************************** // // This is the main loop that runs the application. // //***************************************************************************** int main(void) { tRectangle sRect; tUSBMode eLastMode; char *pcString; // // Enable lazy stacking for interrupt handlers. This allows floating-point // instructions to be used within interrupt handlers, but at the expense of // extra stack usage. // ROM_FPULazyStackingEnable(); // // Set the system clock to run at 50MHz from the PLL. // ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // Initially wait for device connection. // g_eUSBState = STATE_NO_DEVICE; eLastMode = eUSBModeOTG; g_eCurrentUSBMode = eUSBModeOTG; // // Enable Clocking to the USB controller. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0); // // Configure the required pins for USB operation. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG); ROM_GPIOPinConfigure(GPIO_PG4_USB0EPEN); ROM_GPIOPinTypeUSBDigital(GPIO_PORTG_BASE, GPIO_PIN_4); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL); ROM_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7); ROM_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1); // // Configure SysTick for a 100Hz interrupt. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND); ROM_SysTickEnable(); ROM_SysTickIntEnable(); // // Enable Interrupts // ROM_IntMasterEnable(); // // Configure UART0 for debug output. // ConfigureUART(); // // Initialize the USB stack mode and pass in a mode callback. // USBStackModeSet(0, eUSBModeOTG, ModeCallback); // // Register the host class drivers. // USBHCDRegisterDrivers(0, g_ppHostClassDrivers, g_ui32NumHostClassDrivers); // // Open an instance of the keyboard driver. The keyboard does not need // to be present at this time, this just save a place for it and allows // the applications to be notified when a keyboard is present. // g_psKeyboardInstance = USBHKeyboardOpen(KeyboardCallback, g_pui8Buffer, KEYBOARD_MEMORY_SIZE); // // Initialize the power configuration. This sets the power enable signal // to be active high and does not enable the power fault. // USBHCDPowerConfigInit(0, USBHCD_VBUS_AUTO_HIGH | USBHCD_VBUS_FILTER); // // Initialize the USB controller for OTG operation with a 2ms polling // rate. // USBOTGModeInit(0, 2000, g_pui8HCDPool, HCD_MEMORY_SIZE); // // Initialize the display driver. // CFAL96x64x16Init(); // // Initialize the graphics context. // GrContextInit(&g_sContext, &g_sCFAL96x64x16); // // Fill the top part of the screen with blue to create the banner. // sRect.i16XMin = 0; sRect.i16YMin = 0; sRect.i16XMax = GrContextDpyWidthGet(&g_sContext) - 1; sRect.i16YMax = (2 * DISPLAY_BANNER_HEIGHT) - 1; GrContextForegroundSet(&g_sContext, DISPLAY_BANNER_BG); GrRectFill(&g_sContext, &sRect); // // Change foreground for white text. // GrContextForegroundSet(&g_sContext, DISPLAY_TEXT_FG); // // Put the application name in the middle of the banner. // GrContextFontSet(&g_sContext, g_psFontFixed6x8); GrStringDrawCentered(&g_sContext, "usb-host-", -1, GrContextDpyWidthGet(&g_sContext) / 2, 4, 0); GrStringDrawCentered(&g_sContext, "keyboard", -1, GrContextDpyWidthGet(&g_sContext) / 2, 14, 0); // // Calculate the number of characters that will fit on a line. // Make sure to leave a small border for the text box. // g_ui32CharsPerLine = (GrContextDpyWidthGet(&g_sContext) - 4) / GrFontMaxWidthGet(g_psFontFixed6x8); // // Calculate the number of lines per usable text screen. This requires // taking off space for the top and bottom banners and adding a small bit // for a border. // g_ui32LinesPerScreen = (GrContextDpyHeightGet(&g_sContext) - (3*(DISPLAY_BANNER_HEIGHT + 1)))/ GrFontHeightGet(g_psFontFixed6x8); // // Open and instance of the keyboard class driver. // UARTprintf("Host Keyboard Application\n"); // // Initial update of the screen. // UpdateStatus(); // // The main loop for the application. // while(1) { // // Tell the OTG library code how much time has passed in // milliseconds since the last call. // USBOTGMain(GetTickms()); // // Has the USB mode changed since last time we checked? // if(g_eCurrentUSBMode != eLastMode) { // // Remember the new mode. // eLastMode = g_eCurrentUSBMode; switch(eLastMode) { case eUSBModeHost: pcString = "HOST"; break; case eUSBModeDevice: pcString = "DEVICE"; break; case eUSBModeNone: pcString = "NONE"; break; default: pcString = "UNKNOWN"; break; } UARTprintf("USB mode changed to %s\n", pcString); } switch(g_eUSBState) { // // This state is entered when they keyboard is first detected. // case STATE_KEYBOARD_INIT: { // // Initialized the newly connected keyboard. // USBHKeyboardInit(g_psKeyboardInstance); // // Proceed to the keyboard connected state. // g_eUSBState = STATE_KEYBOARD_CONNECTED; // // Update the screen now that the keyboard has been // initialized. // UpdateStatus(); USBHKeyboardModifierSet(g_psKeyboardInstance, g_ui32Modifiers); break; } case STATE_KEYBOARD_UPDATE: { // // If the application detected a change that required an // update to be sent to the keyboard to change the modifier // state then call it and return to the connected state. // g_eUSBState = STATE_KEYBOARD_CONNECTED; USBHKeyboardModifierSet(g_psKeyboardInstance, g_ui32Modifiers); break; } case STATE_KEYBOARD_CONNECTED: { // // Nothing is currently done in the main loop when the keyboard // is connected. // break; } case STATE_UNKNOWN_DEVICE: { // // Nothing to do as the device is unknown. // break; } case STATE_NO_DEVICE: { // // Nothing is currently done in the main loop when the keyboard // is not connected. // break; } default: { break; } } } }
void __saveds UpdateStatusInterface(rsiCONTEXT *rc, float percent, float elapsed, int y, int lines, rsiSMALL_COLOR *line) { UpdateStatus(rc, percent, elapsed, y, lines, line); }
int CArduinoNeoPixelShutter::Initialize() { CArduinoNeoPixelHub* hub = static_cast<CArduinoNeoPixelHub*>(GetParentHub()); if (!hub || !hub->IsPortAvailable()) { return ERR_NO_PORT_SET; } char hubLabel[MM::MaxStrLength]; hub->GetLabel(hubLabel); SetParentID(hubLabel); // for backward comp. // set property list // ----------------- // OnOff // ------ CPropertyAction* pAct = new CPropertyAction (this, &CArduinoNeoPixelShutter::OnOnOff); int ret = CreateProperty("OnOff", "1", MM::Integer, false, pAct); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction (this, &CArduinoNeoPixelShutter::OnIntensity); ret = CreateProperty("Intensity", "255", MM::Integer, false, pAct); SetPropertyLimits("Intensity", 0, 255); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction(this, &CArduinoNeoPixelShutter::OnRedBrightness); ret = CreateProperty("Red brightness", "255", MM::Integer, false, pAct); SetPropertyLimits("Red brightness", 0, 255); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction(this, &CArduinoNeoPixelShutter::OnGreenBrightness); ret = CreateProperty("Green brightness", "255", MM::Integer, false, pAct); SetPropertyLimits("Green brightness", 0, 255); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction(this, &CArduinoNeoPixelShutter::OnBlueBrightness); ret = CreateProperty("Blue brightness", "255", MM::Integer, false, pAct); SetPropertyLimits("Blue brightness", 0, 255); if (ret != DEVICE_OK) return ret; pAct = new CPropertyAction(this, &CArduinoNeoPixelShutter::OnMulti); ret = CreateProperty("Multi", "8", MM::Integer, false, pAct); SetPropertyLimits("Multi", 0, 1<<3); if (ret != DEVICE_OK) return ret; // set shutter into the off state //WriteToPort(0); std::vector<std::string> vals; vals.push_back("0"); vals.push_back("1"); ret = SetAllowedValues("OnOff", vals); if (ret != DEVICE_OK) return ret; ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; changedTime_ = GetCurrentMMTime(); initialized_ = true; return DEVICE_OK; }
//***************************************************************************** // // This is the main loop that runs the application. // //***************************************************************************** int main(void) { tRectangle sRect; // // Set the clocking to run directly from the crystal. // ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ); // // Enable the USB mux GPIO. // ROM_SysCtlPeripheralEnable(USB_MUX_GPIO_PERIPH); // // The LM3S3748 board uses a USB mux that must be switched to use the // host connector and not the device connecter. // ROM_GPIOPinTypeGPIOOutput(USB_MUX_GPIO_BASE, USB_MUX_GPIO_PIN); ROM_GPIOPinWrite(USB_MUX_GPIO_BASE, USB_MUX_GPIO_PIN, USB_MUX_SEL_DEVICE); // // Configure SysTick for a 100Hz interrupt. The FatFs driver wants a 10 ms // tick. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / 100); ROM_SysTickEnable(); ROM_SysTickIntEnable(); // // Configure and enable uDMA // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UDMA); SysCtlDelay(10); uDMAControlBaseSet(&sDMAControlTable[0]); uDMAEnable(); // // Initialize the display driver. // Formike128x128x16Init(); // // Turn on the backlight. // Formike128x128x16BacklightOn(); // // Initialize the graphics context. // GrContextInit(&g_sContext, &g_sFormike128x128x16); // // Fill the top 15 rows of the screen with blue to create the banner. // sRect.sXMin = 0; sRect.sYMin = 0; sRect.sXMax = GrContextDpyWidthGet(&g_sContext) - 1; sRect.sYMax = DISPLAY_BANNER_HEIGHT; GrContextForegroundSet(&g_sContext, ClrDarkBlue); GrRectFill(&g_sContext, &sRect); // // Put a white box around the banner. // GrContextForegroundSet(&g_sContext, ClrWhite); GrRectDraw(&g_sContext, &sRect); // // Put the application name in the middle of the banner. // GrContextFontSet(&g_sContext, g_pFontFixed6x8); GrStringDrawCentered(&g_sContext, "usb_dev_msc", -1, GrContextDpyWidthGet(&g_sContext) / 2, 7, 0); // // Initialize the idle timeout and reset all flags. // g_ulIdleTimeout = 0; g_ulFlags = 0; // // Initialize the state to idle. // g_eMSCState = MSC_DEV_IDLE; // // Draw the status bar and set it to idle. // UpdateStatus("Idle", 1); // // Pass our device information to the USB library and place the device // on the bus. // USBDMSCInit(0, (tUSBDMSCDevice *)&g_sMSCDevice); // // Drop into the main loop. // while(1) { switch(g_eMSCState) { case MSC_DEV_READ: { // // Update the screen if necessary. // if(g_ulFlags & FLAG_UPDATE_STATUS) { UpdateStatus("Reading", 0); g_ulFlags &= ~FLAG_UPDATE_STATUS; } // // If there is no activity then return to the idle state. // if(g_ulIdleTimeout == 0) { UpdateStatus("Idle ", 0); g_eMSCState = MSC_DEV_IDLE; } break; } case MSC_DEV_WRITE: { // // Update the screen if necessary. // if(g_ulFlags & FLAG_UPDATE_STATUS) { UpdateStatus("Writing", 0); g_ulFlags &= ~FLAG_UPDATE_STATUS; } // // If there is no activity then return to the idle state. // if(g_ulIdleTimeout == 0) { UpdateStatus("Idle ", 0); g_eMSCState = MSC_DEV_IDLE; } break; } case MSC_DEV_IDLE: default: { break; } } } }
void EbookController::HandleMobiLayoutDone(EbookFormattingTask *ld) { if (formattingThreadNo != ld->threadNo) { // this is a message from cancelled thread, we can disregard //lf("EbookController::MobiLayout() thread msg discarded, curr thread: %d, sending thread: %d", layoutThreadNo, ld->threadNo); return; } //lf("EbookController::HandleMobiLayoutMsg() %d pages, ld=0x%x", ld->pageCount, (int)ld); HtmlPage *pageToShow = NULL; if (!ld->fromBeginning) { // if this is the first page sent, we're currently showing a page // formatted for old window size. Replace that page with new page if (0 == formattingTemp.pagesFromPage.Count()) { CrashIf(0 == ld->pageCount); pageToShow = ld->pages[0]; } formattingTemp.pagesFromPage.Append(ld->pages, ld->pageCount); if (pageToShow) { CrashIf(pageToShow->reparseIdx != pageShown->reparseIdx); ShowPage(pageToShow, false); } //lf("Got %d pages from page, total %d", ld->pageCount, formattingTemp.pagesFromPage.Count()); //UpdateStatus(); return; } // we're showing pages from the beginning if (-1 != startReparseIdx) { // we're formatting a book for which we need to restore // page from previous session CrashIf(formattingTemp.reparseIdx != 0); for (size_t i = 0; i < ld->pageCount; i++) { HtmlPage *pd = ld->pages[i]; if (pd->reparseIdx == startReparseIdx) { pageToShow = pd; } else if (pd->reparseIdx >= startReparseIdx) { // this is the first page whose reparseIdx is greater than // the one we're looking for, so previous page has the data if (i > 0) { pageToShow = ld->pages[i]; //lf("showing page %d", i); } else { if (0 == formattingTemp.pagesFromBeginning.Count()) { pageToShow = ld->pages[0]; } else { size_t pageNo = formattingTemp.pagesFromBeginning.Count() - 1; //lf("showing page %d from formattingTemp.pagesFromBeginning", (int)pageNo); pageToShow = formattingTemp.pagesFromBeginning.At(pageNo); } } } if (pageToShow) { startReparseIdx = -1; break; } } } else { if (0 == formattingTemp.pagesFromBeginning.Count()) { CrashIf(0 == ld->pageCount); pageToShow = ld->pages[0]; //lf("showing ld->pages[0], pageCount = %d", ld->pageCount); } } formattingTemp.pagesFromBeginning.Append(ld->pages, ld->pageCount); //lf("Got %d pages from beginning, total %d", ld->pageCount, formattingTemp.pagesFromBeginning.Count()); if (0 == formattingTemp.reparseIdx) { // if we're starting from the beginning, show the first page as // quickly as we can if (pageToShow) ShowPage(pageToShow, false); } if (ld->finished) { CrashIf(pagesFromBeginning || pagesFromPage); pagesFromBeginning = new Vec<HtmlPage *>(formattingTemp.pagesFromBeginning); formattingTemp.pagesFromBeginning.Reset(); size_t pageCount = formattingTemp.pagesFromPage.Count(); if (pageCount > 0) { pagesFromPage = new Vec<HtmlPage *>(formattingTemp.pagesFromPage); formattingTemp.pagesFromPage.Reset(); } StopFormattingThread(); } UpdateStatus(); }
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: // Get the window and client dimensions GetClientRect(hWnd, &window.rect); int width = window.rect.right - window.rect.left; int height = window.rect.bottom - window.rect.top; // Create toolbar toolbar.hwnd = CreateWindow(TOOLBARCLASSNAME, NULL, WS_VISIBLE | WS_CHILD | TBSTYLE_TOOLTIPS, 0, 0, 0, 0, hWnd, (HMENU)TOOLBAR_ID, hInst, NULL); SendMessage(toolbar.hwnd, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); SendMessage(toolbar.hwnd, TB_SETBITMAPSIZE, 0, MAKELONG(24, 24)); SendMessage(toolbar.hwnd, TB_SETMAXTEXTROWS, 0, 0); // Add bitmap AddToolbarBitmap(toolbar.hwnd, "Toolbar"); // Add buttons AddToolbarButtons(toolbar.hwnd); // Resize toolbar SendMessage(toolbar.hwnd, TB_AUTOSIZE, 0, 0); GetWindowRect(toolbar.hwnd, &toolbar.rect); MapWindowPoints(NULL, hWnd, (POINT *)&toolbar.rect, 2); // Create status bar status.hwnd = CreateWindow(STATUSCLASSNAME, " Timebase: 1.0ms", WS_VISIBLE | WS_CHILD | SBARS_SIZEGRIP, 0, 0, 0, 0, hWnd, (HMENU)STATUS_ID, hInst, NULL); GetWindowRect(status.hwnd, &status.rect); MapWindowPoints(NULL, hWnd, (POINT *)&status.rect, 2); // Create tooltip tooltip.hwnd = CreateWindow(TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hWnd, NULL, hInst, NULL); SetWindowPos(tooltip.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); tooltip.info.cbSize = sizeof(tooltip.info); tooltip.info.hwnd = hWnd; tooltip.info.uFlags = TTF_IDISHWND | TTF_SUBCLASS; // Create X scale xscale.hwnd = CreateWindow(WC_STATIC, NULL, WS_VISIBLE | WS_CHILD | SS_NOTIFY | SS_OWNERDRAW, 0, status.rect.top - SCALE_HEIGHT, width, SCALE_HEIGHT, hWnd, (HMENU)XSCALE_ID, hInst, NULL); GetWindowRect(xscale.hwnd, &xscale.rect); MapWindowPoints(NULL, hWnd, (POINT *)&xscale.rect, 2); // Add X scale to tooltip tooltip.info.uId = (UINT_PTR)xscale.hwnd; tooltip.info.lpszText = "X scale"; SendMessage(tooltip.hwnd, TTM_ADDTOOL, 0, (LPARAM) &tooltip.info); // Create Y scale yscale.hwnd = CreateWindow(WC_STATIC, NULL, WS_VISIBLE | WS_CHILD | SS_NOTIFY | SS_OWNERDRAW, 0, toolbar.rect.bottom, SCALE_WIDTH, xscale.rect.top - toolbar.rect.bottom, hWnd, (HMENU)YSCALE_ID, hInst, NULL); GetWindowRect(yscale.hwnd, &yscale.rect); MapWindowPoints(NULL, hWnd, (POINT *)&yscale.rect, 2); // Add Y scale to tooltip tooltip.info.uId = (UINT_PTR)yscale.hwnd; tooltip.info.lpszText = "Y scale"; SendMessage(tooltip.hwnd, TTM_ADDTOOL, 0, (LPARAM) &tooltip.info); // Create scope scope.hwnd = CreateWindow(WC_STATIC, NULL, WS_VISIBLE | WS_CHILD | SS_NOTIFY | SS_OWNERDRAW, yscale.rect.right, toolbar.rect.bottom, width - yscale.rect.right, xscale.rect.top - toolbar.rect.bottom, hWnd, (HMENU)SCOPE_ID, hInst, NULL); // Add scope to tooltip tooltip.info.uId = (UINT_PTR)scope.hwnd; tooltip.info.lpszText = "Scope display"; SendMessage(tooltip.hwnd, TTM_ADDTOOL, 0, (LPARAM) &tooltip.info); // Start audio thread audio.thread = CreateThread(NULL, 0, AudioThread, hWnd, 0, &audio.id); break; // Colour static text case WM_CTLCOLORSTATIC: return (LRESULT)GetSysColorBrush(COLOR_WINDOW); break; // Draw item case WM_DRAWITEM: return DrawItem(wParam, lParam); break; // Disable menus by capturing this message case WM_INITMENU: break; // Capture system character key to stop pop up menus and other // nonsense case WM_SYSCHAR: break; // Buttons case WM_COMMAND: switch (LOWORD(wParam)) { // Level case LEVEL_ID: DisplayLevelControl(hWnd, wParam, lParam); break; // Bright line case BRIGHT_ID: scope.bright = !scope.bright; break; // Single shot case SINGLE_ID: scope.single = !scope.single; break; // Trigger case TRIGGER_ID: scope.trigger = TRUE; break; // Sync case SYNC_ID: scope.polarity = !scope.polarity; SendMessage(toolbar.hwnd, TB_CHANGEBITMAP, SYNC_ID, scope.polarity? NEGATIVE_BM: POSITIVE_BM); break; // Timebase case TIMEBASE_ID: DisplayTimebaseMenu(hWnd, wParam, lParam); break; // Storage case STORAGE_ID: scope.storage = !scope.storage; break; // Clear case CLEAR_ID: scope.clear = TRUE; break; // Left case LEFT_ID: xscale.start -= xscale.step; if (xscale.start < 0) xscale.start = 0; float scale = 1.0 / (((float)SAMPLE_RATE / 100000.0) * scope.scale); scope.start = xscale.start / scale; InvalidateRgn(xscale.hwnd, NULL, TRUE); break; // Right case RIGHT_ID: scale = 1.0 / (((float)SAMPLE_RATE / 100000.0) * scope.scale); xscale.start += xscale.step; scope.start = xscale.start / scale; if (scope.start >= scope.length) { xscale.start -= xscale.step; scope.start = xscale.start / scale; } InvalidateRgn(xscale.hwnd, NULL, TRUE); break; // Start case START_ID: scope.start = 0; scope.index = 0; xscale.start = 0; InvalidateRgn(xscale.hwnd, NULL, TRUE); break; // End case END_ID: scale = 1.0 / (((float)SAMPLE_RATE / 100000.0) * scope.scale); while (scope.start < scope.length) { xscale.start += xscale.step; scope.start = xscale.start / scale; } xscale.start -= xscale.step; scope.start = xscale.start / scale; InvalidateRgn(xscale.hwnd, NULL, TRUE); break; // Reset case RESET_ID: scope.index = 0; scope.start = 0; scope.bright = FALSE; scope.single = FALSE; scope.polarity = FALSE; scope.storage = FALSE; SendMessage(toolbar.hwnd, TB_CHECKBUTTON, BRIGHT_ID, FALSE); SendMessage(toolbar.hwnd, TB_CHECKBUTTON, SINGLE_ID, FALSE); SendMessage(toolbar.hwnd, TB_CHANGEBITMAP, SYNC_ID, POSITIVE_BM); SendMessage(toolbar.hwnd, TB_CHECKBUTTON, STORAGE_ID, FALSE); break; // Scope case SCOPE_ID: ScopeClicked(wParam, lParam); break; } // Update status UpdateStatus(); // Set the focus back to the window SetFocus(hWnd); break; // Menu command case WM_MENUCOMMAND: // Set up timebase timebase.index = wParam; break; // Notify case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case TBN_DROPDOWN: switch (((LPNMTOOLBAR)lParam)->iItem) { case LEVEL_ID: DisplayLevelControl(hWnd, wParam, lParam); break; case TIMEBASE_ID: DisplayTimebaseMenu(hWnd, wParam, lParam); break; } return TBDDRET_DEFAULT; break; } break; // Size case WM_SIZE: EnumChildWindows(hWnd, EnumChildProc, (LPARAM)hWnd); break; // Sizing case WM_SIZING: return WindowResizing(hWnd, wParam, lParam); break; // Key pressed case WM_KEYDOWN: KeyDown(wParam, lParam); break; // Mixer control change case MM_MIXM_CONTROL_CHANGE: LevelChange(wParam, lParam); break; // Process other messages. case WM_DESTROY: waveInStop(audio.hwi); waveInClose(audio.hwi); PostQuitMessage(0); break; // Everything else default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; }
//***************************************************************************** // // This function listens for a link request from another SimpliciTI device. // //***************************************************************************** tBoolean LinkFrom(void) { linkID_t linkID1; uint8_t pucMsg[MAX_APP_PAYLOAD], ucLen, ucLtid; unsigned long ulCount; smplStatus_t eRetcode; // // Tell the user what we're doing. // UpdateStatus(false, "Listening for link..."); // // Keep the compiler happy. // eRetcode = SMPL_TIMEOUT; // // Turn on LED 1 to indicate that we are listening. // SetLED(1, true); // // Listen for link for 10 seconds or so. This logic may fail if you // happen to have sat around for about 13.6 years between starting the // example and pressing the mode selection button. I suspect I will be // forgiven for this. // ulCount = g_ulSysTickCount + (LINK_TIMEOUT_SECONDS * TICKS_PER_SECOND); while (ulCount > g_ulSysTickCount) { // // Process our message queue to keep the widget library happy. // WidgetMessageQueueProcess(); // // Listen for a link. This call takes quite some time to return. // eRetcode = SMPL_LinkListen(&linkID1); // // Was the link successful? // if (SMPL_SUCCESS == eRetcode) { // // Yes - drop out of the loop. // break; } } // // Did we link successfully? // if(eRetcode != SMPL_SUCCESS) { // // No - Tell the user what happened and return an error. // UpdateStatus(false, "Failed to link!"); return(false); } // // Turn off LED 1 to indicate that our listen succeeded. // UpdateStatus(false, "Link succeeded."); SetLED(1, false); // // Clear our message counter. // ulCount = 0; // // Enter an infinite loop polling for messages. // while (1) { // // Turn the radio off and pretend to sleep for a second or so. // SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0); SPIN_ABOUT_A_SECOND; /* emulate MCU sleeping */ // // Turn the radio back on again. // SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0); // // Were any messages "received"? // // The receive call results in polling the Access Point. The success // case occurs when a payload is actually returned. When there is no // frame waiting for the device a frame with no payload is returned by // the Access Point. Note that this loop will retrieve any and all // frames that are waiting for this device on the specified link ID. // This call will also return frames that were received directly. It // is possible to get frames that were repeated either from the initial // transmission from the peer or via a Range Extender. This is why we // implement the TID check. // do { // // Receive whatever the AP has for us. // eRetcode = SMPL_Receive(linkID1, pucMsg, &ucLen); // // Did we get a real frame? // if((eRetcode == SMPL_SUCCESS) && ucLen) { // // Tell the user what's going on. // UpdateStatus(false, "Received msg %d", ++ulCount); // // Process our message queue to keep the widget library happy. // WidgetMessageQueueProcess(); // // Check the application sequence number to detect late or missing // frames. // ucLtid = *(pucMsg+1); if (ucLtid) { // // If the current TID is non-zero and the last one we saw was // less than this one assume we've received the 'next' one. // if (g_ucTid < ucLtid) { // // 'Next' frame. We may have missed some but we don't // care. // if ((*pucMsg == 1) || (*pucMsg == 2)) { // // We're good. Toggle the requested LED. // ToggleLED(*pucMsg); } // // Remember the last TID. // g_ucTid = ucLtid; } // // If current TID is non-zero and less than or equal to the last // one we saw assume we received a duplicate. Just ignore it. // } else { // // Current TID is zero so the count wrapped or we just started. // Let's just accept it and start over. // if ((*pucMsg == 1) || (*pucMsg == 2)) { // // We're good. Toggle the requested LED. // ToggleLED(*pucMsg); } // // Remember the last TID. // g_ucTid = ucLtid; } } } while ((eRetcode == SMPL_SUCCESS) & ucLen); } }
DWORD WINAPI AudioThread(LPVOID lpParameter) { // Set up timebase scope.scale = timebase.values[timebase.index]; xscale.scale = scope.scale; xscale.step = 500 * xscale.scale; // Update display InvalidateRgn(xscale.hwnd, NULL, TRUE); UpdateStatus(); // Create wave format structure static WAVEFORMATEX wf = {WAVE_FORMAT_PCM, CHANNELS, SAMPLE_RATE, SAMPLE_RATE * BLOCK_ALIGN, BLOCK_ALIGN, BITS_PER_SAMPLE, 0}; MMRESULT mmr; // Open a waveform audio input device mmr = waveInOpen(&audio.hwi, WAVE_MAPPER | WAVE_FORMAT_DIRECT, &wf, (DWORD_PTR)audio.id, (DWORD_PTR)NULL, CALLBACK_THREAD); if (mmr != MMSYSERR_NOERROR) { static char s[64]; waveInGetErrorText(mmr, s, sizeof(s)); MessageBox(window.hwnd, s, "WaveInOpen", MB_OK | MB_ICONERROR); return mmr; } do { // Mixer structures static MIXERLINE mxl = {sizeof(MIXERLINE)}; static MIXERCONTROL mxc = {sizeof(MIXERCONTROL)}; static MIXERLINECONTROLS mxlc = {sizeof(MIXERLINECONTROLS)}; static MIXERCONTROLDETAILS mxcd = {sizeof(MIXERCONTROLDETAILS)}; static MIXERCONTROLDETAILS_UNSIGNED mxcdu; // Open a mixer device mmr = mixerOpen(&mixer.hmx, (UINT)audio.hwi, (DWORD_PTR)window.hwnd, 0, CALLBACK_WINDOW | MIXER_OBJECTF_HWAVEIN); if (mmr != MMSYSERR_NOERROR) break; // Mixer line types DWORD types[] = {MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE, MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY, MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER, MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE, MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER, MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC, MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED, MIXERLINE_COMPONENTTYPE_SRC_DIGITAL, MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT, MIXERLINE_COMPONENTTYPE_SRC_ANALOG, MIXERLINE_COMPONENTTYPE_SRC_LINE}; // Get mixer line info for (int i = 0; i < Length(types); i++) { // Try a component type mxl.dwComponentType = types[i]; // Get the info mmr = mixerGetLineInfo((HMIXEROBJ)mixer.hmx, &mxl, MIXER_GETLINEINFOF_COMPONENTTYPE); // Try again if error if (mmr != MMSYSERR_NOERROR) continue; // Check if line is active if (mxl.fdwLine & MIXERLINE_LINEF_ACTIVE) { mixer.pmxl = &mxl; break; } } // No mixer line if (mixer.pmxl == NULL) break; // Get a volume control mxlc.dwLineID = mxl.dwLineID; mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; mxlc.cControls = 1; mxlc.cbmxctrl = sizeof(mxc); mxlc.pamxctrl = &mxc; mmr = mixerGetLineControls((HMIXEROBJ)mixer.hmx, &mxlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); if (mmr != MMSYSERR_NOERROR) break; // Got a volume control mixer.pmxc = &mxc; // Get the control details mxcd.dwControlID = mxc.dwControlID; mxcd.cChannels = MIXERCONTROL_CONTROLF_UNIFORM; mxcd.cbDetails = sizeof(mxcdu); mxcd.paDetails = &mxcdu; mmr = mixerGetControlDetails((HMIXEROBJ)mixer.hmx, &mxcd, MIXER_GETCONTROLDETAILSF_VALUE); if (mmr != MMSYSERR_NOERROR) break; mixer.pmxcd = &mxcd; mixer.pmxcdu = &mxcdu; } while (FALSE); // Create the waveform audio input buffers and structures static short data[4][STEP]; static WAVEHDR hdrs[4] = {{(LPSTR)data[0], sizeof(data[0]), 0, 0, 0, 0}, {(LPSTR)data[1], sizeof(data[1]), 0, 0, 0, 0}, {(LPSTR)data[2], sizeof(data[2]), 0, 0, 0, 0}, {(LPSTR)data[3], sizeof(data[3]), 0, 0, 0, 0}}; for (int i = 0; i < Length(hdrs); i++) { // Prepare a waveform audio input header mmr = waveInPrepareHeader(audio.hwi, &hdrs[i], sizeof(WAVEHDR)); if (mmr != MMSYSERR_NOERROR) { static char s[64]; waveInGetErrorText(mmr, s, sizeof(s)); MessageBox(window.hwnd, s, "WaveInPrepareHeader", MB_OK | MB_ICONERROR); return mmr; } // Add a waveform audio input buffer mmr = waveInAddBuffer(audio.hwi, &hdrs[i], sizeof(WAVEHDR)); if (mmr != MMSYSERR_NOERROR) { static char s[64]; waveInGetErrorText(mmr, s, sizeof(s)); MessageBox(window.hwnd, s, "WaveInAddBuffer", MB_OK | MB_ICONERROR); return mmr; } } // Start the waveform audio input mmr = waveInStart(audio.hwi); if (mmr != MMSYSERR_NOERROR) { static char s[64]; waveInGetErrorText(mmr, s, sizeof(s)); MessageBox(window.hwnd, s, "WaveInStart", MB_OK | MB_ICONERROR); return mmr; } // Create a message loop for processing thread messages MSG msg; BOOL flag; while ((flag = GetMessage(&msg, (HWND)-1, 0, 0)) != 0) { if (flag == -1) break; // Process messages switch (msg.message) { // Audio input opened case MM_WIM_OPEN: // Not used break; // Audio input data case MM_WIM_DATA: WaveInData(msg.wParam, msg.lParam); break; // Audio input closed case MM_WIM_CLOSE: // Not used break; } } return msg.wParam; }
void WaveInData(WPARAM wParam, LPARAM lParam) { static int index; static int count; static short state; static short last; // Create buffer for processing the audio data static short buffer[SAMPLES]; // Initialise data structs if (scope.data == NULL) { scope.data = buffer; scope.length = timebase.counts[timebase.index]; } // Copy the input data short *data = (short *)((WAVEHDR *)lParam)->lpData; // State machine for sync and copying data to display buffer switch (state) { // INIT: waiting for sync case INIT: index = 0; if (scope.bright) state++; else { if (scope.single && !scope.trigger) break; // Initialise sync int dx = 0; // Sync polarity if (scope.polarity) { for (int i = 0; i < STEP; i++) { dx = data[i] - last; if (dx < 0 && last > 0 && data[i] < 0) { index = i; state++; break; } last = data[i]; } } else { for (int i = 0; i < STEP; i++) { dx = data[i] - last; if (dx > 0 && last < 0 && data[i] > 0) { index = i; state++; break; } last = data[i]; } } } // No sync, try next time if (state == 0) break; // Reset trigger if (scope.single && scope.trigger) scope.trigger = FALSE; // FIRST: First chunk of data case FIRST: // Update count count = timebase.counts[timebase.index]; scope.length = count; // Copy data memmove(buffer, data + index, (STEP - index) * sizeof(short)); index = STEP - index; // If done, wait for sync again if (index >= count) state = INIT; // Else get some more data next time else state++; break; // NEXT: Subsequent chunks of data case NEXT: // Copy data memmove(buffer + index, data, STEP * sizeof(short)); index += STEP; // Done, wait for sync again if (index >= count) state = INIT; // Else if last but one chunk, get last chunk next time else if (index + STEP >= count) state++; break; // LAST: Last chunk of data case LAST: // Copy data memmove(buffer + index, data, (count - index) * sizeof(short)); // Wait for sync next time state = INIT; break; } // Give the buffer back waveInAddBuffer(audio.hwi, (WAVEHDR *)lParam, sizeof(WAVEHDR)); if (scope.scale != timebase.values[timebase.index]) { // Set up scale scope.scale = timebase.values[timebase.index]; xscale.scale = scope.scale; xscale.step = 500 * xscale.scale; // Reset start scope.start = 0; xscale.start = 0; // Update display InvalidateRgn(xscale.hwnd, NULL, TRUE); UpdateStatus(); } // Update display InvalidateRgn(scope.hwnd, NULL, TRUE); }
NS_IMETHODIMP MailEwsLoadCalendarItemsCallback::LocalOperation(void * response) { load_item_response * r = (load_item_response *)response; if (!r) return NS_OK; ews_item ** item = r->item; nsresult rv; mailews_logger << "create calIEvent on main threads:" << r->item_count << std::endl; nsCOMPtr<nsIMutableArray> calendarItems = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCString ownerEmail; rv = GetOwnerEmail(m_pIncomingServer, ownerEmail); NS_ENSURE_SUCCESS(rv, rv); for(int i=0;i < r->item_count;i++) { if (item[i]->item_type == EWS_Item_Calendar) { ews_calendar_item * cal_item = (ews_calendar_item*)item[i]; nsCOMPtr<calIEvent> e = do_CreateInstance(CAL_EVENT_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); if (item[i]->mime_content) { char *decodedContent = PL_Base64Decode(item[i]->mime_content, strlen(item[i]->mime_content), nullptr); nsCString data; data.Adopt(decodedContent); CleanUpIcalString(data); rv = e->SetIcalString(data); NS_ENSURE_SUCCESS(rv, rv); nsCString uid(((ews_calendar_item*)item[i])->uid); if (uid.IsEmpty()) { GenerateUid(uid); mailews_logger << "generate uid for event:" << item[i]->item_id << "," << item[i]->change_key << "," << uid.get() << std::endl << data.get() << std::endl; } e->SetId(uid); nsCOMPtr<calIDateTime> dtStart; e->GetStartDate(getter_AddRefs(dtStart)); if (!dtStart) { mailews_logger << "skip no start date event:" << item[i]->item_id << "," << item[i]->change_key << "," << uid.get() << std::endl << data.get() << std::endl; continue; } rv = e->RemoveAllAttendees(); NS_ENSURE_SUCCESS(rv, rv); rv = UpdateAttendee(e, (ews_calendar_item*)item[i], ownerEmail, true); NS_ENSURE_SUCCESS(rv, rv); rv = UpdateAttendee(e, (ews_calendar_item*)item[i], ownerEmail, false); NS_ENSURE_SUCCESS(rv, rv); rv = UpdateOccurrence(e, (ews_calendar_item*)item[i]); NS_ENSURE_SUCCESS(rv, rv); rv = UpdateStatus(e, ownerEmail); NS_ENSURE_SUCCESS(rv, rv); } else { rv = From(m_pIncomingServer, (ews_calendar_item *)item[i], e); NS_ENSURE_SUCCESS(rv, rv); } //Save item id rv = SetPropertyString(e, NS_LITERAL_STRING("X-ITEM-ID"), nsCString(item[i]->item_id)); NS_ENSURE_SUCCESS(rv, rv); //Save change key rv = SetPropertyString(e, NS_LITERAL_STRING("X-CHANGE-KEY"), nsCString(item[i]->change_key)); NS_ENSURE_SUCCESS(rv, rv); //Save Master id if (cal_item->recurring_master_id) { rv = SetPropertyString(e, NS_LITERAL_STRING("X-MASTER_ID"), nsCString(cal_item->recurring_master_id)); NS_ENSURE_SUCCESS(rv, rv); rv = SetPropertyString(e, NS_LITERAL_STRING("X-MASTER_UID"), nsCString(cal_item->recurring_master_uid)); NS_ENSURE_SUCCESS(rv, rv); } else if (cal_item->calendar_item_type == EWS_CalendarItemType_Single) { e->SetRecurrenceId(nullptr); } calendarItems->AppendElement(e, false); } } nsCOMPtr<nsIArray> resultArray(do_QueryInterface(calendarItems)); mailews_logger << "create calIEvent on main threads done:" << r->item_count << std::endl; return m_pCalCallback->OnResult(resultArray); }
// update the user lists.. void IRCQuery::ChangeUserNick(char *OtherNick) { if (m_OtherNick) free(m_OtherNick); m_OtherNick = strdup(OtherNick); UpdateStatus(); }
//***************************************************************************** // // Main application entry function. // //***************************************************************************** int main(void) { tBoolean bRetcode; smplStatus_t eRetcode; ioctlScanChan_t sScan; freqEntry_t pFreq[NWK_FREQ_TBL_SIZE]; tBoolean bFirstTimeThrough; unsigned long ulLoop; uint8_t ucLast; // // Set the system clock to run at 50MHz from the PLL // ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // NB: We don't call PinoutSet() in this testcase since the EM header // expansion board doesn't currently have an I2C ID EEPROM. If we did // call PinoutSet() this would configure all the EPI pins for SDRAM and // we don't want to do this. // g_eDaughterType = DAUGHTER_NONE; // // Enable peripherals required to drive the LCD. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH); // // Configure SysTick for a 10Hz interrupt. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND); ROM_SysTickEnable(); ROM_SysTickIntEnable(); // // Initialize the display driver. // Kitronix320x240x16_SSD2119Init(); // // Initialize the touch screen driver. // TouchScreenInit(); // // Set the touch screen event handler. // TouchScreenCallbackSet(WidgetPointerMessage); // // Add the compile-time defined widgets to the widget tree. // WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading); // // Initialize the status string. // UpdateStatus("Initializing..."); // // Paint the widget tree to make sure they all appear on the display. // WidgetPaint(WIDGET_ROOT); // // Initialize the SimpliciTI BSP. // BSP_Init(); // // Set the SimpliciTI device address using the current Ethernet MAC address // to ensure something like uniqueness. // bRetcode = SetSimpliciTIAddress(); // // Did we have a problem with the address? // if(!bRetcode) { // // Yes - make sure the display is updated then hang the app. // WidgetMessageQueueProcess(); while(1) { // // MAC address is not set so hang the app. // } } // // Turn on both our LEDs // SetLED(1, true); SetLED(2, true); UpdateStatus("Joining network..."); // // Initialize the SimpliciTI stack but don't set any receive callback. // while(1) { eRetcode = SMPL_Init((uint8_t (*)(linkID_t))0); if(eRetcode == SMPL_SUCCESS) { break; } ToggleLED(1); ToggleLED(2); SPIN_ABOUT_A_SECOND; } // // Tell the user what's up. // UpdateStatus("Sniffing..."); // // Set up for our first sniff. // sScan.freq = pFreq; bFirstTimeThrough = true; ucLast = 0xFF; // // Keep sniffing forever. // while (1) { // // Wait a while. // SPIN_ABOUT_A_QUARTER_SECOND; // // Scan for the active channel. // SMPL_Ioctl(IOCTL_OBJ_FREQ, IOCTL_ACT_SCAN, &sScan); // // Did we find a signal? // if (1 == sScan.numChan) { if (bFirstTimeThrough) { // // Set the initial LED state. // SetLED(1, false); SetLED(2, true); // // Wait a while. // for(ulLoop = 0; ulLoop < 15; ulLoop--) { // // Toggle both LEDs and wait a bit. // ToggleLED(1); ToggleLED(2); SPIN_ABOUT_A_QUARTER_SECOND; } bFirstTimeThrough = false; } // // Has the channel changed since the last time we updated the // display? // if(pFreq[0].logicalChan != ucLast) { // // Remember the channel we just detected. // ucLast = pFreq[0].logicalChan; // // Tell the user which channel we found to be active. // UpdateStatus("Active channel is %d.", pFreq[0].logicalChan); // // Set the "LEDs" to mimic the behavior of the MSP430 versions // of this application. // switch(pFreq[0].logicalChan) { case 0: { /* GREEN OFF */ /* RED OFF */ SetLED(1, false); SetLED(2, false); break; } case 1: { /* GREEN OFF */ /* RED ON */ SetLED(1, false); SetLED(2, true); break; } case 2: { /* GREEN ON */ /* RED OFF */ SetLED(1, true); SetLED(2, false); break; } case 3: { /* GREEN ON */ /* RED ON */ SetLED(1, true); SetLED(2, true); break; } case 4: { /* blink them both... */ SetLED(1, false); SetLED(2, false); SPIN_ABOUT_A_QUARTER_SECOND; SetLED(1, true); SetLED(2, true); SPIN_ABOUT_A_QUARTER_SECOND; SetLED(1, false); SetLED(2, false); } } } } } }
void CPanasonicNode::SendCommand(const std::string command) { std::string sPanasonicCall = ""; if (m_CurrentStatus.Status() == MSTAT_OFF) { // no point trying to send a command if we know the device is off // no network on Panasonic TV's when it's in the off state _log.Log(LOG_ERROR, "Panasonic Plugin: (%s) Device is Off, cannot send command.", m_Name.c_str()); return; } if (command == "Home") sPanasonicCall = buildXMLStringNetCtl("CANCEL-ONOFF"); else if (command == "Up") sPanasonicCall = buildXMLStringNetCtl("UP-ONOFF"); else if (command == "Down") sPanasonicCall = buildXMLStringNetCtl("DOWN-ONOFF"); else if (command == "Left") sPanasonicCall = buildXMLStringNetCtl("LEFT-ONOFF"); else if (command == "Right") sPanasonicCall = buildXMLStringNetCtl("RIGHT-ONOFF"); else if (command == "ChannelUp") sPanasonicCall = buildXMLStringNetCtl("CH_UP-ONOFF"); else if (command == "ChannelDown") sPanasonicCall = buildXMLStringNetCtl("CH_DOWN-ONOFF"); else if (command == "VolumeUp") sPanasonicCall = buildXMLStringNetCtl("VOLUP-ONOFF"); else if (command == "VolumeDown") sPanasonicCall = buildXMLStringNetCtl("VOLDOWN-ONOFF"); else if (command == "Mute") sPanasonicCall = buildXMLStringNetCtl("MUTE-ONOFF"); else if (command == "inputtv") sPanasonicCall = buildXMLStringNetCtl("TV-ONOFF"); else if (command == "inputav") sPanasonicCall = buildXMLStringNetCtl("AV-ONOFF"); else if (command == "Red") sPanasonicCall = buildXMLStringNetCtl("RED-ONOFF"); else if (command == "Green") sPanasonicCall = buildXMLStringNetCtl("GREEN-ONOFF"); else if (command == "Blue") sPanasonicCall = buildXMLStringNetCtl("BLUE-ONOFF"); else if (command == "Yellow") sPanasonicCall = buildXMLStringNetCtl("YELLOW-ONOFF"); else if (command == "ContextMenu") sPanasonicCall = buildXMLStringNetCtl("MENU-ONOFF"); else if (command == "Channels" || command == "guide") sPanasonicCall = buildXMLStringNetCtl("EPG-ONOFF"); else if (command == "Back" || command == "Return") sPanasonicCall = buildXMLStringNetCtl("RETURN-ONOFF"); else if (command == "Select") sPanasonicCall = buildXMLStringNetCtl("ENTER-ONOFF"); else if (command == "Info") sPanasonicCall = buildXMLStringNetCtl("INFO-ONOFF"); else if (command == "1") sPanasonicCall = buildXMLStringNetCtl("D1-ONOFF"); else if (command == "2") sPanasonicCall = buildXMLStringNetCtl("D2-ONOFF"); else if (command == "3") sPanasonicCall = buildXMLStringNetCtl("D3-ONOFF"); else if (command == "4") sPanasonicCall = buildXMLStringNetCtl("D4-ONOFF"); else if (command == "5") sPanasonicCall = buildXMLStringNetCtl("D5-ONOFF"); else if (command == "6") sPanasonicCall = buildXMLStringNetCtl("D6-ONOFF"); else if (command == "7") sPanasonicCall = buildXMLStringNetCtl("D7-ONOFF"); else if (command == "8") sPanasonicCall = buildXMLStringNetCtl("D8-ONOFF"); else if (command == "9") sPanasonicCall = buildXMLStringNetCtl("D9-ONOFF"); else if (command == "0") sPanasonicCall = buildXMLStringNetCtl("D0-ONOFF"); else if (command == "hdmi1") sPanasonicCall = buildXMLStringNetCtl("HDMI1"); else if (command == "hdmi2") sPanasonicCall = buildXMLStringNetCtl("HDMI2"); else if (command == "hdmi3") sPanasonicCall = buildXMLStringNetCtl("HDMI3"); else if (command == "hdmi4") sPanasonicCall = buildXMLStringNetCtl("HDMI4"); else if (command == "Rewind") sPanasonicCall = buildXMLStringNetCtl("REW-ONOFF"); else if (command == "FastForward") sPanasonicCall = buildXMLStringNetCtl("FF-ONOFF"); else if (command == "PlayPause") sPanasonicCall = buildXMLStringNetCtl("PLAY-ONOFF"); else if (command == "Stop") sPanasonicCall = buildXMLStringNetCtl("STOP-ONOFF"); else if (command == "pause") sPanasonicCall = buildXMLStringNetCtl("PAUSE-ONOFF"); else if (command == "Power" || command == "power" || command == "off" || command == "Off") sPanasonicCall = buildXMLStringNetCtl("POWER-ONOFF"); else if (command == "ShowSubtitles") sPanasonicCall = buildXMLStringNetCtl("STTL-ONOFF"); else if (command == "On" || command == "on") { _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Can't use command: '%s'.", m_Name.c_str(), command.c_str()); // Workaround to get the plugin to reset device status, otherwise the UI goes out of sync with plugin m_CurrentStatus.Clear(); m_CurrentStatus.Status(MSTAT_UNKNOWN); UpdateStatus(true); } else _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Unknown command: '%s'.", m_Name.c_str(), command.c_str()); if (sPanasonicCall.length()) { if (handleWriteAndRead(sPanasonicCall) != "ERROR") _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Sent command: '%s'.", m_Name.c_str(), sPanasonicCall.c_str()); //else // _log.Log(LOG_NORM, "Panasonic Plugin: (%s) can't send command: '%s'.", m_Name.c_str(), sPanasonicCall.c_str()); } }
//***************************************************************************** // // This function attempts to link to another SimpliciTI device by sending a // link request. // //***************************************************************************** tBoolean LinkTo(void) { linkID_t linkID1; uint8_t pucMsg[2], ucWrap; unsigned long ulCount; smplStatus_t eRetcode; // // Our message counter hasn't wrapped. // ucWrap = 0; // // Turn on LED 2 // SetLED(2, true); // // Tell the user what we're doing. // UpdateStatus(false, "Attempting to link..."); // // Try to link for about 10 seconds. // for(ulCount = 0; ulCount < LINK_TIMEOUT_SECONDS; ulCount++) { // // Try to link. // eRetcode = SMPL_Link(&linkID1); // // Did we succeed? // if(eRetcode == SMPL_SUCCESS) { // // Yes - drop out of the loop. // break; } // // We didn't link so toggle the LEDs, wait a bit then try again. // ToggleLED(1); ToggleLED(2); SPIN_ABOUT_A_SECOND; } // // Did the link succeed? // if(eRetcode != SMPL_SUCCESS) { // // No - return an error code. // UpdateStatus(false, "Failed to link!"); return(false); } else { UpdateStatus(false, "Link succeeded."); } // // Turn off the second LED now that we have linked. // SetLED(2, false); #ifdef FREQUENCY_AGILITY // // The radio comes up with Rx off. If Frequency Agility is enabled we need // it to be on so we don't miss a channel change broadcast. We need to // hear this since this application has no ack. The broadcast from the AP // is, therefore, the only way to find out about a channel change. // SMPL_Ioctl( IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_RXON, 0); #endif // // Set up the initial message and message counter. // pucMsg[0] = 2; pucMsg[1] = ++g_ucTid; ulCount = 0; // // We've linked successfully so drop into an infinite loop during which // we send messages to the receiver every 5 seconds or so. // while (1) { // // Send a message every 5 seconds. This could be emulating a sleep. // #ifndef FREQUENCY_AGILITY // // If Frequency Agility is disabled we don't need to listen for the // broadcast channel change command. // SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_SLEEP, 0); #endif // // Kill about 5 seconds. // SPIN_ABOUT_A_SECOND; SPIN_ABOUT_A_SECOND; SPIN_ABOUT_A_SECOND; SPIN_ABOUT_A_SECOND; SPIN_ABOUT_A_SECOND; #ifndef FREQUENCY_AGILITY // // See comment above...If Frequency Agility is not enabled we never // listen so it is OK if we just awaken leaving Rx off. // SMPL_Ioctl(IOCTL_OBJ_RADIO, IOCTL_ACT_RADIO_AWAKE, 0); #endif // // Send a message. // eRetcode = SMPL_Send(linkID1, pucMsg, sizeof(pucMsg)); if (SMPL_SUCCESS == eRetcode) { // // Toggle LED 1 to indicate that we sent something. // ToggleLED(1); // // Set up the next message. Every 8th message toggle LED 1 instead // of LED 2 on the receiver. // pucMsg[0] = (++ucWrap & 0x7) ? 2 : 1; pucMsg[1] = ++g_ucTid; } // // Tell the user what we did. // UpdateStatus(false, "Sent msg %d (%s).", ++ulCount, MapSMPLStatus(eRetcode)); } }
void Rmp440LE::Initialize() { // Parameters std::string transportType, ipAddress, devicePort; int portNumber; std::string odometryTopic, jointStatesTopic, inertialTopic, pseTopic, motorStatusTopic, batteryTopic, velocityCommandTopic, deadmanTopic, audioCommandTopic, faultStatusTopic; double updateFrequency, maxTranslationalVelocity, maxTurnRate; m_NodeHandle.param("transport_type", transportType, std::string("udp")); m_NodeHandle.param("ip_address", ipAddress, std::string("192.168.0.40")); m_NodeHandle.param("port_number", portNumber, 8080); m_NodeHandle.param("device_port", devicePort, std::string("/dev/ttyACM0")); m_NodeHandle.param("update_frequency", updateFrequency, 50.0); m_NodeHandle.param("odometry_topic", odometryTopic, std::string("/rmp440le/odom")); m_NodeHandle.param("joint_states_topic", jointStatesTopic, std::string("/rmp440le/joint_states")); m_NodeHandle.param("inertial_topic", inertialTopic, std::string("/rmp440le/inertial")); m_NodeHandle.param("pse_topic", pseTopic, std::string("/rmp440le/pse")); m_NodeHandle.param("motor_status_topic", motorStatusTopic, std::string("/rmp440le/motor_status")); m_NodeHandle.param("battery_topic", batteryTopic, std::string("/rmp440le/battery")); m_NodeHandle.param("velocity_command_topic", velocityCommandTopic, std::string("/rmp440le/base/vel_cmd")); m_NodeHandle.param("deadman_topic", deadmanTopic, std::string("/rmp440le/deadman")); m_NodeHandle.param("audio_command_topic", audioCommandTopic, std::string("/rmp440le/audio_cmd")); m_NodeHandle.param("fault_status_topic", faultStatusTopic, std::string("/rmp440le/fault_status")); m_NodeHandle.param("max_translational_velocity", maxTranslationalVelocity, 8.0); m_NodeHandle.param("max_turn_rate", maxTurnRate, 4.4); // Start communication try { if (transportType == std::string("udp")) { if ((portNumber < 0) || (portNumber > PORT_NUMBER_MAX)) { ROS_ERROR_STREAM("Invalid port number: " << portNumber << " should be between 0 and " << PORT_NUMBER_MAX); return; } m_Rmp440LEInterface.Initialize(ipAddress, static_cast<uint16_t>(portNumber)); } else if (transportType == std::string("usb")) { m_Rmp440LEInterface.Initialize(devicePort); } else { ROS_ERROR_STREAM("Unknown/unsupported transport: " << transportType); return; } m_Rmp440LEInterface.ResetParamsToDefault(); m_Rmp440LEInterface.SetConfiguration(segway::RmpConfigurationCommandSet::SET_AUDIO_COMMAND, static_cast<uint32_t>(segway::MOTOR_AUDIO_TEST_SWEEP)); ros::Duration(2.0).sleep(); // Reset wheel encoders bool integratorsReset = m_Rmp440LEInterface.ResetIntegrators(segway::RESET_ALL_POSITION_DATA); if (!integratorsReset) { ROS_WARN_STREAM("Unable to reset position integrators."); } else { m_Rmp440LEInterface.SetConfiguration(segway::RmpConfigurationCommandSet::SET_AUDIO_COMMAND, static_cast<uint32_t>(segway::MOTOR_AUDIO_TEST_SWEEP)); } ros::Duration(2.0).sleep(); // Set the max speeds bool maxSpeedSet = m_Rmp440LEInterface.SetConfiguration(segway::RmpConfigurationCommandSet::SET_MAXIMUM_VELOCITY, static_cast<float>(maxTranslationalVelocity)); maxSpeedSet = maxSpeedSet && m_Rmp440LEInterface.SetConfiguration(segway::RmpConfigurationCommandSet::SET_MAXIMUM_TURN_RATE, static_cast<float>(maxTurnRate)); if (!maxSpeedSet) { ROS_WARN_STREAM("Unable to set the maximum speed."); } else { m_Rmp440LEInterface.SetConfiguration(segway::RmpConfigurationCommandSet::SET_AUDIO_COMMAND, static_cast<uint32_t>(segway::MOTOR_AUDIO_TEST_SWEEP)); } // Set up ROS communication m_OdometryPublisher = m_NodeHandle.advertise<nav_msgs::Odometry>(odometryTopic, 1); m_JointStatesPublisher = m_NodeHandle.advertise<sensor_msgs::JointState>(jointStatesTopic, 1); m_InertialPublisher = m_NodeHandle.advertise<sensor_msgs::Imu>(inertialTopic, 1); m_PsePublisher = m_NodeHandle.advertise<sensor_msgs::Imu>(pseTopic, 1); m_MotorStatusPublisher = m_NodeHandle.advertise<rmp_msgs::MotorStatus>(motorStatusTopic, 1); m_BatteryPublisher = m_NodeHandle.advertise<rmp_msgs::Battery>(batteryTopic, 1); m_FaultStatusPublisher = m_NodeHandle.advertise<rmp_msgs::FaultStatus>(faultStatusTopic, 1); m_VelocityCommandSubscriber = m_NodeHandle.subscribe<geometry_msgs::TwistStamped>(velocityCommandTopic, 1, &Rmp440LE::ProcessVelocityCommand, this); m_DeadmanSubscriber = m_NodeHandle.subscribe<rmp_msgs::BoolStamped>(deadmanTopic, 1, &Rmp440LE::ProcessDeadman, this); m_AudioCommandSubscriber = m_NodeHandle.subscribe<rmp_msgs::AudioCommand>(audioCommandTopic, 1, &Rmp440LE::ProcessAudioCommand, this); if (updateFrequency < UPDATE_FREQUENCY_MIN) { updateFrequency = UPDATE_FREQUENCY_MIN; } else if (updateFrequency > UPDATE_FREQUENCY_MAX) { updateFrequency = UPDATE_FREQUENCY_MAX; } ros::Rate rate(updateFrequency); InitializeMessages(); ros::Time lastUpdate = ros::Time::now(); ros::Duration maxUpdatePeriod(MAX_UPDATE_PERIOD); bool forceUpdate = false; // Processing loop while (ros::ok()) { ros::spinOnce(); if ((ros::Time::now() - lastUpdate) > maxUpdatePeriod) { forceUpdate = true; } if (m_Rmp440LEInterface.Update(forceUpdate)) { UpdateStatus(); lastUpdate = ros::Time::now(); forceUpdate = false; } rate.sleep(); } } catch (std::exception& rException) { ROS_ERROR_STREAM("Exception caught: " << rException.what() << ". Will return."); return; } }
//***************************************************************************** // // Main application entry function. // //***************************************************************************** int main(void) { tBoolean bSuccess, bRetcode, bInitialized; // // Set the system clock to run at 50MHz from the PLL // MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // NB: We don't call PinoutSet() in this testcase since the EM header // expansion board doesn't currently have an I2C ID EEPROM. If we did // call PinoutSet() this would configure all the EPI pins for SDRAM and // we don't want to do this. // g_eDaughterType = DAUGHTER_NONE; // // Enable peripherals required to drive the LCD. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH); // // Configure SysTick for a 10Hz interrupt. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND); ROM_SysTickEnable(); ROM_SysTickIntEnable(); // // Initialize the display driver. // Kitronix320x240x16_SSD2119Init(); // // Initialize the touch screen driver. // TouchScreenInit(); // // Set the touch screen event handler. // TouchScreenCallbackSet(WidgetPointerMessage); // // Add the compile-time defined widgets to the widget tree. // WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading); // // Paint the widget tree to make sure they all appear on the display. // WidgetPaint(WIDGET_ROOT); // // Initialize the SimpliciTI BSP. // BSP_Init(); // // Set the SimpliciTI device address using the current Ethernet MAC address // to ensure something like uniqueness. // bRetcode = SetSimpliciTIAddress(); if(!bRetcode) { // // The Ethernet MAC address can't have been set so hang here since we // don't have an address to use for SimpliciTI. // WidgetMessageQueueProcess(); while(1) { // // MAC address is not set so hang the app. // } } // // First time through, we need to initialize the SimpliciTI stack. // bInitialized = false; // // The main loop starts here now that we have joined the network. // while(1) { // // Tell the user what to do. // UpdateStatus(true, "Please choose the operating mode."); // // Now wait until the user selects whether we should run as the sender // or the receiver. // while(g_ulMode == MODE_UNDEFINED) { // // Just spin, processing UI messages and waiting for someone to // press one of the mode buttons. // WidgetMessageQueueProcess(); } // // At this point, the mode is set so remove the buttons from the // display and replace them with the LEDs. // WidgetRemove((tWidget *)&g_sBtnContainer); WidgetAdd((tWidget *)&g_sBackground, (tWidget *)&g_sLEDContainer); WidgetPaint((tWidget *)&g_sBackground); // // Tell the user what we're doing now. // UpdateStatus(false, "Joining network..."); if(!bInitialized) { // // Initialize the SimpliciTI stack We keep trying to initialize until // we get a success return code. This indicates that we have also // successfully joined the network. // while(SMPL_SUCCESS != SMPL_Init((uint8_t (*)(linkID_t))0)) { ToggleLED(1); ToggleLED(2); SPIN_ABOUT_A_SECOND; } // // Now that we are initialized, remember not to call this again. // bInitialized = true; } // // Once we have joined, turn both LEDs on and tell the user what we want // them to do. // SetLED(1, true); SetLED(2, true); // // Now call the function that initiates communication in // the desired mode. Note that these functions will not return // until communication is established or an error occurs. // if(g_ulMode == MODE_SENDER) { bSuccess = LinkTo(); } else { bSuccess = LinkFrom(); } // // If we were unsuccessfull, go back to the mode selection // display. // if(!bSuccess) { // // Remove the LEDs and show the buttons again. // WidgetRemove((tWidget *)&g_sLEDContainer); WidgetAdd((tWidget *)&g_sBackground, (tWidget *)&g_sBtnContainer); WidgetPaint((tWidget *)&g_sBackground); // // Tell the user what happened. // UpdateStatus(false, "Error establishing communication!"); // // Remember that we don't have an operating mode chosen. // g_ulMode = MODE_UNDEFINED; } } }
/* Convert the event from the callbacks in actions */ void InputManager::customEvent( QEvent *event ) { int i_type = event->type(); IMEvent *ple = static_cast<IMEvent *>(event); if( i_type == ItemChanged_Type ) UpdateMeta( ple->p_item ); if( !hasInput() ) return; /* Actions */ switch( i_type ) { case PositionUpdate_Type: UpdatePosition(); break; case StatisticsUpdate_Type: UpdateStats(); break; case ItemChanged_Type: /* Ignore ItemChanged_Type event that does not apply to our input */ if( p_item == ple->p_item ) { UpdateStatus(); // UpdateName(); UpdateArt(); /* Update duration of file */ } break; case ItemStateChanged_Type: // TODO: Fusion with above state UpdateStatus(); // UpdateName(); // UpdateNavigation(); This shouldn't be useful now // UpdateTeletext(); Same break; case NameChanged_Type: UpdateName(); break; case MetaChanged_Type: UpdateMeta(); UpdateName(); /* Needed for NowPlaying */ UpdateArt(); /* Art is part of meta in the core */ break; case InfoChanged_Type: UpdateInfo(); break; case ItemTitleChanged_Type: UpdateNavigation(); UpdateName(); /* Display the name of the Chapter, if exists */ break; case ItemRateChanged_Type: UpdateRate(); break; case ItemEsChanged_Type: UpdateTeletext(); // We don't do anything ES related. Why ? break; case ItemTeletextChanged_Type: UpdateTeletext(); break; case InterfaceVoutUpdate_Type: UpdateVout(); break; case SynchroChanged_Type: emit synchroChanged(); break; case CachingEvent_Type: UpdateCaching(); break; case BookmarksChanged_Type: emit bookmarksChanged(); break; case InterfaceAoutUpdate_Type: UpdateAout(); break; case RecordingEvent_Type: UpdateRecord(); break; case ProgramChanged_Type: UpdateProgramEvent(); break; case EPGEvent_Type: UpdateEPG(); break; default: msg_Warn( p_intf, "This shouldn't happen: %i", i_type ); assert(0); } }
// Redraw the current board and update status bar info void SimpleGoPanel::UpdateBoard() { memcpy(board, history[curmove], BOARDMEMORYLEN); wxClientDC dc(this); DrawBoard(dc, board); UpdateStatus(); }
void MultiSelectDlg::OnItemToggle(cb_unused wxCommandEvent& event) { UpdateStatus(); }
nsresult nsNNTPNewsgroupList::ProcessXOVERLINE(const char *line, uint32_t *status) { uint32_t message_number=0; // int32_t lines; bool read_p = false; nsresult rv = NS_OK; NS_ASSERTION(line, "null ptr"); if (!line) return NS_ERROR_NULL_POINTER; if (m_newsDB) { char *xoverline = PL_strdup(line); if (!xoverline) return NS_ERROR_OUT_OF_MEMORY; rv = ParseLine(xoverline, &message_number); PL_strfree(xoverline); xoverline = nullptr; if (NS_FAILED(rv)) return rv; } else return NS_ERROR_NOT_INITIALIZED; NS_ASSERTION(message_number > m_lastProcessedNumber || message_number == 1, "bad message_number"); if (m_set && message_number > m_lastProcessedNumber + 1) { /* There are some articles that XOVER skipped; they must no longer exist. Mark them as read in the newsrc, so we don't include them next time in our estimated number of unread messages. */ if (m_set->AddRange(m_lastProcessedNumber + 1, message_number - 1)) { /* This isn't really an important enough change to warrant causing the newsrc file to be saved; we haven't gathered any information that won't also be gathered for free next time. */ } } m_lastProcessedNumber = message_number; if (m_knownArts.set) { int result = m_knownArts.set->Add(message_number); if (result < 0) { if (status) *status = result; return NS_ERROR_NOT_INITIALIZED; } } if (message_number > m_lastMsgNumber) m_lastMsgNumber = message_number; else if (message_number < m_firstMsgNumber) m_firstMsgNumber = message_number; if (m_set) { read_p = m_set->IsMember(message_number); } /* Update the progress meter with a percentage of articles retrieved */ if (m_lastMsgNumber > m_firstMsgNumber) { int32_t totalToDownload = m_lastMsgToDownload - m_firstMsgToDownload + 1; int32_t lastIndex = m_lastProcessedNumber - m_firstMsgNumber + 1; int32_t numDownloaded = lastIndex; int32_t totIndex = m_lastMsgNumber - m_firstMsgNumber + 1; PRTime elapsedTime = PR_Now() - m_lastStatusUpdate; if (elapsedTime > MIN_STATUS_UPDATE_INTERVAL || lastIndex == totIndex) UpdateStatus(false, numDownloaded, totalToDownload); } return NS_OK; }
void ocpnCompass::SetColorScheme( ColorScheme cs ) { UpdateStatus( true ); }
/** DoLoadFile * * Handles loading an assembly file into the simulator */ void ComplxFrame::DoLoadFile(const wxFileName& filename) { //CleanUp(); lc3_state dummy_state; lc3_init(dummy_state); // Save the symbols std::map<std::string, unsigned short> symbol_table = state.symbols; std::map<unsigned short, std::string> rev_symbol_table = state.rev_symbols; state.symbols.clear(); state.rev_symbols.clear(); lc3_remove_plugins(state); try { std::vector<code_range> ranges; lc3_assemble(dummy_state, filename.GetFullPath().ToStdString(), false); lc3_assemble(state, filename.GetFullPath().ToStdString(), ranges); modified_addresses.clear(); for (const auto& code_range : ranges) modified_addresses.push_back(ViewRange(code_range.location, code_range.location + code_range.size)); // Dummy call to update hidden addresses. wxCommandEvent event; OnUpdateHideAddresses(event); } catch (LC3AssembleException e) { wxMessageBox(wxString::Format("BAD STUDENT! %s", e.what()), _("Loading ") + filename.GetFullName() + _(" Failed")); goto merge; } catch (std::vector<LC3AssembleException> e) { std::stringstream oss; for (unsigned int i = 0; i < e.size(); i++) oss << e[i].what() << std::endl; wxMessageBox(wxString::Format("BAD STUDENT! %s", oss.str()), _("Loading ") + filename.GetFullName() + _(" Failed")); goto merge; } //if (DoAssemble(filename)) return; currentFile = filename; SetTitle(wxString::Format("Complx - %s", filename.GetFullPath())); merge: std::map<std::string, unsigned short>::const_iterator i; std::map<unsigned short, std::string>::const_iterator j; for (i = symbol_table.begin(); i != symbol_table.end(); ++i) { state.symbols[i->first] = i->second; } for (j = rev_symbol_table.begin(); j != rev_symbol_table.end(); ++j) { state.rev_symbols[j->first] = j->second; } //DoLoad(filename); UpdateStatus(); UpdateRegisters(); UpdateMemory(); }
DWORD WINAPI LimitPlus( LPVOID lpVoid ) { int i, j; LPHACK_PARAMS lphp = (LPHACK_PARAMS) lpVoid; const HWND hWnd = lphp->myHwnd; const LPTARGETINFO lpTarget = lphp->lpTarget; EnableMenuItem( GetMenu( hWnd ), IDM_WATCH, MF_BYCOMMAND | MF_GRAYED ); EnableMenuItem( GetMenu( hWnd ), IDM_UNWATCH, MF_BYCOMMAND | MF_ENABLED ); g_dwTargetProcessId[ 2 ] = WATCHING_IDLE; UpdateStatus( hWnd ); TCHAR lpszTargetPath[ MAX_PATH * 2 ]; TCHAR lpszTargetExe[ MAX_PATH * 2 ]; lstrcpy( lpszTargetPath, lpTarget->szPath ); lstrcpy( lpszTargetExe, lpTarget->szExe ); wsprintf( g_szTarget[ 2 ], TEXT( "%s (Watching)" ), lpszTargetPath ); for( i = 8; i < 12; i++ ) { lstrcpy( lphp->lpszStatus[ i ], TEXT( "" ) ); } lstrcpy( lphp->lpszStatus[ 13 ], TEXT( "Watching..." ) ); TCHAR str[ MAX_PATH * 2 ]; #ifdef _UNICODE lstrcpy( lphp->lpszStatus[ 14 ], lpszTargetPath ); #else lstrcpy( str, lpszTargetPath ); if( lstrlen( str ) >= 19 ) { str[ 15 ] = '\0'; PathToExeEx( str, MAX_PATH * 2 ); } lstrcpy( lphp->lpszStatus[ 14 ], str ); #endif wsprintf( str, TEXT( "Watching : %s" ), lpszTargetPath ); WriteDebugLog( str ); AdjustLength( lphp->lpszStatus[ 14 ] ); g_Slider[ 2 ] = (BYTE) GetSliderIni( lpszTargetPath ); for( ; ; ) { if( lphp->lpTarget->dwProcessId == TARGET_PID_NOT_SET ) { g_dwTargetProcessId[ 2 ] = PathToProcess( lpszTargetPath ); } else { g_dwTargetProcessId[ 2 ] = lphp->lpTarget->dwProcessId; wsprintf( str, TEXT( "Watching : ProcessID given : %08lX" ), g_dwTargetProcessId[ 2 ] ); WriteDebugLog( str ); } if( g_dwTargetProcessId[ 2 ] == g_dwTargetProcessId[ 0 ] ) { if( g_bHack[ 0 ] ) { SendMessage( hWnd, WM_USER_STOP, 0U, 0L ); } Sleep( 500UL ); for( i = 0; i < 4; i++ ) { lstrcpy( lphp->lpszStatus[ i ], TEXT( "" ) ); } g_dwTargetProcessId[ 0 ] = TARGET_PID_NOT_SET; lstrcpy( g_szTarget[ 0 ], TARGET_UNDEF ); } else if( g_dwTargetProcessId[ 2 ] == g_dwTargetProcessId[ 1 ] ) { if( g_bHack[ 1 ] ) { SendMessage( hWnd, WM_USER_STOP, 1U, 0L ); } Sleep( 500UL ); for( i = 4; i < 8; i++ ) { lstrcpy( lphp->lpszStatus[ i ], TEXT( "" ) ); } g_dwTargetProcessId[ 1 ] = TARGET_PID_NOT_SET; lstrcpy( g_szTarget[ 1 ], TEXT( "<target not specified>" ) ); } if( g_dwTargetProcessId[ 2 ] == (DWORD) -1 ) { if( lstrcmp( lphp->lpszStatus[ 15 ], TEXT( "Not found" ) ) != 0 ) { wsprintf( lphp->lpszStatus[ 15 ], TEXT( "Not found" ) ); InvalidateRect( hWnd, NULL, TRUE ); } for( j = 0; j < 80; j++ ) // wait 8 seconds { Sleep( 100UL ); if( ! g_bHack[ 3 ] ) goto EXIT_THREAD; } } else { wsprintf( str, TEXT( "Watching : Found! <%s>" ), lpszTargetPath ); WriteDebugLog( str ); lphp->lpTarget->dwProcessId = g_dwTargetProcessId[ 2 ]; lstrcpy( lphp->lpTarget->szPath, lpszTargetPath ); lstrcpy( lphp->lpTarget->szExe , lpszTargetExe ); lstrcpy( lphp->lpTarget->szText, TEXT( "" ) ); g_Slider[ 2 ] = (BYTE) GetSliderIni( lpszTargetPath ); SendMessage( hWnd, WM_USER_HACK, (WPARAM) 2, (LPARAM) lphp ); UpdateStatus( hWnd ); wsprintf( lphp->lpszStatus[ 15 ], TEXT( "Found ( %08lX )" ), g_dwTargetProcessId[ 2 ] ); InvalidateRect( hWnd, NULL, TRUE ); while( g_dwTargetProcessId[ 2 ] != TARGET_PID_NOT_SET ) { Sleep( 100UL ); if( g_bHack[ 3 ] == FALSE ) { WriteDebugLog( TEXT( "g_bHack[ 3 ] == FALSE" ) ); goto EXIT_THREAD; } } if( WaitForSingleObject( hSemaphore[ 2 ], 1000UL ) != WAIT_OBJECT_0 ) { g_bHack[ 2 ] = FALSE; MessageBox( hWnd, TEXT("Sema Error in LimitPlus()"), APP_NAME, MB_OK | MB_ICONEXCLAMATION ); goto EXIT_THREAD; } g_dwTargetProcessId[ 2 ] = WATCHING_IDLE; UpdateStatus( hWnd ); } } EXIT_THREAD: WriteDebugLog( TEXT( "Watch: Exiting Thread..." ) ); // if the Watched is idle, we will free the slot #2 when 'unwatch' is posted // (Otherwise, #2 should be still active) if( g_dwTargetProcessId[ 2 ] == WATCHING_IDLE ) { g_dwTargetProcessId[ 2 ] = TARGET_PID_NOT_SET; lphp->lpTarget->dwProcessId = TARGET_PID_NOT_SET; g_bHack[ 2 ] = FALSE; ReleaseSemaphore( hSemaphore[ 2 ], 1L, (LONG *) NULL ); } if( ReleaseSemaphore( hSemaphore[ 3 ], 1L, (LONG *) NULL ) ) { WriteDebugLog( TEXT( "* Sema3 Released" ) ); } else { WriteDebugLog( TEXT( "[!] Sema3 Not released" ) ); } lstrcpy( lphp->lpszStatus[ 13 ], TEXT( "* Not watching *" ) ); lstrcpy( lphp->lpszStatus[ 14 ], lpszTargetPath ); AdjustLength( lphp->lpszStatus[ 14 ] ); lstrcpy( lphp->lpszStatus[ 15 ], TEXT( "" ) ); InvalidateRect( hWnd, NULL, TRUE ); if( ! g_bHack[ 2 ] ) { EnableMenuItem( GetMenu( hWnd ), IDM_WATCH, MF_BYCOMMAND | MF_ENABLED ); } EnableMenuItem( GetMenu( hWnd ), IDM_UNWATCH, MF_BYCOMMAND | MF_GRAYED ); UpdateStatus( hWnd ); g_bHack[ 3 ] = FALSE; // just in case return NOT_WATCHING; }
int MCL_NanoDrive_XYStage::Initialize() { // BEGIN LOCKING HandleListLock(); int err = DEVICE_OK; int possHandle = 0; bool valid = false; ProductInformation pi; memset(&pi, 0, sizeof(ProductInformation)); if (initialized_) { // If already initialized, no need to continue goto INIT_ERROR; } if(!MCL_CorrectDriverVersion()) { err = MCL_INVALID_DRIVER; goto INIT_ERROR; } int numHandles = MCL_GrabAllHandles(); if (numHandles == 0) { // No handles, i.e. no devices currently attached err = MCL_INVALID_HANDLE; goto INIT_ERROR; } int* handlesToUseOrRelease = NULL; handlesToUseOrRelease = (int*) malloc(sizeof(int*) * numHandles); MCL_GetAllHandles(handlesToUseOrRelease, numHandles); HandleListType* device = (HandleListType*)GlobalHeapAllocate(sizeof(HandleListType)); device->Initialize(possHandle, XY_TYPE); for (int i = 0; i < numHandles; i++) { possHandle = handlesToUseOrRelease[i]; device->setHandle(possHandle); MCL_GetProductInfo(&pi, possHandle); // check to see which axes are valid bool validXaxis = ((pi.axis_bitmap & VALIDX) == VALIDX); bool validYaxis = ((pi.axis_bitmap & VALIDY) == VALIDY); if ( (validXaxis && validYaxis) && (!HandleExistsOnLockedList(device)) && (possHandle > 0) ) { valid = true; HandleListAddToLockedList(device); MCLhandle_ = possHandle; // release handles not in use. for (int j = i+1; j < numHandles; j++) { possHandle = handlesToUseOrRelease[j]; if (!HandleExistsOnLockedList(possHandle) && possHandle > 0) { MCL_ReleaseHandle(possHandle); } } break; // found a valid handle, so no need to check any further } else { if (!HandleExistsOnLockedList(possHandle) && possHandle > 0) { MCL_ReleaseHandle(possHandle); } } } free (handlesToUseOrRelease); if (!valid) { GlobalHeapFree(device); err = MCL_INVALID_HANDLE; goto INIT_ERROR; } xMin_ = 0; yMin_ = 0; xMax_ = MCL_GetCalibration(XAXIS, MCLhandle_); if (xMax_ < 0) { err = (int) xMax_; goto INIT_ERROR; } yMax_ = MCL_GetCalibration(YAXIS, MCLhandle_); if (yMax_ < 0) { err = (int) yMax_; goto INIT_ERROR; } if (pi.Product_id == 0x1230 || pi.Product_id == 0x1253 || pi.Product_id == 0x2201 || pi.Product_id == 0x2203 || pi.Product_id == 0x2253) { stepSizeX_um_ = xMax_ / NUM_STEPS_20; stepSizeY_um_ = yMax_ / NUM_STEPS_20; is20Bit_ = true; } else { stepSizeX_um_ = xMax_ / NUM_STEPS_16; stepSizeY_um_ = yMax_ / NUM_STEPS_16; is20Bit_ = false; } curXpos_ = MCL_SingleReadN(XAXIS, MCLhandle_); if ((int)curXpos_ < 0) { err = (int) curXpos_; goto INIT_ERROR; } curYpos_ = MCL_SingleReadN(YAXIS, MCLhandle_); if ((int)curYpos_ < 0) { err = (int) curYpos_; goto INIT_ERROR; } serialNumber_ = MCL_GetSerialNumber(MCLhandle_); if (serialNumber_ < 0) { err = (int) serialNumber_; goto INIT_ERROR; } err = SetDeviceProperties(); if (err != DEVICE_OK) { goto INIT_ERROR; } err = UpdateStatus(); if (err != DEVICE_OK) { goto INIT_ERROR; } initialized_ = true; INIT_ERROR: // END LOCKING HandleListUnlock(); return err; }
//***************************************************************************** // // This is the callback from the USB HID keyboard handler. // // \param psKbInstance is ignored by this function. // \param ui32Event is one of the valid events for a keyboard device. // \param ui32MsgParam is defined by the event that occurs. // \param pvMsgData is a pointer to data that is defined by the event that // occurs. // // This function will be called to inform the application when a keyboard has // been plugged in or removed and any time a key is pressed or released. // // \return None. // //***************************************************************************** void KeyboardCallback(tUSBHKeyboard *psKbInstance, uint32_t ui32Event, uint32_t ui32MsgParam, void *pvMsgData) { char cChar; switch(ui32Event) { // // New Key press detected. // case USBH_EVENT_HID_KB_PRESS: { // // If this was a Caps Lock key then update the Caps Lock state. // if(ui32MsgParam == HID_KEYB_USAGE_CAPSLOCK) { // // The main loop needs to update the keyboard's Caps Lock // state. // g_eUSBState = STATE_KEYBOARD_UPDATE; // // Toggle the current Caps Lock state. // g_ui32Modifiers ^= HID_KEYB_CAPS_LOCK; // // Update the screen based on the Caps Lock status. // UpdateStatus(); } else if(ui32MsgParam == HID_KEYB_USAGE_SCROLLOCK) { // // The main loop needs to update the keyboard's Scroll Lock // state. // g_eUSBState = STATE_KEYBOARD_UPDATE; // // Toggle the current Scroll Lock state. // g_ui32Modifiers ^= HID_KEYB_SCROLL_LOCK; } else if(ui32MsgParam == HID_KEYB_USAGE_NUMLOCK) { // // The main loop needs to update the keyboard's Scroll Lock // state. // g_eUSBState = STATE_KEYBOARD_UPDATE; // // Toggle the current Num Lock state. // g_ui32Modifiers ^= HID_KEYB_NUM_LOCK; } else { // // Was this the backspace key? // if((uint8_t)ui32MsgParam == HID_KEYB_USAGE_BACKSPACE) { // // Yes - set the ASCII code for a backspace key. This is // not returned by USBHKeyboardUsageToChar since this only // returns printable characters. // cChar = ASCII_BACKSPACE; } else { // // This is not backspace so try to map the usage code to a // printable ASCII character. // cChar = (char) USBHKeyboardUsageToChar(g_psKeyboardInstance, &g_sUSKeyboardMap, (uint8_t)ui32MsgParam); } // // A zero value indicates there was no textual mapping of this // usage code. // if(cChar != 0) { PrintChar(cChar); } } break; } case USBH_EVENT_HID_KB_MOD: { // // This application ignores the state of the shift or control // and other special keys. // break; } case USBH_EVENT_HID_KB_REL: { // // This applications ignores the release of keys as well. // break; } } }
//***************************************************************************** // // Main application entry function. // //***************************************************************************** int main(void) { tBoolean bRetcode; smplStatus_t eRetcode; ioctlToken_t eToken; // // Set the system clock to run at 50MHz from the PLL // ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); // // NB: We don't call PinoutSet() in this testcase since the EM header // expansion board doesn't currently have an I2C ID EEPROM. If we did // call PinoutSet() this would configure all the EPI pins for SDRAM and // we don't want to do this. // g_eDaughterType = DAUGHTER_NONE; // // Enable peripherals required to drive the LCD. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE); ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH); // // Configure SysTick for a 10Hz interrupt. // ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND); ROM_SysTickEnable(); ROM_SysTickIntEnable(); // // Initialize the display driver. // Kitronix320x240x16_SSD2119Init(); // // Initialize the touch screen driver. // TouchScreenInit(); // // Set the touch screen event handler. // TouchScreenCallbackSet(WidgetPointerMessage); // // Add the compile-time defined widgets to the widget tree. // WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading); // // Initialize the status string. // UpdateStatus("Initializing..."); // // Paint the widget tree to make sure they all appear on the display. // WidgetPaint(WIDGET_ROOT); // // Initialize the SimpliciTI BSP. // BSP_Init(); // // Set the SimpliciTI device address using the current Ethernet MAC address // to ensure something like uniqueness. // bRetcode = SetSimpliciTIAddress(); // // Did we have a problem with the address? // if(!bRetcode) { // // Yes - make sure the display is updated then hang the app. // WidgetMessageQueueProcess(); while(1) { // // MAC address is not set so hang the app. // } } // // Turn on both our LEDs // SetLED(1, true); SetLED(2, true); UpdateStatus("Waiting..."); // // Initialize the SimpliciTI stack but don't set any receive callback. // while(1) { eRetcode = SMPL_Init((uint8_t (*)(linkID_t))0); if(eRetcode == SMPL_SUCCESS) { break; } ToggleLED(1); ToggleLED(2); SPIN_ABOUT_A_SECOND; } // This code example changes the Link token to be distributed to those who // Join. For the example here this should be done before anyone joins so // the Join context is defaulted to OFF for this scenario. See the // smpl_config.dat file. After the link token is set the Join context must // be enabled. // // NOTE that this is done after initialization. For APs the init sequence // consists of a step in which a link token is generated. The sequence here // overrides that setting. It can be used to distribute different link // tokens to different devices. The sequence here is a simple example of // how to use the IOCTL interface to set the Link token for subsequent // Joiners. // // You might want to be careful about following this particular example if // you are restoring from NV unless you are setting a fixed value as is // done here. Unconditionally setting a random value will make it // essentially impossible for newly joining devices to link to devices that // joined before the AP was reset since they will have different link // tokens. // eToken.tokenType = TT_LINK; eToken.token.linkToken = 0x78563412; SMPL_Ioctl(IOCTL_OBJ_TOKEN, IOCTL_ACT_SET, &eToken); // // Enable join context. // SMPL_Ioctl(IOCTL_OBJ_AP_JOIN, IOCTL_ACT_ON, 0); // // Tell the user what's up. // UpdateStatus("Access point active."); // // Do nothing after this - the SimpliciTI stack code handles all the // access point function required. // while(1) { // // Process the widget message queue. // WidgetMessageQueueProcess(); } }
//***************************************************************************** // // Set the SimpliciTI device address as the least significant 4 digits of the // device Ethernet MAC address. This ensures that the address is unique across // Stellaris devices. If the MAC address has not been set, we return false to // indicate failure. // //***************************************************************************** tBoolean SetSimpliciTIAddress(void) { unsigned long ulUser0, ulUser1; addr_t sAddr; // // Make sure we are using 4 byte addressing. // ASSERT(NET_ADDR_SIZE == 4); // // Get the MAC address from the non-volatile user registers. // ROM_FlashUserGet(&ulUser0, &ulUser1); // // Has the MAC address been programmed? // if((ulUser0 == 0xffffffff) || (ulUser1 == 0xffffffff)) { // // No - we don't have an address so return a failure. // UpdateStatus("Flash user registers are clear"); UpdateStatus("Error - address not set!"); return(false); } else { // // The MAC address is stored with 3 bytes in each of the 2 flash user // registers. Extract the least significant 4 MAC bytes for use as the // SimpliciTI device address. // sAddr.addr[0] = ((ulUser1 >> 16) & 0xff); sAddr.addr[1] = ((ulUser1 >> 8) & 0xff); sAddr.addr[2] = ((ulUser1 >> 0) & 0xff); sAddr.addr[3] = ((ulUser0 >> 16) & 0xff); // // SimpliciTI requires that the first byte of the device address is // never either 0x00 or 0xFF so we check for these cases and invert the // first bit if either is detected. This does result in the // possibility of two devices having the same address but, for example // purposes, is likely to be fine. // if((sAddr.addr[0] == 0x00) || (sAddr.addr[0] == 0xFF)) { sAddr.addr[0] ^= 0x80; } // // Tell the SimpliciTI stack which device address we want to use. // SMPL_Ioctl(IOCTL_OBJ_ADDR, IOCTL_ACT_SET, &sAddr); } // // If we get here, all is well. // return(true); }
void CECGDlg::OnBnClickedWIFIConnect() { // TODO: 在此加入控制項告知處理常式程式碼 DWORD IDThread; HANDLE hWIFIThread; //SOCKADDR_IN target; UpdateData(TRUE); int len = m_strURL.GetLength(); char *pURL = new char [len]; if(pURL == NULL) { UpdateStatus(L"In OnBnClickedWIFIConnect: new pURL error!", ADDSTR2STATUS); return; } for(int i = 0 ; i < len ; i++) pURL[i] = (char)m_strURL.GetAt(i); pURL[len] = '\0'; int port = _ttoi(m_strPort); int ret; ret = TCPClientSetup(s, pURL, port); if (ret == 1) { UpdateStatus(L"Failed to create socket!", ADDSTR2STATUS); return; } else if (ret == 2) { UpdateStatus(L"Failed to connect to server!", ADDSTR2STATUS); ::closesocket(s); return; } /*ret = TCPClientSetup(socketGain, pURL, 5566); if (ret == 1) { UpdateStatus(L"Failed to create socket!", ADDSTR2STATUS); return; } else if (ret == 2) { UpdateStatus(L"Failed to connect to server!", ADDSTR2STATUS); ::closesocket(socketGain); return; }*/ InitializeCriticalSection(&m_csCompressedDataBuf); //InitializeCriticalSection(&m_csGainBuf); m_ExitWIFIThreadEvent = CreateEvent(NULL, TRUE, FALSE, NULL); /* Commented by Michael hWIFIThread = CreateThread(0, 0, WIFIThread, this, 0, &IDThread); if(hWIFIThread == NULL) { UpdateStatus(L"Failed to create Network threads!", ADDSTR2STATUS); return; } CloseHandle(hWIFIThread); */ m_BtnWIFIConnect.EnableWindow(FALSE); m_BtnWIFIDisconnect.EnableWindow(TRUE); m_BtnPhoneConnect.EnableWindow(FALSE); //Display status UpdateStatus(L"Open Socket!", ADDSTR2STATUS); delete [] pURL; }