uint8_t BayRF24::sendPayload(void) { if (_powerdown) powerUp(); else stopListening(); openWritingPipe (_pipe); uint8_t res; res = RF24::write(getPayload(), getPacketLength()); uint8_t curr_pa = 0; while (!res && curr_pa < 4) { setPALevel((rf24_pa_dbm_e) curr_pa); delayMicroseconds(random(2000)); res = RF24::write(getPayload(), getPacketLength()); curr_pa++; } if (_powerdown) powerDown(); else { txStandBy(); startListening(); } return !res; }
void FarDlgContainer::DefSize(intptr_t & sumw, intptr_t & sumh, intptr_t & fit) { sumw = sumh = 0; intptr_t groupw = 0; intptr_t grouph = 0; fit = getPayload()(L"FitWidth").operator int(); for (size_t Index = 0; Index < childs.size(); Index++) { FarDlgNode & obj = child(Index); if (obj(L"Visible")) { intptr_t w, h, f; obj.DefSize(w, h, f); groupw += w + 2; if (h > grouph) grouph = h; if (!obj(L"NoBreak")) { if (groupw - 2 > sumw) sumw = groupw - 2; sumh += grouph; groupw = grouph = 0; } } } }
void OctreeHeadlessViewer::queryOctree() { char serverType = getMyNodeType(); PacketType packetType = getMyQueryMessageType(); if (_hasViewFrustum) { ConicalViewFrustums views { _viewFrustum }; _octreeQuery.setConicalViews(views); } else { _octreeQuery.clearConicalViews(); } auto nodeList = DependencyManager::get<NodeList>(); auto node = nodeList->soloNodeOfType(serverType); if (node && node->getActiveSocket()) { auto queryPacket = NLPacket::create(packetType); // encode the query data auto packetData = reinterpret_cast<unsigned char*>(queryPacket->getPayload()); int packetSize = _octreeQuery.getBroadcastData(packetData); queryPacket->setPayloadSize(packetSize); // make sure we still have an active socket nodeList->sendUnreliablePacket(*queryPacket, *node); } }
/** * Finalize at most the first 'count' elements of the allocation by applying * the finalizer to each element in turn, from last to first, thus ensuring * that elements of the array are destroyed in the opposite order to that in * which they were created. */ void Header::finalize(count_t count) { if (finalizer_t f = getFinalizer()) // Not yet finalized? { size_t n = getElementSize(); // ...size of element size_t c = std::min(getElementCount(),count); // ...el's to destroy byte_t* p = getPayload(); // ...head of payload byte_t* q = p + c * n; // ...tail of payload /* Clear the 'finalizer' flag to signal that the finalization has been taken care of. We do so *before* invoking 'f', in case 'f' goes and frees the entire allocation in which the header sits, as happens to the underlying pages of class ScopedArena, for example...*/ _flags &= ~finalizer; // ...taken care of /* Finalize each of the elements from the end of the array back toward its beginning, that is, in the opposite order to that in which they were first constructed...*/ for (size_t i=0; i!=c; ++i) // ...for each element { f(q -= n); // ....call finalizer } /* It is now no longer safe to access any of this object's members...*/ } }
void PNGHandler::handle() { const ScrapeData::Data *data = getPayload(); // std::cout << "Item[" << getId() << "] handler [png]" << std::endl; lodepng::State state; std::vector<unsigned char> image; std::vector<unsigned char> buffer(data->payload().begin(), data->payload().end()); unsigned width, height; unsigned error = lodepng::decode(image, width, height, state, reinterpret_cast<const unsigned char *>(data->payload().c_str()), data->payload().size()); if (error) { std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; return; } std::cout << "Filesize: " << buffer.size() << " (" << buffer.size() / 1024 << "K)" << std::endl; addMeta("image_width", reinterpret_cast<unsigned int>(width)); std::cout << "Width: " << width << std::endl; addMeta("image_height", reinterpret_cast<unsigned int>(height)); std::cout << "Height: " << height << std::endl; addMeta("image_pixels", reinterpret_cast<unsigned int>(width * height)); std::cout << "Num pixels: " << width * height << std::endl; displayPNGInfo(state.info_png); }
bufferStruct receiveSendData(bufferStruct buffer){ bufferStruct result; if(getAck(buffer.bufferLength, buffer.buffer) & NEED_ACK > 0){ #if STATE_UART_DEBUG >= 2 uart_putstr ("seAck\r\n"); #endif state = STATE_SENDING_ACK; backupData.bufferLength = buffer.bufferLength; memcpy(backupData.buffer, buffer.buffer, buffer.bufferLength); sendAck(buffer); } else { result.bufferLength = getPayloadLength(buffer.bufferLength, buffer.buffer); memcpy(result.buffer, getPayload(buffer.bufferLength, buffer.buffer), result.bufferLength); #if STATE_UART_DEBUG >= 3 uart_putc('%'); uart_putc(result.bufferLength); uart_putc('%'); for(uint8_t i = 0; i < result.bufferLength; ++i){ uart_putc(result.buffer[i]); } uart_putc('%'); #endif } return result; }
/* * status = recToBinKey(rwrec, bin_val, &index, NULL); * * Given the SiLK Flow record 'rwrec', compute the flow-rate ratio * specified by '*index', and write a binary representation of * that value into 'bin_val'. */ static skplugin_err_t recToBinKey( const rwRec *rwrec, uint8_t *bin_value, void *idx, void UNUSED(**extra)) { uint64_t val_u64; switch (*((unsigned int*)(idx))) { case PAYLOAD_BYTES_KEY: val_u64 = getPayload(rwrec); break; case PAYLOAD_RATE_KEY: val_u64 = DOUBLE_TO_UINT64(PAYLOAD_RATE_RWREC(rwrec)); break; case PCKTS_PER_SEC_KEY: val_u64 = DOUBLE_TO_UINT64(PCKT_RATE_RWREC(rwrec)); break; case BYTES_PER_SEC_KEY: val_u64 = DOUBLE_TO_UINT64(BYTE_RATE_RWREC(rwrec)); break; case BYTES_PER_PACKET_KEY: val_u64 = DOUBLE_TO_UINT64(BYTES_PER_PACKET_RWREC(rwrec)); break; default: return SKPLUGIN_ERR_FATAL; } val_u64 = hton64(val_u64); memcpy(bin_value, &val_u64, RATE_BINARY_SIZE_KEY); return SKPLUGIN_OK; }
// 1) The request uri should be /actor_name/admin_module/admin_attributes?parameter=parameter_value,parameter=parameter_value // / root /cell[0] / cell[1] / parameters // /<-- request path --------------------------------------------------------------->/ void AdminAsyncServlet::doGet(idgs::http::server::HttpRequest& req) { VLOG(2) << "doGet for http req: " << req.getRequestPath(); std::string actorName = req.getRootPath(); std::shared_ptr<google::protobuf::Message> payload; if (!getPayload(req.getRequestPath(), payload) ) { LOG(ERROR) << "get pay load error for request " << req.getRequestPath(); idgs::http::server::HttpResponse rep = idgs::http::server::HttpResponse::createReply(idgs::http::server::HttpResponse::bad_request, "get pay load error"); handler(rep); return; } if (req.getBody() != "") { /// } idgs::actor::ActorMessagePtr actorMsg(new idgs::actor::ActorMessage); actorMsg->setSourceActorId(getActorId()); int32_t localMemId = idgs::util::singleton<idgs::Application>::getInstance().getMemberManager()->getLocalMemberId(); actorMsg->setSourceMemberId(localMemId); actorMsg->setOperationName("get"); actorMsg->setPayload(payload); actorMsg->setDestActorId(actorName); actorMsg->setDestMemberId(actorMsg->getSourceMemberId()); VLOG(3) << "has sent http actor message: " << actorMsg->toString(); idgs::util::singleton<idgs::actor::RpcFramework>::getInstance().getActorFramework()->sendMessage(actorMsg); }
ErrorResponse::ErrorResponse(const std::vector<uint8_t>& response) : Response(Type::Error) { auto payload = getPayload(response); // We don't have a request type, so less length checking is done ahead of time if (payload.size() != 1) throw std::invalid_argument("Invalid error response payload size"); m_error = (Error) payload[0]; }
static skplugin_err_t addRecToBinAgg( const rwRec *rwrec, uint8_t *dest, void *idx, void UNUSED(**extra)) { uint64_t val[2]; switch (*((unsigned int*)(idx))) { case PAYLOAD_BYTES_AGG: memcpy(val, dest, sizeof(uint64_t)); val[0] += getPayload(rwrec); memcpy(dest, val, sizeof(uint64_t)); return SKPLUGIN_OK; case PAYLOAD_RATE_AGG: memcpy(val, dest, RATE_BINARY_SIZE_AGG); val[0] += getPayload(rwrec); val[1] += RWREC_MICRO_DURATION(rwrec); memcpy(dest, val, RATE_BINARY_SIZE_AGG); return SKPLUGIN_OK; case PCKTS_PER_SEC_AGG: memcpy(val, dest, RATE_BINARY_SIZE_AGG); val[0] += rwRecGetPkts(rwrec); val[1] += RWREC_MICRO_DURATION(rwrec); memcpy(dest, val, RATE_BINARY_SIZE_AGG); return SKPLUGIN_OK; case BYTES_PER_SEC_AGG: memcpy(val, dest, RATE_BINARY_SIZE_AGG); val[0] += rwRecGetBytes(rwrec); val[1] += RWREC_MICRO_DURATION(rwrec); memcpy(dest, val, RATE_BINARY_SIZE_AGG); return SKPLUGIN_OK; case BYTES_PER_PACKET_AGG: memcpy(val, dest, RATE_BINARY_SIZE_AGG); val[0] += rwRecGetBytes(rwrec); val[1] += rwRecGetPkts(rwrec); memcpy(dest, val, RATE_BINARY_SIZE_AGG); return SKPLUGIN_OK; } return SKPLUGIN_ERR_FATAL; }
PubsubsqlListNode::PubsubsqlListNode(const size_t aNodeSizeB, const char* aString, const size_t aStringLen) : mSizeB(aNodeSizeB) , mStringLen(aStringLen) , mNext(nullptr) { char* dst = static_cast<char*>(getPayload()); strncpy(dst, aString, aStringLen); dst[aStringLen] = '\0'; // guard }
void Datagram::deserializeToDatagram(unsigned char *datagramChars, int datagramLength) { seqNumber = convertToInteger(datagramChars, 0); ackNumber = convertToInteger(datagramChars, 4); ackFlag = convertToBoolean(datagramChars, 8); finFlag = convertToBoolean(datagramChars, 9); length = convertToShort(datagramChars, 10); data = getPayload(datagramChars, length); }
//---------------------------------------------------------------- // IElement::mustSave // bool IElement::mustSave() const { const IPayload & payload = getPayload(); return (fixedSize_ || (storageFlags_ & kAlwaysSave) || !payload.isDefault() || (payload.isComposite() && payload.hasVoid())); }
HelloResponse::HelloResponse(const HelloRequest& UNUSED(request), const std::vector<uint8_t>& response) : Response(Type::Hello) { auto payload = getPayload(response); // getPayload will do size checking for us uint8_t protocolVersion = payload[0]; uint8_t resetFlags = payload[1]; std::string deviceConfig(payload.begin() + 2, payload.end()); m_devInfo = std::make_shared<DeviceInfo>(protocolVersion, resetFlags, deviceConfig); }
/* == operator */ bool SFPacket::operator==(SFPacket const& pPacket) { bool retval=false; if((pPacket.getType() == type) && (pPacket.getLength() == length) && (pPacket.getSeqno() == seqno)) { if((type == SF_PACKET_ACK) || (type == SF_PACKET_NO_ACK)) { retval = (memcmp(pPacket.getPayload(), getPayload(), length) == 0); } } return retval; }
void InbReq<&yajr::rpc::method::echo>::process() const { LOG(DEBUG); OutboundResult ( this, GeneratorFromValue(getPayload()) /* payload from inbound req */ ) . send(); }
void *ChangeLightRepresentation (void *param) { (void)param; OCStackResult result = OC_STACK_ERROR; uint8_t j = 0; uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2; OCObservationId obsNotify[numNotifies]; while (!gQuitFlag) { sleep(3); Light.power += 5; if (gLightUnderObservation) { OIC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power); if (gObserveNotifyType == 1) { // Notify list of observers. Alternate observers on the list will be notified. j = 0; for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2)) { if (interestedObservers[i].valid == true) { obsNotify[j] = interestedObservers[i].observationId; j++; } } OCRepPayload* payload = getPayload(gResourceUri, Light.power, Light.state); result = OCNotifyListOfObservers (Light.handle, obsNotify, j, payload, OC_NA_QOS); OCRepPayloadDestroy(payload); } else if (gObserveNotifyType == 0) { // Notifying all observers result = OCNotifyAllObservers (Light.handle, OC_NA_QOS); if (OC_STACK_NO_OBSERVERS == result) { OIC_LOG (INFO, TAG, "=======> No more observers exist, stop sending observations"); gLightUnderObservation = 0; } } else { OIC_LOG (ERROR, TAG, "Incorrect notification type selected"); } } } return NULL; }
int main(void) { uint8_t src_packet[128] = {0x05, 0x30, 0x00, 0x00, 0x0A}; uint8_t rcvd_msg[128] = {0}; uint8_t rcvd_payload[128] = {0}; uint8_t rcvd_length; uint8_t rcvd_payloadLength; uint8_t rcvd_rssi; uint8_t Type; uint16_t Addr; uint8_t radio_channel; uint16_t radio_panID; Type = Type_Light; Addr = 0x0001; radio_channel = 18; radio_panID = 0x00AA; Initial(Addr, Type, radio_channel, radio_panID); setTimer(1,RETRANSMIT_PERIOD,UNIT_MS); while(1){ // Periodically send the msg if(checkTimer(1)){ RF_Tx(0xFFFF,src_packet,5); } // When received some packet if(RF_Rx(rcvd_msg, &rcvd_length, &rcvd_rssi)){ getPayloadLength(&rcvd_payloadLength, rcvd_msg); getPayload(rcvd_payload, rcvd_msg, rcvd_payloadLength); // Check 1)header, 2)sequence number, 3)isACK field if(rcvd_payload[0]==0x05 && rcvd_payload[1]==0x30 && rcvd_payload[2]==src_packet[2] && rcvd_payload[3]==1){ src_packet[2]++; // Change the payload here } } if(src_packet[2]==0x14) break; } while(1){ if(checkTimer(1)){ setGPIO(1,1); } } }
// jbodah void printPacketContents( packet *newPacket ) { char dstString[30] ; bufFlush( dstString ) ; getVerboseFrameKind(newPacket, dstString) ; printf( "\tseqNum\t\t'%c' %d \n\tframeKind\t%s \n\tpayload\t\t%s \n\tCRC\t\t'%c' %d\n", getSeqNum(newPacket), (int)getSeqNum(newPacket), dstString, getPayload(newPacket), getCRC(newPacket), (int)getCRC(newPacket) ) ; }
std::shared_ptr<ActorMessage> ActorMessage::createMulticastMessage() { int32_t sourceMemberId = ::idgs::util::singleton<idgs::cluster::ClusterFramework>::getInstance().getMemberManager()->getLocalMemberId(); std::shared_ptr<ActorMessage> multMsg = std::make_shared < ActorMessage > (*this); RpcMessage* rpcMsg = multMsg->getRpcMessage().get(); rpcMsg->mutable_source_actor()->set_member_id(sourceMemberId); rpcMsg->mutable_dest_actor()->set_member_id(ALL_MEMBERS); rpcMsg->set_channel(TC_MULTICAST); multMsg->setPayload(getPayload()); return multMsg; }
void AbstractAudioInterface::emitAudioPacket(const void* audioData, size_t bytes, quint16& sequenceNumber, const Transform& transform, glm::vec3 avatarBoundingBoxCorner, glm::vec3 avatarBoundingBoxScale, PacketType packetType, QString codecName) { static std::mutex _mutex; using Locker = std::unique_lock<std::mutex>; auto nodeList = DependencyManager::get<NodeList>(); SharedNodePointer audioMixer = nodeList->soloNodeOfType(NodeType::AudioMixer); if (audioMixer && audioMixer->getActiveSocket()) { Locker lock(_mutex); auto audioPacket = NLPacket::create(packetType); // FIXME - this is not a good way to determine stereoness with codecs.... quint8 isStereo = bytes == AudioConstants::NETWORK_FRAME_BYTES_STEREO ? 1 : 0; // write sequence number auto sequence = sequenceNumber++; audioPacket->writePrimitive(sequence); // write the codec audioPacket->writeString(codecName); if (packetType == PacketType::SilentAudioFrame) { // pack num silent samples quint16 numSilentSamples = isStereo ? AudioConstants::NETWORK_FRAME_SAMPLES_STEREO : AudioConstants::NETWORK_FRAME_SAMPLES_PER_CHANNEL; audioPacket->writePrimitive(numSilentSamples); } else { // set the mono/stereo byte audioPacket->writePrimitive(isStereo); } // pack the three float positions audioPacket->writePrimitive(transform.getTranslation()); // pack the orientation audioPacket->writePrimitive(transform.getRotation()); audioPacket->writePrimitive(avatarBoundingBoxCorner); audioPacket->writePrimitive(avatarBoundingBoxScale); if (audioPacket->getType() != PacketType::SilentAudioFrame) { // audio samples have already been packed (written to networkAudioSamples) int leadingBytes = audioPacket->getPayloadSize(); audioPacket->setPayloadSize(leadingBytes + bytes); memcpy(audioPacket->getPayload() + leadingBytes, audioData, bytes); } nodeList->flagTimeForConnectionStep(LimitedNodeList::ConnectionStep::SendAudioPacket); nodeList->sendUnreliablePacket(*audioPacket, *audioMixer); } }
bool LLNotification::payloadContainsAll(const std::vector<std::string>& required_fields) const { for(std::vector<std::string>::const_iterator required_fields_it = required_fields.begin(); required_fields_it != required_fields.end(); required_fields_it++) { std::string required_field_name = *required_fields_it; if( ! getPayload().has(required_field_name)) { return false; // a required field was not found } } return true; // all required fields were found }
//---------------------------------------------------------------- // IElement::setCrc32 // IElement & IElement::setCrc32(bool enableCrc32) { if (enableCrc32 && getPayload().isComposite()) { storageFlags_ |= kComputeCrc32; } else { storageFlags_ &= ~kComputeCrc32; } return *this; }
//This function takes the request as an input and returns the response OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest) { if(!ehRequest) { return nullptr; } if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION) { OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation")); return nullptr; } return getPayload(gResourceUri, Light.brightness); }
XMLMessageBean* XMLMessage::getBean() { XMLMessageBean* resultBean = (XMLMessageBean*)NULL; if (!hasPayload()) return resultBean; // NULL char *data = (char*)getPayload()->data(); if (data == NULL) return resultBean; // NULL // // Hugh hack to get message number quickly. // const char *messagePrefix = "<MessageType type=\"int\">", *messageSuffix = "</MessageType>"; char *messnumBegin = NULL, *messnumEnd = NULL; if ((messnumBegin = strstr(data, messagePrefix)) == NULL) return resultBean; // NULL if ((messnumEnd = strstr(messnumBegin, messageSuffix)) == NULL) return resultBean; // NULL // Should be replaced with a call to xml.datatype.DataTypeInt::decode() messnumBegin += strlen(messagePrefix); char *cp = messnumBegin; while (cp != messnumEnd) { if (!isdigit(*cp)) // Check for junk return resultBean; // NULL cp++; } int numLen = messnumEnd - messnumBegin; char *strNum = new char[numLen+1]; /** CJM 09-09-05.. fix for memory instability */ memset( strNum, 0x00, numLen+1 ); strncpy(strNum, messnumBegin, numLen); int mNum = atoi(strNum); delete[] strNum; if (m_ApplicationBean != NULL) resultBean = m_ApplicationBean->getXMLMessageBean(mNum); if (resultBean != NULL) resultBean->decode(data); return resultBean; }
int HardwareState::getValue(int module, bool i2c){ switch (module){ case HW_ENERGY_MODULE: return getEnergy(i2c); case HW_PAYLOAD_MODULE: return getPayload(i2c); case HW_SBAND_MODULE: return getSband(i2c); case HW_SOLARP_MODULE: return getSolarPanels(i2c); case HW_TEMP_MODULE: return getTemperature(i2c); case HW_TERMAL_CTRL_MODULE: return getThermalControl(i2c); } }
/* * status = filter(rwrec, data, NULL); * * The function actually used to implement filtering for the * plugin. Returns SKPLUGIN_FILTER_PASS if the record passes the * filter, SKPLUGIN_FILTER_FAIL if it fails the filter. */ static skplugin_err_t filter( const rwRec *rwrec, void UNUSED(*cbdata), void UNUSED(**extra)) { uint64_t payload; double rate; /* filter by payload-bytes */ if (payload_bytes.is_active) { payload = getPayload(rwrec); if (payload < payload_bytes.min || payload > payload_bytes.max) { /* failed */ return SKPLUGIN_FILTER_FAIL; } } /* filter by payload-rate */ if (payload_rate.is_active) { rate = PAYLOAD_RATE_RWREC(rwrec); if (rate < payload_rate.min || rate > payload_rate.max) { /* failed */ return SKPLUGIN_FILTER_FAIL; } } /* filter by packets-per-second */ if (pckt_rate.is_active) { rate = PCKT_RATE_RWREC(rwrec); if (rate < pckt_rate.min || rate > pckt_rate.max) { /* failed */ return SKPLUGIN_FILTER_FAIL; } } /* filter by bytes-per-second */ if (byte_rate.is_active) { rate = BYTE_RATE_RWREC(rwrec); if (rate < byte_rate.min || rate > byte_rate.max) { /* failed */ return SKPLUGIN_FILTER_FAIL; } } return SKPLUGIN_FILTER_PASS; }
string Packet::toString() const{ // Serialize this object for the network string delimiter = "\n"; stringstream serialization; serialization << getType(); serialization << delimiter; struct tm *nowtm; char tmbuf[64] ; nowtm = localtime(&timeSent); strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm); string timeString (tmbuf); serialization << timeString; serialization << delimiter; serialization << getLifeTime(); serialization << delimiter; serialization << getPacketNumber(); serialization << delimiter; serialization << getHopCount(); serialization << delimiter; serialization << getSourceAddress(); serialization << delimiter; serialization << getDestinationAddress(); serialization << delimiter; serialization << getPayload(); return serialization.str(); }
/** * Return true if the object looks to be in good shape. Centralizes a number * of consistency checks that would otherwise clutter up the code, and, since * only ever called from within assertions, can be eliminated entirely by the * compiler from the release build. */ bool Header::consistent() const { /* A vector finalizer implies having a non-trivial array element count...*/ if (has(vectorFinalizer)) // Vector finalizer? { assert(getElementCount() >= 2); // ...proper count } else { assert(getElementCount() == 1); // ...trivial count } assert(has(finalizer) == (getFinalizer()!=0)); // Check finalizer() assert(aligned(getPayload())); // Check it's aligned return true; // Appears to be good }
/** Unpacks a message from a zeromq message */ static Message unpack(const zmq::message_t &msg) { auto begin = reinterpret_cast<const capnp::word*>(msg.data()); // NOLINT auto end = reinterpret_cast<const capnp::word*>(static_cast<const char*>(msg.data()) + msg.size()); // NOLINT kj::ArrayPtr<const capnp::word> ptr(begin, end); capnp::FlatArrayMessageReader msg_reader(ptr); capnqml::Message ret; auto reader = msg_reader.getRoot<serialize::Message>(); ret.setType(static_cast<Message::Type>(reader.getType())); ret.setEndpoint(reader.getEndpoint().cStr()); ret.setExpectsAnswer(reader.getExpectsAnswer()); ret.setId(reader.getId()); ret.setOriginator(reader.getOriginator()); ret.setSchema(reader.getSchema().cStr()); auto payload = reader.getPayload(); Message::Payload data(payload.begin(), payload.end()); ret.setData(std::move(data)); return ret; }