void AbstractChatNetPackageSender::serialize( float dt ) { if(getPeer()->isConnected() == false) { return; } if(getPeer()->getNumberOfConnections() == 0) { return; } if(NetworkState::getBool(getPeer()->getPeerConfiguration(),NL_SERIALIZEKEY_PEER_SENDAUTOMESSAGES,false)) { _autoMessageTimer += dt; if(_autoMessageTimer > _autoMessageInterval) { // TODO: @student : read the following comments // note: if nothing works start debugging here ... // getPeer()->log(ELogType_Message, "sending auto message"); std::ostringstream autoMessage; autoMessage << "Hello - " << _autoMessageIdx; sendChatLine(autoMessage.str().c_str()); _autoMessageTimer = 0.0f; ++_autoMessageIdx; // reset the message content // otherwise the next auto message will not be send _sendMessage._content = ""; } } }
//============================================================================== void handleEvent (ComponentPeer& newPeer, Point<float> positionWithinPeer, Time time, const ModifierKeys newMods, float newPressure) { lastTime = time; const bool pressureChanged = (pressure != newPressure); pressure = newPressure; ++mouseEventCounter; const Point<float> screenPos (newPeer.localToGlobal (positionWithinPeer)); if (isDragging() && newMods.isAnyMouseButtonDown()) { setScreenPos (screenPos, time, pressureChanged); } else { setPeer (newPeer, screenPos, time); if (ComponentPeer* peer = getPeer()) { if (setButtons (screenPos, time, newMods)) return; // some modal events have been dispatched, so the current event is now out-of-date peer = getPeer(); if (peer != nullptr) setScreenPos (screenPos, time, pressureChanged); } } }
void ClientChatNetPackageSender::onCtrlEditEnd(CCObject* sender) { // note: the notification center spreads the function call // to every registered observer // so you have to explicitly check if // the sender is the object you want to deal with CCControlEditBox* editBox(dynamic_cast<CCControlEditBox*>(sender)); if(editBox != nullptr) { const char* editContent(editBox->getTextField()->getString()); if(sl::isEmptyString(editContent) == false) { if(editBox == _ctrlName) { getPeer()->log(ELogType_Message, "%s name is:%s", __FUNCTION__, editContent); _name = editContent; } else if(editBox == _ctrlMessage) { getPeer()->log(ELogType_Message, "%s message is:%s", __FUNCTION__, editContent); // we can now send this message ... SLAString message(editContent); this->sendChatLine(message); editBox->getTextField()->setString(nullptr); } } } }
// TODO: @student : extend the protocol. // so the receiver can split the package into name and content void ServerChatNetPackageDispatcher::dispatchPacket(unsigned char packetIdentifier, NativePacket* nativePacket ) { NetMessageIDTypes eNetMessageID(static_cast<NetMessageIDTypes>(packetIdentifier)); const bool validMessageId((eNetMessageID > NETMSG_ID_START) && (eNetMessageID < NETMSG_ID_END)); if(validMessageId == false) { return; } switch(eNetMessageID) { case NETMSG_ID_CHATLINE: { const char* message = (const char*)nativePacket->data; // skip the packet identifier message++; if(isEmptyString(message) == true) { getPeer()->log(ELogType_Error, "received an empty chat message"); } else { // TODO: split the packet ... ChatMessage chatMessage("---", message); addChatMessage(chatMessage); // now broadcast this message to everyone else connected to this peer // except for the sender getPeer()->accessRakNetPeer()->Send((const char*)nativePacket->data, nativePacket->length, HIGH_PRIORITY, RELIABLE_ORDERED, 0, nativePacket->systemAddress, true); } } break; default: break; } }
//============================================================================== void handleEvent (ComponentPeer* const newPeer, Point<int> positionWithinPeer, Time time, const ModifierKeys newMods) { jassert (newPeer != nullptr); lastTime = time; ++mouseEventCounter; const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer)); if (isDragging() && newMods.isAnyMouseButtonDown()) { setScreenPos (screenPos, time, false); } else { setPeer (newPeer, screenPos, time); if (ComponentPeer* peer = getPeer()) { if (setButtons (screenPos, time, newMods)) return; // some modal events have been dispatched, so the current event is now out-of-date peer = getPeer(); if (peer != nullptr) setScreenPos (screenPos, time, false); } } }
const u32 CNetManager::getPing() { if(getPeer()) return getPeer()->roundTripTime; else return 0; }
void Component::dispose() { if ( isLightWeight() == FALSE ) { getPeer()->Show( FALSE ); // avoid flicker getPeer()->Destroy(); // destroy assocaiated peer } }
void run(){ int len; int buffer_pos = 0; char tmpbuff[SIGNALING_BUFFER_SIZE]; getPeer()->onSignalingThreadStarted(); pthread_mutex_unlock(&startMutex); while(signalingContinue){ getPeer()->processMessages(); if(!isConnected){ isConnected = tryconnect(); sleep(1); } else if((len = recv(signalingSocket, signalingBuffer + buffer_pos, SIGNALING_BUFFER_SIZE - buffer_pos, 0)) > 0){ bool msgComplete = false; buffer_pos += len; do{ msgComplete = false; int msg_length = *(int*)signalingBuffer; if(buffer_pos > msg_length){ this->processMessage(signalingBuffer+4, msg_length ); memcpy(tmpbuff, signalingBuffer+4+msg_length, SIGNALING_BUFFER_SIZE - 4 - msg_length); memcpy(signalingBuffer, tmpbuff, SIGNALING_BUFFER_SIZE - 4 - msg_length); buffer_pos -= (4 + msg_length); msgComplete = true; } }while(msgComplete && buffer_pos > 0); }else if(len == 0){ //std::cout << "[SIG] Disconnected" << std::endl; isConnected = false; close(signalingSocket); getPeer()->disconnect(); } } close(signalingSocket); getPeer()->onSignalingThreadStopped(); delete getPeer(); //TODO deleting peer segfaults while terminating audio stack !! pthread_mutex_unlock(&stopMutex); //std::cout << "[SIG] Quit" << std::endl; }
/** * This function is for the configuration code. * Return false to abort configuration. */ bool configureHook() { if (!(requires("ObcInterface")->connectTo(getPeer("Obc")->provides("ObcInterface")))){ log(Info) << "connection problem to service" << endlog(); } if (!(requires("CameraInterface")->connectTo(getPeer("Camera")->provides("CameraInterface")))){ log(Info) << "connection problem to service" << endlog(); } // ... return true; }
// TODO: @student : extend the protocol. // so the receiver can split the package into name and content void ClientChatNetPackageDispatcher::dispatchPacket(unsigned char packetIdentifier, NativePacket* nativePacket ) { NetMessageIDTypes eNetMessageID(static_cast<NetMessageIDTypes>(packetIdentifier)); const bool validMessageId((eNetMessageID > NETMSG_ID_START) && (eNetMessageID < NETMSG_ID_END)); if(validMessageId == false) { return; } switch(eNetMessageID) { case NETMSG_ID_CHATLINE: { const char* message = (const char*)nativePacket->data; // skip the packet identifier message++; if(isEmptyString(message) == true) { getPeer()->log(ELogType_Error, "received an empty chat message"); } else { // TODO: @student : split the packet ... ChatMessage chatMessage("---", message); addChatMessage(chatMessage); } } break; case NETMSG_ID_JSONOBJECT: { // TODO: @student : this might not be enough ... const char* message = (const char*)nativePacket->data; // skip the packet identifier message++; if(isEmptyString(message) == true) { getPeer()->log(ELogType_Error, "received an empty chat message"); } else { SLAString json(message); getPeer()->log(ELogType_Info, "received json %s", json.c_str()); CCDictionary* dictionary = CCJSONConverter::dictionaryFrom(json.c_str()); getPeer()->log(ELogType_Info, dictionary); // DONE: @student : read the relevant dictionary members and pass them to the chat message CCObject *aMessage = dictionary->objectForKey("message"); CCDictionary *messDictionary = dynamic_cast<CCDictionary*>(aMessage); const CCString *aSender = messDictionary->valueForKey("sender"); const CCString *aContent = messDictionary->valueForKey("content"); ChatMessage chatMessage(aSender->getCString(), aContent->getCString()); addChatMessage(chatMessage); } } break; default: break; } }
// TODO: @student : extend the protocol. // so the receiver can split the package into name and content void AbstractChatNetPackageSender::sendChatLine(const SLAString& text) { // safety check ... if(text.length() > 2000) { getPeer()->log(ELogType_Error, "ERROR text message is to long"); } else if(text.length() == 0) { return; } else if(_sendMessage._content.compare(text.c_str()) == 0) { // prevent spam return; } _sendMessage._sender = _name; _sendMessage._content = text; const SLSize messageSize(2048); char message[messageSize]; memset(message,0,sizeof(char) * messageSize); // the first byte carries the message id message[0] = (char)(NETMSG_ID_CHATLINE); strcat(message, _sendMessage._sender.c_str()); strcat(message, " - "); strcat(message, _sendMessage._content.c_str()); // Message now holds what we want to broadcast // message is the data to send // strlen(message) + 1 is to send the null terminator sendData(message, (const int) strlen(message) + 1); // TODO: @student : split into 2 functions and let the chat work with json. // note: this is just a little json how to ... if(getPeer()->isServer()) { if(NetworkState::getBool(getPeer()->getPeerConfiguration(),NL_SERIALIZEKEY_SERVER_SEND_JSON_AUTOMESSAGES,false)) { CCDictionary* messageDictionary(CCDictionary::create()); CCDictionary* singleMessageDictionary(CCDictionary::create()); messageDictionary->setObject(singleMessageDictionary, "message"); singleMessageDictionary->setObject(CCString::create(text.c_str()),"content"); singleMessageDictionary->setObject(CCString::create(_name.c_str()),"sender"); CCString* json = CCJSONConverter::strFrom(messageDictionary); // zero out the data which have been send previously memset(message,0,sizeof(char) * messageSize); message[0] = (char)(NETMSG_ID_JSONOBJECT); strcat(message, json->getCString()); sendData(message, (const int) strlen(message)+1); } } }
void GameObjectReplica::DeallocReplica(RakNet::Connection_RM3 *sourceConnection) { // note: if the source connection is null then the replicamanager is Deallocating // the replicas he's created // the default implementation calls delete this !!! // we do not want this // instead we remove the actor from the scene // so - do not call the base class #if SL_CODERVERSION_CP if(getPeer() != nullptr) { getPeer()->log(ELogType_Message, "DeallocReplica: %s", getName().C_String()); } else { SL_PROCESS_APP()->log(ELogType_Message, "DeallocReplica: %s", getName().C_String()); } #endif // the 'default' implementation 'delete this' // would finally lead to the destructor implementation // of replica3 // which does a final call to replica manager Dereference // so we mimic this implementation here // and set the replica manager to null afterwards // this might actually destroy the whole object // so we need to do smth to stay alive // until we leave the function if(_replicaComponent != nullptr) { GameActorComponentPtr replicaComponentPtr(_replicaComponent); { replicaComponentPtr->removeFromGameplayLayer(); _replicaComponent = nullptr; if (replicaManager) { replicaManager->Dereference(this); // mimic the network id object destructor code if(GetNetworkIDManager() != nullptr) { GetNetworkIDManager()->StopTrackingNetworkIDObject(this); } replicaManager = nullptr; } setPeer(nullptr); } } else { if (replicaManager) { replicaManager->Dereference(this); replicaManager = nullptr; } setPeer(nullptr); } }
ReplicaManager* GameObjectReplica::getReplicaManager() const { // first we try to retrieve the replica manager directly from the replica it self // this might not always be successful therefor the fall back if(replicaManager != nullptr) { return dynamic_cast<ReplicaManager*>(replicaManager); } if(getPeer() != nullptr) { return getPeer()->getReplicaManager(); } return nullptr; }
void ClientChatNetPackageSender::onCtrlEditEnd(CCObject* sender) { // note: the notification center spreads the function call // to every registered observer // so you have to explicitly check if // the sender is the object you want to deal with CCControlEditBox* editBox(dynamic_cast<CCControlEditBox*>(sender)); if(editBox != nullptr) { const char* editContent(editBox->getTextField()->getString()); if(sl::isEmptyString(editContent) == false) { if(editBox == _ctrlName) { getPeer()->log(ELogType_Message, "%s name is:%s", __FUNCTION__, editContent); _name = editContent; } else if(editBox == _ctrlMessage) { getPeer()->log(ELogType_Message, "%s message is:%s", __FUNCTION__, editContent); // we can now send this message ... //Security Checks if (strlen(editContent) > 2000) { getPeer()->log(ELogType_Error, "ERROR text message is too long"); } else if (strlen(editContent) == 0) { return; } CCDictionary* messageDictionary(CCDictionary::create()); CCDictionary* singleMessageDictionary(CCDictionary::create()); messageDictionary->setObject(singleMessageDictionary, "message"); singleMessageDictionary->setObject(CCString::create(editContent),"content"); singleMessageDictionary->setObject(CCString::create(_name),"sender"); CCString* json = CCJSONConverter::strFrom(messageDictionary); const SLSize messageSize(2048); char message[messageSize]; // zero out the data which have been send previously memset(message,0,sizeof(char) * messageSize); message[0] = (char)(NETMSG_ID_JSONOBJECT); strcat(message, json->getCString()); sendData(message, (const int) strlen(message)+1); //OLD: we can now send this message ... //SLAString message(editContent); //this->sendChatLine(message); editBox->getTextField()->setString(nullptr); } } } }
//============================================================================== static AndroidComponentPeer* findPeerForJavaView (JNIEnv* env, jobject viewToFind) { for (int i = getNumPeers(); --i >= 0;) { AndroidComponentPeer* const ap = static_cast <AndroidComponentPeer*> (getPeer(i)); jassert (dynamic_cast <AndroidComponentPeer*> (getPeer(i)) != nullptr); if (env->IsSameObject (ap->view.get(), viewToFind)) return ap; } return nullptr; }
bool ResizableWindow::isMinimised() const { if (auto* peer = getPeer()) return peer->isMinimised(); return false; }
bool ResizableWindow::isMinimised() const { if (ComponentPeer* const peer = getPeer()) return peer->isMinimised(); return false; }
void WebBrowserComponent::checkWindowAssociation() { if (isShowing()) { if (browser->browser == nullptr && getPeer() != nullptr) { browser->createBrowser(); reloadLastURL(); } else { if (blankPageShown) goBack(); } } else { if (browser != nullptr && unloadPageWhenBrowserIsHidden && ! blankPageShown) { // when the component becomes invisible, some stuff like flash // carries on playing audio, so we need to force it onto a blank // page to avoid this.. blankPageShown = true; browser->goToURL ("about:blank", 0, 0); } } }
bool Sink::startHook() { unsigned int buffer_space(1); // 0 == base time (backup, for other messages that do not have time stamps) std::stringstream column_buffer; column_buffer << "time, "; for(unsigned int i = 0; i < m_ports.size(); ++i) { if(!m_ports[i]->configure())// Determine amongst others the number of data elements of each port { log(Error) << "Could not configure port: " << *(m_ports[i]->port_name) << endlog(); return false; } buffer_space += m_ports[i]->nr_of_elements; if(i != 0) { column_buffer << ", "; } if(!m_ports[i]->getElementNames(column_buffer)) { log(Error) << "Could not get the column names for port: " << *(m_ports[i]->port_name) << endlog(); return false; } } // Create the write buffer m_buffer.data.resize(buffer_space, 0.0); buffer.setDataSample(m_buffer); // Setup buffer refs unsigned int elems = 1; for(unsigned int i = 0; i < m_ports.size(); ++i) { m_ports[i]->buffer = m_buffer.data.begin()+elems; elems += m_ports[i]->nr_of_elements; } // store column names in file writer OperationCaller<void(std::string) > op_setColumnNames; TaskContext* task_ptr = getPeer("FileWriter"); if(task_ptr == NULL) { log(Error) << "Could not find peer FileWriter" << endlog(); return false; } op_setColumnNames = task_ptr->getOperation("writeLine"); if(!op_setColumnNames.ready()) { log(Error) << "Could not connect to FileWriter.writeLine" << endlog(); return false; } op_setColumnNames(column_buffer.str()); m_start_time = ros::Time::now(); return TaskContext::startHook(); }
void OpenGLComponent::paint (Graphics&) { ComponentPeer* const peer = getPeer(); if (useThread) { if (peer != nullptr && isShowing()) { #if ! JUCE_LINUX updateContext(); #endif if (! threadStarted) { threadStarted = true; startRenderThread(); } } } else { updateContext(); if (! renderAndSwapBuffers()) return; } if (peer != nullptr) { const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition()); peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight()); } }
virtual void copyTo(ISecUser& destination) { destination.setAuthenticateStatus(getAuthenticateStatus()); destination.setName(getName()); destination.setFullName(getFullName()); destination.setFirstName(getFirstName()); destination.setLastName(getLastName()); destination.setEmployeeID(getEmployeeID()); destination.setRealm(getRealm()); destination.setFqdn(getFqdn()); destination.setPeer(getPeer()); destination.credentials().setPassword(credentials().getPassword()); destination.credentials().setSessionToken(credentials().getSessionToken()); destination.credentials().setSignature(credentials().getSignature()); CDateTime exp; credentials().getPasswordExpiration(exp); destination.credentials().setPasswordExpiration(exp); CDateTime tmpTime; destination.setPasswordExpiration(getPasswordExpiration(tmpTime)); destination.setStatus(getStatus()); CriticalBlock b(crit); Owned<IPropertyIterator> Itr = m_parameters->getIterator(); ForEach(*Itr) { destination.setProperty(Itr->getPropKey(),m_parameters->queryProp(Itr->getPropKey())); } // DBGLOG("Copied name %s to %s",getName(),destination.getName()); }
void processConnect(int peerid, Json::Value message){ std::vector<std::string> channels; rtc::JsonArrayToStringVector(message["channels"], &channels); getPeer()->onConnectionRequest(peerid, channels); }
JNIEXPORT jstring JNICALL Java_com_codeminders_hidapi_HIDDevice_getIndexedString (JNIEnv *env, jobject self, jint index) { hid_device *peer = getPeer(env, self); if(!peer) { throwIOException(env, peer); return NULL; /* not an error, freed previously */ } wchar_t data[MAX_BUFFER_SIZE]; int res = hid_get_indexed_string(peer, index, data, MAX_BUFFER_SIZE); if(res < 0) { /* We decided not to treat this as an error, but return an empty string in this case throwIOException(env, peer); return NULL; */ data[0] = 0; } char *u8 = convertToUTF8(env, data); jstring string = env->NewStringUTF(u8); free(u8); return string; }
void Connection::send(u16 peer_id, u8 channelnum, SharedBuffer<u8> data, bool reliable) { { //MutexAutoLock peerlock(m_peers_mutex); if (m_peers.find(peer_id) == m_peers.end()) return; } //dout_con<<getDesc()<<" sending to peer_id="<<peer_id<<std::endl; assert(channelnum < CHANNEL_COUNT); ENetPacket *packet = enet_packet_create(*data, data.getSize(), reliable ? ENET_PACKET_FLAG_RELIABLE : 0); ENetPeer *peer = getPeer(peer_id); if(!peer) { deletePeer(peer_id, false); return; } if (enet_peer_send(peer, channelnum, packet) < 0) { infostream<<"enet_peer_send failed peer="<<peer_id<<" reliable="<<reliable<< " size="<<data.getSize()<<std::endl; if (reliable) deletePeer(peer_id, false); return; } }
JNIEXPORT jint JNICALL Java_com_codeminders_hidapi_HIDDevice_readTimeout (JNIEnv *env, jobject self, jbyteArray data, jint milliseconds ) { hid_device *peer = getPeer(env, self); if(!peer) { throwIOException(env, peer); return 0; /* not an error, freed previously */ } jsize bufsize = env->GetArrayLength(data); jbyte *buf = env->GetByteArrayElements(data, NULL); int read = hid_read_timeout(peer, (unsigned char*) buf, bufsize, milliseconds); env->ReleaseByteArrayElements(data, buf, read==-1?JNI_ABORT:0); if(read == 0) /* time out */ { return 0; } else if(read == -1) { throwIOException(env, peer); return 0; /* not an error, freed previously */ } return read; }
void DirectShowComponent::paint (Graphics& g) { if (videoLoaded) { if (needToRecreateNativeWindow) { context->peerChanged(); needToRecreateNativeWindow = false; } if (needToUpdateViewport) { context->updateVideoPosition(); needToUpdateViewport = false; } context->repaint(); ComponentPeer* const peer = getPeer(); if (peer != nullptr) peer->addMaskedRegion (getScreenBounds() - peer->getScreenPosition()); } else { g.fillAll (Colours::grey); } }
void MainComponent::parentHierarchyChanged() { auto* newPeer = getPeer(); if (peer != newPeer) { peer = newPeer; auto previousRenderingEngine = renderingEngines[currentRenderingEngineIdx]; renderingEngines.clear(); if (peer != nullptr) renderingEngines = peer->getAvailableRenderingEngines(); renderingEngines.add ("OpenGL Renderer"); currentRenderingEngineIdx = renderingEngines.indexOf (previousRenderingEngine); if (currentRenderingEngineIdx < 0) { #if JUCE_ANDROID currentRenderingEngineIdx = (renderingEngines.size() - 1); #else currentRenderingEngineIdx = peer->getCurrentRenderingEngine(); #endif } updateRenderingEngine (currentRenderingEngineIdx); } }
int handleWrite(NINA::NINAHandle) { std::cout << "Sending reply ..." << std::endl; getPeer().send(mBuf, mSize); NINA::Reactor<POLICY>::getSingleton().removeHandler(this, NINA::Events::WRITE); return 0; }
void ResizableWindow::setFullScreen (const bool shouldBeFullScreen) { if (shouldBeFullScreen != isFullScreen()) { updateLastPos(); fullscreen = shouldBeFullScreen; if (isOnDesktop()) { if (ComponentPeer* const peer = getPeer()) { // keep a copy of this intact in case the real one gets messed-up while we're un-maximising const Rectangle<int> lastPos (lastNonFullScreenPos); peer->setFullScreen (shouldBeFullScreen); if ((! shouldBeFullScreen) && ! lastPos.isEmpty()) setBounds (lastPos); } else { jassertfalse; } } else { if (shouldBeFullScreen) setBounds (0, 0, getParentWidth(), getParentHeight()); else setBounds (lastNonFullScreenPos); } resized(); } }
virtual void copyTo(ISecUser& destination) { destination.setAuthenticateStatus(getAuthenticateStatus()); destination.setName(getName()); destination.setFullName(getFullName()); destination.setFirstName(getFirstName()); destination.setLastName(getLastName()); destination.setRealm(getRealm()); destination.setFqdn(getFqdn()); destination.setPeer(getPeer()); destination.credentials().setPassword(credentials().getPassword()); CDateTime tmpTime; destination.setPasswordExpiration(getPasswordExpiration(tmpTime)); destination.setStatus(getStatus()); if(m_parameters.get()==NULL) return; CriticalBlock b(crit); Owned<IPropertyIterator> Itr = m_parameters->getIterator(); Itr->first(); while(Itr->isValid()) { destination.setProperty(Itr->getPropKey(),m_parameters->queryProp(Itr->getPropKey())); Itr->next(); } //addToken is not currently implemented.... // DBGLOG("Copied name %s to %s",getName(),destination.getName()); }