示例#1
0
void RemotePicberry::run()
{
    char response[6];
    int percentage = 0;
    bool multi_round = false;
    int round = 0;

    if(mode == SRV_WRITE) {
        multi_round = true;
        sendFile();
        sendFinishFileSend();
    }

    while(working) {
        if(picberry_socket.bytesAvailable() ||
                picberry_socket.waitForReadyRead()) {
            picberry_socket.readLine(response, 5);
            qDebug() << response;
            if(QString(response) == "@FIN") {
                if(!multi_round) {
                    working=false;
                }
                else if(multi_round && round==1) {
                    sendFinishFirstRun();
                }
                else if(multi_round && round==2) {
                    working = false;
                }
                round++;
            }
            else if(QString(response) == "@ERR") {
                sendError();
                working = false;
                return;
            }
            else {
                sscanf(response, "@%d", &percentage);
                sendProgress(percentage);
            }
        }
    }
    if(mode == SRV_READ) {
        sendStartFileReceive();
        receiveFile();
    }
    picberry_socket.readAll();
    sendFinish();
}
示例#2
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->ui->b_disconnect->setEnabled(false);
    this->ui->b_send->setEnabled(false);
    this->ui->b_sendlast->setEnabled(false);
    this->ui->b_receive->setEnabled(false);
    this->ui->b_verify->setEnabled(false);
    this->stlink = new stlinkv2();
    this->devices = new DeviceList(this);
    this->tfThread = new transferThread();

    if (this->devices->IsLoaded()) {

        this->ui->gb_top->setEnabled(true);
        this->log(QString::number(this->devices->getDevicesCount())+" Device descriptions loaded.");
        QObject::connect(this->ui->b_quit,SIGNAL(clicked()),this,SLOT(Quit()));
        QObject::connect(this->ui->b_qt,SIGNAL(clicked()),qApp,SLOT(aboutQt()));
        QObject::connect(this->ui->b_connect, SIGNAL(clicked()), this, SLOT(Connect()));
        QObject::connect(this->ui->b_disconnect, SIGNAL(clicked()), this, SLOT(Disconnect()));
        QObject::connect(this->ui->b_send, SIGNAL(clicked()), this, SLOT(Send()));
        QObject::connect(this->ui->b_sendlast, SIGNAL(clicked()), this, SLOT(SendLast()));
        QObject::connect(this->ui->b_receive, SIGNAL(clicked()), this, SLOT(Receive()));
        QObject::connect(this->ui->b_verify, SIGNAL(clicked()), this, SLOT(Verify()));
        QObject::connect(this->ui->b_halt, SIGNAL(clicked()), this, SLOT(HaltMCU()));
        QObject::connect(this->ui->b_run, SIGNAL(clicked()), this, SLOT(RunMCU()));
        QObject::connect(this->ui->b_reset, SIGNAL(clicked()), this, SLOT(ResetMCU()));
        QObject::connect(this->ui->r_jtag, SIGNAL(clicked()), this, SLOT(setModeJTAG()));
        QObject::connect(this->ui->r_swd, SIGNAL(clicked()), this, SLOT(setModeSWD()));
        QObject::connect(this->ui->b_hardReset, SIGNAL(clicked()), this, SLOT(HardReset()));

        // Thread
        QObject::connect(this->tfThread, SIGNAL(sendProgress(quint32)), this, SLOT(updateProgress(quint32)));
        QObject::connect(this->tfThread, SIGNAL(sendStatus(QString)), this, SLOT(updateStatus(QString)));
        QObject::connect(this->tfThread, SIGNAL(sendLoaderStatus(QString)), this, SLOT(updateLoaderStatus(QString)));
        QObject::connect(this->stlink, SIGNAL(bufferPct(quint32)), this, SLOT(updateLoaderPct(quint32)));
        QObject::connect(this->tfThread, SIGNAL(sendLock(bool)), this, SLOT(lockUI(bool)));
        QObject::connect(this->ui->b_stop, SIGNAL(clicked()), this->tfThread, SLOT(halt()));
        QObject::connect(this->tfThread, SIGNAL(sendLog(QString)), this, SLOT(log(QString)));

        // Help
        QObject::connect(this->ui->b_help, SIGNAL(clicked()), this, SLOT(showHelp()));
    }
