Esempio n. 1
0
/** \brief Create network communicator instance.
 *
 *  Creates and sets up a network communicator instance.
 *  The instance connects over network interface 'iface' to server at 'addr' on port 'port'.
 *
 *  \param addr Server address (IP or domain name).
 *  \param port Server port to connect to.
 *  \param iface Network interface to use for connection.
 *  \param commID Identifier of this network communicator.
 *  \param devID Id of this obu.
 *  \return Shared pointer to freshly created network communicator instance..
 */
shared_ptr<NetworkCommunicator> Initializer::createComm(string addr, string port, string iface, uint8_t commID, uint8_t devID) {

    shared_ptr<NetworkCommunicator> result;

    // Create and initialize communicator.
    shared_ptr<NW_SocketInterface> interface(new NW_SocketInterface(
            AF_UNSPEC,
            SOCK_STREAM,
            addr,
            port,
            iface));

    uint16_t status = 0;

    // Initialize server connection.
    if ((status=interface->initialize())) {
        printErr(INIT_ERR_DEV_SETUP, "server");
        return result;
    }

    // Processor instances for building up data frames.
    shared_ptr<ProcDataFrame> frame(new ProcDataFrame);
    shared_ptr<ProcPayload> payload(new ProcPayload(devID));

    // Network communicator instance.
    result = shared_ptr<NetworkCommunicator>(new NetworkCommunicator(commID));

    // Append Frame processors
    if (!result->appenProc(payload) ||
            !result->appenProc(frame) ||
            !result->appenProc(interface)) {
        printErr(INIT_ERR_DEV_APPEND, "frame processor");
        return shared_ptr<NetworkCommunicator>();
    }

    return result;
}
TEST_F(ElfInterfaceArmTest, FindEntry_multiple_entries_odd) {
  ElfInterfaceArm interface(&memory_);
  interface.set_start_offset(0x1000);
  interface.set_total_entries(5);
  memory_.SetData32(0x1000, 0x5000);
  memory_.SetData32(0x1008, 0x6000);
  memory_.SetData32(0x1010, 0x7000);
  memory_.SetData32(0x1018, 0x8000);
  memory_.SetData32(0x1020, 0x9000);

  uint64_t entry_offset;
  ASSERT_TRUE(interface.FindEntry(0x8100, &entry_offset));
  ASSERT_EQ(0x1010U, entry_offset);

  // To guarantee that we are using the cache on the second run,
  // set the memory to a different value.
  memory_.SetData32(0x1000, 0x15000);
  memory_.SetData32(0x1008, 0x16000);
  memory_.SetData32(0x1010, 0x17000);
  memory_.SetData32(0x1018, 0x18000);
  memory_.SetData32(0x1020, 0x19000);
  ASSERT_TRUE(interface.FindEntry(0x8100, &entry_offset));
  ASSERT_EQ(0x1010U, entry_offset);
}
Esempio n. 3
0
  void operator ()()
  {
    boost::scoped_ptr<pcl::Grabber> interface(new pcl::OpenNIGrabber);
    boost::signals2::connection c;

    if(format == ecto::pcl::FORMAT_XYZRGB){
      boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> point_cloud_cb =
          boost::bind(&SimpleKinectGrabber::cloud_xyzrgb_cb_, this, _1);
      c = interface->registerCallback(point_cloud_cb);
    }else if(format == ecto::pcl::FORMAT_XYZ){
      boost::function<void(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)> point_cloud_cb =
          boost::bind(&SimpleKinectGrabber::cloud_xyz_cb_, this, _1);
      c = interface->registerCallback(point_cloud_cb);
    }

    interface->start();

    runmutex_.lock(); // blocks until the destructor unlocks it
    runmutex_.unlock(); // unlock it again... why does this stop a crash?

    c.disconnect();

    interface->stop();
  }
