void BluetoothSensor::run()
{
    bool updateDB = false;
    bool scan = false;

    print("Running, CTRL+C to quit...");

    // index of the device currently scanned
    unsigned int deviceIndex = 0;

    while(!quit)
    {
        // update device db if previous update didn't succeed
        if (m_updateDBNeeded) m_updateDBNeeded = !updateDeviceData();

        // make sure that current device index is valid.
        // this also guarantees that no scanning is made when there are no devices.
        if (deviceIndex < m_devices.size())
        {
            checkDevice(deviceIndex);
        }

        // move to next device, start from beginning when at the end
        deviceIndex++;
        if (deviceIndex >= m_devices.size()) deviceIndex = 0;

        // check if there are arrived mqtt messages (commands)
        do
        {
            processIncomingMessages(updateDB, scan);
            if (updateDB)
            {
                m_updateDBNeeded = !updateDeviceData();
            }
            if (scan)
            {
                discoverDevices();
            }
        }

        // check arrived messages again after database update or device discovery,
        // so that a possible request for those is processed before continuing
        while ((updateDB || scan) && !quit);

        // check that Mosquitto is still connected.
        // if Mosquitto disconnects there can be messages from this iteration
        // which aren't sent at all, but missing some outgoing messages
        // shouldn't be too big of a problem.
        if (!m_mosquitto->isConnected())
        {
            printError("Mosquitto disconnected");
            if (connectMosquitto())
            {
                // update device db and send hello after mosquitto reconnect
                m_updateDBNeeded = !updateDeviceData();
                sendHello();
            }
        }
    }
}
static PyObject *
DynamicMusic_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
	DynamicMusicP* self = (DynamicMusicP*)type->tp_alloc(type, 0);

	if(self != nullptr)
	{
		PyObject* object;
		if(!PyArg_ParseTuple(args, "O:device", &object))
			return nullptr;
		Device* device = checkDevice(object);

		try
		{
			self->dynamicMusic = new std::shared_ptr<aud::DynamicMusic>(new aud::DynamicMusic(*reinterpret_cast<std::shared_ptr<aud::IDevice>*>(device->device)));
		}
		catch(aud::Exception& e)
		{
			Py_DECREF(self);
			PyErr_SetString(AUDError, e.what());
			return nullptr;
		}
	}

	return (PyObject *)self;
}
Beispiel #3
0
IOService *AppleUSBCDC::probe(IOService *provider, SInt32 *score)
{
	IOUSBDevice *newDevice = NULL;
	UInt8		classValue = 0;
    OSNumber	*classInfo = NULL;
	SInt32		newScore = 0;
    IOService   *res;
	
	XTRACE(this, 0, *score, "probe");
	
	OSBoolean *boolObj = OSDynamicCast(OSBoolean, provider->getProperty("kCDCDoNotMatchThisDevice"));
    if (boolObj && boolObj->isTrue())
    {
        XTRACE(this, 0, *score, "probe - provider doesn't want us to match");
        return NULL;
    }
	
		// Check the device class, we need to handle Miscellaneous or Composite class a little different
	
	classInfo = (OSNumber *)provider->getProperty("bDeviceClass");
    if (classInfo)
    {
        classValue = classInfo->unsigned32BitValue();
		if ((classValue == kUSBCompositeClass) || (classValue == kUSBMiscellaneousClass))
		{
			newDevice = OSDynamicCast(IOUSBDevice, provider);
			if(!newDevice)
			{
				XTRACE(this, 0, 0, "probe - provider invalid");
			} else {
					// Check if it has CDC interfaces
					
				if (checkDevice(newDevice))
				{
					newScore = 1;			// We need to see the device before the Composite driver does
				} else {
					XTRACE(this, 0, 0, "probe - Composite or Micsellaneous class but not CDC");
					return NULL;			// We're not interested
				}
			}
		}
	}

	*score += newScore;
	
    res = super::probe(provider, score);
	
	XTRACE(this, 0, *score, "probe - Exit");
    
    return res;
    
}/* end probe */
Beispiel #4
0
/**
 * Constructor of MMSCDA class.
 *
 * It does initializing by calling MMSAV::initialize()
 * and checks the given device. If the device is not correct
 * "/dev/dvd" will be used.
 *
 * @param   window  [in]    main window for dvd playing
 * @param   device  [in]    device to check as dvd device
 * @param   verbose [in]    if true the xine engine writes debug messages to stdout
 */