示例#3
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    mUi(new Ui::MainWindow)
{
    mUi->setupUi(this);
    mUi->b_disconnect->setEnabled(false);
    this->lockUI(true);
    mStlink = new stlinkv2();
    mDevices = new DeviceInfoList(this);
    mTfThread = new transferThread();

    mLastAction = ACTION_NONE;

    if (mDevices->IsLoaded()) {

        this->log(QString::number(mDevices->getDevicesCount())+" Device descriptions loaded.");
        QObject::connect(mUi->b_quit,SIGNAL(clicked()),this,SLOT(quit()));
        QObject::connect(mUi->b_connect, SIGNAL(clicked()), this, SLOT(connect()));
        QObject::connect(mUi->b_disconnect, SIGNAL(clicked()), this, SLOT(disconnect()));
        QObject::connect(mUi->b_send, SIGNAL(clicked()), this, SLOT(send()));
        QObject::connect(mUi->b_receive, SIGNAL(clicked()), this, SLOT(receive()));
        QObject::connect(mUi->b_verify, SIGNAL(clicked()), this, SLOT(verify()));
        QObject::connect(mUi->b_repeat, SIGNAL(clicked()), this, SLOT(repeat()));
        QObject::connect(mUi->b_halt, SIGNAL(clicked()), this, SLOT(haltMCU()));
        QObject::connect(mUi->b_run, SIGNAL(clicked()), this, SLOT(runMCU()));
        QObject::connect(mUi->b_reset, SIGNAL(clicked()), this, SLOT(resetMCU()));
        QObject::connect(mUi->r_jtag, SIGNAL(clicked()), this, SLOT(setModeJTAG()));
        QObject::connect(mUi->r_swd, SIGNAL(clicked()), this, SLOT(setModeSWD()));
        QObject::connect(mUi->b_hardReset, SIGNAL(clicked()), this, SLOT(hardReset()));

        // Thread
        QObject::connect(mTfThread, SIGNAL(sendProgress(quint32)), this, SLOT(updateProgress(quint32)));
        QObject::connect(mTfThread, SIGNAL(sendStatus(QString)), this, SLOT(updateStatus(QString)));
        QObject::connect(mTfThread, SIGNAL(sendLoaderStatus(QString)), this, SLOT(updateLoaderStatus(QString)));
        QObject::connect(mStlink, SIGNAL(bufferPct(quint32)), this, SLOT(updateLoaderPct(quint32)));
        QObject::connect(mTfThread, SIGNAL(sendLock(bool)), this, SLOT(lockUI(bool)));
        QObject::connect(mUi->b_stop, SIGNAL(clicked()), mTfThread, SLOT(halt()));
        QObject::connect(mTfThread, SIGNAL(sendLog(QString)), this, SLOT(log(QString)));

        // Help
        QObject::connect(mUi->b_help, SIGNAL(clicked()), this, SLOT(showHelp()));

        // Usb stuff
        QObject::connect(mStlink, SIGNAL(deviceDetected(QString)), this, SLOT(log(QString)));
    }
示例#4
0
void recethread::onSendProgress(qint64 iSize, double iProgress)
{
    qDebug() << "recethread sendprogress";
    emit sendProgress(iSize,iProgress);
}
示例#5
0
void *updatethreadproc(void*)
{
	char tempDir[PATH_MAX] = "";		/* Flawfinder: ignore */
	FSRef tempDirRef;
	char temp[PATH_MAX] = "";	/* Flawfinder: ignore */
	// *NOTE: This buffer length is used in a scanf() below.
	char deviceNode[1024] = "";	/* Flawfinder: ignore */
	LLFILE *downloadFile = NULL;
	OSStatus err;
	ProcessSerialNumber psn;
	char target[PATH_MAX] = "";		/* Flawfinder: ignore */
	FSRef targetRef;
	FSRef targetParentRef;
	FSVolumeRefNum targetVol;
	FSRef trashFolderRef;
	Boolean replacingTarget = false;

	memset(&tempDirRef, 0, sizeof(tempDirRef));
	memset(&targetRef, 0, sizeof(targetRef));
	memset(&targetParentRef, 0, sizeof(targetParentRef));
	
	try
	{
		// Attempt to get a reference to the Second Life application bundle containing this updater.
		// Any failures during this process will cause us to default to updating /Applications/Second Life.app
		{
			FSRef myBundle;

			err = GetCurrentProcess(&psn);
			if(err == noErr)
			{
				err = GetProcessBundleLocation(&psn, &myBundle);
			}

			if(err == noErr)
			{
				// Sanity check:  Make sure the name of the item referenced by targetRef is "Second Life.app".
				FSRefMakePath(&myBundle, (UInt8*)target, sizeof(target));
				
				llinfos << "Updater bundle location: " << target << llendl;
			}
			
			// Our bundle should be in Second Life.app/Contents/Resources/AutoUpdater.app
			// so we need to go up 3 levels to get the path to the main application bundle.
			if(err == noErr)
			{
				err = FSGetCatalogInfo(&myBundle, kFSCatInfoNone, NULL, NULL, NULL, &targetRef);
			}
			if(err == noErr)
			{
				err = FSGetCatalogInfo(&targetRef, kFSCatInfoNone, NULL, NULL, NULL, &targetRef);
			}
			if(err == noErr)
			{
				err = FSGetCatalogInfo(&targetRef, kFSCatInfoNone, NULL, NULL, NULL, &targetRef);
			}
			
			// And once more to get the parent of the target
			if(err == noErr)
			{
				err = FSGetCatalogInfo(&targetRef, kFSCatInfoNone, NULL, NULL, NULL, &targetParentRef);
			}
			
			if(err == noErr)
			{
				FSRefMakePath(&targetRef, (UInt8*)target, sizeof(target));
				llinfos << "Path to target: " << target << llendl;
			}
			
			// Sanity check: make sure the target is a bundle with the right identifier
			if(err == noErr)
			{
				// Assume the worst...
				err = -1;

				if(isFSRefViewerBundle(&targetRef))
				{
					// This is the bundle we're looking for.
					err = noErr;
					replacingTarget = true;
				}
			}
			
			// Make sure the target's parent directory is writable.
			if(err == noErr)
			{
				if(!isDirWritable(targetParentRef))
				{
					// Parent directory isn't writable.
					llinfos << "Target parent directory not writable." << llendl;
					err = -1;
					replacingTarget = false;
				}
			}

			if(err != noErr)
			{
				Boolean isDirectory;
				llinfos << "Target search failed, defaulting to /Applications/" << gProductName << ".app." << llendl;
				
				// Set up the parent directory
				err = FSPathMakeRef((UInt8*)"/Applications", &targetParentRef, &isDirectory);
				if((err != noErr) || (!isDirectory))
				{
					// We're so hosed.
					llinfos << "Applications directory not found, giving up." << llendl;
					throw 0;
				}
				
				snprintf(target, sizeof(target), "/Applications/%s.app", gProductName);		

				memset(&targetRef, 0, sizeof(targetRef));
				err = FSPathMakeRef((UInt8*)target, &targetRef, NULL);
				if(err == fnfErr)
				{
					// This is fine, just means we're not replacing anything.
					err = noErr;
					replacingTarget = false;
				}
				else
				{
					replacingTarget = true;
				}

				// Make sure the target's parent directory is writable.
				if(err == noErr)
				{
					if(!isDirWritable(targetParentRef))
					{
						// Parent directory isn't writable.
						llinfos << "Target parent directory not writable." << llendl;
						err = -1;
						replacingTarget = false;
					}
				}

			}
			
			// If we haven't fixed all problems by this point, just bail.
			if(err != noErr)
			{
				llinfos << "Unable to pick a target, giving up." << llendl;
				throw 0;
			}
		}
		
		// Find the volID of the volume the target resides on
		{
			FSCatalogInfo info;
			err = FSGetCatalogInfo(
				&targetParentRef,
				kFSCatInfoVolume,
				&info,
				NULL, 
				NULL,  
				NULL);
				
			if(err != noErr)
				throw 0;
			
			targetVol = info.volume;
		}

		// Find the temporary items and trash folders on that volume.
		err = FSFindFolder(
			targetVol,
			kTrashFolderType,
			true,
			&trashFolderRef);

		if(err != noErr)
			throw 0;

#if 0 // *HACK for DEV-11935 see below for details.

		FSRef tempFolderRef;

		err = FSFindFolder(
			targetVol,
			kTemporaryFolderType,
			true,
			&tempFolderRef);
		
		if(err != noErr)
			throw 0;
		
		err = FSRefMakePath(&tempFolderRef, (UInt8*)temp, sizeof(temp));

		if(err != noErr)
			throw 0;

#else		

		// *HACK for DEV-11935  the above kTemporaryFolderType query was giving
		// back results with path names that seem to be too long to be used as
		// mount points.  I suspect this incompatibility was introduced in the
		// Leopard 10.5.2 update, but I have not verified this. 
		char const HARDCODED_TMP[] = "/tmp";
		strncpy(temp, HARDCODED_TMP, sizeof(HARDCODED_TMP));

#endif // 0 *HACK for DEV-11935
		
		// Skip downloading the file if the dmg was passed on the command line.
		std::string dmgName;
		if(gDmgFile != NULL) {
			dmgName = basename((char *)gDmgFile);
			char * dmgDir = dirname((char *)gDmgFile);
			strncpy(tempDir, dmgDir, sizeof(tempDir));
			err = FSPathMakeRef((UInt8*)tempDir, &tempDirRef, NULL);
			if(err != noErr) throw 0;
			chdir(tempDir);
			goto begin_install;
		} else {
			// Continue on to download file.
			dmgName = "SecondLife.dmg";
		}

		
		strncat(temp, "/SecondLifeUpdate_XXXXXX", (sizeof(temp) - strlen(temp)) - 1);
		if(mkdtemp(temp) == NULL)
		{
			throw 0;
		}
		
		strncpy(tempDir, temp, sizeof(tempDir));
		temp[sizeof(tempDir) - 1] = '\0';
		
		llinfos << "tempDir is " << tempDir << llendl;

		err = FSPathMakeRef((UInt8*)tempDir, &tempDirRef, NULL);

		if(err != noErr)
			throw 0;
				
		chdir(tempDir);
		
		snprintf(temp, sizeof(temp), "SecondLife.dmg");		
		
		downloadFile = LLFile::fopen(temp, "wb");		/* Flawfinder: ignore */
		if(downloadFile == NULL)
		{
			throw 0;
		}

		{
			CURL *curl = curl_easy_init();

			curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	//		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curl_download_callback);
			curl_easy_setopt(curl, CURLOPT_FILE, downloadFile);
			curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
			curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, &curl_progress_callback_func);
			curl_easy_setopt(curl, CURLOPT_URL,	gUpdateURL);
			curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
			
			sendProgress(0, 1, CFSTR("Downloading..."));
			
			CURLcode result = curl_easy_perform(curl);
			
			curl_easy_cleanup(curl);
			
			if(gCancelled)
			{
				llinfos << "User cancel, bailing out."<< llendl;
				throw 0;
			}
			
			if(result != CURLE_OK)
			{
				llinfos << "Error " << result << " while downloading disk image."<< llendl;
				throw 0;
			}
			
			fclose(downloadFile);
			downloadFile = NULL;
		}

	begin_install:
		sendProgress(0, 0, CFSTR("Mounting image..."));
		LLFile::mkdir("mnt", 0700);
		
		// NOTE: we could add -private at the end of this command line to keep the image from showing up in the Finder,
		//		but if our cleanup fails, this makes it much harder for the user to unmount the image.
		std::string mountOutput;
		boost::format cmdFormat("hdiutil attach %s -mountpoint mnt");
		cmdFormat % dmgName;
		FILE* mounter = popen(cmdFormat.str().c_str(), "r");		/* Flawfinder: ignore */
		
		if(mounter == NULL)
		{
			llinfos << "Failed to mount disk image, exiting."<< llendl;
			throw 0;
		}
		
		// We need to scan the output from hdiutil to find the device node it uses to attach the disk image.
		// If we don't have this information, we can't detach it later.
		while(mounter != NULL)
		{
			size_t len = fread(temp, 1, sizeof(temp)-1, mounter);
			temp[len] = 0;
			mountOutput.append(temp);
			if(len < sizeof(temp)-1)
			{
				// End of file or error.
				int result = pclose(mounter);
				if(result != 0)
				{
					// NOTE: We used to abort here, but pclose() started returning 
					// -1, possibly when the size of the DMG passed a certain point 
					llinfos << "Unexpected result closing pipe: " << result << llendl; 
				}
				mounter = NULL;
			}
		}
		
		if(!mountOutput.empty())
		{
			const char *s = mountOutput.c_str();
			const char *prefix = "/dev/";
			char *sub = strstr(s, prefix);
			
			if(sub != NULL)
			{
				sub += strlen(prefix);	/* Flawfinder: ignore */
				sscanf(sub, "%1023s", deviceNode);	/* Flawfinder: ignore */
			}
		}
		
		if(deviceNode[0] != 0)
		{
			llinfos << "Disk image attached on /dev/" << deviceNode << llendl;
		}
		else
		{
			llinfos << "Disk image device node not found!" << llendl;
			throw 0; 
		}
		
		// Get an FSRef to the new application on the disk image
		FSRef sourceRef;
		FSRef mountRef;
		snprintf(temp, sizeof(temp), "%s/mnt", tempDir);		

		llinfos << "Disk image mount point is: " << temp << llendl;

		err = FSPathMakeRef((UInt8 *)temp, &mountRef, NULL);
		if(err != noErr)
		{
			llinfos << "Couldn't make FSRef to disk image mount point." << llendl;
			throw 0;
		}

		sendProgress(0, 0, CFSTR("Searching for the app bundle..."));
		err = findAppBundleOnDiskImage(&mountRef, &sourceRef);
		if(err != noErr)
		{
			llinfos << "Couldn't find application bundle on mounted disk image." << llendl;
			throw 0;
		}
		else
		{
			llinfos << "found the bundle." << llendl;
		}

		sendProgress(0, 0, CFSTR("Preparing to copy files..."));
		
		FSRef asideRef;
		char aside[MAX_PATH];		/* Flawfinder: ignore */
		
		// this will hold the name of the destination target
		CFStringRef appNameRef;

		if(replacingTarget)
		{
			// Get the name of the target we're replacing
			HFSUniStr255 appNameUniStr;
			err = FSGetCatalogInfo(&targetRef, 0, NULL, &appNameUniStr, NULL, NULL);
			if(err != noErr)
				throw 0;
			appNameRef = FSCreateStringFromHFSUniStr(NULL, &appNameUniStr);
			
			// Move aside old version (into work directory)
			err = FSMoveObject(&targetRef, &tempDirRef, &asideRef);
			if(err != noErr)
			{
				llwarns << "failed to move aside old version (error code " << 
					err << ")" << llendl;
				throw 0;
			}

			// Grab the path for later use.
			err = FSRefMakePath(&asideRef, (UInt8*)aside, sizeof(aside));
		}
		else
		{
			// Construct the name of the target based on the product name
			char appName[MAX_PATH];		/* Flawfinder: ignore */
			snprintf(appName, sizeof(appName), "%s.app", gProductName);		
			appNameRef = CFStringCreateWithCString(NULL, appName, kCFStringEncodingUTF8);
		}
		
		sendProgress(0, 0, CFSTR("Copying files..."));
		
		llinfos << "Starting copy..." << llendl;

		// Copy the new version from the disk image to the target location.
		err = FSCopyObjectSync(
				&sourceRef,
				&targetParentRef,
				appNameRef,
				&targetRef,
				kFSFileOperationDefaultOptions);
		
		// Grab the path for later use.
		err = FSRefMakePath(&targetRef, (UInt8*)target, sizeof(target));
		if(err != noErr)
			throw 0;

		llinfos << "Copy complete. Target = " << target << llendl;

		if(err != noErr)
		{
			// Something went wrong during the copy.  Attempt to put the old version back and bail.
			(void)FSDeleteObject(&targetRef);
			if(replacingTarget)
			{
				(void)FSMoveObject(&asideRef, &targetParentRef, NULL);
			}
			throw 0;
		}
		else
		{
			// The update has succeeded.  Clear the cache directory.

			sendProgress(0, 0, CFSTR("Clearing cache..."));
	
			llinfos << "Clearing cache..." << llendl;
			
			char mask[LL_MAX_PATH];		/* Flawfinder: ignore */
			snprintf(mask, LL_MAX_PATH, "%s*.*", gDirUtilp->getDirDelimiter().c_str());		
			gDirUtilp->deleteFilesInDir(gDirUtilp->getExpandedFilename(LL_PATH_CACHE,""),mask);
			
			llinfos << "Clear complete." << llendl;

		}
	}
	catch(...)
	{
		if(!gCancelled)
			if(gFailure == noErr)
				gFailure = -1;
	}

	// Failures from here on out are all non-fatal and not reported.
	sendProgress(0, 3, CFSTR("Cleaning up..."));

	// Close disk image file if necessary
	if(downloadFile != NULL)
	{
		llinfos << "Closing download file." << llendl;

		fclose(downloadFile);
		downloadFile = NULL;
	}

	sendProgress(1, 3);
	// Unmount image
	if(deviceNode[0] != 0)
	{
		llinfos << "Detaching disk image." << llendl;

		snprintf(temp, sizeof(temp), "hdiutil detach '%s'", deviceNode);		
		system(temp);		/* Flawfinder: ignore */
	}

	sendProgress(2, 3);

	// Move work directory to the trash
	if(tempDir[0] != 0)
	{
//		chdir("/");
//		FSDeleteObjects(tempDirRef);

		llinfos << "Moving work directory to the trash." << llendl;

		err = FSMoveObject(&tempDirRef, &trashFolderRef, NULL);
		if(err != noErr) {
			llwarns << "failed to move files to trash, (error code " <<
				err << ")" << llendl;
		}

//		snprintf(temp, sizeof(temp), "rm -rf '%s'", tempDir);
//		printf("%s\n", temp);
//		system(temp);
	}
	
	if(!gCancelled  && !gFailure && (target[0] != 0))
	{
		llinfos << "Touching application bundle." << llendl;

		snprintf(temp, sizeof(temp), "touch '%s'", target);		
		system(temp);		/* Flawfinder: ignore */

		llinfos << "Launching updated application." << llendl;

		snprintf(temp, sizeof(temp), "open '%s'", target);		
		system(temp);		/* Flawfinder: ignore */
	}

	sendDone();
	
	return(NULL);
}
void transferThread::send(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("Could not open the file.");
        return;
    }
    emit sendLock(true);
    this->m_stop = false;
    quint32 step_size = 116;
    const quint32 from = 0;
    const quint32 to = file.size();

    quint32 progress, oldprogress;
    qint32 read;
    char *buf2 = new char[step_size];

    qDebug() << "File size" << file.size();

    if (!this->m_btl->eraseFlash(file.size())) {

        emit sendStatus("Erase failed");
        emit sendLog("Erase failed");
        qDebug() << "Erase failed";
        emit sendLock(false);
        return;
    }
    else {
        emit sendStatus("Erase OK");
        emit sendLog("Erase OK");
        qDebug() << "Erase OK";
    }

    qInformal() << "Writing from" << "0x"+QString::number(from, 16) << "to" << "0x"+QString::number(to, 16);

    emit sendStatus("Transfering");
    emit sendLog("Transfering");

    progress = 0;
    for (int i=0; i<=file.size(); i+=step_size) {

        if (this->m_stop)
            break;

        if (file.atEnd()) {
            qDebug() << "End Of File";
            break;
        }

        memset(buf2, 0, step_size);
        if ((read = file.read(buf2, step_size)) <= 0)
            break;
        qDebug() << "Read" << read << "Bytes from disk";
        QByteArray buf(buf2, read);

        if (this->m_btl->writeFlash(i, &buf, step_size) < read){
            emit sendStatus("Transfer failed");
            emit sendLog("Transfer failed");
            break;
        }

        oldprogress = progress;
        progress = (i*100)/file.size();
        if (progress > oldprogress) { // Push only if number has increased
            emit sendProgress(progress);
            qInformal() << "Progress:"<< QString::number(progress)+"%";
        }

    }
    emit sendLoaderStatus("Idle");
    file.close();
    delete buf2;

    emit sendProgress(100);
    emit sendStatus("Transfer done");
    emit sendLog("Transfer done");
    qInformal() << "Transfer done";

    emit sendLock(false);
}
void transferThread::verify(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("Could not open the file.");
        return;
    }
    emit sendLock(true);
    this->m_stop = false;
    const quint32 buf_size = 512;
    const quint32 from = 0;
    const quint32 to = file.size();
    qInformal() << "Reading from" << QString::number(from, 16) << "to" << QString::number(to, 16);
    quint32 addr, progress, oldprogress;
    QByteArray data_local, data_remote;

    progress = 0;
    for (quint32 i=0; i<file.size(); i+=buf_size)
    {
        if (this->m_stop)
            break;

        usleep(50000);

        data_local = file.read(buf_size);
        qDebug() << "Read" << data_local.size() << "Bytes from disk";
        addr = i;

        if (!data_local.size()) break;
        int read_size = this->m_btl->readMem(addr, &data_remote, data_local.size());
        if (read_size < data_local.size()) {// Read same amount of data as from file.

            file.close();
            emit sendProgress(0);
            emit sendStatus("Verification Failed");
            qInformal() << "Verification Failed";
            qInformal() << "read" << read_size << "valid" << data_local.size();
            emit sendLock(false);
            return;
        }

        if (data_remote != data_local) {

            file.close();
            emit sendProgress(100);
            emit sendStatus("Verification failed at 0x"+QString::number(addr, 16));

            QString stmp, sbuf;
            for (int b=0;b<data_local.size();b++) {
                stmp.append(QString().sprintf("%02X ", (uchar)data_local.at(b)));
                sbuf.append(QString().sprintf("%02X ", (uchar)data_remote.at(b)));
            }
            qCritical() << "Verification failed at 0x"+QString::number(addr, 16) <<
                           "\r\n Expecting:" << stmp << "\r\n       Got:" << sbuf;
            emit sendLock(false);
            return;
        }
        oldprogress = progress;
        progress = (i*100)/file.size();
        if (progress > oldprogress) { // Push only if number has increased
            emit sendProgress(progress);
            qInformal() << "Progress:"<< QString::number(progress)+"%";
        }
        emit sendStatus("Verified "+QString::number(i/1024)+" kilobytes out of "+QString::number(file.size()/1024));
    }

    file.close();
    emit sendProgress(100);
    emit sendStatus("Verification OK");
    qInformal() << "Verification OK";
    emit sendLock(false);
}
//Function: Run
//Description: Runs acquisition routine in a new thread
//			   This function cannot access gui widgets so all variables are frozen when thread class instance is created
void AcqThread::run()
{
        int             error=0;
        TaskHandle	digTaskHandle=0;
        bool		done;
        int		retVal;
        int		numZSteps;
        int             iZCount;
        int		x1;
        int		x2;
        int		y1;
        int		y2;
        int		numValidXSamps;
        int		numValidYSamps;
        double		debug;

	//set to not be terminated (default)
	terminate = false;

	//scaling coeff has not been calculated for this acq yet
	bScaleCoeffCalc = false;		

	//overscan values have not yet been calculated into the fov
	scanEng->setOverscanCalculated(false);

	done = false;

        do
        {
            //if regular acq (not line scan), call generateWaveForms
            if(!bLinescan)
            {
                scanEng->initScan(true,false);
                retVal = scanEng->generateWaveForms();
                retVal = acqEng->initAcq(true,false);
            }
            else  //Line scan mode
            {
                retVal = scanEng->initScan(true,true);

                if(!NIVisionCurrContourInfo)
                {
                    emit sendMessageForPopup("Error","No data points defined\n");
                    goto Error;
                }
                if (NIVisionCurrContourInfo->type != IMAQ_LINE)
                {
                    emit sendMessageForPopup("Error","Points must be defined with line tool\n");
                    goto Error;
                }

                //grab endpoints from line contour
                x1=NIVisionCurrContourInfo->structure.line->start.x;
                y1=NIVisionCurrContourInfo->structure.line->start.y;
                x2=NIVisionCurrContourInfo->structure.line->end.x;
                y2=NIVisionCurrContourInfo->structure.line->end.y;
		
                //Update data class
                data2P->Header.setLsX1(x1);
                data2P->Header.setLsX2(x2);
                data2P->Header.setLsY1(y1);
                data2P->Header.setLsY2(y2);

                //Calc the voltages that correspond to the x1,y1,x2,y2.  These will define the line scan waveforms.
                double x1V,y1V,x2V,y2V;
                CalcXYVoltsFromPxlVal(x1, y1, x1V, y1V);
                scanEng->setROIPt1XVolts(x1V);
                scanEng->setROIPt1YVolts(y1V);
                CalcXYVoltsFromPxlVal(x2, y2, x2V, y2V);
                scanEng->setROIPt2XVolts(x2V);
                scanEng->setROIPt2YVolts(y2V);

                retVal = scanEng->generateLineScanWaveForms();
                retVal = acqEng->initAcq(true,true);
            }
		
            //_____Setup for 3D Acq if needed_____
            if (acqEng->getB3DAcq())
            {
                numZSteps = this->CalcNumZSteps();
                CalcIntensityScalingCoeff();
            }
            else
                numZSteps = 1;

            //_____DAQmx DigOut Configure Code (Sample clock for Aout and Ain)____________________________________________
            DAQmxErrChk (DAQmxCreateTask("SampleClockTask",&digTaskHandle));
            DAQmxErrChk (DAQmxCreateCOPulseChanFreq (digTaskHandle, "/Dev1/ctr1", "SampleClock", DAQmx_Val_Hz, DAQmx_Val_Low,
                            0.1, scanEng->getSamp_Rate(), 0.5));
            if (bLinescan)
                DAQmxErrChk (DAQmxCfgImplicitTiming(digTaskHandle,DAQmx_Val_ContSamps ,scanEng->getNumSampsPerFrame_LS()))
            else
                DAQmxErrChk (DAQmxCfgImplicitTiming(digTaskHandle,DAQmx_Val_ContSamps ,scanEng->getNumSampsPerFrame()))


            //_____config AOut task for triggered, finite samps_____
            retVal = scanEng->configDAQmxTask(true, false);

            //_____Write samples to daq board_____
            retVal = scanEng->writeDAQmxTask();

            //_____Config AIn task for triggered, finite samps_____
            retVal = acqEng->configDAQmxTask(true, false);

            pDone = 0;
		
            for (iZCount = 0; iZCount < numZSteps; iZCount++)
            {
                //Only if there are Z steps to do
                if(numZSteps>1)
                {
                    //update Z Pos
                    zStep.setDesiredZPos(acqEng->getZStartPos() + (acqEng->getZStepSize() * iZCount));
                    //if (zStep->getDesiredZPos() != acqEng->getZPos())
                    if(numZSteps!=1)
                        zStep.MoveTo(zStep.getDesiredZPos(),zStep.getCurrentStepConvFactor());

                    //Manual zPos Calculations
                    //acqEng->setZPos(acqEng->getZPos()+acqEng->getZStepSize());
                    acqEng->setZPos(zStep.getCurrentZPos());

                    emit sigZPosChange(zStep.getCurrentZPos());

                    //Update pDone for updating gui progress bar
                    pDone = ((double)iZCount)/((double)numZSteps);
                    emit sendProgress(pDone);

                    //update gui field
                    //TwoPhotonGui::doubleSpinBox_zPos->setValue(zStepEng->getCurrentZPos()); NEED IMPLEMENTATION

                    //update acqEng field
                    //acqEng->setZPos(zStep->getCurrentZPos());		NOTE: this isn't working, using manual z-pos calculations
                }

                //if Aom Voltage scaling is selected, update Aom
                if(aomCtrl->getBIntScaling())
                {
                    debug = CalcAomIntVoltage((acqEng->getZStartPos()-acqEng->getZPos()));
                    AomUpdate(debug);		//turns AOM on
                }
                else
                {
                    AomUpdate(aomCtrl->getAomOnVoltage());  //Turns on AOM (no updating for depth)
                }


                //_____Start DAQmx Read._____
                retVal = acqEng->startDAQmxTask();
                //_____Start DAQmx write._____
                retVal = scanEng->startDAQmxTask();

                //_____Start DAQmx Trig._____
                DAQmxErrChk (DAQmxStartTask(digTaskHandle))
                //_____Perform read.  Execution will pause until all samps acquired._____
                retVal = acqEng->readDAQmxTask();

                /*		Added for diagnostics.  I want to write out the acq buffer here before I flip even rows.


                */

                /*
                        NEED IMPLEMENTATION
                //_____Update Histogram._____
                retVal = ProcessDataForHistogram(appState->acqStruct);
                if (appState->acqStruct.bInput1)
                        DeleteGraphPlot (appState->panelHandle, PANEL_HIST1, -1, VAL_IMMEDIATE_DRAW);
                        PlotXY (appState->panelHandle, PANEL_HIST1, appState->binsArray, appState->histArray1, NUM_BINS,
                                VAL_SHORT_INTEGER, VAL_UNSIGNED_INTEGER, VAL_VERTICAL_BAR, VAL_SOLID_SQUARE, VAL_SOLID,
                                1, VAL_BLUE);
                if (appState->acqStruct.bInput2)
                        DeleteGraphPlot (appState->panelHandle, PANEL_HIST2, -1, VAL_DELAYED_DRAW);
                        PlotXY (appState->panelHandle, PANEL_HIST2, appState->binsArray, appState->histArray2, NUM_BINS,
                                VAL_SHORT_INTEGER, VAL_UNSIGNED_INTEGER, VAL_VERTICAL_BAR, VAL_SOLID_SQUARE, VAL_SOLID,
                                1, VAL_BLUE);
                */

                //Update image display
                retVal = ProcessDataForDisplay(bLinescan);
                if(!bLinescan)
                {
                    numValidXSamps = (int)acqEng->getnumValidXSamps();
                    numValidYSamps = (int)acqEng->getnumValidYSamps();
                    if (!bLifetimeFov)
                    {
                        //Had to move imaq.. calls out of this thread.  Wasn't updating when called from this thread.
                        // using signal to notify other thread that new image data are in the image pointers.
                        imaqArrayToImage(*ptrToimage1, *ptrToimageData1, (int)acqEng->getnumValidXSamps(),(int)acqEng->getnumValidYSamps());
                        imaqDisplayImage(*ptrToimage1, displayWinNum1, 1);
                        //emit this->sigUdateVisionWindows(displayWinNum1,numValidXSamps,numValidYSamps);
                    }
                }
                else
                {
                    numValidXSamps = (int)acqEng->getWidth();
                    numValidYSamps = (int)acqEng->getRepeats();
                    if (!bLifetimeFov)
                    {
                        imaqArrayToImage(*ptrToimage2, *ptrToimageData2, (int)acqEng->getWidth(),(int)acqEng->getRepeats());
                        imaqDisplayImage(*ptrToimage2, displayWinNum2, 1);
                        //emit this->sigUdateVisionWindows(displayWinNum2,numValidXSamps,numValidYSamps);
                    }
                }

                //imaqHistogram(image1,65536,0,1,NULL);

                //Update Data2P class instance before writing it to file
                updateDataPtr();

                //Save the data to file if requested
                if (acqEng->getSaveData())
                {
                    if(!bLinescan)
                    {
                            Update2PDataStruct();

                            if (acqEng->getBInput1())
                                    retVal = data2P->WriteTheData(1,acqEng);
                            if (acqEng->getBInput2())
                                    retVal = data2P->WriteTheData(2,acqEng);
                    }
                    else	//If linescan, need to record correct lineLength/lineRate
                    {
                            retVal =scanEng->calcLineLengthStruct(x1,y1,x2,y2);
                            retVal =scanEng->calcLineRate();
                            Update2PDataStruct();
                            data2P->Header.setLineRate(data2P->Header.getLinescanRate());	//ensure linerate recorded is that of linescan

                            if (acqEng->getBInput1())
                                retVal = data2P->WriteTheData(1,acqEng);
                            if (acqEng->getBInput2())
                                retVal = data2P->WriteTheData(2,acqEng);
                    }

                }

                DAQmxStopTask(digTaskHandle);
                retVal = acqEng->stopDAQmxTask();
                retVal = scanEng->stopDAQmxTask();
                //retVal = scanEng->clearDAQmxTask();
                //scanEng->setScanTaskHandle(0);

                if(terminate)
                        goto Kill;

                //turn off Aom until ready to image again (set to 0 volts)
                AomUpdate(0.0);
                aomCtrl->setAomOn(false);
            }
Kill:
            retVal = scanEng->stopDAQmxTask();
            //Cleanup ...
            //	retVal = AcqEngineStopDAQmxTask(acqStruct);
            DAQmxClearTask(scanEng->getScanTaskHandle());
            scanEng->setScanTaskHandle(0);
            //	retVal = ScanEngineStopDAQmxTask(scanStruct);
            DAQmxClearTask(acqEng->getAcqTaskHandle());
            acqEng->setAcqTaskHandle(0);
            DAQmxClearTask(digTaskHandle);

            scanEng->releaseMemory();
            acqEng->releaseMemory();

        }while(bContinuous && (!terminate));

	/*
	SetCtrlVal(appState->panelHandle,PANEL_ledRunning,0);	NEED IMPLEMENTATION
	SetCtrlVal(appState->panelHandle,PANEL_ledAcquiring,0);
	SetCtrlVal(appState->panelHandle,PANEL_cbx3DAcq,0);
	SetCtrlVal(appState->panelHandle,PANEL_cbxSave,0);
	
	
	*/

	//Disable Aom (set to 0 volts)--------------------
	AomUpdate(0.0);
	aomCtrl->setAomOn(false);

	bScaleCoeffCalc = false;

	pDone = 0;

	emit acqFinished();

	quit();
	return;

Error:
	//return;

	if( DAQmxFailed(error) )
            DAQmxGetExtendedErrorInfo(errBuff,2048);

            //DAQmxDisconnectTerms ("/Dev1/PFI12", "/Dev1/PFI1");

	if( digTaskHandle!=0 ) 
	{
            // _____DAQmx Stop Code
            DAQmxStopTask(digTaskHandle);
            DAQmxClearTask(digTaskHandle);
	}
	if( scanEng->getScanTaskHandle() != 0 ) 
	{
            DAQmxStopTask(scanEng->getScanTaskHandle());
            DAQmxClearTask(scanEng->getScanTaskHandle());
            scanEng->setScanTaskHandle(0);

            //SetCtrlVal(appState->panelHandle,PANEL_ledRunning,0);		NEED IMPLEMENTATION
            //SetCtrlVal(appState->panelHandle,PANEL_ledAcquiring,0);
	}
	if( acqEng->getAcqTaskHandle() != 0 ) 
	{
            DAQmxStopTask(acqEng->getAcqTaskHandle());
            DAQmxClearTask(acqEng->getAcqTaskHandle());
            acqEng->setAcqTaskHandle(0);
	}
	
	if (scanEng->getMemIsAllocated())
            scanEng->releaseMemory();
	
	if (acqEng->getMemIsAllocated())
            acqEng->releaseMemory();


//	if( DAQmxFailed(error) )
//		QMessageBox::about(this,"DAQmx Error",errBuff);
        emit sendMessageForPopup("DAQmx Error",errBuff);
	emit acqFinished();
	return;

}
示例#9
0
void DeviceConnector::processMessages()
{
    if ( messageQueue.isEmpty() )
        return;
    MessageRecord *msg = messageQueue.first();
    switch ( msg->state )
    {
        case NoMessage:
            connect();
            if ( !mSocket )
            {
                qDebug() << "No socket, retrying...";
                QTimer::singleShot( 500, this, SLOT(processMessages()) );
                return;
            }
            if ( loginDone )
                msg->state = Message;
            else
                msg->state = WaitForWelcome;
            QTimer::singleShot( 0, this, SLOT(processMessages()) );
            emit sendProgress( 10 );
            break;

        case WaitForWelcome:
            qDebug() << "wait for welcome";
            emit sendProgress( 20 );
            break;

        case User:
            // send user name
            // TODO this name comes in the 220 message!
            sendMessage( QString("USER %1").arg(loginName) );
            msg->state = WaitForUserOk;
            emit sendProgress( 30 );
            break;

        case WaitForUserOk:
            qDebug() << "wait for user ok";
            emit sendProgress( 40 );
            break;

        case Password:
            // send password
            sendMessage( "PASS Qtopia::deviceupdater" );
            msg->state = WaitForPasswordOk;
            emit sendProgress( 50 );
            break;

        case WaitForPasswordOk:
            qDebug() << "wait for user ok";
            emit sendProgress( 60 );
            break;

        case Message:
            // Now send the message
            emit sendProgress( 70 );
            {
                QTextStream os( mSocket );
                os << "CALLB " << msg->channel << " " << msg->message << " "
                   << msg->data.toBase64() << endl;
            }
            qDebug() << "send:" << msg->channel << "...";
            msg->state = WaitForMessageOk;
            break;

        case WaitForMessageOk:
            qDebug() << "wait for message ok";
            emit sendProgress( 80 );
            break;

        case MessageDelivered:
        case MessageFailed:
            emit sendProgress( 100 );
            if ( msg->state == MessageDelivered )
                emit deviceConnMessage( tr( "Device update message delivered" ));
            else
                emit deviceConnMessage( tr( "Device update message failed" ));
            if ( messageQueue.isEmpty() )
                teardown();
            Q_ASSERT( msg == messageQueue.first() );
            messageQueue.removeFirst();
            delete msg;
            break;

        default:
            qFatal( "Unknown state!" );
    }
}