Esempio n. 4
0
void KDynamicJobTracker::registerJob(KJob *job)
{
    if (!d->kuiserverTracker) {
        d->kuiserverTracker = new KUiServerJobTracker();
    }

    d->trackers[job].kuiserverTracker = d->kuiserverTracker;
    d->trackers[job].kuiserverTracker->registerJob(job);

    QDBusInterface interface("org.kde.kuiserver", "/JobViewServer", "",
    QDBusConnection::sessionBus(), this);
    QDBusReply<bool> reply = interface.call("requiresJobTracker");

    if (reply.isValid() && reply.value()) {
        //create a widget tracker in addition to kuiservertracker.
        if (!d->widgetTracker) {
            d->widgetTracker = new KWidgetJobTracker();
        }
        d->trackers[job].widgetTracker = d->widgetTracker;
        d->trackers[job].widgetTracker->registerJob(job);
    }

    Q_ASSERT(d->trackers[job].kuiserverTracker || d->trackers[job].widgetTracker);
}
Esempio n. 5
0
int Interpreteur(char *Buffer, struct Global *g )
{ 
  /* definir arg1 , arg2 */
  char arg0[80],arg1[80],arg2[80],arg3[80],arg4[80] ;
  int rc ;
  bzero(arg1,sizeof(arg1));
  bzero(arg2,sizeof(arg2));
  bzero(arg3,sizeof(arg3));

  fprintf(stderr,"La chaine a interpreter est %s \n",Buffer ) ;
  sscanf(Buffer,"%s %s %s\n",arg1,arg2,arg3 ) ;
  if (strcmp(arg1,"interface")==0)
      rc = interface(arg2,g) ;
  else if (strcmp(arg1,"connexion")==0)
        rc = connexion(Buffer,g) ;
  else if ( !strcmp(arg1,"ip"))
        rc = ip(Buffer,g) ;
  else if (!strcmp(arg1,"show"))
	rc = show ( Buffer,g ) ;
  else if ( ( strcmp(arg1,"load") == 0 ) && ( strcmp(arg2,"filter") == 0 ))
       {
        LectureTableFiltrage(arg3,g->TableFiltrage,&(g->NbrRegles),g->NbrLignes) ;
        return(NEAN) ;
       }
  else if ( strcmp(arg1,"help")==0)
       AfficheAide() ;
  else if ( strcmp(arg1,"exit")==0 ) 
       exit(0) ;
  else if (Blanc1013(arg1)) fprintf(stderr,"Ligne vide \n" ) ;
  else
      {
       printf("Erreur de syntaxe \n") ;
       return(0) ;
       }
  return(rc) ;
}
TEST_F(ElfInterfaceArmTest, HandleType_arm_exidx) {
  ElfInterfaceArm interface(&memory_);

  Elf32_Phdr phdr;
  interface.set_start_offset(0x1000);
  interface.set_total_entries(100);
  phdr.p_vaddr = 0x2000;
  phdr.p_memsz = 0xa00;

  // Verify that if reads fail, we don't set the values but still get true.
  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
  ASSERT_EQ(0x1000U, interface.start_offset());
  ASSERT_EQ(100U, interface.total_entries());

  // Verify that if the second read fails, we still don't set the values.
  memory_.SetData32(
      0x1000 + reinterpret_cast<uint64_t>(&phdr.p_vaddr) - reinterpret_cast<uint64_t>(&phdr),
      phdr.p_vaddr);
  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
  ASSERT_EQ(0x1000U, interface.start_offset());
  ASSERT_EQ(100U, interface.total_entries());

  // Everything is correct and present.
  memory_.SetData32(
      0x1000 + reinterpret_cast<uint64_t>(&phdr.p_memsz) - reinterpret_cast<uint64_t>(&phdr),
      phdr.p_memsz);
  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
  ASSERT_EQ(0x2000U, interface.start_offset());
  ASSERT_EQ(320U, interface.total_entries());

  // Non-zero load bias.
  interface.set_load_bias(0x1000);
  ASSERT_TRUE(interface.HandleType(0x1000, 0x70000001));
  ASSERT_EQ(0x1000U, interface.start_offset());
  ASSERT_EQ(320U, interface.total_entries());
}
Esempio n. 7
0
/*!
    Places a call to the remote method specified by \a method
    on this interface, using \a args as arguments. This function
    returns immediately after queueing the call. The reply from
    the remote function is delivered to the \a returnMethod on
    object \a receiver. If an error occurs, the \a errorMethod
    on object \a receiver is called instead.

    This function returns true if the queueing succeeds. It does
    not indicate that the executed call succeeded. If it fails,
    the \a errorMethod is called. If the queueing failed, this
    function returns false and no slot will be called.
 
    The \a returnMethod must have as its parameters the types returned
    by the function call. Optionally, it may have a QDBusMessage
    parameter as its last or only parameter.  The \a errorMethod must
    have a QDBusError as its only parameter.

    \since 4.3
    \sa QDBusError, QDBusMessage
 */
