Пример #1
0
void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc)
{
    double decDelta = 0.;
    double amt = 0;
    // double fakeDeltas []= {0, -5, -2, 2, 4, 5, 5, 5, 5 };
    PHD_Point currMountLocation;
    try
    {
        if (m_scope->TransformCameraCoordinatesToMountCoordinates(currentCamLoc, currMountLocation))
            throw ERROR_INFO("BLT: CamToMount xForm failed");
        if (m_bltState != BLT_STATE_INITIALIZE)
        {
            decDelta = currMountLocation.Y - m_markerPoint.Y;
            m_cumClearingDistance += decDelta;                                    // use signed value
            //if (m_bltState == BLT_STATE_CLEAR_NORTH)                            // DEBUG ONLY
            //    decDelta = fakeDeltas[wxMin(m_stepCount, 7)];
        }
        switch (m_bltState)
        {
        case BLT_STATE_INITIALIZE:
            m_stepCount = 0;
            m_markerPoint = currMountLocation;
            m_startingPoint = currMountLocation;
            // Compute pulse size for clearing backlash - just use the last known guide rate
            m_pulseWidth = BACKLASH_EXPECTED_DISTANCE * 1.25 / m_lastDecGuideRate;      // px/px_per_ms, bump it to sidestep near misses
            m_acceptedMoves = 0;
            m_lastClearRslt = 0;
            m_cumClearingDistance = 0;
            m_backlashExemption = false;
            m_Rslt = MEASUREMENT_VALID;
            // Get this state machine in synch with the guider state machine - let it drive us, starting with backlash clearing step
            m_bltState = BLT_STATE_CLEAR_NORTH;
            m_scope->SetGuidingEnabled(true);
            pFrame->pGuider->EnableMeasurementMode(true);                   // Measurement results now come to us
            break;

        case BLT_STATE_CLEAR_NORTH:
            // Want to see the mount moving north for 3 consecutive moves of >= expected distance pixels
            if (m_stepCount == 0)
            {
                // Get things moving with the first clearing pulse
                Debug.AddLine(wxString::Format("BLT starting North backlash clearing using pulse width of %d,"
                    " looking for moves >= %d px", m_pulseWidth, BACKLASH_EXPECTED_DISTANCE));
                pFrame->ScheduleCalibrationMove(m_scope, NORTH, m_pulseWidth);
                m_stepCount = 1;
                m_lastStatus = wxString::Format("Clearing North backlash, step %d", m_stepCount);
                break;
            }
            if (fabs(decDelta) >= BACKLASH_EXPECTED_DISTANCE)
            {
                if (m_acceptedMoves == 0 || (m_lastClearRslt * decDelta) > 0)    // Just starting or still moving in same direction
                {
                    m_acceptedMoves++;
                    Debug.AddLine(wxString::Format("BLT accepted clearing move of %0.2f", decDelta));
                }
                else
                {
                    m_acceptedMoves = 0;            // Reset on a direction reversal
                    Debug.AddLine(wxString::Format("BLT rejected clearing move of %0.2f, direction reversal", decDelta));
                }
            }
            else
                Debug.AddLine(wxString::Format("BLT backlash clearing move of %0.2f px was not large enough", decDelta));
            if (m_acceptedMoves < BACKLASH_MIN_COUNT)                    // More work to do
            {
                if (m_stepCount < MAX_CLEARING_STEPS)
                {
                    if (fabs(m_cumClearingDistance) > BACKLASH_EXEMPTION_DISTANCE)
                    {
                        // We moved the mount a substantial distance north but the individual moves were too small - probably a bad calibration,
                        // so let the user proceed with backlash measurement before we push the star too far
                        Debug.AddLine(wxString::Format("BLT: Cum backlash of %0.2f px is at least half of expected, continue with backlash measurement", m_cumClearingDistance));
                        m_backlashExemption = true;
                    }
                    else
                    {
                        if (!OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels()))
                        {
                            pFrame->ScheduleCalibrationMove(m_scope, NORTH, m_pulseWidth);
                            m_stepCount++;
                            m_markerPoint = currMountLocation;
                            m_lastClearRslt = decDelta;
                            m_lastStatus = wxString::Format("Clearing North backlash, step %d (up to limit of %d)", m_stepCount, MAX_CLEARING_STEPS);
                            Debug.AddLine(wxString::Format("BLT: %s, LastDecDelta = %0.2f px", m_lastStatus, decDelta));
                            break;
                        }
                    }
                }
                else
                {
                    m_lastStatus = _("Could not clear North backlash - test failed");
                    m_Rslt = MEASUREMENT_INVALID;
                    throw ERROR_INFO("BLT: Could not clear N backlash");
                }
            }
            if (m_acceptedMoves >= BACKLASH_MIN_COUNT || m_backlashExemption || OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels()))    // Ok to go ahead with actual backlash measurement
            {
                m_markerPoint = currMountLocation;            // Marker point at start of big Dec move North
                m_bltState = BLT_STATE_STEP_NORTH;
                double totalBacklashCleared = m_stepCount * m_pulseWidth;
                // Want to move the mount North at >=500 ms, regardless of image scale. But reduce pulse width if it would exceed 80% of the tracking rectangle - 
                // need to leave some room for seeing deflections and dec drift
                m_pulseWidth = wxMax((int)NORTH_PULSE_SIZE, m_scope->GetCalibrationDuration());
                m_pulseWidth = wxMin(m_pulseWidth, (int)floor(0.7 * (double)pFrame->pGuider->GetMaxMovePixels() / m_lastDecGuideRate));
                m_stepCount = 0;
                // Move 50% more than the backlash we cleared or >=8 secs, whichever is greater.  We want to leave plenty of room
                // for giving South moves time to clear backlash and actually get moving
                m_northPulseCount = wxMax((MAX_NORTH_PULSES + m_pulseWidth - 1) / m_pulseWidth,
                                          totalBacklashCleared * 1.5 / m_pulseWidth);  // Up to 8 secs

                Debug.AddLine(wxString::Format("BLT: Starting North moves at Dec=%0.2f", currMountLocation.Y));
                // falling through to start moving North            
            }

        case BLT_STATE_STEP_NORTH:
            if (m_stepCount < m_northPulseCount && !OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels()))
            {
                m_lastStatus = wxString::Format("Moving North for %d ms, step %d / %d", m_pulseWidth, m_stepCount + 1, m_northPulseCount);
                Debug.AddLine(wxString::Format("BLT: %s, DecLoc = %0.2f", m_lastStatus, currMountLocation.Y));
                m_northBLSteps.push_back(currMountLocation.Y);
                pFrame->ScheduleCalibrationMove(m_scope, NORTH, m_pulseWidth);
                m_stepCount++;
                break;
            }
            else
            {
                // Either got finished or ran out of room
                Debug.AddLine(wxString::Format("BLT: North pulses ended at Dec location %0.2f, DecDelta=%0.2f px", currMountLocation.Y, decDelta));
                m_northBLSteps.push_back(currMountLocation.Y);
                if (m_stepCount < m_northPulseCount)
                {
                    if (m_stepCount < 0.5 * m_northPulseCount)
                    {
                        pFrame->Alert(_("Star too close to edge for accurate measurement of backlash"));
                        m_Rslt = MEASUREMENT_INVALID;
                    }
                    Debug.AddLine("BLT: North pulses truncated, too close to frame edge");
                }
                m_northRate = fabs(decDelta / (m_stepCount * m_pulseWidth));
                m_northPulseCount = m_stepCount;
                m_stepCount = 0;
                m_bltState = BLT_STATE_STEP_SOUTH;
                // falling through to moving back South
            }

        case BLT_STATE_STEP_SOUTH:
            if (m_stepCount < m_northPulseCount)
            {
                m_lastStatus = wxString::Format("Moving South for %d ms, step %d / %d", m_pulseWidth, m_stepCount + 1, m_northPulseCount);
                Debug.AddLine(wxString::Format("BLT: %s, DecLoc = %0.2f", m_lastStatus, currMountLocation.Y));
                m_southBLSteps.push_back(currMountLocation.Y);
                pFrame->ScheduleCalibrationMove(m_scope, SOUTH, m_pulseWidth);
                m_stepCount++;
                break;
            }
            // Now see where we ended up - fall through to testing this correction
            Debug.AddLine(wxString::Format("BLT: South pulses ended at Dec location %0.2f", currMountLocation.Y));
            m_southBLSteps.push_back(currMountLocation.Y);
            m_endSouth = currMountLocation;
            m_bltState = BLT_STATE_TEST_CORRECTION;
            m_stepCount = 0;
            // fall through

        case BLT_STATE_TEST_CORRECTION:
            if (m_stepCount == 0)
            {
                // decDelta contains the nominal backlash amount
                m_backlashResultPx = fabs(decDelta);
                m_backlashResultMs = (int)(m_backlashResultPx / m_northRate);          // our north rate is probably better than the calibration rate
                if (m_Rslt == MEASUREMENT_VALID)
                {
                    if (m_backlashResultMs >= 0.8 * m_northPulseCount * m_pulseWidth)
                        m_Rslt = MEASUREMENT_IMPAIRED;      // May not have moved far enough north for accurate measurement
                }
                Debug.AddLine(wxString::Format("BLT: Backlash amount is %0.2f px, %d ms", m_backlashResultPx, m_backlashResultMs));
                // Don't try this refinement if the clearing pulse will cause us to lose the star
                if (m_backlashResultPx < pFrame->pGuider->GetMaxMovePixels())
                {
                    m_lastStatus = wxString::Format(_("Issuing test backlash correction of %d ms"), m_backlashResultMs);
                    Debug.AddLine(m_lastStatus);
                    // This should put us back roughly to where we issued the big North pulse unless the backlash is very large
                    pFrame->ScheduleCalibrationMove(m_scope, SOUTH, m_backlashResultMs);
                    m_stepCount++;
                }
                else
                {
                    int maxFrameMove = (int)floor((double)pFrame->pGuider->GetMaxMovePixels() / m_northRate);
                    Debug.AddLine(wxString::Format("BLT: Clearing pulse is very large, issuing max S move of %d", maxFrameMove));
                    pFrame->ScheduleCalibrationMove(m_scope, SOUTH, maxFrameMove);       // One more pulse to cycle the state machine
                    m_bltState = BLT_STATE_RESTORE;
                }
                break;
            }
            // See how close we came, maybe fine-tune a bit
            Debug.AddLine(wxString::Format("BLT: Trial backlash pulse resulted in net DecDelta = %0.2f px, Dec Location %0.2f", decDelta, currMountLocation.Y));
            if (fabs(decDelta) > TRIAL_TOLERANCE)
            {
                double pulse_delta = fabs(currMountLocation.Y - m_endSouth.Y);
                if ((m_endSouth.Y - m_markerPoint.Y) * decDelta < 0)                // Sign change, went too far
                {
                    m_backlashResultMs *= m_backlashResultPx / pulse_delta;
                    Debug.AddLine(wxString::Format("BLT: Trial backlash resulted in overshoot - adjusting pulse size by %0.2f", m_backlashResultPx / pulse_delta));
                }
                else
                {
                    double corr_factor = (m_backlashResultPx / pulse_delta - 1.0) * 0.5 + 1.0;          // apply 50% of the correction to avoid over-shoot
                    //m_backlashResultMs *= corr_factor;
                    Debug.AddLine(wxString::Format("BLT: Trial backlash resulted in under-correction - under-shot by %0.2f", corr_factor));
                }
            }
            else
                Debug.AddLine("BLT: Initial backlash pulse resulted in final delta of < 2 px");

            m_bltState = BLT_STATE_RESTORE;
            m_stepCount = 0;
            // fall through

        case BLT_STATE_RESTORE:
            // We could be a considerable distance from where we started, so get back close to the starting point without losing the star
            if (m_stepCount == 0)
            {
                Debug.AddLine(wxString::Format("BLT: Starting Dec position at %0.2f, Ending Dec position at %0.2f", m_markerPoint.Y, currMountLocation.Y));
                amt = fabs(currMountLocation.Y - m_startingPoint.Y);
                if (amt > pFrame->pGuider->GetMaxMovePixels())
                {
                    m_restoreCount = (int)floor((amt / m_northRate) / m_pulseWidth);
                    Debug.AddLine(wxString::Format("BLT: Final restore distance is %0.1f px, approx %d steps", amt, m_restoreCount));
                    m_stepCount = 0;
                }
                else
                    m_bltState = BLT_STATE_WRAPUP;
            }
            if (m_stepCount < m_restoreCount)
            {

                pFrame->ScheduleCalibrationMove(m_scope, SOUTH, m_pulseWidth);
                m_stepCount++;
                m_lastStatus = _("Restoring star position");
                Debug.AddLine("BLT: Issuing restore pulse count %d of %d ms", m_stepCount, m_pulseWidth);
                break;
            }
            m_bltState = BLT_STATE_WRAPUP;
            // fall through

        case BLT_STATE_WRAPUP:
            m_lastStatus = _("Measurement complete");
            CleanUp();
            m_bltState = BLT_STATE_COMPLETED;
            break;

        case BLT_STATE_COMPLETED:
            break;

        case BLT_STATE_ABORTED:
            m_lastStatus = _("Measurement halted");
            Debug.AddLine("BLT: measurement process halted by user");
            CleanUp();
            break;
        }                       // end of switch on state
    }
    catch (const wxString& msg)
    {
        Debug.AddLine(wxString::Format("BLT: Exception thrown in logical state %d", (int)m_bltState));
        m_bltState = BLT_STATE_ABORTED;
        m_lastStatus = _("Measurement encountered an error: " + msg);
        Debug.AddLine("BLT: " + m_lastStatus);
        CleanUp();
    }
}
Пример #2
0
int SdkServerBuffer::__GetStreamDataBlockState(client_buffer_t * pCBuffer,struct iovec * pIoVec,int & iovlen,int & begin)
{
    unsigned int expectidx,curidx;
    stream_pack_t* pCBlock=NULL;
    int ret;

    SDK_ASSERT(pCBuffer->m_State == cb_block_state);
    SDK_ASSERT(pCBuffer->m_pBlock);
    if (pCBuffer->m_pBlock->m_Idx != pCBuffer->m_SourceIdx)
    {
        ERROR_INFO("pblock idx 0x%x sourceidx 0x%x\n",pCBuffer->m_pBlock->m_Idx,
                   pCBuffer->m_SourceIdx);
    }
    SDK_ASSERT(pCBuffer->m_pBlock->m_Idx == pCBuffer->m_SourceIdx);

    if (pCBuffer->m_WriteLen < pCBuffer->m_TotalLen)
    {
        ret = this->__SetIov(pCBuffer,pIoVec,iovlen,begin);
        if (ret < 0)
        {
            return ret;
        }
        return 1;
    }

    /*now we should free the buffer*/
    this->__FreeStreamPack(pCBuffer->m_pBlock);

    SDK_ASSERT(this->m_PackSize == this->m_MaxPacks);
    /*first we pretend to find the next one if not success ,just change into cb_i_frame_state*/
    this->__ChangeClientBufferState(pCBuffer,cb_seq_state,__FILE__,__LINE__);
    expectidx = pCBuffer->m_SourceIdx;
    expectidx += 1;
    if (pCBuffer->m_SourceIdx == MAX_STREAM_IDX_32)
    {
        expectidx = 0;
    }

    curidx = pCBuffer->m_CurIdx;
    curidx += 1;
    curidx %= this->m_PackSize;
    pCBlock = this->m_pPacks[curidx];
    SDK_ASSERT(pCBlock);
    if (pCBlock->m_Idx == expectidx)
    {
        /*we got this one*/
        pCBuffer->m_CurIdx = curidx;
        pCBuffer->m_SourceIdx = pCBlock->m_Idx;
        ret = this->__FormatMessageHeader(pCBuffer,pCBlock);
        if (ret < 0)
        {
            return ret;
        }
        ret = this->__SetIov(pCBuffer,pIoVec,iovlen,begin);
        if (ret < 0)
        {
            return ret;
        }
        return 1;
    }
    /*we find the next one*/

    return this->__SearchUntilIframe(pCBuffer,pIoVec,iovlen,begin);
}
Пример #3
0
bool GuiderOneStar::UpdateCurrentPosition(usImage *pImage, FrameDroppedInfo *errorInfo)
{
    if (!m_star.IsValid() && m_star.X == 0.0 && m_star.Y == 0.0)
    {
        Debug.AddLine("UpdateCurrentPosition: no star selected");
        errorInfo->starError = Star::STAR_ERROR;
        errorInfo->starMass = 0.0;
        errorInfo->starSNR = 0.0;
        errorInfo->status = _("No star selected");
        return true;
    }

    bool bError = false;

    try
    {
        Star newStar(m_star);

        if (!newStar.Find(pImage, m_searchRegion, pFrame->GetStarFindMode()))
        {
            errorInfo->starError = newStar.GetError();
            errorInfo->starMass = 0.0;
            errorInfo->starSNR = 0.0;
            errorInfo->status = StarStatusStr(newStar);
            m_star.SetError(newStar.GetError());
            throw ERROR_INFO("UpdateCurrentPosition():newStar not found");
        }

        // check to see if it seems like the star we just found was the
        // same as the original star.  We do this by comparing the
        // mass
        m_massChecker->SetExposure(pFrame->RequestedExposureDuration());
        double limits[3];
        if (m_massChangeThresholdEnabled &&
            m_massChecker->CheckMass(newStar.Mass, m_massChangeThreshold, limits))
        {
            m_star.SetError(Star::STAR_MASSCHANGE);
            errorInfo->starError = Star::STAR_MASSCHANGE;
            errorInfo->starMass = newStar.Mass;
            errorInfo->starSNR = newStar.SNR;
            errorInfo->status = StarStatusStr(m_star);
            pFrame->SetStatusText(wxString::Format(_("Mass: %.0f vs %.0f"), newStar.Mass, limits[1]), 1);
            Debug.Write(wxString::Format("UpdateGuideState(): star mass new=%.1f exp=%.1f thresh=%.0f%% range=(%.1f, %.1f)\n", newStar.Mass, limits[1], m_massChangeThreshold * 100, limits[0], limits[2]));
            m_massChecker->AppendData(newStar.Mass);
            throw THROW_INFO("massChangeThreshold error");
        }

        // update the star position, mass, etc.
        m_star = newStar;
        m_massChecker->AppendData(newStar.Mass);

        const PHD_Point& lockPos = LockPosition();
        if (lockPos.IsValid())
        {
            double distance = newStar.Distance(lockPos);
            UpdateCurrentDistance(distance);
        }

        pFrame->pProfile->UpdateData(pImage, m_star.X, m_star.Y);

        pFrame->AdjustAutoExposure(m_star.SNR);
        int exp;
        bool auto_exp;
        pFrame->GetExposureInfo(&exp, &auto_exp);
        if (auto_exp)
        {
            if (exp >= 1)
                errorInfo->status.Printf(_T("m=%.0f SNR=%.1f Exp=%0.1f s"), m_star.Mass, m_star.SNR, (double) exp / 1000.);
            else
                errorInfo->status.Printf(_T("m=%.0f SNR=%.1f Exp=%d ms"), m_star.Mass, m_star.SNR, exp);
        }
        else
            errorInfo->status.Printf(_T("m=%.0f SNR=%.1f"), m_star.Mass, m_star.SNR);
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
        pFrame->ResetAutoExposure(); // use max exposure duration
    }

    return bError;
}
Пример #4
0
        /*success ,so we do this*/
        pBuffer = NULL;
        usleep(20000);

        seekoff += bufret;
        framenum += 1;
        pts += 1800;
    }