MMSCDA::MMSCDA(MMSWindow *window, const string device, const bool verbose)  {
    MMSAV::initialize(verbose, window);

    /* at first check for DVD device */
    checkDevice(device);

    /* save window width/height */
    if(window) {
		MMSFBRectangle rect = window->getGeometry();
		this->windowWidth  = rect.w;
		this->windowHeight = rect.h;
    }
}
Beispiel #5
0
void PCIProvider::requestProbe()
{
	kern_spinlock_lock(&_lock);

	for(int bus=0; bus<256; bus++)
	{
		for(int device=0; device<32; device++)
		{
			checkDevice(bus, device);
		}
	}

	_firstRun = false;
	kern_spinlock_unlock(&_lock);
}
Beispiel #6
0
Torch::Torch(QObject *parent) :
    QObject(parent)
{
    m_deviceName = "";
    m_deviceSupported = false;
    m_hasBrightness = true;
    m_controlPath = "/sys/class/leds/led:flash_torch/brightness";

    checkDevice();

    strobotimer = new QTimer();
    strobotimer->setSingleShot(false);

    connect(strobotimer, SIGNAL(timeout()), this, SLOT(p_strobotimerTimeout()));

    lastBrightness = 1;
    strobostate = false;
}
Beispiel #7
0
long CDPreferences::onCmdDeviceAdd(FXObject*,FXSelector,void*)
{
    FXInputDialog dialog(this,"Add CD-ROM Device","Device name:");
    if(dialog.execute())
    {
        FXString devnam=dialog.getText();

        if(!checkDevice(devnam))
        {
            FXMessageBox::error(this,MBOX_OK,"Invalid CD Audio Device","%s is not a valid CD audio device.  ",devnam.text());
        }
        else
        {
            std::list<FXString>::iterator iter=std::find(remdev.begin(),remdev.end(),devnam);
            if(iter!=remdev.end())
                remdev.erase(iter);
            else
                adddev.push_back(devnam);
            devlist->appendItem(devnam);
        }
    }
    return 1;
}
Beispiel #8
0
/* FIXME it is nearly common with VAAPI */
bool VideoDecoderD3DPrivate::getBuffer(void **opaque, uint8_t **data)//vlc_va_t *external, AVFrame *ff)
{
    if (!checkDevice())
        return false;
    /* Grab an unused surface, in case none are, try the oldest
     * XXX using the oldest is a workaround in case a problem happens with libavcodec */
    int i, old;
    for (i = 0, old = 0; i < surfaces.size(); i++) {
        const va_surface_t *s = surfaces[i];
        if (!s->ref)
            break;
        if (s->order < surfaces[old]->order)
            old = i;
    }
    if (i >= surfaces.size())
        i = old;
    va_surface_t *s = surfaces[i];
    s->ref = 1;
    s->order = surface_order++;
    *data = (uint8_t*)s->getSurface();
    *opaque = s;
    return true;
}
void MultiTouchManager::handleFingerDown(const SDL_Event &event)
{
    updateFinger(event, true);
    const SDL_TouchFingerEvent &touch = event.tfinger;
    checkDevice(touch.touchId, touch.fingerId);
}
Beispiel #10
0
MidiDriver::DeviceHandle MidiDriver::detectDevice(int flags) {
	// Query the selected music device (defaults to MT_AUTO device).
	Common::String selDevStr = ConfMan.hasKey("music_driver") ? ConfMan.get("music_driver") : Common::String("auto");
	DeviceHandle hdl = getDeviceHandle(selDevStr.empty() ? Common::String("auto") : selDevStr);
	DeviceHandle reslt = 0;

	_forceTypeMT32 = false;

	// Check whether the selected music driver is compatible with the
	// given flags.
	switch (getMusicType(hdl)) {
	case MT_PCSPK:
		if (flags & MDT_PCSPK)
			reslt = hdl;
		break;

	case MT_PCJR:
		if (flags & MDT_PCJR)
			reslt = hdl;
		break;

	case MT_CMS:
		if (flags & MDT_CMS)
			reslt = hdl;
		break;

	case MT_ADLIB:
		if (flags & MDT_ADLIB)
			reslt = hdl;
		break;

	case MT_C64:
		if (flags & MDT_C64)
			reslt = hdl;
		break;

	case MT_AMIGA:
		if (flags & MDT_AMIGA)
			reslt = hdl;
		break;

	case MT_APPLEIIGS:
		if (flags & MDT_APPLEIIGS)
			reslt = hdl;
		break;

	case MT_TOWNS:
		if (flags & MDT_TOWNS)
			reslt = hdl;
		break;

	case MT_PC98:
		if (flags & MDT_PC98)
			reslt = hdl;
		break;

	case MT_GM:
	case MT_GS:
	case MT_MT32:
		if (flags & MDT_MIDI)
			reslt = hdl;
		break;

	case MT_NULL:
		reslt = hdl;
		break;

	default:
		break;
	}

	Common::String failedDevStr;
	if (getMusicType(hdl) == MT_INVALID) {
		// If the expressly selected driver or device cannot be found (no longer compiled in, turned off, etc.)
		// we display a warning and continue.
		failedDevStr = selDevStr;
		Common::String warningMsg = Common::String::format(_("The selected audio device '%s' was not found (e.g. might be turned off or disconnected)."), failedDevStr.c_str()) + " " + _("Attempting to fall back to the next available device...");
		GUI::MessageDialog dialog(warningMsg);
		dialog.runModal();
	}

	MusicType tp = getMusicType(reslt);
	if (tp != MT_INVALID && tp != MT_AUTO) {
		if (checkDevice(reslt)) {
			return reslt;
		} else {
			// If the expressly selected device cannot be used we display a warning and continue.
			failedDevStr = getDeviceString(hdl, MidiDriver::kDeviceName);
			Common::String warningMsg = Common::String::format(_("The selected audio device '%s' cannot be used. See log file for more information."), failedDevStr.c_str()) + " " + _("Attempting to fall back to the next available device...");
			GUI::MessageDialog dialog(warningMsg);
			dialog.runModal();
		}
	}

	// If the selected driver did not match the flags setting,
	// we try to determine a suitable and "optimal" music driver.
	const MusicPlugin::List p = MusicMan.getPlugins();
	// If only MDT_MIDI but not MDT_PREFER_MT32 or MDT_PREFER_GM is set we prefer the other devices (which will always be
	// detected since they are hard coded and cannot be disabled).
	bool skipMidi = !(flags & (MDT_PREFER_GM | MDT_PREFER_MT32));
	while (flags != MDT_NONE) {
		if ((flags & MDT_MIDI) && !skipMidi) {
			// If a preferred MT32 or GM device has been selected that device gets returned if available.
			Common::String devStr;
			if (flags & MDT_PREFER_MT32)
				devStr = ConfMan.hasKey("mt32_device") ? ConfMan.get("mt32_device") : Common::String("null");
			else if (flags & MDT_PREFER_GM)
				devStr = ConfMan.hasKey("gm_device") ? ConfMan.get("gm_device") : Common::String("null");
			else
				devStr = "auto";
			
			// Default to Null device here, since we also register a default null setting for
			// the MT32 or GM device in the config manager.
			hdl = getDeviceHandle(devStr.empty() ? Common::String("null") : devStr);
			const MusicType type = getMusicType(hdl);

			// If we have a "Don't use GM/MT-32" setting we skip this part and jump
			// to AdLib, PC Speaker etc. detection right away.
			if (type != MT_NULL) {
				if (type == MT_INVALID) {
					// If the preferred (expressly requested) selected driver or device cannot be found (no longer compiled in, turned off, etc.)
					// we display a warning and continue. Don't warn about the missing device if we did already (this becomes relevant if the
					// missing device is selected as preferred device and also as GM or MT-32 device).
					if (failedDevStr != devStr) {
						Common::String warningMsg = Common::String::format(_("The preferred audio device '%s' was not found (e.g. might be turned off or disconnected)."), devStr.c_str()) + " " + _("Attempting to fall back to the next available device...");
						GUI::MessageDialog dialog(warningMsg);
						dialog.runModal();
					}
				} else if (type != MT_AUTO) {
					if (checkDevice(hdl)) {
						if (flags & MDT_PREFER_MT32)
							// If we have a preferred MT32 device we disable the gm/mt32 mapping (more about this in mididrv.h).
							_forceTypeMT32 = true;
						return hdl;
					} else {
						// If the preferred (expressly requested) device cannot be used we display a warning and continue.
						// Don't warn about the failing device if we did already (this becomes relevant if the failing
						// device is selected as preferred device and also as GM or MT-32 device).
						if (failedDevStr != getDeviceString(hdl, MidiDriver::kDeviceName)) {
							Common::String warningMsg = Common::String::format(_("The preferred audio device '%s' cannot be used. See log file for more information."), getDeviceString(hdl, MidiDriver::kDeviceName).c_str()) + " " + _("Attempting to fall back to the next available device...");
							GUI::MessageDialog dialog(warningMsg);
							dialog.runModal();
						}
					}
				}

				// If no specific device is selected (neither in the scummvm nor in the game domain)
				// and there is no preferred MT32 or GM device selected either or if the detected device is unavailable we arrive here.
				// If MT32 is preferred we try for the first available device with music type 'MT_MT32' (usually the mt32 emulator).
				if (flags & MDT_PREFER_MT32) {
					for (MusicPlugin::List::const_iterator m = p.begin(); m != p.end(); ++m) {
						MusicDevices i = (**m)->getDevices();
						for (MusicDevices::iterator d = i.begin(); d != i.end(); ++d) {
							if (d->getMusicType() == MT_MT32) {
								hdl = d->getHandle();
								if (checkDevice(hdl))
									return hdl;
							}
						}
					}
				}

				// Now we default to the first available device with music type 'MT_GM' if not
				// MT-32 is preferred or if MT-32 is preferred but all other devices have failed.
				if (!(flags & MDT_PREFER_MT32) || flags == (MDT_PREFER_MT32 | MDT_MIDI)) {
					for (MusicPlugin::List::const_iterator m = p.begin(); m != p.end(); ++m) {
						MusicDevices i = (**m)->getDevices();
						for (MusicDevices::iterator d = i.begin(); d != i.end(); ++d) {
							if (d->getMusicType() == MT_GM || d->getMusicType() == MT_GS) {
								hdl = d->getHandle();
								if (checkDevice(hdl))
									return hdl;
							}
						}
					}
					// Detection flags get removed after final detection attempt to avoid further attempts.
					flags &= ~(MDT_MIDI | MDT_PREFER_GM | MDT_PREFER_MT32);
				}
			}
		}

		// The order in this list is important, since this is the order of preference
		// (e.g. MT_ADLIB is checked before MT_PCJR and MT_PCSPK for a good reason).
		// Detection flags get removed after detection attempt to avoid further attempts.
		if (flags & MDT_TOWNS) {
			tp = MT_TOWNS;
			flags &= ~MDT_TOWNS;
		} else if (flags & MDT_PC98) {
			tp = MT_PC98;
			flags &= ~MDT_PC98;
		} else if (flags & MDT_ADLIB) {
			tp = MT_ADLIB;
			flags &= ~MDT_ADLIB;
		} else if (flags & MDT_PCJR) {
			tp = MT_PCJR;
			flags &= ~MDT_PCJR;
		} else if (flags & MDT_PCSPK) {
			tp = MT_PCSPK;
			flags &= ~MDT_PCSPK;
		} else if (flags & MDT_C64) {
			tp = MT_C64;
			flags &= ~MDT_C64;
		} else if (flags & MDT_AMIGA) {
			tp = MT_AMIGA;
			flags &= ~MDT_AMIGA;
		} else if (flags & MDT_APPLEIIGS) {
			tp = MT_APPLEIIGS;
			flags &= ~MDT_APPLEIIGS;
		} else if (flags & MDT_MIDI) {
			// If we haven't tried to find a MIDI device yet we do this now.
			skipMidi = false;
			continue;
		} else if (flags) {
			// Invalid flags. Set them to MDT_NONE to leave detection loop.
			flags = MDT_NONE;
			tp = MT_AUTO;
		}

		for (MusicPlugin::List::const_iterator m = p.begin(); m != p.end(); ++m) {
			MusicDevices i = (**m)->getDevices();
			for (MusicDevices::iterator d = i.begin(); d != i.end(); ++d) {
				if (d->getMusicType() == tp) {
					hdl = d->getHandle();
					if (checkDevice(hdl))
						return hdl;
				}
			}
		}
	}

	return 0;
}
Beispiel #11
0
int main(int argc, char **argv)
{
    char cDiskName[] = "/dev/sg2";
    int fd = open(cDiskName, O_RDWR);
    if (fd < 0)
    {
        printf("Open error: %s, errno=%d (%s)\n", cDiskName, errno, strerror(errno));
        return 1;
    }

    if (!checkDevice(fd)) {
        printf("checkDevice fail\n");
        return 2;
    }
    printf("init ok\n");

    DataInfo_t datainfo;
    int last_addr = 0;
    DeviceState_t last_state = STATE_INVALIDxx;
    DI_Status_t last_status = DI_STATUS_INVALIDxx;

    unsigned scanned_imgs = 0;

    while (true) {
        // get state: scanning or idle
        DeviceState_t state = GetDeviceState(fd);
        if (state >= STATE_INVALIDxx || state < 0) {
            return 7;
        }
        if (state != last_state) {
            printf("DeviceState: %d => %s\n", (unsigned)state, state_lut[state]);
        }

        // get data info: new data ready or not?
        if (!GetDeviceDataInfo(fd, &datainfo)) {
            return 8;
        }
        if (datainfo.status < 0 || datainfo.status > 2) {
            return 9;
        }
        if (datainfo.status != last_status || datainfo.addr != last_addr) {
            dumpDataInfo(&datainfo);
        }

        if (datainfo.status != DI_STATUS_NOT_READY) {
            // there's data for us
            unsigned imgbufsize = datainfo.width * datainfo.height;
            if (datainfo.color == DI_COLOR_COLOR) {
                imgbufsize *= 3;
            }

            // image buffer
            unsigned char *imgbuf = new unsigned char[imgbufsize];

            // read data
            bool ok = MemoryRead(fd, datainfo.addr, imgbuf, imgbufsize);
            if (ok) {
                printf("read %d bytes\n", imgbufsize);

                shuffleBitmap(imgbuf, imgbufsize, datainfo.width, datainfo.height, datainfo.color);

                int ifd;
                if (!scanned_imgs) {
                    ifd = open("out.data", O_WRONLY|O_CREAT|O_TRUNC, 0644);
                } else {
                    ifd = open("out.data", O_WRONLY|O_APPEND);
                }

                if (ifd) {
                    write(ifd, imgbuf, imgbufsize);
                    close(ifd);

                    scanned_imgs++;
                }
            } else {
                printf("failed reading data\n");
            }

            delete [] imgbuf;
            imgbuf = 0;
        }

        usleep(20000);
        last_state = state;
        last_status = datainfo.status;
        last_addr = datainfo.addr;
    }

    close(fd);
    printf("all ok\n");
    return 0;
}
// Thread that gets and sends CPU usage
static DWORD WINAPI mainThread(LPVOID args)
{
	UNREFERENCED_PARAMETER(args);

	bool usbOk = true;
	byte checkCounter = 0;
	byte pokeCounter = 0;

	while(1)
	{
		// If exit event is set then exit thread, otherwise wait for timeout and do the usual CPU stuff
		if(WaitForSingleObject(hThreadExitEvent, SAMPLERATE) != WAIT_TIMEOUT)
			break;

		// Get usage
		byte cpuUsage = getCPUUsage();

		EnterCriticalSection(&cs);

		// Store sample
		sample.samples[sample.idx++] = cpuUsage;
		if(sample.idx >= sample.count)
			sample.idx = 0;

		// Get average
		uint avg = 0;
		for(uint i=0;i<sample.count;i++)
			avg += sample.samples[i];
		avg /= sample.count;

		LeaveCriticalSection(&cs);

		cpuUsage = (byte)avg;

		// Show CPU usage
		actions_showCPULoad(cpuUsage);

		// Constantly searching for USB devices takes up a lot of CPU time,
		// so here we only check for new device every so often.
		if(!usbOk)
		{
			if(++checkCounter < (USB_CHECK_INTERVAL / SAMPLERATE))
				continue;
			checkCounter = 0;
		}

		// Send to USB
		if((usbOk = checkDevice(usbOk)))
		{
			if(device_get()->ledMode == MODE_CPU_USAGE)
			{
				// Workout colour
				s_rgbVal colour;
				getCPUColour(cpuUsage, &colour);

				// Send colour
				usbOk = device_setColour(&colour);
			}
			else
			{
				// Just send pokes if not in CPU usage mode,
				// this sees if the device is still connected
				if(++pokeCounter >= (USB_POKE_INTERVAL / SAMPLERATE))
				{
					pokeCounter = 0;
					usbOk = device_poke();
				}
			}
		}
	}

	return EXIT_SUCCESS;
}