bool QDBusAbstractInterface::callWithCallback(const QString &method,
                                              const QList<QVariant> &args,
                                              QObject *receiver,
                                              const char *returnMethod,
                                              const char *errorMethod)
{
    Q_D(QDBusAbstractInterface);

    if (!d->isValid || !d->canMakeCalls())
        return false;

    QDBusMessage msg = QDBusMessage::createMethodCall(service(),
                                                      path(),
                                                      interface(),
                                                      method);
    QDBusMessagePrivate::setParametersValidated(msg, true);
    msg.setArguments(args);

    d->lastError = 0;
    return d->connection.callWithCallback(msg,
                                          receiver,
                                          returnMethod,
                                          errorMethod);
}
Esempio n. 8
0
void
NetPulseView::Update()
{
	BNetworkInterface interface(fCookie);

	if ((interface.Flags() & IFF_UP) != 0) {
		ifreq_stats stats;
		if (interface.GetStats(stats) == B_OK) {
			fInputRate = fDecayRate * (stats.receive.bytes - fInputBytes)
				+ (1 - fDecayRate) * fInputRate;
			fOutputRate = fDecayRate * (stats.send.bytes - fOutputBytes)
				+ (1 - fDecayRate) * fOutputRate;

			fInputBytes = stats.receive.bytes;
			fOutputBytes = stats.send.bytes;
		}

		fMaxInputRate = fInputRate >= fMaxInputRate
			? fInputRate
			: 0.9 * fMaxInputRate;
		fMaxOutputRate = fOutputRate >= fMaxOutputRate
			? fOutputRate
			: 0.9 * fMaxOutputRate;

		if (!fEnable || fMaxInputRate > 0 || fMaxOutputRate > 0) {
			UpdateBitmap();
			Draw(Bounds());
		}
	} else {
		fInputRate = fOutputRate = 0;
		fMaxInputRate = fMaxOutputRate = 0;
		if (fEnable)
			Draw(Bounds());
	}
	fEnable = ((interface.Flags() & IFF_UP) != 0);
}
Esempio n. 9
0
int main(int argc, char *argv[]){
  FILE *fin,*fout;
  /*  char seqchar, seqname[MAXLETTER];*/
  /*  char outname[MAXLETTER];*/
  /*  fpos_t position;*/
  /*  int i,sw;*/
  size_t list_size;
  NAMELIST *list, *list2;

  interface(argc, argv, &fin, &fout);

  fprintf(stderr,"Reading index\n");
  list=read_all(fin);
  fclose(fin);

  fprintf(stderr,"Editing index\n");
  list2=edit_list(list, &list_size);

  fprintf(stderr,"Sorting index\n");
  sort_and_output(list2, list_size, fout);
  fclose(fout);
  fprintf(stderr,"fpicupmakebindex finished successfully.\n");
  return 0;
}
Esempio n. 10
0
void SkypeConnection::tryConnect() {
	kDebug(SKYPE_DEBUG_GLOBAL);

	{
		QDBusInterface interface("com.Skype.API", "/com/Skype", "com.Skype.API", BUS);
		QDBusReply <QString> reply = interface.call("Invoke", "PING");

		bool started = interface.isValid();
		bool loggedin = reply.value() == "PONG";

		if ( ! started || ! loggedin ){
			if (--d->timeRemaining == 0) {
				d->startTimer->stop();
				d->startTimer->deleteLater();
				d->startTimer = 0L;
				if ( !started )
					emit error(i18n("Could not find Skype.\nYou need to install the original dynamic linked Skype version 2.0 binary from http://www.skype.com"));
				else
					emit error(i18n("Please login to Skype first"));
				disconnectSkype(crLost);
				emit connectionDone(seNoSkype, 0);
				return;
			}
			return;//Maybe next time
		}
	}

	d->startTimer->stop();
	d->startTimer->deleteLater();
	d->startTimer = 0L;
	if (d->waitBeforeConnect) {
		QTimer::singleShot(1000 * d->waitBeforeConnect, this, SLOT(startLogOn()));
		//Skype does not like being bothered right after it's start, give it a while to breathe
	} else
		startLogOn();//OK, it's your choise
}
Esempio n. 11
0
void JournalPlugin::slotNewJournal()
{
    interface()->openJournalEditor(QString(), QDate());
}
Esempio n. 12
0
uint2 Gamepad::data() {
  if(counter >= 16) return 1;
  uint2 result = interface()->inputPoll(port, Input::Device::Joypad, 0, counter);
  if(latched == 0) counter++;
  return result;
}
Esempio n. 13
0
void PanelKMenu::slotRunCommand()
{
    QString interface( "org.kde.krunner" );
    org::kde::krunner::Interface desktopInterface( interface, "/Interface", QDBusConnection::sessionBus() );
    desktopInterface.display();
}
Esempio n. 14
0
void KJotsPlugin::newBook()
{
  core()->selectPlugin( this );
  interface()->createNewBook();
}
Esempio n. 15
0
void KJotsPlugin::newPage()
{
  core()->selectPlugin( this );
  interface()->newPage();
}
Esempio n. 16
0
int main(int argc, char **argv)
{
	int ret = EXIT_FAILURE;
	char *mesh_iface = mesh_dfl_iface;

	if ((argc > 1) && (strcmp(argv[1], "-m") == 0)) {
		if (argc < 3) {
			printf("Error - the option '-m' needs a parameter\n");
			goto err;
		}

		mesh_iface = argv[2];

		argv += 2;
		argc -= 2;
	}

	if (argc < 2) {
		printf("Error - no command specified\n");
		goto err;
	}

	if (strcmp(argv[1], "-h") == 0)
		goto err;

	if (strcmp(argv[1], "-v") == 0) {
		printf("batctl %s [batman-adv: ", SOURCE_VERSION);

		ret = read_file("", module_ver_path, USE_READ_BUFF | SILENCE_ERRORS, 0, 0);
		if ((line_ptr) && (line_ptr[strlen(line_ptr) - 1] == '\n'))
			line_ptr[strlen(line_ptr) - 1] = '\0';

		if (ret == EXIT_SUCCESS)
			printf("%s]\n", line_ptr);
		else
			printf("module not loaded]\n");

		free(line_ptr);
		exit(EXIT_SUCCESS);
	}

	/* TODO: remove this generic check here and move it into the individual functions */
	/* check if user is root */
	if ((strcmp(argv[1], "bisect") != 0) && ((getuid()) || (getgid()))) {
		fprintf(stderr, "Error - you must be root to run '%s' !\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	if ((strcmp(argv[1], "ping") == 0) || (strcmp(argv[1], "p") == 0)) {

		ret = ping(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "traceroute") == 0) || (strcmp(argv[1], "tr") == 0)) {

		ret = traceroute(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "tcpdump") == 0) || (strcmp(argv[1], "td") == 0)) {

		ret = tcpdump(argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "interface") == 0) || (strcmp(argv[1], "if") == 0)) {

		ret = interface(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "originators") == 0) || (strcmp(argv[1], "o") == 0)) {

		ret = handle_debug_table(mesh_iface, argc - 1, argv + 1,
					 DEBUG_ORIGINATORS, originators_usage);

	} else if ((strcmp(argv[1], "translocal") == 0) || (strcmp(argv[1], "tl") == 0)) {

		ret = handle_debug_table(mesh_iface, argc - 1, argv + 1,
					 DEBUG_TRANSTABLE_LOCAL, trans_local_usage);

	} else if ((strcmp(argv[1], "transglobal") == 0) || (strcmp(argv[1], "tg") == 0)) {

		ret = handle_debug_table(mesh_iface, argc - 1, argv + 1,
					 DEBUG_TRANSTABLE_GLOBAL, trans_global_usage);

	} else if ((strcmp(argv[1], "softif_neigh") == 0) || (strcmp(argv[1], "sn") == 0)) {

		ret = handle_debug_table(mesh_iface, argc - 1, argv + 1,
					 DEBUG_SOFTIF_NEIGH, softif_neigh_usage);

	} else if ((strcmp(argv[1], "loglevel") == 0) || (strcmp(argv[1], "ll") == 0)) {

		ret = handle_loglevel(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "log") == 0) || (strcmp(argv[1], "l") == 0)) {

		ret = log_print(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "interval") == 0) || (strcmp(argv[1], "it") == 0)) {

		ret = handle_sys_setting(mesh_iface, argc - 1, argv + 1,
					 SYS_ORIG_INTERVAL, orig_interval_usage, NULL);

	} else if ((strcmp(argv[1], "vis_mode") == 0) || (strcmp(argv[1], "vm") == 0)) {

		ret = handle_sys_setting(mesh_iface, argc - 1, argv + 1,
					 SYS_VIS_MODE, vis_mode_usage, sysfs_param_server);

	} else if ((strcmp(argv[1], "vis_data") == 0) || (strcmp(argv[1], "vd") == 0)) {

		ret = vis_data(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "gw_mode") == 0) || (strcmp(argv[1], "gw") == 0)) {

		ret = handle_gw_setting(mesh_iface, argc - 1, argv + 1);

	} else if ((strcmp(argv[1], "gateways") == 0) || (strcmp(argv[1], "gwl") == 0)) {

		ret = handle_debug_table(mesh_iface, argc - 1, argv + 1,
					 DEBUG_GATEWAYS, gateways_usage);

	} else if ((strcmp(argv[1], "aggregation") == 0) || (strcmp(argv[1], "ag") == 0)) {

		ret = handle_sys_setting(mesh_iface, argc - 1, argv + 1,
					 SYS_AGGR, aggregation_usage, sysfs_param_enable);

	} else if ((strcmp(argv[1], "bonding") == 0) || (strcmp(argv[1], "b") == 0)) {

		ret = handle_sys_setting(mesh_iface, argc - 1, argv + 1,
					 SYS_BONDING, bonding_usage, sysfs_param_enable);

	} else if ((strcmp(argv[1], "fragmentation") == 0) || (strcmp(argv[1], "f") == 0)) {

		ret = handle_sys_setting(mesh_iface, argc - 1, argv + 1,
					 SYS_FRAG, fragmentation_usage, sysfs_param_enable);

	} else if ((strcmp(argv[1], "ap_isolation") == 0) || (strcmp(argv[1], "ap") == 0)) {

		ret = handle_sys_setting(mesh_iface, argc - 1, argv + 1,
					 SYS_AP_ISOLA, ap_isolation_usage, sysfs_param_enable);

	} else if ((strcmp(argv[1], "bisect") == 0)) {

		ret = bisect(argc - 1, argv + 1);

	} else {
		printf("Error - no command specified\n");
		print_usage();
	}

	return ret;