out:
    if(pBuffer)
    {
        free(pBuffer);
    }
    pBuffer = NULL;
    if(fp)
    {
        fclose(fp);
    }
    fp = NULL;

    DEBUG_INFO("\n");
    this->m_ThreadExited = 1;
    return (void*)ret;
}

#else /*AUDIO_DUAL_FILE_EMULATE*/
void* SdkAudioStream::__ThreadImpl()
{
    int ret;
    void* pBuffer = NULL;
    /*for 16 k*/
    uint32_t buflen,bufret;
    uint32_t infosize=1024,inputsize;
    std::auto_ptr<unsigned char> pExInfo2(new unsigned char[infosize]);
    unsigned char* pExInfo =pExInfo2.get();
    struct timeval tmval;
    uint32_t lastidx=0;
    GMI_RESULT gmiret;
    unsigned long long pts=0,lasttick=0,curtick=0;
    struct timespec tmspec;

    buflen = 0x1000;
    if(this->m_Format == audio_format_g711 ||
            this->m_Format == audio_format_default)
    {
        /*for 16k bytes*/
        buflen = 0x4000;
    }
    DEBUG_INFO("start thread impl\n");
    while(this->m_ThreadRunning)
    {

        if(pBuffer== NULL)
        {
            /*we reuse the buffer ,when last time not get data and insert ,so we can limit the time*/
            pBuffer = malloc(buflen);
        }
        if(pBuffer == NULL)
        {
            ret = -errno ? -errno : -1;
            goto out;
        }

        bufret = buflen;
        inputsize= infosize;
        gmiret = this->m_IPCClient.Read(pBuffer,&bufret,&tmval,pExInfo,&inputsize);
        if(gmiret ==GMI_SUCCESS)
        {
            ExtMediaEncInfo* pInfo=(ExtMediaEncInfo*)pExInfo;
            /*now to get the */
            pts = VFREQ_PER_SECOND(tmval.tv_sec) + VFREQ_PER_USECOND(tmval.tv_usec);
            if(pts < 100000)
            {
                /*make sure it is not overflow*/
                pts *= 9;
                pts /= 100;
            }
            else
            {
                pts /= 100;
                pts *= 9;
            }

            ret = clock_gettime(CLOCK_MONOTONIC,&tmspec);
            if(ret < 0)
            {
                ERROR_INFO("could not get time error(%d)\n",errno);
            }
            else
            {
                curtick = VFREQ_PER_SECOND(tmspec.tv_sec) + VFREQ_PER_NANOSECOND(tmspec.tv_nsec);
                if(lasttick && (curtick - lasttick) >200000)
                {
                    ERROR_INFO("audio[%d] curtick(%lld) lasttick(%lld) (%lld)\n",pInfo->s_FrameNum,curtick,lasttick,(curtick-lasttick));
                }
				lasttick = curtick;
            }



            if(pInfo->s_FrameNum != (lastidx + 1))
            {
                DEBUG_INFO("framenum (%d) != (%d + 1)\n",pInfo->s_FrameNum,lastidx);
            }
            lastidx = pInfo->s_FrameNum;
            if((lastidx % 200)==0)
            {
                DEBUG_BUFFER_FMT(pBuffer,bufret,"framenum %d",lastidx);
            }

            ret = this->__PushStreamData(pBuffer,bufret,pInfo->s_FrameNum,pts);
            if(ret < 0)
            {
                goto out;
            }
            /*insert success ,so we should not free this buffer*/
            pBuffer = NULL;

        }
        else
        {
            /*we are not success ,so we sleep for a while*/
            usleep(20000);
        }

    }
    ret = 0;

out:
    if(pBuffer)
    {
        free(pBuffer);
    }
    pBuffer = NULL;
    DEBUG_INFO("stop thread impl\n");
    this->m_ThreadExited = 1;
    return (void*) ret;
}
Пример #5
0
Mount::MOVE_RESULT WorkerThread::HandleMove(MyFrame::PHD_MOVE_REQUEST *pArgs)
{
    Mount::MOVE_RESULT result = Mount::MOVE_OK;

    try
    {
        if (pArgs->pMount->HasNonGuiMove())
        {
            Debug.AddLine(wxString::Format("Handling move in thread for %s dir=%d",
                    pArgs->pMount->GetMountClassName(),
                    pArgs->direction));

            if (pArgs->calibrationMove)
            {
                Debug.AddLine("calibration move");

                result = pArgs->pMount->CalibrationMove(pArgs->direction, pArgs->duration);
                if (result != Mount::MOVE_OK)
                {
                    throw ERROR_INFO("CalibrationMove failed");
                }
            }
            else
            {
                Debug.AddLine(wxString::Format("endpoint = (%.2f, %.2f)",
                    pArgs->vectorEndpoint.X, pArgs->vectorEndpoint.Y));

                result = pArgs->pMount->Move(pArgs->vectorEndpoint, pArgs->moveType);
                if (result != Mount::MOVE_OK)
                {
                    throw ERROR_INFO("Move failed");
                }
            }
        }
        else
        {
            // we don't have a non-gui guide function, so we send this to the
            // main frame routine that handles guides requests

            Debug.AddLine("Sending move to myFrame");

            wxSemaphore semaphore;
            pArgs->pSemaphore = &semaphore;

            wxCommandEvent evt(REQUEST_MOUNT_MOVE_EVENT, GetId());
            evt.SetClientData(pArgs);
            wxQueueEvent(m_pFrame, evt.Clone());

            // wait for the request to complete
            pArgs->pSemaphore->Wait();

            pArgs->pSemaphore = NULL;
            result = pArgs->moveResult;

            if (result != Mount::MOVE_OK)
            {
                throw ERROR_INFO("myFrame handled move failed");
            }
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        if (result == Mount::MOVE_OK)
            result = Mount::MOVE_ERROR;
    }

    Debug.AddLine(wxString::Format("move complete, result=%d", result));

    return result;
}
Пример #6
0
int InsertModuleFileName(HMODULE hModule)
{
    HANDLE hProcess=NULL;
    DWORD dret;
#ifdef _UNICODE
    wchar_t *pModuleFullNameW=NULL;
    int modulefullnamesize=0;
#else
    char *pModuleFullNameA=NULL;
#endif
    char* pModuleFullName=NULL,*pModulePartName=NULL;
    int lasterr=0;
    int ret;
    unsigned int fullnamesize=1024;

    if(st_InjectModuleInited == 0)
    {
        return -ERROR_NOT_SUPPORTED;
    }

    hProcess = GetCurrentProcess();
    do
    {
        lasterr = 0;
#ifdef _UNICODE
        pModuleFullNameW = (wchar_t*)calloc(sizeof(*pModuleFullNameW),fullnamesize);
        if(pModuleFullNameW == NULL)
        {
            ret = LAST_ERROR_CODE();
            goto fail;
        }
        dret = GetModuleFileNameEx(hProcess,hModule,pModuleFullNameW,fullnamesize);
#else
        pModuleFullNameA = calloc(sizeof(*pModuleFullNameA),fullnamesize);
        if(pModuleFullNameA == NULL)
        {
            ret = LAST_ERROR_CODE();
            goto fail;
        }
        dret = GetModuleFileNameEx(hProcess,hModule,pModuleFullNameA,fullnamesize);
#endif


        if(dret == 0 || dret >= fullnamesize)
        {
            lasterr = LAST_ERROR_CODE();
#ifdef _UNICODE
            free(pModuleFullNameW);
            pModuleFullNameW = NULL;
#else
            free(pModuleFullNameA);
            pModuleFullNameA = NULL;
#endif
            fullnamesize <<= 1;
        }
    }
    while(lasterr == ERROR_INSUFFICIENT_BUFFER);

    if(dret == 0 || dret >= fullnamesize)
    {
        ret = LAST_ERROR_CODE();
        ERROR_INFO("can not get [0x%x:0x%x] modulefilename error(%d)\n",hProcess,hModule,ret);
        goto fail;
    }

#ifdef _UNICODE
    ret = UnicodeToAnsi(pModuleFullNameW,&pModuleFullName,&modulefullnamesize);
    if(ret < 0)
    {
        ret = LAST_ERROR_CODE();
        goto fail;
    }
#else
    pModuleFullName = pModuleFullNameA;
#endif

    /*now get the name so we should*/
    pModulePartName = strrchr(pModuleFullName,'\\');
    if(pModulePartName)
    {
        pModulePartName ++;
    }
    else
    {
        pModulePartName = pModuleFullName;
    }

    /*now insert the dlls*/
	DEBUG_INFO("Insert into(%s:%s)\n",pModuleFullName,pModulePartName);
    ret = InsertDllNames(pModuleFullName,pModulePartName);
    if(ret < 0)
    {
        ret = LAST_ERROR_CODE();
        ERROR_INFO("could not insert (%s:%s) error(%d)\n",pModuleFullName,pModulePartName,ret);
        goto fail;
    }

    DEBUG_INFO("Insert (%s:%s) succ\n",pModuleFullName,pModulePartName);


#ifdef _UNICODE
    UnicodeToAnsi(NULL,&pModuleFullName,&modulefullnamesize);
    if(pModuleFullNameW)
    {
        free(pModuleFullNameW);
    }
    pModuleFullNameW = NULL;
    pModulePartName = NULL;
#else
    if(pModuleFullNameA)
    {
        free(pModuleFullNameA);
    }
    pModuleFullNameA = NULL;
    pModuleFullName = NULL;
    pModulePartName = NULL;
#endif

    fullnamesize = 0;

    return 0;

fail:
#ifdef _UNICODE
    UnicodeToAnsi(NULL,&pModuleFullName,&modulefullnamesize);
    if(pModuleFullNameW)
    {
        free(pModuleFullNameW);
    }
    pModuleFullNameW = NULL;
    pModulePartName = NULL;
#else
    if(pModuleFullNameA)
    {
        free(pModuleFullNameA);
    }
    pModuleFullNameA = NULL;
    pModuleFullName = NULL;
    pModulePartName = NULL;
#endif
    fullnamesize = 0;
    SetLastError(ret);
    return -ret;

}
Пример #7
0
bool usImage::Load(const wxString& fname)
{
    bool bError = false;

    try
    {
        if (!wxFileExists(fname))
        {
            pFrame->Alert(_("File does not exist - cannot load ") + fname);
            throw ERROR_INFO("File does not exist");
        }

        int status = 0;  // CFITSIO status value MUST be initialized to zero!
        fitsfile *fptr;  // FITS file pointer
        if (!PHD_fits_open_diskfile(&fptr, fname, READONLY, &status))
        {
            int hdutype;
            if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU)
            {
                pFrame->Alert(_("FITS file is not of an image: ") + fname);
                throw ERROR_INFO("Fits file is not an image");
            }

            // Get HDUs and size
            int naxis = 0;
            fits_get_img_dim(fptr, &naxis, &status);
            long fsize[3];
            fits_get_img_size(fptr, 2, fsize, &status);
            int nhdus = 0;
            fits_get_num_hdus(fptr, &nhdus, &status);
            if ((nhdus != 1) || (naxis != 2)) {
                pFrame->Alert(_("Unsupported type or read error loading FITS file ") + fname);
                throw ERROR_INFO("unsupported type");
            }
            if (Init((int) fsize[0], (int) fsize[1]))
            {
                pFrame->Alert(_("Memory allocation error loading FITS file ") + fname);
                throw ERROR_INFO("Memory Allocation failure");
            }
            long fpixel[3] = { 1, 1, 1 };
            if (fits_read_pix(fptr, TUSHORT, fpixel, (int)(fsize[0] * fsize[1]), NULL, ImageData, NULL, &status)) { // Read image
                pFrame->Alert(_("Error reading data from FITS file ") + fname);
                throw ERROR_INFO("Error reading");
            }

            char *key = const_cast<char *>("EXPOSURE");
            float exposure;
            status = 0;
            fits_read_key(fptr, TFLOAT, key, &exposure, NULL, &status);
            if (status == 0)
                ImgExpDur = (int) (exposure * 1000.0);

            key = const_cast<char *>("STACKCNT");
            int stackcnt;
            status = 0;
            fits_read_key(fptr, TINT, key, &stackcnt, NULL, &status);
            if (status == 0)
                ImgStackCnt = (int) stackcnt;

            PHD_fits_close_file(fptr);
        }
        else
        {
            pFrame->Alert(_("Error opening FITS file ") + fname);
            throw ERROR_INFO("error opening file");
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}
Пример #8
0
int fiasco_unpack(struct fiasco * fiasco, const char * dir) {

	int fd;
	char * name;
	char * layout_name;
	struct image * image;
	struct image_list * image_list;
	uint32_t size;
	char cwd[256];
	unsigned char buf[4096];

	if ( dir ) {

		memset(cwd, 0, sizeof(cwd));

		if ( ! getcwd(cwd, sizeof(cwd)) ) {
			ERROR_INFO("Cannot store current directory");
			return -1;
		}

		if ( chdir(dir) < 0 ) {
			ERROR_INFO("Cannot change current directory to %s", dir);
			return -1;
		}

	}

	fiasco_print_info(fiasco);

	image_list = fiasco->first;

	while ( image_list ) {

		fd = -1;
		name = NULL;
		layout_name = NULL;

		image = image_list->image;

		name = image_name_alloc_from_values(image);
		if ( ! name )
			return -1;

		printf("\n");
		printf("Unpacking image...\n");
		image_print_info(image);

		if ( image->layout ) {

			layout_name = calloc(1, strlen(name) + sizeof(".layout")-1 + 1);
			if ( ! layout_name ) {
				free(name);
				ALLOC_ERROR_RETURN(-1);
			}

			sprintf(layout_name, "%s.layout", name);

			printf("    Layout file: %s\n", layout_name);

		}

		printf("    Output file: %s\n", name);

		if ( ! simulate ) {
			fd = open(name, O_RDWR|O_CREAT|O_TRUNC, 0644);
			if ( fd < 0 ) {
				ERROR_INFO("Cannot create output file %s", name);
				free(name);
				free(layout_name);
				return -1;
			}
		}

		image_seek(image, 0);
		while ( 1 ) {
			size = image_read(image, buf, sizeof(buf));
			if ( size == 0 )
				break;
			if ( ! simulate ) {
				if ( write(fd, buf, size) != (ssize_t)size ) {
					ERROR_INFO_STR(name, "Cannot write %d bytes", size);
					close(fd);
					free(name);
					free(layout_name);
					return -1;
				}
			}
		}

		free(name);

		if ( ! simulate )
			close(fd);

		if ( image->layout ) {

			if ( ! simulate ) {
				fd = open(layout_name, O_RDWR|O_CREAT|O_TRUNC, 0644);
				if ( fd < 0 ) {
					ERROR_INFO("Cannot create layout file %s", layout_name);
					free(layout_name);
					return -1;
				}

				size = strlen(image->layout);

				if ( write(fd, image->layout, size) != (ssize_t)size ) {
					ERROR_INFO_STR(layout_name, "Cannot write %d bytes", size);
					close(fd);
					free(layout_name);
					return -1;
				}
			}

			free(layout_name);

			if ( ! simulate )
				close(fd);

		}

		image_list = image_list->next;

	}

	if ( dir ) {
		if ( chdir(cwd) < 0 ) {
			ERROR_INFO("Cannot change current directory back to %s", cwd);
			return -1;
		}
	}

	printf("\nDone\n\n");
	return 0;

}
Пример #9
0
struct fiasco * fiasco_alloc_from_file(const char * file) {

	uint8_t byte;
	uint32_t length;
	uint32_t count;
	uint8_t length8;
	uint8_t count8;

	char type[13];
	char device[17];
	char hwrevs[1024];
	char version[257];
	char layout[257];
	uint16_t hash;
	off_t offset;
	struct image * image;

	char hwrev[9];
	unsigned char buf[512];
	unsigned char *pbuf;

	struct fiasco * fiasco = fiasco_alloc_empty();
	if ( ! fiasco )
		return NULL;

	fiasco->fd = open(file, O_RDONLY);
	if ( fiasco->fd < 0 ) {
		ERROR_INFO("Cannot open file");
		fiasco_free(fiasco);
		return NULL;
	}

	fiasco->orig_filename = strdup(file);

	READ_OR_FAIL(fiasco, &byte, 1);
	if ( byte != 0xb4 )
		FIASCO_READ_ERROR(fiasco, "Invalid fiasco signature");

	READ_OR_FAIL(fiasco, &length, 4);
	length = ntohl(length);

	READ_OR_FAIL(fiasco, &count, 4);
	count = ntohl(count);

	VERBOSE("Number of header blocks: %d\n", count);

	while ( count > 0 ) {
		READ_OR_FAIL(fiasco, &byte, 1);
		READ_OR_FAIL(fiasco, &length8, 1);
		READ_OR_FAIL(fiasco, buf, length8);
		if ( byte == 0xe8 ) {
			memset(fiasco->name, 0, sizeof(fiasco->name));
			strncpy(fiasco->name, (char *)buf, length8);
			VERBOSE("Fiasco name: %s\n", fiasco->name);
		} else if ( byte == 0x31 ) {
			memset(fiasco->swver, 0, sizeof(fiasco->swver));
			strncpy(fiasco->swver, (char *)buf, length8);
			VERBOSE("SW version: %s\n", fiasco->swver);
		} else {
			VERBOSE("Unknown header %#x\n", byte);
		}
		--count;
	}

	/* walk the tree */
	while ( 1 ) {

		/* If end of file, return fiasco image */
		READ_OR_RETURN(fiasco, buf, 7);

		/* Header of next image */
		if ( ! ( buf[0] == 0x54 && buf[2] == 0x2E && buf[3] == 0x19 && buf[4] == 0x01 && buf[5] == 0x01 && buf[6] == 0x00 ) ) {
			ERROR("Invalid next image header");
			return fiasco;
		}

		count8 = buf[1];
		if ( count8 > 0 )
			--count8;

		READ_OR_RETURN(fiasco, &hash, 2);
		hash = ntohs(hash);

		memset(type, 0, sizeof(type));
		READ_OR_RETURN(fiasco, type, 12);

		byte = type[0];
		if ( byte == 0xFF )
			return fiasco;

		VERBOSE(" %s\n", type);

		READ_OR_RETURN(fiasco, &length, 4);
		length = ntohl(length);

		/* unknown */
		READ_OR_RETURN(fiasco, buf, 4);

		VERBOSE("   size:    %d bytes\n", length);
		VERBOSE("   hash:    %#04x\n", hash);
		VERBOSE("   subsections: %d\n", count8);

		memset(device, 0, sizeof(device));
		memset(hwrevs, 0, sizeof(hwrevs));
		memset(version, 0, sizeof(version));
		memset(layout, 0, sizeof(layout));

		while ( count8 > 0 ) {

			READ_OR_RETURN(fiasco, &byte, 1);
			READ_OR_RETURN(fiasco, &length8, 1);
			READ_OR_RETURN(fiasco, buf, length8);

			VERBOSE("   subinfo\n");
			VERBOSE("     length: %d\n", length8);
			VERBOSE("     type: ");

			if ( byte == '1' ) {
				memset(version, 0, sizeof(version));
				strncpy(version, (char *)buf, length8);
				VERBOSE("version string\n");
				VERBOSE("       version: %s\n", version);
			} else if ( byte == '2' ) {
				int tmp = length8;
				if ( tmp > 16 ) tmp = 16;
				memset(device, 0, sizeof(device));
				strncpy(device, (char *)buf, tmp);
				VERBOSE("hw revision\n");
				VERBOSE("       device: %s\n", device);
				pbuf = buf + strlen(device) + 1;
				while ( pbuf < buf + length8 ) {
					while ( pbuf < buf + length8 && *pbuf < 32 )
						++pbuf;
					if ( pbuf >= buf + length8 ) break;
					tmp = buf + length8 - pbuf;
					if ( tmp > 8 ) tmp = 8;
					memset(hwrev, 0, sizeof(hwrev));
					strncpy(hwrev, (char *)pbuf, tmp);
					if ( ! hwrevs[0] )
						strcpy(hwrevs, hwrev);
					else {
						size_t len1 = strlen(hwrevs);
						size_t len2 = strlen(hwrev);
						if ( len1 + len2 + 2 < sizeof(hwrevs) ) {
							hwrevs[len1] = ',';
							memcpy(hwrevs+len1+1, hwrev, len2+1);
						}
					}
					VERBOSE("       hw revision: %s\n", hwrev);
					pbuf += strlen(hwrev) + 1;
				}
			} else if ( byte == '3' ) {
				memset(layout, 0, sizeof(layout));
				strncpy(layout, (char *)buf, length8);
				VERBOSE("layout\n");
			} else {
				VERBOSE("unknown ('%c':%#x)\n", byte, byte);
			}

			--count8;
		}

		/* unknown */
		READ_OR_RETURN(fiasco, buf, 1);

		offset = lseek(fiasco->fd, 0, SEEK_CUR);
		if ( offset == (off_t)-1 )
			FIASCO_READ_ERROR(fiasco, "Cannot get offset of file");

		VERBOSE("   version: %s\n", version);
		VERBOSE("   device: %s\n", device);
		VERBOSE("   hwrevs: %s\n", hwrevs);
		VERBOSE("   data at: %#08x\n", (unsigned int)offset);

		image = image_alloc_from_shared_fd(fiasco->fd, length, offset, hash, type, device, hwrevs, version, layout);

		if ( ! image )
			FIASCO_READ_ERROR(fiasco, "Cannot allocate image");

		fiasco_add_image(fiasco, image);

		if ( lseek(fiasco->fd, offset+length, SEEK_SET) == (off_t)-1 )
			FIASCO_READ_ERROR(fiasco, "Cannot seek to next image in file");

	}

}
Пример #10
0
/******************************************
D3DHook_CaptureImageBuffer:
            capture image buffer ,we will copy the format

parameter:
		hProc  process handle that the D3DHook_HookProcess
		strDllName  name of dll to insert last time
		data   data to copy
             len   length of the data
             format      format of the data please see capture.h
             width        the width of the picture
             height       height of the picture

return value:
             filled length of the buffer is success
             otherwise the negative error code

remark :
             this will give the timeout to copy buffer
             and the format will give

******************************************/
extern "C" int D3DHook_CaptureImageBuffer(HANDLE hProc,char* strDllName,char * data, int len, int * format, int * width, int * height)
{
    int ret;
    char* pDllStripName=NULL;
    capture_buffer_t *pCaptureBuffer=NULL,*pCurCaptureBuffer=NULL;
    unsigned int capturesize=sizeof(*pCaptureBuffer);
    HANDLE hHandleProc=NULL;
    unsigned int processid=0;
    BOOL bret;
    SIZE_T curret;
    void* pFnAddr=NULL;
    int getlen=0;
    HANDLE hThread=NULL;
    DWORD threadid=0;
    DWORD stime,etime,ctime,wtime;
    DWORD dret;
    int timeout=3;
    DWORD retcode=(DWORD)-1;


    DEBUG_INFO("\n");
    pDllStripName = strrchr(strDllName,'\\');
    if(pDllStripName == NULL)
    {
        pDllStripName = strDllName;
    }
    else
    {
        pDllStripName ++;
    }
    DEBUG_INFO("\n");

    processid = GetProcessId(hProc);
    DEBUG_INFO("get hProc 0x%08lx processid (%d)\n",hProc,processid);


    hHandleProc = OpenProcess(PROCESS_VM_OPERATION |PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD ,FALSE,processid);
    if(hHandleProc == NULL)
    {
        ret = GetLastError() ? GetLastError() : 1;
        DEBUG_INFO("OpenProcess (%d) error (%d)\n",processid,ret);
        goto fail;
    }

	DEBUG_INFO("\n");
    pCaptureBuffer = (capture_buffer_t*)VirtualAllocEx(hHandleProc,NULL,capturesize,MEM_COMMIT,PAGE_EXECUTE_READWRITE);
    if(pCaptureBuffer == NULL)
    {
        ret = LAST_ERROR_RETURN();
        DEBUG_INFO("\n");
        goto fail;
    }
	DEBUG_INFO("\n");

    pCurCaptureBuffer =(capture_buffer_t*) calloc(sizeof(*pCurCaptureBuffer),1);
    if(pCurCaptureBuffer == NULL)
    {
        ret = LAST_ERROR_RETURN();
        DEBUG_INFO("\n");
        goto fail;
    }

    DEBUG_INFO("current 0x%08lx data 0x%p len(0x%08x)\n",GetCurrentProcess(),data,len);
    pCurCaptureBuffer->m_Data = data;
    pCurCaptureBuffer->m_DataLen = len;
    pCurCaptureBuffer->m_Processid = GetCurrentProcessId();

    /*now copy the memory*/
    bret = WriteProcessMemory(hHandleProc,pCaptureBuffer,pCurCaptureBuffer,sizeof(*pCaptureBuffer),&curret);
    if(!bret)
    {
        ret = LAST_ERROR_RETURN();
        DEBUG_INFO("\n");
        goto fail;
    }

	DEBUG_INFO("\n");
    if(curret != sizeof(*pCaptureBuffer))
    {
        ret = ERROR_INVALID_PARAMETER;
        DEBUG_INFO("\n");
        goto fail;
    }

	DEBUG_INFO("\n");
    /*now to create remote thread*/
    ret = GetRemoteProcAddress(processid,pDllStripName,"CaptureBuffer",&pFnAddr);
    if(ret < 0)
    {
        ret = LAST_ERROR_RETURN();
        DEBUG_INFO("\n");
        goto fail;
    }
	DEBUG_INFO("CaptureBuffer function address 0x%p\n",pFnAddr);

    hThread=CreateRemoteThread(hHandleProc,NULL,0,(LPTHREAD_START_ROUTINE)pFnAddr,pCaptureBuffer,0,&threadid);
    if(hThread == NULL)
    {
        ret = LAST_ERROR_RETURN();
        DEBUG_INFO("\n");
        goto fail;
    }
	DEBUG_INFO("\n");

    stime = GetTickCount();
    etime = stime + timeout* 1000;
    ctime = stime;

    while(TimeExpire(ctime,etime)==0)
    {
        wtime = 2000;
        if((etime - ctime) < wtime)
        {
            wtime = (etime - ctime);
        }
        dret = WaitForSingleObject(hThread,wtime);
        if(dret == WAIT_OBJECT_0)
        {
            bret = GetExitCodeThread(hThread,&retcode);
            if(bret)
            {
                break;
            }
            else if(GetLastError() != STILL_ACTIVE)
            {
                ret = LAST_ERROR_RETURN();
                DEBUG_INFO("\n");
                goto fail;
            }
            /*still alive ,continue*/
        }
        else if(dret == WAIT_TIMEOUT)
        {
            ;
        }
        else
        {
            ret = LAST_ERROR_RETURN();
            DEBUG_INFO("\n");
            goto fail;
        }
        ctime= GetTickCount();
    }

    if(TimeExpire(ctime, etime))
    {
        ret = WAIT_TIMEOUT;
        DEBUG_INFO("\n");
        goto fail;
    }

    ret =(int) retcode;
    if(ret < 0)
    {
        ret = -ret;
        DEBUG_INFO("\n");
        goto fail;
    }

    /*get the length*/
    getlen = ret;

    /*now to read from the memory as the  result*/
    bret = ReadProcessMemory(hHandleProc,pCaptureBuffer,pCurCaptureBuffer,sizeof(*pCurCaptureBuffer),&curret);
    if(!bret)
    {
        ret = LAST_ERROR_RETURN();
        DEBUG_INFO("\n");
        goto fail;
    }

    if(curret != sizeof(*pCurCaptureBuffer))
    {
        ret = ERROR_INVALID_OPERATION;
        DEBUG_INFO("\n");
        goto fail;
    }


    *format = pCurCaptureBuffer->m_Format;
    *width = pCurCaptureBuffer->m_Width;
    *height = pCurCaptureBuffer->m_Height;


    /*all is ok ,so we should do this*/
    if(hThread)
    {
        CloseHandle(hThread);
    }
    hThread=NULL;
    if(pCaptureBuffer)
    {
        bret = VirtualFreeEx(hHandleProc,pCaptureBuffer,capturesize,MEM_DECOMMIT);
        if(!bret)
        {
            ERROR_INFO("could not free %p size %d on %x error (%d)\n",pCaptureBuffer,capturesize,hHandleProc,GetLastError());
        }
    }
    if(pCurCaptureBuffer)
    {
        free(pCurCaptureBuffer);
    }
    pCurCaptureBuffer = NULL;
    if(hHandleProc)
    {
        CloseHandle(hHandleProc);
    }
    hHandleProc = NULL;

    return getlen;

fail:
    if(hThread)
    {
        CloseHandle(hThread);
    }
    hThread=NULL;
    if(pCaptureBuffer)
    {
        bret = VirtualFreeEx(hHandleProc,pCaptureBuffer,capturesize,MEM_DECOMMIT);
        if(!bret)
        {
            ERROR_INFO("could not free %p size %d on %x error (%d)\n",pCaptureBuffer,capturesize,hHandleProc,GetLastError());
        }
    }
    if(pCurCaptureBuffer)
    {
        free(pCurCaptureBuffer);
    }
    pCurCaptureBuffer = NULL;
    if(hHandleProc)
    {
        CloseHandle(hHandleProc);
    }
    hHandleProc = NULL;
    SetLastError(ret);
    return -ret;

}
Пример #11
0
int fiasco_write_to_file(struct fiasco * fiasco, const char * file) {

	int fd = -1;
	int i;
	int device_count;
	uint32_t size;
	uint32_t length;
	uint16_t hash;
	uint8_t length8;
	char ** device_hwrevs_bufs;
	const char * str;
	const char * type;
	struct image_list * image_list;
	struct image * image;
	unsigned char buf[4096];

	if ( ! fiasco )
		return -1;

	printf("Generating Fiasco image %s...\n", file);

	if ( ! fiasco->first )
		FIASCO_WRITE_ERROR(file, fd, "Nothing to write");

	if ( strlen(fiasco->name)+1 > UINT8_MAX )
		FIASCO_WRITE_ERROR(file, fd, "Fiasco name string is too long");

	if ( strlen(fiasco->swver)+1 > UINT8_MAX )
		FIASCO_WRITE_ERROR(file, fd, "SW version string is too long");

	if ( ! simulate ) {
		fd = open(file, O_RDWR|O_CREAT|O_TRUNC, 0644);
		if ( fd < 0 ) {
			ERROR_INFO("Cannot create file");
			return -1;
		}
	}

	printf("Writing Fiasco header...\n");

	WRITE_OR_FAIL(file, fd, "\xb4", 1); /* signature */

	if ( fiasco->name[0] )
		str = fiasco->name;
	else
		str = "OSSO UART+USB";

	length = 4 + strlen(str) + 3;
	if ( fiasco->swver[0] )
		length += strlen(fiasco->swver) + 3;
	length = htonl(length);
	WRITE_OR_FAIL(file, fd, &length, 4); /* FW header length */

	if ( fiasco->swver[0] )
		length = htonl(2);
	else
		length = htonl(1);
	WRITE_OR_FAIL(file, fd, &length, 4); /* FW header blocks count */

	/* Fiasco name */
	length8 = strlen(str)+1;
	WRITE_OR_FAIL(file, fd, "\xe8", 1);
	WRITE_OR_FAIL(file, fd, &length8, 1);
	WRITE_OR_FAIL(file, fd, str, length8);

	/* SW version */
	if ( fiasco->swver[0] ) {
		printf("Writing SW version: %s\n", fiasco->swver);
		length8 = strlen(fiasco->swver)+1;
		WRITE_OR_FAIL(file, fd, "\x31", 1);
		WRITE_OR_FAIL(file, fd, &length8, 1);
		WRITE_OR_FAIL(file, fd, fiasco->swver, length8);
	};

	printf("\n");

	image_list = fiasco->first;

	while ( image_list ) {

		image = image_list->image;

		if ( ! image )
			FIASCO_WRITE_ERROR(file, fd, "Empty image");

		printf("Writing image...\n");
		image_print_info(image);

		type = image_type_to_string(image->type);

		if ( ! type )
			FIASCO_WRITE_ERROR(file, fd, "Unknown image type");

		if ( image->version && strlen(image->version) > UINT8_MAX )
			FIASCO_WRITE_ERROR(file, fd, "Image version string is too long");

		if ( image->layout && strlen(image->layout) > UINT8_MAX )
			FIASCO_WRITE_ERROR(file, fd, "Image layout is too long");

		device_hwrevs_bufs = device_list_alloc_to_bufs(image->devices);

		device_count = 0;
		if ( device_hwrevs_bufs && device_hwrevs_bufs[0] )
			for ( ; device_hwrevs_bufs[device_count]; ++device_count );

		printf("Writing image header...\n");

		/* signature */
		WRITE_OR_FAIL_FREE(file, fd, "T", 1, device_hwrevs_bufs);

		/* number of subsections */
		length8 = device_count+1;
		if ( image->version )
			++length8;
		if ( image->layout )
			++length8;
		WRITE_OR_FAIL_FREE(file, fd, &length8, 1, device_hwrevs_bufs);

		/* unknown */
		WRITE_OR_FAIL_FREE(file, fd, "\x2e\x19\x01\x01\x00", 5, device_hwrevs_bufs);

		/* checksum */
		hash = htons(image->hash);
		WRITE_OR_FAIL_FREE(file, fd, &hash, 2, device_hwrevs_bufs);

		/* image type name */
		memset(buf, 0, 12);
		strncpy((char *)buf, type, 12);
		WRITE_OR_FAIL_FREE(file, fd, buf, 12, device_hwrevs_bufs);

		/* image size */
		size = htonl(image->size);
		WRITE_OR_FAIL_FREE(file, fd, &size, 4, device_hwrevs_bufs);

		/* unknown */
		WRITE_OR_FAIL_FREE(file, fd, "\x00\x00\x00\x00", 4, device_hwrevs_bufs);

		/* append version subsection */
		if ( image->version ) {
			WRITE_OR_FAIL_FREE(file, fd, "1", 1, device_hwrevs_bufs); /* 1 - version */
			length8 = strlen(image->version)+1; /* +1 for NULL term */
			WRITE_OR_FAIL_FREE(file, fd, &length8, 1, device_hwrevs_bufs);
			WRITE_OR_FAIL_FREE(file, fd, image->version, length8, device_hwrevs_bufs);
		}

		/* append device & hwrevs subsection */
		for ( i = 0; i < device_count; ++i ) {
			WRITE_OR_FAIL_FREE(file, fd, "2", 1, device_hwrevs_bufs); /* 2 - device & hwrevs */
			length8 = ((uint8_t *)(device_hwrevs_bufs[i]))[0];
			WRITE_OR_FAIL_FREE(file, fd, &length8, 1, device_hwrevs_bufs);
			WRITE_OR_FAIL_FREE(file, fd, device_hwrevs_bufs[i]+1, length8, device_hwrevs_bufs);
		}
		free(device_hwrevs_bufs);

		/* append layout subsection */
		if ( image->layout ) {
			WRITE_OR_FAIL(file, fd, "3", 1); /* 3 - layout */
			length8 = strlen(image->layout);
			WRITE_OR_FAIL(file, fd, &length8, 1);
			WRITE_OR_FAIL(file, fd, image->layout, length8);
		}

		/* dummy byte - end of all subsections */
		WRITE_OR_FAIL(file, fd, "\x00", 1);

		printf("Writing image data...\n");

		image_seek(image, 0);
		while ( 1 ) {
			size = image_read(image, buf, sizeof(buf));
			if ( size == 0 )
				break;
			WRITE_OR_FAIL(file, fd, buf, size);
		}

		image_list = image_list->next;

		if ( image_list )
			printf("\n");

	}

	if ( ! simulate )
		close(fd);

	printf("\nDone\n\n");
	return 0;

}
Пример #12
0
UINT CPageSmartUpdate::UpdateThread(LPVOID pParam)
{
    int i;
    unsigned int len;   //bin file lenght
    int result;
    CPageSmartUpdate *pSmartUpdate = (CPageSmartUpdate *)pParam;
    CString name, str;
    BYTE CID;
    BYTE index = 0;

    pSmartUpdate->m_bUpdateThreadRun = true;

    INFO("正准备软件升级...\r\n");
    //>>>>>>>>S1:COM handle
    //判断串口是否打开
    if(false == g_pSerialProtocol->isSerialOpen())//串口已经打开,则进行关闭操作
    {
        INFO("错误:请先打开串口\r\n");
        pSmartUpdate->addInfo2Display(_T("错误:请先打开串口\r\n"));
        pSmartUpdate->m_bUpdateThreadRun = false;
        pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
        return 0;
    }
    
    str.Format("提示:检测到%d待升级文件,正在进行中...\r\n", pSmartUpdate->m_AioBinFileCount);
    pSmartUpdate->addInfo2Display(str);

    while (!pSmartUpdate->checkTarget(CID,name))
    {
        if (CID != pSmartUpdate->getPacketCID())
        {
            pSmartUpdate->setPacketCID(CID);
        }
        if (pSmartUpdate->SaveFiletoRAM(&len, name) < 0)
        {
            INFO("错误:文件拷贝至内存失败\r\n");
            pSmartUpdate->addInfo2Display(_T("错误:文件拷贝至内存失败\r\n"));
            pSmartUpdate->m_bUpdateThreadRun = false;
            pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
            return 0;
        }
        else
        {
            INFO("提示:文件长度 = %d  字节\r\n", len);
            pSmartUpdate->displayProgressAIO(index, 1);
        }

        //>>>>>>>>S3:Send Update Tag, Target ready to download.
        i = 5;
        INFO("(1/5)等待目标板确认包...");
        while(--i)
        {
            if (pSmartUpdate->SendResetAndUpdateTag()) break;
        }
        pSmartUpdate->DisplayOKorError(i);
        if (i == 0)
        {
            pSmartUpdate->addInfo2Display(_T("错误:等待目标板确认包失败\r\n"));
            pSmartUpdate->m_bUpdateThreadRun = false;
            pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
            return 0;
        }
        pSmartUpdate->displayProgressAIO(index, 3);

        //>>>>>>>>S4:Send UPDATE_SOL
        i = 5;
        INFO("(2/5)等待文件长度确认包...");
        while(--i)
        {
            result = pSmartUpdate->SendUpdateStartOfLenght(len);
            if (0 != result) break;
        }
        if (-1 == result)
        {
            INFO("Error(文件大小超出Flash范围)\r\n");
            pSmartUpdate->addInfo2Display(_T("错误:文件大小超出Flash范围\r\n"));
            pSmartUpdate->m_bUpdateThreadRun = false;
            pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
            return 0;
        }
        pSmartUpdate->DisplayOKorError(i);
        if (i == 0)
        {
            pSmartUpdate->addInfo2Display(_T("错误:等待目标板长度确认包失败\r\n"));
            pSmartUpdate->m_bUpdateThreadRun = false;
            pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
            return 0;
        }
        pSmartUpdate->displayProgressAIO(index, 5);

        INFO("(3/5)正在传送数据:\r\n");
        do 
        {
            result = pSmartUpdate->SendUpdateStartOfData(len);
            if (result > 0)
            {
                i = 5 + 90 * (len - result)/len;
                pSmartUpdate->displayProgressAIO(index, i);
            }
        } while(result > 0);
        
        INFO("\r\n(3/5)正在传送数据结果:");
        if (0 == result)
        {
            pSmartUpdate->DisplayOKorError(1);
        }
        else 
        {
            pSmartUpdate->DisplayOKorError(0);
            if (-1 == result)
            {
                ERROR_INFO("目标板异常终止");
            }
            else if (-2 == result)
            {
                ERROR_INFO("等待响应超时!");
            }
            pSmartUpdate->addInfo2Display(_T("错误:数据传输失败\r\n"));
            pSmartUpdate->m_bUpdateThreadRun = false;
            pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
            return 0;
        }

        //>>>>>>>>S6:Send UPDATE_EOT
        i = 5;
        INFO("(4/5)等待文件结束确认包...");
        while(--i)
        {
            if (pSmartUpdate->SendUpdateEndOfTransmit()) break;
        }
        pSmartUpdate->DisplayOKorError(i);
        if (i == 0)
        {
            pSmartUpdate->addInfo2Display(_T("错误:等待文件结束确认包失败\r\n"));
            pSmartUpdate->m_bUpdateThreadRun = false;
            pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
            return 0;
        }
        pSmartUpdate->displayProgressAIO(index, 97);

        INFO("(5/5)等待烧写进Flash:");
        for (i = 0; i < 1000; i++)
        {  
            result = pSmartUpdate->WaitUpdateWrite2FlashDone();
            if (0 == result) 
            {
                INFO("OK.\r\n");
                break;
            }
            else if (-1 == result)
            {
                INFO("Error.\r\n");
                break;
            }
            INFO(".");
            if (i % 50 == 0)
            {
                INFO("\r\n");
            }
        }
        if (1000 == i)
        {
            ERROR_INFO("超时\r\n");
        }
        pSmartUpdate->displayProgressAIO(index, 100);
        index++;
        if (index != pSmartUpdate->m_AioBinFileCount)
        {
            MSG("准备烧写下一个文件!\r\n");
            Sleep(6000); //wait for reboot!
        }
    }
    
    INFO("\r\n===========================");
    INFO("\r\n===========================");
    INFO("\r\n===========================");
    INFO("\r\n>>>>>>>>烧写已完成<<<<<<<<<\r\n");
    pSmartUpdate->addInfo2Display(_T("\r\n>>>>烧写成功<<<<\r\n"));
    pSmartUpdate->m_bUpdateThreadRun = false;
    pSmartUpdate->GetDlgItem(IDC_BTN_AIO_UPDATE)->SetWindowTextA("AIO板升级");
    return 0;
}
Пример #13
0
int main(int argc, char **argv) {

#ifdef _OPENMP
  printf("ERKALE - Geometry optimization from Hel, OpenMP version, running on %i cores.\n",omp_get_max_threads());
#else
  printf("ERKALE - Geometry optimization from Hel, serial version.\n");
#endif
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc!=2) {
    printf("Usage: $ %s runfile\n",argv[0]);
    return 0;
  }

  // Initialize libint
  init_libint_base();
  // Initialize libderiv
  init_libderiv_base();

  Timer tprog;
  tprog.print_time();

  // Parse settings
  Settings set;
  set.add_scf_settings();
  set.add_string("SaveChk","File to use as checkpoint","erkale.chk");
  set.add_string("LoadChk","File to load old results from","");
  set.add_bool("ForcePol","Force polarized calculation",false);
  set.add_bool("FreezeCore","Freeze the atomic cores?",false);
  set.add_string("Optimizer","Optimizer to use: CGFR, CGPR, BFGS, BFGS2 (default), SD","BFGS2");
  set.add_int("MaxSteps","Maximum amount of geometry steps",256);
  set.add_string("Criterion","Convergence criterion to use: LOOSE, NORMAL, TIGHT, VERYTIGHT","NORMAL");
  set.add_string("OptMovie","xyz movie to store progress in","optimize.xyz");
  set.add_string("Result","File to save optimized geometry in","optimized.xyz");
  set.set_string("Logfile","erkale_geom.log");
  set.parse(std::string(argv[1]),true);
  set.print();

  bool verbose=set.get_bool("Verbose");
  int maxiter=set.get_int("MaxSteps");
  std::string optmovie=set.get_string("OptMovie");
  std::string result=set.get_string("Result");

  // Interpret optimizer
  enum minimizer alg;
  std::string method=set.get_string("Optimizer");
  if(stricmp(method,"CGFR")==0)
    alg=gCGFR;
  else if(stricmp(method,"CGPR")==0)
    alg=gCGPR;
  else if(stricmp(method,"BFGS")==0)
    alg=gBFGS;
  else if(stricmp(method,"BFGS2")==0)
    alg=gBFGS2;
  else if(stricmp(method,"SD")==0)
    alg=gSD;
  else {
    ERROR_INFO();
    throw std::runtime_error("Unknown optimization method.\n");
  }

  // Interpret optimizer
  enum convergence crit;
  method=set.get_string("Criterion");
  if(stricmp(method,"LOOSE")==0)
    crit=LOOSE;
  else if(stricmp(method,"NORMAL")==0)
    crit=NORMAL;
  else if(stricmp(method,"TIGHT")==0)
    crit=TIGHT;
  else if(stricmp(method,"VERYTIGHT")==0)
    crit=VERYTIGHT;
  else {
    ERROR_INFO();
    throw std::runtime_error("Unknown optimization method.\n");
  }

  // Redirect output?
  std::string logfile=set.get_string("Logfile");
  if(stricmp(logfile,"stdout")!=0) {
    // Redirect stdout to file
    FILE *outstream=freopen(logfile.c_str(),"w",stdout);
    if(outstream==NULL) {
      ERROR_INFO();
      throw std::runtime_error("Unable to redirect output!\n");
    } else
      fprintf(stderr,"\n");
  }

  // Read in atoms.
  std::string atomfile=set.get_string("System");
  const std::vector<atom_t> origgeom=load_xyz(atomfile);
  std::vector<atom_t> atoms(origgeom);

  // Are any atoms fixed?
  std::vector<size_t> dofidx;
  for(size_t i=0;i<atoms.size();i++) {
    bool fixed=false;

    if(atoms[i].el.size()>3)
      if(stricmp(atoms[i].el.substr(atoms[i].el.size()-3),"-Fx")==0) {
	fixed=true;
	atoms[i].el=atoms[i].el.substr(0,atoms[i].el.size()-3);
      }

    // Add to degrees of freedom
    if(!fixed)
      dofidx.push_back(i);
  }

  // Read in basis set
  BasisSetLibrary baslib;
  std::string basfile=set.get_string("Basis");
  baslib.load_gaussian94(basfile);
  printf("\n");

  // Save to output
  save_xyz(atoms,"Initial configuration",optmovie,false);

  // Minimizer options
  opthelper_t pars;
  pars.atoms=atoms;
  pars.baslib=baslib;
  pars.set=set;
  pars.dofidx=dofidx;

  /* Starting point */
  gsl_vector *x = gsl_vector_alloc (3*dofidx.size());
  for(size_t i=0;i<dofidx.size();i++) {
    gsl_vector_set(x,3*i,atoms[dofidx[i]].x);
    gsl_vector_set(x,3*i+1,atoms[dofidx[i]].y);
    gsl_vector_set(x,3*i+2,atoms[dofidx[i]].z);
  }

  // GSL status
  int status;

  const gsl_multimin_fdfminimizer_type *T;
  gsl_multimin_fdfminimizer *s;

  gsl_multimin_function_fdf minimizer;

  minimizer.n = x->size;
  minimizer.f = calc_E;
  minimizer.df = calc_f;
  minimizer.fdf = calc_Ef;
  minimizer.params = (void *) &pars;

  if(alg==gCGFR) {
    T = gsl_multimin_fdfminimizer_conjugate_fr;
    if(verbose) printf("Using Fletcher-Reeves conjugate gradients.\n");
  } else if(alg==gCGPR) {
    T = gsl_multimin_fdfminimizer_conjugate_pr;
    if(verbose) printf("Using Polak-Ribière conjugate gradients.\n");
  } else if(alg==gBFGS) {
    T = gsl_multimin_fdfminimizer_vector_bfgs;
    if(verbose) printf("Using the BFGS minimizer.\n");
  } else if(alg==gBFGS2) {
    T = gsl_multimin_fdfminimizer_vector_bfgs2;
    if(verbose) printf("Using the BFGS2 minimizer.\n");
  } else if(alg==gSD) {
    T = gsl_multimin_fdfminimizer_steepest_descent;
    if(verbose) printf("Using the steepest descent minimizer.\n");
  } else {
    ERROR_INFO();
    throw std::runtime_error("Unsupported minimizer\n");
  }

  // Run an initial calculation
  double oldE=calc_E(x,minimizer.params);

  // Turn off verbose setting
  pars.set.set_bool("Verbose",false);
  // and load from old checkpoint
  pars.set.set_string("LoadChk",pars.set.get_string("SaveChk"));

  // Initialize minimizer
  s = gsl_multimin_fdfminimizer_alloc (T, minimizer.n);

  // Use initial step length of 0.02 bohr, and a line search accuracy
  // 1e-1 (recommended in the GSL manual for BFGS)
  gsl_multimin_fdfminimizer_set (s, &minimizer, x, 0.02, 1e-1);

  // Store old force
  arma::mat oldf=interpret_force(s->gradient);

  fprintf(stderr,"Geometry optimizer initialized in %s.\n",tprog.elapsed().c_str());
  fprintf(stderr,"Entering minimization loop with %s optimizer.\n",set.get_string("Optimizer").c_str());

  fprintf(stderr,"%4s %16s %10s %10s %9s %9s %9s %9s %s\n","iter","E","dE","dE/dEproj","disp max","disp rms","f max","f rms", "titer");

  std::vector<atom_t> oldgeom(atoms);

  bool convd=false;
  int iter;

  for(iter=1;iter<=maxiter;iter++) {
    printf("\nGeometry iteration %i\n",(int) iter);
    fflush(stdout);

    Timer titer;

    status = gsl_multimin_fdfminimizer_iterate (s);

    if (status) {
      fprintf(stderr,"GSL encountered error: \"%s\".\n",gsl_strerror(status));
      break;
    }

    // New geometry is
    std::vector<atom_t> geom=get_atoms(s->x,pars);

    // Calculate displacements
    double dmax, drms;
    get_displacement(geom, oldgeom, dmax, drms);

    // Calculate projected change of energy
    double dEproj=calculate_projection(geom,oldgeom,oldf,pars.dofidx);
    // Actual change of energy is
    double dE=s->f - oldE;

    // Switch geometries
    oldgeom=geom;
    // Save old force

    // Get forces
    double fmax, frms;
    get_forces(s->gradient, fmax, frms);

    // Save geometry step
    char comment[80];
    sprintf(comment,"Step %i",(int) iter);
    save_xyz(get_atoms(s->x,pars),comment,optmovie,true);

    // Check convergence
    bool fmaxconv=false, frmsconv=false;
    bool dmaxconv=false, drmsconv=false;

    switch(crit) {

    case(LOOSE):
      if(fmax < 2.5e-3)
	fmaxconv=true;
      if(frms < 1.7e-3)
	frmsconv=true;
      if(dmax < 1.0e-2)
	dmaxconv=true;
      if(drms < 6.7e-3)
	drmsconv=true;
      break;

    case(NORMAL):
      if(fmax < 4.5e-4)
	fmaxconv=true;
      if(frms < 3.0e-4)
	frmsconv=true;
      if(dmax < 1.8e-3)
	dmaxconv=true;
      if(drms < 1.2e-3)
	drmsconv=true;
      break;

    case(TIGHT):
      if(fmax < 1.5e-5)
	fmaxconv=true;
      if(frms < 1.0e-5)
	frmsconv=true;
      if(dmax < 6.0e-5)
	dmaxconv=true;
      if(drms < 4.0e-5)
	drmsconv=true;
      break;

    case(VERYTIGHT):
      if(fmax < 2.0e-6)
	fmaxconv=true;
      if(frms < 1.0e-6)
	frmsconv=true;
      if(dmax < 6.0e-6)
	dmaxconv=true;
      if(drms < 4.0e-6)
	drmsconv=true;
      break;

    default:
      ERROR_INFO();
      throw std::runtime_error("Not implemented!\n");
    }

    // Converged?
    const static char cconv[]=" *";

    double dEfrac;
    if(dEproj!=0.0)
      dEfrac=dE/dEproj;
    else
      dEfrac=0.0;

    fprintf(stderr,"%4d % 16.8f % .3e % .3e %.3e%c %.3e%c %.3e%c %.3e%c %s\n", (int) iter, s->f, dE, dEfrac, dmax, cconv[dmaxconv], drms, cconv[drmsconv], fmax, cconv[fmaxconv], frms, cconv[frmsconv], titer.elapsed().c_str());
    fflush(stderr);

    convd=dmaxconv && drmsconv && fmaxconv && frmsconv;

    if(convd) {
      fprintf(stderr,"Converged.\n");
      break;
    }

    // Store old energy
    oldE=s->f;
    // Store old force
    oldf=interpret_force(s->gradient);
  }

  if(convd)
    save_xyz(get_atoms(s->x,pars),"Optimized geometry",result);

  gsl_multimin_fdfminimizer_free (s);

  gsl_vector_free (x);

  if(iter==maxiter && !convd) {
    printf("Geometry convergence was not achieved!\n");
  }


  printf("Running program took %s.\n",tprog.elapsed().c_str());

  return 0;
}
Пример #14
0
enum calcd run_calc(const BasisSet & basis, Settings & set, bool force) {
  // Checkpoint file to load
  std::string loadname=set.get_string("LoadChk");

  if(stricmp(loadname,"")==0) {
    // Nothing to load - run full calculation.
    calculate(basis,set,force);
    if(force)
      return FULLCALC;
    else
      return ECALC;
  }

  // Was the calculation converged?
  bool convd;
  BasisSet oldbas;
  {
    Checkpoint chkpt(loadname,false);
    chkpt.read("Converged",convd);
    chkpt.read(oldbas);
  }
  if(!convd) {
    // Old calculation was not converged - run full calculation
    set.set_string("LoadName","");
    calculate(basis,set,force);
    if(force)
      return FULLCALC;
    else
      return ECALC;
  }

  // Copy the checkpoint if necessary
  std::string savename=set.get_string("SaveChk");
  if(stricmp(savename,loadname)!=0) {
    // Copy the file
    std::ostringstream oss;
    oss << "cp " << loadname << " " << savename;
    int cp=system(oss.str().c_str());
    if(cp) {
      ERROR_INFO();
      throw std::runtime_error("Failed to copy checkpoint file.\n");
    }
  }

  // Strict integrals?
  bool strictint(set.get_bool("StrictIntegrals"));
  
  // Check if the basis set is different
  if(!(basis==oldbas)) {
    // Basis set is different or calculation was not converged - need
    // to run calculation. Project Fock matrix to new basis and
    // diagonalize to get new orbitals
    {
      // Open in write mode, don't truncate
      Checkpoint chkpt(savename,true,false);

      // Save basis
      chkpt.write(basis);
      // Overlap matrix
      arma::mat S=basis.overlap();
      chkpt.write("S",S);
      arma::mat Sinvh=BasOrth(S,set);
      chkpt.write("Sinvh",Sinvh);

      // Restricted or unrestricted run?
      bool restr;
      chkpt.read("Restricted",restr);
      chkpt.read(oldbas);

      if(restr) {
	rscf_t sol;
	std::vector<double> occs;
	chkpt.read("H",sol.H);
	chkpt.read("occs",occs);

	// Form new orbitals by diagonalizing H in new geometry
	diagonalize(S,Sinvh,sol);

	// Form new density
	sol.P=form_density(sol.C,occs);

	// Write basis set, orbitals and density
	chkpt.write("C",sol.C);
	chkpt.write("E",sol.E);
	chkpt.write("P",sol.P);

      } else {
	uscf_t sol;
	std::vector<double> occa, occb;
	chkpt.read("Ha",sol.Ha);
	chkpt.read("Hb",sol.Hb);
	chkpt.read("occa",occa);
	chkpt.read("occb",occb);

	// Form new orbitals by diagonalizing H in new geometry
	diagonalize(S,Sinvh,sol);

	// Form new density
	sol.Pa=form_density(sol.Ca,occa);
	sol.Pb=form_density(sol.Cb,occb);
	sol.P=sol.Pa+sol.Pb;

	// Write basis set, orbitals and density
	chkpt.write("Ca",sol.Ca);
	chkpt.write("Cb",sol.Cb);
	chkpt.write("Ea",sol.Ea);
	chkpt.write("Eb",sol.Eb);
	chkpt.write("Pa",sol.Pa);
	chkpt.write("Pb",sol.Pb);
	chkpt.write("P",sol.P);
      }

      // Calculation is now not converged
      bool conv=false;
      chkpt.write("Converged",conv);
    }

    // Now we can do the SCF calculation
    calculate(basis,set,force);
    if(force)
      return FULLCALC;
    else
      return ECALC;
  }

  // Because we are here, the basis set is the same.
  if(!force)
    // No force required, can just read energy from file.
    return NOCALC;

  // Have converged energy, compute force.
  // Open the checkpoint in write mode, don't truncate it
  Checkpoint chkpt(savename,true,false);

  // SCF structure
  SCF solver(basis,set,chkpt);

  // Do a plain Hartree-Fock calculation?
  bool hf= (stricmp(set.get_string("Method"),"HF")==0);
  bool rohf=(stricmp(set.get_string("Method"),"ROHF")==0);

  dft_t dft;
  if(!hf && !rohf) {
    // Get exchange and correlation functionals as well as grid settings
    dft=parse_dft(set,false);
  }
    
  // Force
  arma::vec f;

  double tol;
  chkpt.read("tol",tol);

  // Multiplicity
  int mult=set.get_int("Multiplicity");
  // Amount of electrons
  int Nel=basis.Ztot()-set.get_int("Charge");

  if(mult==1 && Nel%2==0 && !set.get_bool("ForcePol")) {
    rscf_t sol;
    chkpt.read("C",sol.C);
    chkpt.read("E",sol.E);
    chkpt.read("H",sol.H);
    chkpt.read("P",sol.P);

    std::vector<double> occs;
    chkpt.read("occs",occs);

    // Restricted case
    if(hf) {
      f=solver.force_RHF(sol,occs,FINETOL);
    } else {
      DFTGrid grid(&basis,set.get_bool("Verbose"),dft.lobatto);
      DFTGrid nlgrid(&basis,set.get_bool("Verbose"),dft.lobatto);

      // Fixed grid?
      if(dft.adaptive)
	grid.construct(sol.P,dft.gridtol,dft.x_func,dft.c_func);
      else {
	grid.construct(dft.nrad,dft.lmax,dft.x_func,dft.c_func,strictint);
	if(dft.nl)
	  nlgrid.construct(dft.nlnrad,dft.nllmax,true,false,strictint,true);
      }
      f=solver.force_RDFT(sol,occs,dft,grid,nlgrid,FINETOL);
    }

  } else {

    uscf_t sol;
    chkpt.read("Ca",sol.Ca);
    chkpt.read("Ea",sol.Ea);
    chkpt.read("Ha",sol.Ha);
    chkpt.read("Pa",sol.Pa);

    chkpt.read("Cb",sol.Cb);
    chkpt.read("Eb",sol.Eb);
    chkpt.read("Hb",sol.Hb);
    chkpt.read("Pb",sol.Pb);
    chkpt.read("P",sol.P);

    std::vector<double> occa, occb;
    chkpt.read("occa",occa);
    chkpt.read("occb",occb);

    if(hf) {
      f=solver.force_UHF(sol,occa,occb,tol);
    } else if(rohf) {
      int Nela, Nelb;
      chkpt.read("Nel-a",Nela);
      chkpt.read("Nel-b",Nelb);

      throw std::runtime_error("Not implemented!\n");
      //      f=solver.force_ROHF(sol,Nela,Nelb,tol);
    } else {
      DFTGrid grid(&basis,set.get_bool("Verbose"),dft.lobatto);
      DFTGrid nlgrid(&basis,set.get_bool("Verbose"),dft.lobatto);

      // Fixed grid?
      if(dft.adaptive)
	grid.construct(sol.P,dft.gridtol,dft.x_func,dft.c_func);
      else {
	grid.construct(dft.nrad,dft.lmax,dft.x_func,dft.c_func,strictint);
	if(dft.nl)
	  nlgrid.construct(dft.nlnrad,dft.nllmax,true,false,strictint,true);
      }
      f=solver.force_UDFT(sol,occa,occb,dft,grid,nlgrid,tol);
    }
  }

  chkpt.write("Force",f);
  chkpt.close();

  return FORCECALC;
}
Пример #15
0
Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration)
{
    MOVE_RESULT result = MOVE_OK;

    try
    {
        Debug.AddLine("Guiding  Dir = %d, Dur = %d", direction, duration);

        if (!IsConnected())
        {
            throw ERROR_INFO("ASCOM Scope: attempt to guide when not connected");
        }

        if (!m_canPulseGuide)
        {
            // Could happen if move command is issued on the Aux mount or CanPulseGuide property got changed on the fly
            pFrame->Alert(_("ASCOM driver does not support PulseGuide"));
            throw ERROR_INFO("ASCOM scope: guide command issued but PulseGuide not supported");
        }

        GITObjRef scope(m_gitEntry);

        // First, check to see if already moving

        CheckSlewing(&scope, &result);

        if (IsGuiding(&scope))
        {
            Debug.AddLine("Entered PulseGuideScope while moving");
            int i;
            for (i = 0; i < 20; i++)
            {
                wxMilliSleep(50);

                CheckSlewing(&scope, &result);

                if (!IsGuiding(&scope))
                    break;

                Debug.AddLine("Still moving");
            }
            if (i == 20)
            {
                Debug.AddLine("Still moving after 1s - aborting");
                throw ERROR_INFO("ASCOM Scope: scope is still moving after 1 second");
            }
            else
            {
                Debug.AddLine("Movement stopped - continuing");
            }
        }

        // Do the move

        VARIANTARG rgvarg[2];
        rgvarg[1].vt = VT_I2;
        rgvarg[1].iVal = direction;
        rgvarg[0].vt = VT_I4;
        rgvarg[0].lVal = (long) duration;

        DISPPARAMS dispParms;
        dispParms.cArgs = 2;
        dispParms.rgvarg = rgvarg;
        dispParms.cNamedArgs = 0;
        dispParms.rgdispidNamedArgs = NULL;

        wxStopWatch swatch;

        HRESULT hr;
        EXCEPINFO excep;
        Variant vRes;

        if (FAILED(hr = scope.IDisp()->Invoke(dispid_pulseguide, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD,
            &dispParms, &vRes, &excep, NULL)))
        {
            Debug.AddLine(wxString::Format("pulseguide: [%x] %s", hr, _com_error(hr).ErrorMessage()));

            // Make sure nothing got by us and the mount can really handle pulse guide - HIGHLY unlikely
            if (scope.GetProp(&vRes, L"CanPulseGuide") && vRes.boolVal != VARIANT_TRUE)
            {
                Debug.AddLine("Tried to guide mount that has no PulseGuide support");
                // This will trigger a nice alert the next time through Guide
                m_canPulseGuide = false;
            }
            throw ERROR_INFO("ASCOM Scope: pulseguide command failed: " + ExcepMsg(excep));
        }

        long elapsed = swatch.Time();
        if (elapsed < (long)duration)
        {
            unsigned long rem = (unsigned long)((long)duration - elapsed);

            Debug.AddLine("PulseGuide returned control before completion, sleep %lu", rem + 10);

            if (WorkerThread::MilliSleep(rem + 10))
                throw ERROR_INFO("ASCOM Scope: thread terminate requested");
        }

        if (IsGuiding(&scope))
        {
            Debug.AddLine("scope still moving after pulse duration time elapsed");

            // try waiting a little longer. If scope does not stop moving after 1 second, try doing AbortSlew
            // if it still does not stop after 2 seconds, bail out with an error

            enum { GRACE_PERIOD_MS = 1000,
                   TIMEOUT_MS = GRACE_PERIOD_MS + 1000, };

            bool timeoutExceeded = false;
            bool didAbortSlew = false;

            while (true)
            {
                ::wxMilliSleep(20);

                if (WorkerThread::InterruptRequested())
                    throw ERROR_INFO("ASCOM Scope: thread interrupt requested");

                CheckSlewing(&scope, &result);

                if (!IsGuiding(&scope))
                {
                    Debug.AddLine("scope move finished after %ld + %ld ms", (long)duration, swatch.Time() - (long)duration);
                    break;
                }

                long now = swatch.Time();

                if (!didAbortSlew && now > duration + GRACE_PERIOD_MS && m_abortSlewWhenGuidingStuck)
                {
                    Debug.AddLine("scope still moving after %ld + %ld ms, try aborting slew", (long)duration, now - (long)duration);
                    AbortSlew(&scope);
                    didAbortSlew = true;
                    continue;
                }

                if (now > duration + TIMEOUT_MS)
                {
                    timeoutExceeded = true;
                    break;
                }
            }

            if (timeoutExceeded && IsGuiding(&scope))
            {
                throw ERROR_INFO("timeout exceeded waiting for guiding pulse to complete");
            }
        }
    }
    catch (const wxString& msg)
    {
        POSSIBLY_UNUSED(msg);

        if (result == MOVE_OK)
        {
            result = MOVE_ERROR;

            if (!WorkerThread::InterruptRequested())
            {
                pFrame->Alert(_("PulseGuide command to mount has failed - guiding is likely to be ineffective."));
            }
        }
    }

    if (result == MOVE_STOP_GUIDING)
    {
        if (pConfig->Global.GetBoolean(SlewWarningEnabledKey(), true))
        {
            pFrame->Alert(_("Guiding stopped: the scope started slewing."), 
                _("Don't show\nthis again"), SuppressSlewAlert, 0);
        }
    }

    return result;
}
Пример #16
0
bool Camera_WDMClass::SelectDeviceAndMode()
{
    bool error = false;
    CVVidCapture *vidCap = 0;
    bool inited = false;
    bool connected = false;

    try
    {
        vidCap = CVPlatform::GetPlatform()->AcquireVideoCapture();

        // Init the library
        if (CVFAILED(vidCap->Init()))
        {
            wxMessageBox(_T("Error initializing WDM services"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("CVFAILED(VidCap->Init())");
        }
        inited = true;

        // Enumerate devices
        int nDevices;
        if (CVFAILED(vidCap->GetNumDevices(nDevices)))
        {
            wxMessageBox(_T("Error detecting WDM devices"), _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("CVFAILED(m_pVidCap->GetNumDevices(nDevices))");
        }

        int deviceNumber;

        if (nDevices == 0)
        {
            deviceNumber = 0;
        }
        else
        {
            wxArrayString devices;

            for (int i = 0; i < nDevices; i++)
            {
                CVVidCapture::VIDCAP_DEVICE devInfo;
                if (CVSUCCESS(vidCap->GetDeviceInfo(i, devInfo)))
                {
                    devices.Add(wxString::Format("%d: %s", i, devInfo.DeviceString));
                }
                else
                {
                    devices.Add(wxString::Format("%d: Not available"),i);
                }
            }

            deviceNumber = wxGetSingleChoiceIndex(_("Select WDM camera"), _("Camera choice"), devices);

            if (deviceNumber == -1)
            {
                throw ERROR_INFO("deviceNumber == -1");
            }
        }

        // Connect to camera
        if (!CVSUCCESS(vidCap->Connect(deviceNumber)))
        {
            wxMessageBox(wxString::Format("Error connecting to WDM device #%d", deviceNumber), _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("Error connecting to WDM device");
        }
        connected = true;

        int numModes = 0;
        vidCap->GetNumSupportedModes(numModes);

        wxArrayString modeNames;

        for (int curmode = 0; curmode < numModes; curmode++)
        {
            CVVidCapture::VIDCAP_MODE modeInfo;
            if (CVSUCCESS(vidCap->GetModeInfo(curmode, modeInfo)))
            {
                modeNames.Add(wxString::Format("%dx%d (%s)", modeInfo.XRes, modeInfo.YRes,
                    vidCap->GetFormatModeName(modeInfo.InputFormat)));
            }
        }

        // Let user choose mode
        int deviceMode = wxGetSingleChoiceIndex(_("Select camera mode"), _("Camera mode"), modeNames);

        if (deviceMode == -1)
        {
            // canceled
            throw ERROR_INFO("user did not choose a mode");
        }

        m_deviceNumber = deviceNumber;
        m_deviceMode = deviceMode;

        pConfig->Profile.SetInt("/camera/WDM/deviceNumber", m_deviceNumber);
        pConfig->Profile.SetInt("/camera/WDM/deviceMode", m_deviceMode);
    }
    catch (const wxString& msg)
    {
        POSSIBLY_UNUSED(msg);
        error = true;
    }

    if (vidCap)
    {
        if (connected)
            vidCap->Disconnect();
        if (inited)
            vidCap->Uninit();
        CVPlatform::GetPlatform()->Release(vidCap);
    }

    return error;
}
Пример #17
0
BOOL InsertDlls(HANDLE hProcess)
{
    int ret;
    BOOL bret;
    int i;
    char* pFullName=NULL,*pPartName=NULL;
    LPCSTR rlpDlls[2];
    i = 0;
    while(1)
    {
        assert(pFullName == NULL && pPartName == NULL);
        ret = GetDllNames(i,&pFullName,&pPartName);
        if(ret < 0)
        {
            assert(pFullName == NULL && pPartName == NULL);
            ERROR_INFO("Get [%d] name error(%d)\n",i,ret);
            ret = -ret;
            goto fail;
        }
        else if(ret == 0)
        {
            break;
        }

        rlpDlls[0] = pFullName;
        rlpDlls[1] = pPartName;
        DEBUG_INFO("update (%s:%s)\n",pFullName,pPartName);

        bret = UpdateImports(hProcess,rlpDlls,2);
        if(!bret)
        {
            ret = LAST_ERROR_CODE();
            ERROR_INFO("Import Dll(%s:%s) error(%d)\n",pFullName,pPartName,ret);
        }

        free(pFullName);
        free(pPartName);
        pFullName = NULL;
        pPartName = NULL;
        i ++;

    }
    if(pFullName)
    {
        free(pFullName);
    }
    pFullName = NULL;
    if(pPartName)
    {
        free(pPartName);
    }
    pPartName = NULL;

    return TRUE;
fail:
    if(pFullName)
    {
        free(pFullName);
    }
    pFullName = NULL;
    if(pPartName)
    {
        free(pPartName);
    }
    pPartName = NULL;
    SetLastError(ret);
    return FALSE;
}
Пример #18
0
bool Camera_WDMClass::Connect(const wxString& camId)
{
    bool bError = false;

    try
    {
        m_deviceNumber = pConfig->Profile.GetInt("/camera/WDM/deviceNumber", -1);
        m_deviceMode = pConfig->Profile.GetInt("/camera/WDM/deviceMode", -1);

        if (m_deviceNumber == -1 || m_deviceMode == -1)
            if (SelectDeviceAndMode())
                throw ERROR_INFO("SelectDeviceAndMode failed");

        // Setup VidCap library
        m_pVidCap = CVPlatform::GetPlatform()->AcquireVideoCapture();

        // Init the library
        if (CVFAILED(m_pVidCap->Init()))
        {
            wxMessageBox(_T("Error initializing WDM services"),_("Error"),wxOK | wxICON_ERROR);
            throw ERROR_INFO("CVFAILED(VidCap->Init())");
        }

        // Connect to camera
        if (CVSUCCESS(m_pVidCap->Connect(m_deviceNumber)))
        {
            int devNameLen = 0;

            // find the length of the name
            m_pVidCap->GetDeviceName(NULL, devNameLen);
            ++devNameLen;

            // now get the name
            char *devName = new char[devNameLen];
            m_pVidCap->GetDeviceName(devName, devNameLen);

            Name = wxString::Format("%s", devName);

            delete[] devName;
        }
        else
        {
            wxMessageBox(wxString::Format("Error connecting to WDM device #%d", m_deviceNumber), _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("Error connecting to WDM device");
        }

        if (CVFAILED(m_pVidCap->SetMode(m_deviceMode)))
        {
            wxMessageBox(wxString::Format("Error activating video mode %d", m_deviceMode), _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("setmode() failed");
        }

        // get the x and y size
        CVVidCapture::VIDCAP_MODE modeInfo;
        if (CVFAILED(m_pVidCap->GetCurrentMode(modeInfo)))
        {
            wxMessageBox(wxString::Format("Error probing video mode %d", m_deviceMode),_("Error"),wxOK | wxICON_ERROR);
            throw ERROR_INFO("GetCurrentMode() failed");
        }

        FullSize = wxSize(modeInfo.XRes, modeInfo.YRes);

        // Start the stream
        m_captureMode = NOT_CAPTURING; // Make sure we don't start saving yet

        if (CVFAILED(m_pVidCap->StartImageCap(CVImage::CVIMAGE_GREY, CaptureCallback, this)))
        {
            wxMessageBox(_T("Failed to start image capture!"),_("Error"),wxOK | wxICON_ERROR);
            throw ERROR_INFO("StartImageCap() failed");
        }

        pFrame->StatusMsg(wxString::Format("%d x %d mode activated", modeInfo.XRes, modeInfo.YRes));

        Connected = true;
    }
    catch (const wxString& msg)
    {
        POSSIBLY_UNUSED(msg);
        bError = true;

        if (m_pVidCap)
        {
            m_pVidCap->Uninit();
            CVPlatform::GetPlatform()->Release(m_pVidCap);

            m_pVidCap = NULL;
        }
    }

    return bError;
}
Пример #19
0
/*
 * OnExposeComplete is the dispatch routine that is called when an image has been taken
 * by the background thread.
 *
 * It:
 * - causes the image to be redrawn by calling pGuider->UpateImageDisplay()
 * - calls the routine to update the guider state (which may do nothing)
 * - calls any other appropriate state update routine depending upon the current state
 * - updates button state based on appropriate state variables
 * - schedules another exposure if CaptureActive is stil true
 *
 */
void MyFrame::OnExposeComplete(usImage *pNewFrame, bool err)
{
    try
    {
        Debug.Write("OnExposeComplete: enter\n");

        m_exposurePending = false;

        if (pGuider->GetPauseType() == PAUSE_FULL)
        {
            delete pNewFrame;
            Debug.Write("guider is paused, ignoring frame, not scheduling exposure\n");
            return;
        }

        if (err)
        {
            Debug.Write("OnExposeComplete: Capture Error reported\n");

            delete pNewFrame;

            StopCapturing();
            if (pGuider->IsCalibratingOrGuiding())
            {
                pGuider->StopGuiding();
                pGuider->UpdateImageDisplay();
            }
            pGuider->Reset(false);
            CaptureActive = m_continueCapturing;
            UpdateButtonsStatus();
            PhdController::AbortController("Error reported capturing image");
            StatusMsg(_("Stopped."));

            // some camera drivers disconnect the camera on error
            if (!pCamera->Connected)
                m_statusbar->UpdateStates();

            throw ERROR_INFO("Error reported capturing image");
        }
        ++m_frameCounter;

        if (m_rawImageMode && !m_rawImageModeWarningDone)
        {
            WarnRawImageMode();
            m_rawImageModeWarningDone = true;
        }

        // check for dark frame compatibility in case the frame size changed (binning changed)
        if (pCamera->DarkFrameSize() != m_prevDarkFrameSize)
        {
            CheckDarkFrameGeometry();
        }

        pGuider->UpdateGuideState(pNewFrame, !m_continueCapturing);
        pNewFrame = NULL; // the guider owns it now

        PhdController::UpdateControllerState();

        Debug.Write(wxString::Format("OnExposeComplete: CaptureActive=%d m_continueCapturing=%d\n",
            CaptureActive, m_continueCapturing));

        CaptureActive = m_continueCapturing;

        if (CaptureActive)
        {
            ScheduleExposure();
        }
        else
        {
            FinishStop();
        }
    }
    catch (const wxString& Msg)
    {
        POSSIBLY_UNUSED(Msg);
        UpdateButtonsStatus();
    }
}
Пример #20
0
std::vector<contr_t> slater_fit(double zeta, int am, int nf, bool verbose, int method) {
  sto_params_t par;
  par.zeta=zeta;
  par.l=am;
  par.Nf=nf;
  par.method=method;

  int maxiter=1000;

  // Degrees of freedom
  int dof;
  if(par.method==0 && nf>=2)
    dof=2;
  else
    // Full optimization
    par.method=2;

  if(par.method==1 && nf>=4)
    dof=4;
  else
    // Full optimization
    par.method=2;

  // Full optimization
  if(par.method==2)
    dof=par.Nf;

  gsl_multimin_function_fdf minfunc;
  minfunc.n=dof;
  minfunc.f=eval_difference;
  minfunc.df=eval_difference_df;
  minfunc.fdf=eval_difference_fdf;
  minfunc.params=(void *) &par;

  gsl_multimin_fdfminimizer *min;
  // Allocate minimizer
  //  min=gsl_multimin_fdfminimizer_alloc(gsl_multimin_fdfminimizer_vector_bfgs2,dof);
  min=gsl_multimin_fdfminimizer_alloc(gsl_multimin_fdfminimizer_conjugate_pr,dof);

  gsl_vector *x;
  x=gsl_vector_alloc(dof);

  // Initialize vector
  gsl_vector_set_all(x,0.0);

  // Set starting point
  switch(par.method) {
    
  case(2):
    // Legendre - same as for even tempered
  case(1):
    // Well tempered - same initialization as for even-tempered
  case(0):
    // Even tempered, set alpha=1.0 and beta=2.0
    gsl_vector_set(x,0,1.0);
    if(dof>1)
      gsl_vector_set(x,1,2.0);
    break;
  
    /*
  case(2):
    // Free minimization, set exponents to i
    for(int i=0;i<nf;i++)
      gsl_vector_set(x,i,i);
    break;
    */

  default:
    ERROR_INFO();
    throw std::runtime_error("Unknown Slater fitting method.\n");
  }
  
  // Set minimizer
  gsl_multimin_fdfminimizer_set(min, &minfunc, x, 0.01, 1e-4);

  // Iterate
  int iter=0;
  int iterdelta=0;
  int status;
  double cost=0;

  if(verbose) printf("Iteration\tDelta\n");
  do {
    iter++;
    iterdelta++;

    // Simplex
    status = gsl_multimin_fdfminimizer_iterate(min);
    if (status) {
      //      printf("Encountered GSL error \"%s\"\n",gsl_strerror(status));
      break;
    }

    // Are we converged?
    status = gsl_multimin_test_gradient (min->gradient, 1e-12);
    if (verbose && status == GSL_SUCCESS)
      {
        printf ("converged to minimum at\n");
      }

    if(min->f!=cost) {
      if(verbose) printf("%i\t%e\t%e\t%e\n",iter,min->f,min->f-cost,gsl_blas_dnrm2(min->gradient));
      cost=min->f;
      iterdelta=0;
    }

  } while (status == GSL_CONTINUE && iterdelta < maxiter);

  // Get best exponents and coefficients
  std::vector<double> optexp=get_exps(min->x,&par);
  arma::vec optc=solve_coefficients(optexp,par.zeta,par.l);

  // Free memory
  gsl_vector_free(x);
  gsl_multimin_fdfminimizer_free(min);

  // Return
  std::vector<contr_t> ret(nf);
  for(int i=0;i<nf;i++) {
    ret[i].z=optexp[i];
    ret[i].c=optc[i];
  }

  return ret;
}
Пример #21
0
UINT CPageUpdate::UpdateThread(LPVOID pParam)
{
    int i;
    unsigned int len;   //bin file lenght
    int result;
    CPageUpdate *pPageUpdate = (CPageUpdate *)pParam;
    CString  filePath;

    pPageUpdate->m_bUpdateThreadRun = true;

    INFO("正准备软件升级...\r\n");

    //>>>>>>>>S1:COM handle
    //判断串口是否打开
    if(false == g_pSerialProtocol->isSerialOpen())//串口已经打开,则进行关闭操作
    {
        INFO("错误:请先打开串口\r\n");
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }

    //>>>>>>>>S2:File handle
    pPageUpdate->m_filePath.GetWindowText(filePath);
    if (pPageUpdate->SaveFiletoRAM(&len, filePath) < 0)
    {
        INFO("错误:文件拷贝至内存失败\r\n");
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }
    else
    {
        INFO("提示:文件长度 = %d  字节\r\n", len);
    }

    //>>>>>>>>S3:Send Update Tag, Target ready to download.
    i = 5;
    INFO("(1/5)等待目标板确认包...");
    while(--i)
    {
        if (pPageUpdate->SendResetAndUpdateTag()) break;
    }
    pPageUpdate->DisplayOKorError(i);
    if (i == 0)
    {
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }

    //>>>>>>>>S4:Send UPDATE_SOL
    i = 5;
    INFO("(2/5)等待文件长度确认包...");
    while(--i)
    {
        result = pPageUpdate->SendUpdateStartOfLenght(len);
        if (0 != result) break;
    }
    if (-1 == result)
    {
        INFO("Error(文件大小超出Flash范围)\r\n");
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }
    pPageUpdate->DisplayOKorError(i);
    if (i == 0)
    {
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }

    INFO("(3/5)正在传送数据:\r\n");
    do 
    {
        result = pPageUpdate->SendUpdateStartOfData(len);
    } while(result > 0);

    INFO("\r\n(3/5)正在传送数据结果:");
    if (0 == result)
    {
        pPageUpdate->DisplayOKorError(1);
    }
    else 
    {
        pPageUpdate->DisplayOKorError(0);
        if (-1 == result)
        {
            ERROR_INFO("目标板异常终止");
        }
        else if (-2 == result)
        {
            ERROR_INFO("等待响应超时!");
        }
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }

    //>>>>>>>>S6:Send UPDATE_EOT
    i = 5;
    INFO("(4/5)等待文件结束确认包...");
    while(--i)
    {
        if (pPageUpdate->SendUpdateEndOfTransmit()) break;
    }
    pPageUpdate->DisplayOKorError(i);
    if (i == 0)
    {
        pPageUpdate->m_bUpdateThreadRun = false;
        return 0;
    }

    INFO("(5/5)等待烧写进Flash:");
    for (i = 0; i < 1000; i++)
    {  
        result = pPageUpdate->WaitUpdateWrite2FlashDone();
        if (0 == result) 
        {
            INFO("OK.\r\n");
            break;
        }
        else if (-1 == result)
        {
            INFO("Error.\r\n");
            break;
        }
        INFO(".");
        if (i % 50 == 0)
        {
            INFO("\r\n");
        }
    }
    if (1000 == i)
    {
        ERROR_INFO("超时\r\n");
    }
    pPageUpdate->m_bUpdateThreadRun = false;
    return 0;
}
Пример #22
0
std::vector<double> calcYlm_coeff(int l, int mval) {
  // Form list of cartesian coefficients

  // Size of returned array
  const int N=(l+1)*(l+2)/2;

  // Returned array
  std::vector<double> ret;
  ret.reserve(N);
  ret.resize(N);

  int m=abs(mval);

  // Compute prefactor
  double prefac=sqrt((2*l+1)/(4.0*M_PI))*pow(2.0,-l);
  if(m!=0)
    prefac*=sqrt(fact(l-m)*2.0/fact(l+m));

  // Calculate bar Pi contribution
  for(int k=0;k<=(l-m)/2;k++) {
    // Compute factor in front
    double ffac=pow(-1.0,k)*choose(l,k)*choose(2*(l-k),l);
    if(m!=0)
      ffac*=fact(l-2*k)/fact(l-2*k-m);
    ffac*=prefac;

    // Distribute exponents
    for(int a=0;a<=k;a++) {
      double afac=choose(k,a)*ffac;

      for(int b=0;b<=a;b++) {
	double fac=choose(a,b)*afac;

	// Current exponents
	int zexp=2*b-2*k+l-m;
	int yexp=2*(a-b);
	int xexp=2*(k-a);

	// Now, add in the contribution of A or B.
	if(mval>0) {
	  // Contribution from A_m
	  for(int p=0;p<=m;p++) {

	    // Check if term contributes
	    int cosfac;
	    switch((m-p)%4) {
	    case(0):
	      // cos(0) = 1
	      cosfac=1;
	      break;
	    case(1):
	      // cos(pi/2) = 0
	      cosfac=0;
	      break;
	    case(2):
	      // cos(pi) = -1
	      cosfac=-1;
	      break;
	    case(3):
	      // cos(3*pi/2) = 0
	      cosfac=0;
	      break;
	    default:
	      ERROR_INFO();
	      throw std::domain_error("An error occurred in Am(x,y).\n");
	    }

	    if(cosfac!=0) {
	      // OK, term contributes, store result.
	      //	      printf("Contribution to %i %i %i\n",xexp+p,yexp+absm-p,zexp);
	      ret[getind(xexp+p,yexp+m-p,zexp)]+=cosfac*choose(m,p)*fac;
	    }
	  }
	} else if(m==0) {
	  // No A_m or B_m term.
	  ret[getind(xexp,yexp,zexp)]+=fac;

	} else {
	  // B_m contributes
	  for(int p=0;p<=m;p++) {

	    // Check contribution of current term
	    int sinfac;
	    switch((m-p)%4) {
	    case(0):
	      // sin(0) = 0
	      sinfac=0;
	      break;
	    case(1):
	      // sin(pi/2) = 1
	      sinfac=1;
	      break;
	    case(2):
	      // sin(pi) = 0
	      sinfac=0;
	      break;
	    case(3):
	      // sin(3*pi/2) = -1
	      sinfac=-1;
	      break;
	    default:
	      ERROR_INFO();
	      throw std::domain_error("An error occurred in Bm(x,y).\n");
	    }

	    if(sinfac!=0) {
	      // OK, contribution is made
	      //	      printf("Contribution to %i %i %i\n",xexp+p,yexp+absm-p,zexp);
	      ret[getind(xexp+p,yexp+m-p,zexp)]+=sinfac*choose(m,p)*fac;
	    }
	  } // End loop over p
	} // End B_m clause
      } // End loop over b
    } // End loop over a
  } // End loop over k

#ifdef DEBUG
  printf("Y %i %i\n",l,mval);
  for(int ii=0; ii<=l; ii++) {
    int nx=l - ii;
    for(int jj=0; jj<=ii; jj++) {
      int ny=ii - jj;
      int nz=jj;

      if(ret[getind(nx,ny,nz)]!=0)
	printf("%e\t%i\t%i\t%i\n",ret[getind(nx,ny,nz)],nx,ny,nz);
    }
  }
  printf("\n");
#endif

  return ret;
}
Пример #23
0
bool WorkerThread::HandleExpose(MyFrame::EXPOSE_REQUEST *req)
{
    bool bError = false;

    try
    {
        if (WorkerThread::MilliSleep(m_pFrame->GetTimeLapse(), INT_ANY))
        {
            throw ERROR_INFO("Time lapse interrupted");
        }

        if (pCamera->HasNonGuiCapture())
        {
            Debug.Write(wxString::Format("Handling exposure in thread, d=%d o=%x r=(%d,%d,%d,%d)\n", req->exposureDuration,
                                         req->options, req->subframe.x, req->subframe.y, req->subframe.width, req->subframe.height));

            if (GuideCamera::Capture(pCamera, req->exposureDuration, *req->pImage, req->options, req->subframe))
            {
                throw ERROR_INFO("Capture failed");
            }
        }
        else
        {
            Debug.Write(wxString::Format("Handling exposure in myFrame, d=%d o=%x r=(%d,%d,%d,%d)\n", req->exposureDuration,
                                         req->options, req->subframe.x, req->subframe.y, req->subframe.width, req->subframe.height));

            wxSemaphore semaphore;
            req->pSemaphore = &semaphore;

            wxCommandEvent evt(REQUEST_EXPOSURE_EVENT, GetId());
            evt.SetClientData(req);
            wxQueueEvent(m_pFrame, evt.Clone());

            // wait for the request to complete
            req->pSemaphore->Wait();

            bError = req->error;
            req->pSemaphore = NULL;
        }

        Debug.AddLine("Exposure complete");

        if (!bError)
        {
            switch (m_pFrame->GetNoiseReductionMethod())
            {
                case NR_NONE:
                    break;
                case NR_2x2MEAN:
                    QuickLRecon(*req->pImage);
                    break;
                case NR_3x3MEDIAN:
                    Median3(*req->pImage);
                    break;
            }

            req->pImage->CalcStats();
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return  bError;
}
Пример #24
0
int HandleClient(int sock,int rport,char* msg)
{
    int msglen = strlen(msg)+1;
    int ret;
    fd_set rset;
    struct sockaddr_in saddr;
    socklen_t socklen=0;
    int times=0;
    struct timeval tmval;
    int buflen=2000;
    unsigned char buffer[buflen];
    char addrbuf[INET_ADDRSTRLEN];

    while(st_RunLoop)
    {
        memset(&saddr,0,sizeof(saddr));
        saddr.sin_family = AF_INET;
        saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
        saddr.sin_port = htons(rport);

        socklen = sizeof(saddr);
        ret = sendto(sock,msg,msglen,MSG_DONTWAIT,(struct sockaddr*)&saddr,socklen);
        if(ret < 0)
        {
            ret = LAST_ERROR_CODE();
            ERROR_INFO("could not send[%d] msg (%s) error(%d)\n",times,msg,ret);
            goto out;
        }

        FD_ZERO(&rset);
        FD_SET(sock,&rset);
        tmval.tv_sec = 2;
        tmval.tv_usec = 0;
        errno = 0;
        ret = select(sock+1,&rset,NULL,NULL,&tmval);
        if(ret <=0)
        {
            ERROR_INFO("Get errno %d\n",errno);
            ret = LAST_ERROR_CODE();
            ERROR_INFO("could make rset ok (%d)\n",ret);
            goto out;
        }

        if(!FD_ISSET(sock,&rset))
        {
            ret = -EFAULT;
            ERROR_INFO("not set rset\n");
            goto out;
        }

        socklen = sizeof(saddr);
        memset(&saddr,0,socklen);
        ret = recvfrom(sock,buffer,buflen,MSG_DONTWAIT,(struct sockaddr*)&saddr,&socklen);
        if(ret < 0)
        {
            ret = LAST_ERROR_CODE();
            ERROR_INFO("could not receive %d\n",ret);
            goto out;
        }

        DEBUG_INFO("[%d]receive from %s:%d (%s)\n",times,inet_ntop(AF_INET,&(saddr.sin_addr),addrbuf, INET_ADDRSTRLEN),ntohs(saddr.sin_port),buffer);
        times ++;
        sleep(1);
    }

    ret = 0;
out:
    return ret;
}
Пример #25
0
int SdkServerBuffer::__GetStreamDataEndState(client_buffer_t * pCBuffer,struct iovec * pIoVec,int & iovlen,int & begin)
{
    int ret;
    unsigned int i,curidx;
    stream_pack_t *pCBlock=NULL;
    int findidx;

    /*now it is end state*/
    SDK_ASSERT(pCBuffer->m_State == cb_end_state);
    SDK_ASSERT(pCBuffer->m_CurIdx == 0);
    SDK_ASSERT(pCBuffer->m_pBlock == NULL);

    if (this->m_Started == 0)
    {
        return 0;
    }

    /*now we should first to test whether it has something to get*/
    if (this->m_PackSize == 0)
    {
        return 0;
    }

    /*it is filled all the packs ,so we should start scan from the startidx and end to end idx*/
    findidx = -1;
    for (i=0; i<this->m_PackSize; i++)
    {
        curidx = this->m_StartIdx + i;
        curidx %= this->m_PackSize;
        pCBlock = this->m_pPacks[curidx];
        SDK_ASSERT(pCBlock);
        if (pCBlock->m_Type == I_FRAME_TYPE)
        {
            findidx = curidx;
            break;
        }

    }



    if (findidx < 0)
    {
        SDK_ASSERT(pCBlock);
        pCBuffer->m_CurIdx = curidx;
        pCBuffer->m_SourceIdx = pCBlock->m_Idx;
        this->__ChangeClientBufferState(pCBuffer,cb_i_frame_state,__FILE__,__LINE__);
        return 0;
    }
    if (iovlen < 3)
    {
        ERROR_INFO("\n");
        return -ENOSPC;
    }

    pCBuffer->m_CurIdx = findidx;
    pCBuffer->m_SourceIdx = pCBlock->m_Idx;
    ret = this->__FormatMessageHeader(pCBuffer,pCBlock);
    if (ret < 0)
    {
        return ret;
    }
    /*we have copied data ,so change to sequence state*/
    this->__ChangeClientBufferState(pCBuffer,cb_seq_state,__FILE__,__LINE__);

    ret = this->__SetIov(pCBuffer,pIoVec,iovlen,begin);
    if (ret < 0)
    {
        ERROR_INFO("\n");
        return ret;
    }
    return 1;
}
Пример #26
0
 void check_posdef() const {
     if (info != 0)
         throw NumericalError(ERROR_INFO("Matrix is not positive definite"), info);
 }
Пример #27
0
bool GuiderOneStar::AutoSelect(void)
{
    bool bError = false;

    usImage *pImage = CurrentImage();

    try
    {
        if (!pImage || !pImage->ImageData)
        {
            throw ERROR_INFO("No Current Image");
        }

        // If mount is not calibrated, we need to chose a star a bit farther
        // from the egde to allow for the motion of the star during
        // calibration
        //
        int edgeAllowance = 0;
        if (pMount && pMount->IsConnected() && !pMount->IsCalibrated())
            edgeAllowance = wxMax(edgeAllowance, pMount->CalibrationTotDistance());
        if (pSecondaryMount && pSecondaryMount->IsConnected() && !pSecondaryMount->IsCalibrated())
            edgeAllowance = wxMax(edgeAllowance, pSecondaryMount->CalibrationTotDistance());

        Star newStar;
        if (!newStar.AutoFind(*pImage, edgeAllowance, m_searchRegion))
        {
            throw ERROR_INFO("Unable to AutoFind");
        }

        m_massChecker->Reset();

        if (!m_star.Find(pImage, m_searchRegion, newStar.X, newStar.Y, Star::FIND_CENTROID))
        {
            throw ERROR_INFO("Unable to find");
        }

        if (SetLockPosition(m_star))
        {
            throw ERROR_INFO("Unable to set Lock Position");
        }

        if (GetState() == STATE_SELECTING)
        {
            // immediately advance the state machine now, rather than waiting for
            // the next exposure to complete. Socket server clients are going to
            // try to start guiding after selecting the star, but guiding will fail
            // to start if state is still STATE_SELECTING
            Debug.AddLine("AutoSelect: state = %d, call UpdateGuideState", GetState());
            UpdateGuideState(NULL, false);
        }

        UpdateImageDisplay();
        pFrame->pProfile->UpdateData(pImage, m_star.X, m_star.Y);
    }
    catch (wxString Msg)
    {
        if (pImage && pImage->ImageData)
        {
            SaveAutoSelectFailedImg(pImage);
        }

        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}
Пример #28
0
bool ScopeASCOM::Connect(void)
{
    bool bError = false;

    try
    {
        Debug.AddLine("Connecting");

        if (IsConnected())
        {
            wxMessageBox("Scope already connected",_("Error"));
            throw ERROR_INFO("ASCOM Scope: Connected - Already Connected");
        }

        DispatchObj pScopeDriver;

        if (!Create(pScopeDriver))
        {
            wxMessageBox(_T("Could not establish instance of ") + m_choice, _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not establish ASCOM Scope instance");
        }

        // --- get the dispatch IDs we need ...

        // ... get the dispatch ID for the Connected property ...
        if (!pScopeDriver.GetDispatchId(&dispid_connected, L"Connected"))
        {
            wxMessageBox(_T("ASCOM driver problem -- cannot connect"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the Connected property");
        }

        // ... get the dispatch ID for the "IsPulseGuiding" property ....
        m_canCheckPulseGuiding = true;
        if (!pScopeDriver.GetDispatchId(&dispid_ispulseguiding, L"IsPulseGuiding"))
        {
            m_canCheckPulseGuiding = false;
            Debug.AddLine("cannot get dispid_ispulseguiding");
            // don't fail if we can't get the status on this - can live without it as it's really a safety net for us
        }

        // ... get the dispatch ID for the "Slewing" property ....
        if (!pScopeDriver.GetDispatchId(&dispid_isslewing, L"Slewing"))
        {
            wxMessageBox(_T("ASCOM driver missing the Slewing property"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the Slewing property");
        }

        // ... get the dispatch ID for the "PulseGuide" property ....
        if (!pScopeDriver.GetDispatchId(&dispid_pulseguide, L"PulseGuide"))
        {
            wxMessageBox(_T("ASCOM driver missing the PulseGuide property"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the PulseGuide property");
        }

        // ... get the dispatch ID for the "Declination" property ....
        m_canGetCoordinates = true;
        if (!pScopeDriver.GetDispatchId(&dispid_declination, L"Declination"))
        {
            m_canGetCoordinates = false;
            Debug.AddLine("cannot get dispid_declination");
        }
        else if (!pScopeDriver.GetDispatchId(&dispid_rightascension, L"RightAscension"))
        {
            Debug.AddLine("cannot get dispid_rightascension");
            m_canGetCoordinates = false;
        }
        else if (!pScopeDriver.GetDispatchId(&dispid_siderealtime, L"SiderealTime"))
        {
            Debug.AddLine("cannot get dispid_siderealtime");
            m_canGetCoordinates = false;
        }

        if (!pScopeDriver.GetDispatchId(&dispid_sitelatitude, L"SiteLatitude"))
        {
            Debug.AddLine("cannot get dispid_sitelatitude");
        }
        if (!pScopeDriver.GetDispatchId(&dispid_sitelongitude, L"SiteLongitude"))
        {
            Debug.AddLine("cannot get dispid_sitelongitude");
        }

        m_canSlew = true;
        if (!pScopeDriver.GetDispatchId(&dispid_slewtocoordinates, L"SlewToCoordinates"))
        {
            m_canSlew = false;
            Debug.AddLine("cannot get dispid_slewtocoordinates");
        }

        // ... get the dispatch IDs for the two guide rate properties - if we can't get them, no sweat, doesn't matter for actual guiding
        // Used for things like calibration sanity checking, backlash clearing, etc.
        m_canGetGuideRates = true;         // Likely case, required for any ASCOM driver at V2 or later
        if (!pScopeDriver.GetDispatchId(&dispid_decguiderate, L"GuideRateDeclination"))
        {
            Debug.AddLine("cannot get dispid_decguiderate");
            m_canGetGuideRates = false;
            // don't throw if we can't get this one
        }
        else if (!pScopeDriver.GetDispatchId(&dispid_raguiderate, L"GuideRateRightAscension"))
        {
            Debug.AddLine("cannot get dispid_raguiderate");
            m_canGetGuideRates = false;
            // don't throw if we can't get this one
        }

        if (!pScopeDriver.GetDispatchId(&dispid_sideofpier, L"SideOfPier"))
        {
            Debug.AddLine("cannot get dispid_sideofpier");
            dispid_sideofpier = DISPID_UNKNOWN;
        }

        if (!pScopeDriver.GetDispatchId(&dispid_abortslew, L"AbortSlew"))
        {
            Debug.AddLine("cannot get dispid_abortslew");
            dispid_abortslew = DISPID_UNKNOWN;
        }

        struct ConnectInBg : public ConnectMountInBg
        {
            ScopeASCOM *sa;
            ConnectInBg(ScopeASCOM *sa_) : sa(sa_) { }
            bool Entry()
            {
                GITObjRef scope(sa->m_gitEntry);
                // ... set the Connected property to true....
                if (!scope.PutProp(sa->dispid_connected, true))
                {
                    SetErrorMsg(ExcepMsg(scope.Excep()));
                    return true;
                }
                return false;
            }
        };
        ConnectInBg bg(this);

        // set the Connected property to true in a background thread
        if (bg.Run())
        {
            wxMessageBox(_T("ASCOM driver problem during connection: ") + bg.GetErrorMsg(),
                _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not set Connected property to true");
        }

        // get the scope name
        Variant vRes;
        if (!pScopeDriver.GetProp(&vRes, L"Name"))
        {
            wxMessageBox(_T("ASCOM driver problem getting Name property"), _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the scope name: " + ExcepMsg(pScopeDriver.Excep()));
        }

        m_Name = vRes.bstrVal;

        Debug.AddLine("Scope reports its name as " + m_Name);

        m_abortSlewWhenGuidingStuck = false;

        if (m_Name == _T("Gemini Telescope .NET"))
        {
            // Gemini2 firmware (2013 Oct 13 version, perhaps others) has been found to contain a
            // bug where a pulse guide command can fail to complete, with the Guiding property
            // returning true forever. The firmware developer suggests that PHD2 should issue an
            // AbortSlew when this condition is detected.
            Debug.AddLine("ASCOM scope: enabling stuck guide pulse workaround");
            m_abortSlewWhenGuidingStuck = true;
        }

        // see if we can pulse guide
        m_canPulseGuide = true;
        if (!pScopeDriver.GetProp(&vRes, L"CanPulseGuide") || vRes.boolVal != VARIANT_TRUE)
        {
            Debug.AddLine("Connecting to ASCOM scope that does not support PulseGuide");
            m_canPulseGuide = false;
        }

        // see if scope can slew
        m_canSlewAsync = false;
        if (m_canSlew)
        {
            if (!pScopeDriver.GetProp(&vRes, L"CanSlew"))
            {
                Debug.AddLine("ASCOM scope got error invoking CanSlew: " + ExcepMsg(pScopeDriver.Excep()));
                m_canSlew = false;
            }
            else if (vRes.boolVal != VARIANT_TRUE)
            {
                Debug.AddLine("ASCOM scope reports CanSlew = false");
                m_canSlew = false;
            }

            m_canSlewAsync = pScopeDriver.GetProp(&vRes, L"CanSlewAsync") && vRes.boolVal == VARIANT_TRUE;
            Debug.AddLine(wxString::Format("ASCOM scope CanSlewAsync is %s", m_canSlewAsync ? "true" : "false"));
        }

        pFrame->SetStatusText(Name()+_(" connected"));
        Scope::Connect();

        Debug.AddLine("Connect success");
    }
    catch (const wxString& Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}
Пример #29
0
void GuiderOneStar::OnLClick(wxMouseEvent &mevent)
{
    try
    {
        if (mevent.GetModifiers() == wxMOD_CONTROL)
        {
            double const scaleFactor = ScaleFactor();
            wxRealPoint pt((double) mevent.m_x / scaleFactor,
                           (double) mevent.m_y / scaleFactor);
            ToggleBookmark(pt);
            m_showBookmarks = true;
            pFrame->bookmarks_menu->Check(MENU_BOOKMARKS_SHOW, GetBookmarksShown());
            Refresh();
            Update();
            return;
        }

        if (GetState() > STATE_SELECTED)
        {
            mevent.Skip();
            throw THROW_INFO("Skipping event because state > STATE_SELECTED");
        }

        if (mevent.GetModifiers() == wxMOD_SHIFT)
        {
            // Deselect guide star
            InvalidateCurrentPosition(true);
        }
        else
        {
            if ((mevent.m_x <= m_searchRegion) || (mevent.m_x + m_searchRegion >= XWinSize) || (mevent.m_y <= m_searchRegion) || (mevent.m_y + m_searchRegion >= YWinSize))
            {
                mevent.Skip();
                throw THROW_INFO("Skipping event because click outside of search region");
            }

            usImage *pImage = CurrentImage();

            if (pImage->NPixels == 0)
            {
                mevent.Skip();
                throw ERROR_INFO("Skipping event m_pCurrentImage->NPixels == 0");
            }

            double scaleFactor = ScaleFactor();
            double StarX = (double) mevent.m_x / scaleFactor;
            double StarY = (double) mevent.m_y / scaleFactor;

            SetCurrentPosition(pImage, PHD_Point(StarX, StarY));

            if (!m_star.IsValid())
            {
                pFrame->SetStatusText(wxString::Format(_("No star found")));
            }
            else
            {
                SetLockPosition(m_star);
                pFrame->SetStatusText(wxString::Format(_("Selected star at (%.1f, %.1f)"), m_star.X, m_star.Y), 1);
                pFrame->SetStatusText(wxString::Format(_T("m=%.0f SNR=%.1f"), m_star.Mass, m_star.SNR));
                EvtServer.NotifyStarSelected(CurrentPosition());
                SetState(STATE_SELECTED);
                pFrame->UpdateButtonsStatus();
                pFrame->pProfile->UpdateData(pImage, m_star.X, m_star.Y);
            }

            Refresh();
            Update();
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
    }
}
Пример #30
0
int GetModuleInsertedProcess(const char * pPartDll,unsigned int **ppPids,int * pPidsSize)
{
    char *pCmpDllName=NULL;
    std::vector<unsigned int> procvecs;
#ifdef _UNICODE
    int cmpdllnamesize=0;
#endif
    HANDLE hProcSnap=INVALID_HANDLE_VALUE,hModSnap=INVALID_HANDLE_VALUE;
    int ret;
    BOOL bret;
    int numget=0;
    unsigned int *pRetPids = *ppPids;
    unsigned int *pTmpPids=NULL;
    int pidretsize=*pPidsSize;
    PROCESSENTRY32 pentry;
    unsigned int i;

    if(pidretsize == 0 && pRetPids)
    {
        ret = ERROR_INVALID_PARAMETER;
        goto fail;
    }

    hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if(hProcSnap == INVALID_HANDLE_VALUE)
    {
        ret = LAST_ERROR_CODE();
        ERROR_INFO("could not create module32 error(%d)\n",ret);
        goto fail;
    }

    pentry.dwSize = sizeof(pentry);

    bret = Process32First(hProcSnap,&pentry);
    if(!bret)
    {
        ret = LAST_ERROR_CODE();
        ERROR_INFO("could not get process entry error(%d)\n",ret);
        goto fail;
    }


    DEBUG_INFO("Process ID: %d\n", pentry.th32ProcessID);
    ret = __CheckProcessIdModuleInserted(pentry.th32ProcessID,pPartDll);
    if(ret > 0)
    {
        procvecs.push_back(pentry.th32ProcessID);
        numget ++;
    }

    while(Process32Next(hProcSnap,&pentry))
    {
        DEBUG_INFO("Process ID: %d\n",pentry.th32ProcessID);
        ret = __CheckProcessIdModuleInserted(pentry.th32ProcessID,pPartDll);
        if(ret > 0)
        {
            procvecs.push_back(pentry.th32ProcessID);
            numget ++;
        }
    }

    if(procvecs.size() > 0)
    {
        if(pidretsize <(int) procvecs.size())
        {
			pidretsize = procvecs.size();
            pRetPids = (unsigned int*)calloc(sizeof(*pRetPids),pidretsize);
            if(pRetPids == NULL)
            {
                ret = LAST_ERROR_CODE();
                goto fail;
            }
        }
        for(i=0; i<procvecs.size(); i++)
        {
			pRetPids[i] = procvecs[i];
        }
    }

    if(hProcSnap != INVALID_HANDLE_VALUE)
    {
        CloseHandle(hProcSnap);
    }
    hProcSnap = INVALID_HANDLE_VALUE;

    if(pRetPids != *ppPids && *ppPids)
    {
        free(*ppPids);
    }
    *ppPids = pRetPids;
    *pPidsSize = pidretsize;

    procvecs.clear();
    return numget;

fail:
    if(hProcSnap != INVALID_HANDLE_VALUE)
    {
        CloseHandle(hProcSnap);
    }
    hProcSnap = INVALID_HANDLE_VALUE;

    if(pRetPids != *ppPids && pRetPids)
    {
        free(pRetPids);
    }
    pRetPids = NULL;

    procvecs.clear();

    SetLastError(ret);
    return -ret;

}