err:
	print_usage();
	exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{

#   include "addTimeOptions.H"
#   include "setRootCase.H"

#   include "createTime.H"

    // Get times list
    instantList Times = runTime.times();

    // set startTime and endTime depending on -time and -latestTime options
#   include "checkTimeOptions.H"

    runTime.setTime(Times[startTime], startTime);

#   include "createMesh.H"
#   include "readGravitationalAcceleration.H"

    const dictionary& piso = mesh.solutionDict().subDict("PISO");

    label pRefCell = 0;
    scalar pRefValue = 0.0;

    int nNonOrthCorr = 0;
    if (piso.found("nNonOrthogonalCorrectors"))
    {
        nNonOrthCorr = readInt(piso.lookup("nNonOrthogonalCorrectors"));
    }

    for (label i = startTime; i < endTime; i++)
    {
        runTime.setTime(Times[i], i);

        Info<< "Time = " << runTime.timeName() << endl;

        IOobject pdHeader
        (
            "pd",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        IOobject gammaHeader
        (
            "gamma",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        IOobject Uheader
        (
            "U",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        IOobject phiHeader
        (
            "phi",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        // Check all fields exists
        if
        (
            pdHeader.headerOk()
         && gammaHeader.headerOk()
         && Uheader.headerOk()
         && phiHeader.headerOk()
        )
        {
            mesh.readUpdate();

            Info<< "    Reading pd" << endl;
            volScalarField pd(pdHeader, mesh);

            Info<< "    Reading gamma" << endl;
            volScalarField gamma(gammaHeader, mesh);

            Info<< "    Reading U" << endl;
            volVectorField U(Uheader, mesh);

            Info<< "    Reading phi" << endl;
            surfaceScalarField phi(phiHeader, mesh);

            Info<< "Reading transportProperties\n" << endl;
            twoPhaseMixture twoPhaseProperties(U, phi, "gamma");

            twoPhaseProperties.correct();

            // Construct interface from gamma distribution
            interfaceProperties interface(gamma, U, twoPhaseProperties);

            // Create momentum matrix

            const dimensionedScalar& rho1 = twoPhaseProperties.rho1();
            const dimensionedScalar& rho2 = twoPhaseProperties.rho2();

            volScalarField rho
            (
                IOobject
                (
                    "rho",
                    runTime.timeName(),
                    mesh,
                    IOobject::READ_IF_PRESENT
                ),
                gamma*rho1 + (scalar(1) - gamma)*rho2,
                gamma.boundaryField().types()
            );

            surfaceScalarField rhoPhi
            (
                IOobject
                (
                    "rho*phi",
                    runTime.timeName(),
                    mesh,
                    IOobject::NO_READ,
                    IOobject::NO_WRITE
                ),
                fvc::interpolate(rho)*phi
            );

            surfaceScalarField muf = twoPhaseProperties.muf();

            fvVectorMatrix UEqn
            (
                fvm::ddt(rho, U)
              + fvm::div(rhoPhi, U)
              - fvm::laplacian(muf, U)
              - (fvc::grad(U) & fvc::grad(muf))
             ==
                interface.sigmaK()*fvc::grad(gamma)
              + rho*g
            );

            // Solve for static pressure
            volScalarField p
            (
                IOobject
                (
                    "p",
                    runTime.timeName(),
                    mesh,
                    IOobject::READ_IF_PRESENT,
                    IOobject::NO_WRITE
                ),
                pd
            );

            setRefCell(p, piso, pRefCell, pRefValue);

            volScalarField rUA = 1.0/UEqn.A();
            surfaceScalarField rUAf = fvc::interpolate(rUA);

            U = rUA*UEqn.H();

            phi = fvc::interpolate(U) & mesh.Sf();

            for(int nonOrth = 0; nonOrth <= nNonOrthCorr; nonOrth++)
            {
                fvScalarMatrix pEqn
                (
                    fvm::laplacian(rUAf, p) == fvc::div(phi)
                );

                pEqn.setReference(pRefCell, pRefValue);
                pEqn.solve();
            }

            Info << "Writing p" << endl;
            p.write();
        }
        else
        {
            Info << "Not all fields are present.  " << endl;

            if (!pdHeader.headerOk())
            {
                Info << "pd ";
            }

            if (!gammaHeader.headerOk())
            {
                Info << "gamma ";
            }

            if (!Uheader.headerOk())
            {
                Info << "U ";
            }

            if (!phiHeader.headerOk())
            {
                Info << "phi ";
            }

            Info << "missing." << endl;
        }
    }

    Info<< "End\n" << endl;

    return(0);
}
Esempio n. 18
0
uint8 CPU::mmio_read(unsigned addr) {
  if((addr & 0xffc0) == 0x2140) {
    synchronize_smp();
    return smp.port_read(addr & 3);
  }

  switch(addr & 0xffff) {
    case 0x2180: {
      uint8 result = bus.read(0x7e0000 | status.wram_addr);
      status.wram_addr = (status.wram_addr + 1) & 0x01ffff;
      return result;
    }

    case 0x4016: {
      uint8 result = regs.mdr & 0xfc;
      result |= input.port1->data() & 3;
      return result;
    }

    case 0x4017: {
      uint8 result = (regs.mdr & 0xe0) | 0x1c;
      result |= input.port2->data() & 3;
			if (!status.auto_joypad_poll_enabled) interface()->inputNotify(0x4017);
      return result;
    }

    case 0x4210: {
      uint8 result = (regs.mdr & 0x70);
      result |= status.nmi_line << 7;
      result |= 0x02;  //CPU revision
      status.nmi_line = false;
      return result;
    }

    case 0x4211: {
      uint8 result = (regs.mdr & 0x7f);
      result |= status.irq_line << 7;
      status.irq_line = false;
      return result;
    }

    case 0x4212: {
      uint8 result = (regs.mdr & 0x3e);
      unsigned vbstart = ppu.overscan() == false ? 225 : 240;

      if(vcounter() >= vbstart && vcounter() <= vbstart + 2) result |= 0x01;
      if(hcounter() <= 2 || hcounter() >= 1096) result |= 0x40;
      if(vcounter() >= vbstart) result |= 0x80;

      return result;
    }

    case 0x4213: 
			// interface()->inputNotify(0x4213); // if there are lag counter issues with super scope, uncomment this
			return status.pio;

    case 0x4214: return status.rddiv >> 0;
    case 0x4215: return status.rddiv >> 8;
    case 0x4216: return status.rdmpy >> 0;
    case 0x4217: return status.rdmpy >> 8;

    case 0x4218: interface()->inputNotify(0x4218); return status.joy1l;
    case 0x4219: interface()->inputNotify(0x4219); return status.joy1h;
    case 0x421a: interface()->inputNotify(0x421a); return status.joy2l;
    case 0x421b: interface()->inputNotify(0x421b); return status.joy2h;
    case 0x421c: interface()->inputNotify(0x421c); return status.joy3l;
    case 0x421d: interface()->inputNotify(0x421d); return status.joy3h;
    case 0x421e: interface()->inputNotify(0x421e); return status.joy4l;
    case 0x421f: interface()->inputNotify(0x421f); return status.joy4h;
  }

  if((addr & 0xff80) == 0x4300) {
    unsigned i = (addr >> 4) & 7;
    switch(addr & 0xff8f) {
      case 0x4300: {
        return (channel[i].direction << 7)
             | (channel[i].indirect << 6)
             | (channel[i].unused << 5)
             | (channel[i].reverse_transfer << 4)
             | (channel[i].fixed_transfer << 3)
             | (channel[i].transfer_mode << 0);
      }

      case 0x4301: return channel[i].dest_addr;
      case 0x4302: return channel[i].source_addr >> 0;
      case 0x4303: return channel[i].source_addr >> 8;
      case 0x4304: return channel[i].source_bank;
      case 0x4305: return channel[i].transfer_size >> 0;
      case 0x4306: return channel[i].transfer_size >> 8;
      case 0x4307: return channel[i].indirect_bank;
      case 0x4308: return channel[i].hdma_addr >> 0;
      case 0x4309: return channel[i].hdma_addr >> 8;
      case 0x430a: return channel[i].line_counter;
      case 0x430b: case 0x430f: return channel[i].unknown;
    }
  }
Esempio n. 19
0
CPU::~CPU() {
	interface()->freeSharedMemory(wram);
}
Esempio n. 20
0
bool cassette_image_device::call_load()
{
	casserr_t err;
	int cassette_flags;
	const char *extension;
	int is_writable;
	device_image_interface *image = nullptr;
	interface(image);

	if ((has_been_created()) || (length() == 0))
	{
		/* creating an image */
		err = cassette_create((void *)image, &image_ioprocs, &wavfile_format, m_create_opts, CASSETTE_FLAG_READWRITE|CASSETTE_FLAG_SAVEONEXIT, &m_cassette);
		if (err)
			goto error;
	}
	else
	{
		/* opening an image */
		do
		{
			is_writable = !is_readonly();
			cassette_flags = is_writable ? (CASSETTE_FLAG_READWRITE|CASSETTE_FLAG_SAVEONEXIT) : CASSETTE_FLAG_READONLY;
			std::string fname;
			if (software_entry()==nullptr) {
				extension = filetype();
			} else {
				fname = m_mame_file->filename();
				int loc = fname.find_last_of('.');
				if (loc!=-1) {
					extension = fname.substr(loc + 1,fname.length()-loc).c_str();
				} else {
					extension = "";
				}
			}
			err = cassette_open_choices((void *)image, &image_ioprocs, extension, m_formats, cassette_flags, &m_cassette);

			/* this is kind of a hack */
			if (err && is_writable)
				make_readonly();
		}
		while(err && is_writable);

		if (err)
			goto error;
	}

	/* set to default state, but only change the UI state */
	change_state(m_default_state, CASSETTE_MASK_UISTATE);

	/* reset the position */
	m_position = 0.0;
	m_position_time = device().machine().time().as_double();

	/* default channel to 0, speed multiplier to 1 */
	m_channel = 0;
	m_speed = 1;
	m_direction = 1;

	return IMAGE_INIT_PASS;

error:
	image_error_t imgerr = IMAGE_ERROR_UNSPECIFIED;
	switch(err)
	{
		case CASSETTE_ERROR_INTERNAL:
			imgerr = IMAGE_ERROR_INTERNAL;
			break;
		case CASSETTE_ERROR_UNSUPPORTED:
			imgerr = IMAGE_ERROR_UNSUPPORTED;
			break;
		case CASSETTE_ERROR_OUTOFMEMORY:
			imgerr = IMAGE_ERROR_OUTOFMEMORY;
			break;
		case CASSETTE_ERROR_INVALIDIMAGE:
			imgerr = IMAGE_ERROR_INVALIDIMAGE;
			break;
		default:
			imgerr = IMAGE_ERROR_UNSPECIFIED;
			break;
	}
	image->seterror(imgerr, "" );
	return IMAGE_INIT_FAIL;
}
Esempio n. 21
0
int main(int argc, char** argv)
{
    //Command line arguments
    if (argc != 2) {
        std::cout << "Usage: ./experiment splinesFile" << std::endl;
        return -1;
    }
    std::string splinesFile = argv[1];
    
    //Load splines
    Leph::SplineContainer<Leph::Spline> splines;
    splines.importData(splinesFile);
    //Initialize outputs vector
    Leph::VectorLabel outputs;
    for (const auto& sp : splines.get()) {
        outputs.append("output:" + sp.first, 0.0);
    }
    
    //Retrieve splines bounds
    double timeMin = splines.min();
    double timeMax = splines.max();

    //Initialize the robot connection
    Leph::SDKConnection sdkConnection;

    //Initialize Log time serie
    Leph::MatrixLabel serie;
    Leph::VectorLabel logVector = outputs;

    //Initialize Ncurses Interface and state
    bool isRunning = false;
    bool isLogging = false;
    std::string statusRunning = "Movement STOPPED";
    std::string statusLogging = "Logging STOPPED";
    Leph::InterfaceCLI interface("Splines Player");
    interface.addStatus(statusRunning);
    interface.addStatus(statusLogging);
    //Movement enable control
    interface.addBinding(' ', "Movement toggle", [&isRunning, &statusRunning](){
        isRunning = !isRunning;
        if (isRunning) {
            statusRunning = "Movement RUNNING";
        } else {
            statusRunning = "Movement STOPPED";
        }
    });
    //Logging control
    interface.addBinding('l', "Logging toggle", 
        [&isLogging, &statusLogging, &serie, &interface](){
        isLogging = !isLogging;
        if (isLogging) {
            statusLogging = "Logging RUNNING";
        } else {
            //Export logs
            statusLogging = "Logging STOPPED";
            std::string fileName = 
                "/tmp/log-" + Leph::currentDate() + "_raw.csv";
            interface.terminalOut() << "Logging " 
                << serie.size() << " points to " << fileName << std::endl;
            serie.save(fileName);
        }
    });
    
    //Main loop
    double freq = 50.0;
    Leph::Scheduling scheduling;
    scheduling.setFrequency(freq);
    double t = timeMin;
    while (interface.tick(false)) {
        //Compute outputs reference from splines
        for (const auto& sp : splines.get()) {
            outputs("output:" + sp.first) = sp.second.pos(t);
        }
        //Conversion to real Mowgly motors signs
        MotorsLayoutConversion(outputs, "output:");
        //Send references to motors
        sdkConnection.setMotorAngles(outputs);
        //Logging
        if (isLogging) {
            logVector.setOrAppend("time:timestamp", 
                scheduling.timestamp());
            logVector.setOrAppend("time:duration", 
                scheduling.duration());
            logVector.setOrAppend("time:phase", t);
            logVector.mergeInter(outputs);
            sdkConnection.getMotorAngles(logVector);
            sdkConnection.getSensorValues(logVector);
            MotorsLayoutConversion(logVector, "output:");
            MotorsLayoutConversion(logVector, "motor:");
            serie.append(logVector);
        }
        //Phase cycling
        if (isRunning) {
            t += 1.0/freq;
            if (t >= timeMax) t= timeMin;
        }
        //Waiting
        scheduling.wait();
        //Scheduling information
        if (scheduling.isError()) {
            interface.terminalOut() << "Scheduling error: " 
                << scheduling.timeError() << std::endl;
        }
    }
    
    return 0;
}
Esempio n. 22
0
int main(){
    dbInit();
    printf("Ibetres (1.5.15).\nType \"help\" for help.\n\n");
    interface();
    return 0;
}
Esempio n. 23
0
void JournalPlugin::select()
{
    interface()->showJournalView();
}
Esempio n. 24
0
int main(int argc, char** argv)
{
        std::cout << "\nsend_rpc_ra\n";
        std::cout << "\n(C) 2015 Alexander Holler\n\n";

	if (argc != 4) {
		std::cout << "Usage: " <<
			"send_rpc_ra interface destination_ipv6 prefix_ipv6\n" <<
			"Example: " <<
			"send_ra eth0 ff02::1 fecd::\n\n";
		return 1;
	}

	std::string interface(argv[1]);
	std::string destination(argv[2]);
	std::string prefix(argv[3]);

	struct {
		nd_router_advert nra;
		nd_opt_prefix_info opt_prefix_info;
	} my_ra;

	std::memset(&my_ra, 0, sizeof(my_ra));

	my_ra.nra.nd_ra_type = ND_ROUTER_ADVERT;

	msghdr msghdr;
	std::memset(&msghdr, 0, sizeof(msghdr));

	// destination address
	sockaddr_in6 dst;
	std::memset(&dst, 0, sizeof(dst));
	dst.sin6_family = AF_INET6;
	dst.sin6_port = htons(IPPROTO_ICMPV6);

	if (inet_pton(AF_INET6, destination.c_str(), &dst.sin6_addr) != 1) {
		std::cerr << "Error setting destination '" << destination << "'\n";
		return 2;
	}

	msghdr.msg_name = &dst;
	msghdr.msg_namelen = sizeof(dst);

	iovec iov[2];
	std::memset(&iov, 0, sizeof(iov));
	iov[0].iov_base = &my_ra;
	iov[0].iov_len = sizeof(my_ra);
	msghdr.msg_iov = (struct iovec *) &iov;
	msghdr.msg_iovlen = sizeof(iov) / sizeof(struct iovec);

	in6_pktinfo* ipi;
	cmsghdr* cmsg_hdr;
	uint8_t cmsgbuf[CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(*ipi))];
	std::memset(&cmsgbuf, 0, sizeof(cmsgbuf));

	msghdr.msg_control = &cmsgbuf;
	msghdr.msg_controllen = sizeof(cmsgbuf);

	// hop limit
	cmsg_hdr = CMSG_FIRSTHDR(&msghdr);
	cmsg_hdr->cmsg_level = IPPROTO_IPV6;
	cmsg_hdr->cmsg_type = IPV6_HOPLIMIT;
	cmsg_hdr->cmsg_len = CMSG_LEN(sizeof(int));
	cmsgbuf[sizeof(*cmsg_hdr)] = 255; // using CMSG_DATA throws a warning

	// packet info
	cmsg_hdr = CMSG_NXTHDR(&msghdr, cmsg_hdr);
	cmsg_hdr->cmsg_level = IPPROTO_IPV6;
	cmsg_hdr->cmsg_type = IPV6_PKTINFO;
	cmsg_hdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
	ipi = (struct in6_pktinfo *) CMSG_DATA(cmsg_hdr);

	ipi->ipi6_ifindex = if_nametoindex(interface.c_str());
	if (!ipi->ipi6_ifindex) {
		std::cerr << "Interface '" << interface << "' not found!\n";
		return 3;
	}

	in6_addr s_addr;
	std::memset(&s_addr, 0, sizeof(s_addr));

	if (set_src_addr(interface, s_addr)) {
		std::cerr << "Error finding link-local address of interface '" << interface << "'!\n";
		return 4;
	}

	std::memcpy(&ipi->ipi6_addr, &s_addr, sizeof(ipi->ipi6_addr));
	msghdr.msg_iovlen = 1;

	my_ra.opt_prefix_info.nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
	my_ra.opt_prefix_info.nd_opt_pi_len = 4;
	if (inet_pton(AF_INET6, prefix.c_str(), &my_ra.opt_prefix_info.nd_opt_pi_prefix) != 1) {
		std::cerr << "Error converting prefix '" << prefix << "'!\n";
		return 5;
	}
	my_ra.opt_prefix_info.nd_opt_pi_prefix_len = 64;


	if (check_prefix(interface, my_ra.opt_prefix_info.nd_opt_pi_prefix)) {
		std::cerr << "Prefix " << prefix << " seems to be in use!\n";
		return 6;
	}
	my_ra.opt_prefix_info.nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
	my_ra.opt_prefix_info.nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_RADDR;

	// Setting both lifetimes to 1 means the kernel will only delete the
	// link-local address without creating it before.
	my_ra.opt_prefix_info.nd_opt_pi_valid_time = htonl(1);
	my_ra.opt_prefix_info.nd_opt_pi_preferred_time = htonl(1);

	int sock = ::socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
	if (sock < 0) {
		std::cerr << "Error opening raw socket, are you root?\n";
		return 7;
	}
	if (::sendmsg(sock, &msghdr, 0) < 0) {
		::close(sock);
		std::cerr << "Error sending RA ( " << strerror(errno) << ")!\n";
		return 8;
	}
	::close(sock);

	std::cout << "Sent a Router Advertisment with prefix " <<
		prefix << " to " << destination << "\n";

	return 0;
}
Esempio n. 25
0
const AccelerometerSensorChannelInterface* AccelerometerSensorChannelInterface::listenInterface(const QString& id)
{
    return dynamic_cast<const AccelerometerSensorChannelInterface*> (interface(id));
}
Esempio n. 26
0
PPU::~PPU() {
  delete[] surface;
	interface()->freeSharedMemory(vram);
	interface()->freeSharedMemory(oam);
	interface()->freeSharedMemory(cgram);  
}
Esempio n. 27
0
void Cartridge::parse_markup_necdsp(XML::Node &root) {
  if(root.exists() == false) return;
  has_necdsp = true;

  for(unsigned n = 0; n < 16384; n++) necdsp.programROM[n] = 0x000000;
  for(unsigned n = 0; n <  2048; n++) necdsp.dataROM[n] = 0x0000;

  necdsp.frequency = numeral(root["frequency"].data);
  if(necdsp.frequency == 0) necdsp.frequency = 8000000;
  necdsp.revision
  = root["model"].data == "uPD7725"  ? NECDSP::Revision::uPD7725
  : root["model"].data == "uPD96050" ? NECDSP::Revision::uPD96050
  : NECDSP::Revision::uPD7725;
  string firmware = root["firmware"].data;
  string sha256 = root["sha256"].data;

  string path = interface()->path(Slot::Base, firmware);
  unsigned promsize = (necdsp.revision == NECDSP::Revision::uPD7725 ? 2048 : 16384);
  unsigned dromsize = (necdsp.revision == NECDSP::Revision::uPD7725 ? 1024 :  2048);
  unsigned filesize = promsize * 3 + dromsize * 2;

  file fp;
  if(fp.open(path, file::mode::read) == false) {
    interface()->message({ "Warning: NEC DSP firmware ", firmware, " is missing." });
  } else if(fp.size() != filesize) {
    interface()->message({ "Warning: NEC DSP firmware ", firmware, " is of the wrong file size." });
    fp.close();
  } else {
    for(unsigned n = 0; n < promsize; n++) necdsp.programROM[n] = fp.readl(3);
    for(unsigned n = 0; n < dromsize; n++) necdsp.dataROM[n] = fp.readl(2);

    if(!sha256.empty()) {
      //XML file specified SHA256 sum for program. Verify file matches the hash.
      fp.seek(0);
      //uint8_t data[filesize]; //test
			uint8_t *data = (uint8_t*)alloca(filesize);
      fp.read(data, filesize);

      if(sha256 != nall::sha256(data, filesize)) {
        interface()->message({ "Warning: NEC DSP firmware ", firmware, " SHA256 sum is incorrect." });
      }
    }

    fp.close();
  }

  for(auto &node : root) {
    if(node.name == "dr") {
      for(auto &leaf : node) {
        Mapping m({ &NECDSP::dr_read, &necdsp }, { &NECDSP::dr_write, &necdsp });
        parse_markup_map(m, leaf);
        mapping.append(m);
      }
    }
    if(node.name == "sr") {
      for(auto &leaf : node) {
        Mapping m({ &NECDSP::sr_read, &necdsp }, { &NECDSP::sr_write, &necdsp });
        parse_markup_map(m, leaf);
        mapping.append(m);
      }
    }
    if(node.name == "dp") {
      for(auto &leaf : node) {
        Mapping m({ &NECDSP::dp_read, &necdsp }, { &NECDSP::dp_write, &necdsp });
        parse_markup_map(m, leaf);
        mapping.append(m);
      }
    }
  }
}
Esempio n. 28
0
AccelerometerSensorChannelInterface* AccelerometerSensorChannelInterface::controlInterface(const QString& id)
{
    return interface(id);
}
Esempio n. 29
0
void CPU::initialize()
{
	wram = (uint8*)interface()->allocSharedMemory("WRAM",128 * 1024);
}
Esempio n. 30
0
int main(int argc, char **argv) {
	unsigned pid = 0;
	int i;

	// handle CTRL-C
	signal (SIGINT, my_handler);
	signal (SIGTERM, my_handler);

	for (i = 1; i < argc; i++) {
		// default options
		if (strcmp(argv[i], "--help") == 0 ||
		    strcmp(argv[i], "-?") == 0) {
			usage();
			return 0;
		}
		else if (strcmp(argv[i], "--version") == 0) {
			printf("firemon version %s\n\n", VERSION);
			return 0;
		}
		
		// options without a pid argument
		else if (strcmp(argv[i], "--top") == 0) {
			top(); // never to return
		}
		else if (strcmp(argv[i], "--list") == 0) {
			list();
			return 0;
		}
		else if (strcmp(argv[i], "--netstats") == 0) {
			struct stat s;
			if (getuid() != 0 && stat("/proc/sys/kernel/grsecurity", &s) == 0) {
				fprintf(stderr, "Error: this feature is not available on Grsecurity systems\n");
				exit(1);
			}	

			netstats();
			return 0;
		}


		// cumulative options with or without a pid argument
		else if (strcmp(argv[i], "--x11") == 0) {
			arg_x11 = 1;
		}
		else if (strcmp(argv[i], "--cgroup") == 0) {
			arg_cgroup = 1;
		}
		else if (strcmp(argv[i], "--cpu") == 0) {
			arg_cpu = 1;
		}
		else if (strcmp(argv[i], "--seccomp") == 0) {
			arg_seccomp = 1;
		}
		else if (strcmp(argv[i], "--caps") == 0) {
			arg_caps = 1;
		}
		else if (strcmp(argv[i], "--tree") == 0) {
			arg_tree = 1;
		}
		else if (strcmp(argv[i], "--interface") == 0) {
			arg_interface = 1;
		}
		else if (strcmp(argv[i], "--route") == 0) {
			arg_route = 1;
		}
		else if (strcmp(argv[i], "--arp") == 0) {
			arg_arp = 1;
		}

		else if (strncmp(argv[i], "--name=", 7) == 0) {
			char *name = argv[i] + 7;
			if (name2pid(name, (pid_t *) &pid)) {
				fprintf(stderr, "Error: cannot find sandbox %s\n", name);
				return 1;
			}
		}
		
		// etc
		else if (strcmp(argv[i], "--nowrap") == 0)
			arg_nowrap = 1;
		
		// invalid option
		else if (*argv[i] == '-') {
			fprintf(stderr, "Error: invalid option\n");		
			return 1;
		}
		
		// PID argument
		else {
			// this should be a pid number
			char *ptr = argv[i];
			while (*ptr != '\0') {
				if (!isdigit(*ptr)) {
					fprintf(stderr, "Error: not a valid PID number\n");
					exit(1);
				}
				ptr++;
			}

			sscanf(argv[i], "%u", &pid);
			break;
		}
	}

	if (arg_tree)
		tree((pid_t) pid);
	if (arg_interface)
		interface((pid_t) pid);
	if (arg_route)
		route((pid_t) pid);
	if (arg_arp)
		arp((pid_t) pid);
	if (arg_seccomp)
		seccomp((pid_t) pid);
	if (arg_caps)
		caps((pid_t) pid);
	if (arg_cpu)
		cpu((pid_t) pid);
	if (arg_cgroup)
		cgroup((pid_t) pid);
	if (arg_x11)
		x11((pid_t) pid);
	
	if (!arg_route && !arg_arp && !arg_interface && !arg_tree && !arg_caps && !arg_seccomp && !arg_x11)
		procevent((pid_t) pid); // never to return
		
	return 0;
}