Subscriber of MosquittoClient doesn't show single subscribed message in a interval time period - mosquitto

I'm using Mosquitto/Client php library. I have made connected properly between broker and client. When i execute publisher and subscriber then subscriber displays a number of messages but I want to get a single published message when publisher publish the message. How will i get a single message by subscribing the published message?
Subscriber.php
define('BROKER', '192.168.0.13');
define('PORT', 1883);
define('CLIENT_ID', "pubclient_" + getmypid());
$client = new Mosquitto\Client(CLIENT_ID);
$client->onConnect('connect');
$client->onDisconnect('disconnect');
$client->onSubscribe('subscribe');
$client->onMessage('message');
$client->connect(BROKER, PORT, 60);
$client->subscribe('test/foo/bar', 1);
$client->loopForever();
function connect($r) {
echo "Received response code {$r}\n";
}
function subscribe() {
echo "Subscribed to a topic\n";
}
function message($message) {
printf("Got a message on topic %s with payload:\n%s\n", $message->topic, $message->payload);
}
function disconnect() {
echo "Disconnected cleanly\n";
}
publisher.php
define('BROKER', '192.168.0.13');
define('PORT', 1883);
define('CLIENT_ID', "pubclient_" + getmypid());
$client = new Mosquitto\Client(CLIENT_ID);
$client->connect(BROKER, PORT, 5);
while ($client->loop() == 0) {
$message = "Test message at " . date("Y-m-d H:i:s");
$client->publish('test/foo/bar', $message, 1, false);
$client->loop();
sleep(1);
}
I want to publish/subscribe in a specific interval.
Publisher.php publishes a topic with a message in a interval time period and subscriber.php get that topic with that message in a interval time period.

Related

How to get Twilio call status in Laravel?

I have a Laravel app where I have some logic and I'm using Twilio to make the phone call but I want to make when the user missed the phone call after the user will get the SMS and for that, I need to know the call status but how do I get the call status in Laravel. If anybody can help me please feel free to respond.
public function initiateCall(Request $request)
{
// Validate form input
$this->validate($request, [
'phone_number' => 'required|string',
]);
try {
//Lookup phone number to make sure it is valid before initiating call
$phone_number = $this->client->lookups->v1->phoneNumbers($request->phone_number)->fetch();
// If phone number is valid and exists
if ($phone_number) {
// Initiate call and record call
$call = $this->client->account->calls->create(
$request->phone_number, // Destination phone number
$this->from, // Valid Twilio phone number
array(
"record" => True,
"url" => "http://demo.twilio.com/docs/voice.xml"
)
);
if ($call) {
echo 'Call initiated successfully';
} else {
echo 'Call failed!';
}
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} catch (RestException $rest) {
echo 'Error: ' . $rest->getMessage();
}
}
In the else section of the code when the code echo 'Call failed!'
else {
echo 'Call failed!';
}
you can create or call a function here to send a SMS to user after failed call & also you can set a counter variable here that changes the variable's value to indicate that call is failed.

Solace Client Acknowledgement Replay

I'm putting together a Solace Point-to-point solution in C#.
In my subscriber/listener, I am using ClientAck mode to ensure messages are successfully processed before being removed from the queue.
My question (probably due to my limited experience in messaging) is regarding failed messages, e.g. if I cannot process the message and hence not send the Ack, how is the message replayed?
An example of what I have is as follows:
using (ISession session = context.CreateSession(sessionProperties, null, null))
{
ReturnCode returnCode = session.Connect();
if (returnCode == ReturnCode.SOLCLIENT_OK)
{
var endpointProps = new EndpointProperties()
{
Permission = EndpointProperties.EndpointPermission.Consume,
AccessType = EndpointProperties.EndpointAccessType.Exclusive
};
using (IQueue queue = ContextFactory.Instance.CreateQueue(queueName))
{
session.Provision(queue, endpointProps,
ProvisionFlag.IgnoreErrorIfEndpointAlreadyExists | ProvisionFlag.WaitForConfirm, null);
_flow = session.CreateFlow(new FlowProperties { AckMode = MessageAckMode.ClientAck }, queue, null, HandleMessageEvent, HandleFlowEvent);
_flow.Start();
do { WaitEventWaitHandle.WaitOne(); } while (!cancellationToken.IsCancellationRequested);
};
return Task.CompletedTask;
}
else
{
throw new Exception($"Connection failed, return code: {returnCode}");
}
}
and then handling incoming messages
void HandleMessageEvent(object sender, MessageEventArgs args)
{
using (IMessage message = args.Message)
{
try
{
_handler(message.ApplicationMessageType, message.BinaryAttachment);
_flow.Ack(message.ADMessageId);
}
finally
{
WaitEventWaitHandle.Set();
}
}
}
So, if I don't Ack, message remains on queue as expected (and required), however, how (best-practice) can I re-process it without manual intervention?
After a message has been delivered to a consumer from a Solace PubSub+ queue, the message will only be resent if the client unbinds before sending an acknowledgement back. The exception to this is specific to JMS clients with the session.recover() action.
If a message needs to be re-delivered to a C# application after it has already been sent but not acknowledged, the client will need to unbind and rebind to the queue. Note that if there are other clients also bound to the queue, the message may be re-sent to those clients before your client rebinds.

django-channels parse json/data sent via sockets

I have this javascript code that send data to channels
// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send({"test":"data"});
}
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
I'm curios how from message I can get the json {"test":"data"}
here's the view
# Connected to websocket.connect
#channel_session
def ws_connect(message, key):
# Accept connection
message.reply_channel.send({"accept": True})
You implemented the connection callback, but did not implement what should happen when a message arrives the server endpoint. Add add message receive function:
def on_receive(message):
print('test received: {}'.format(message.content['test']))
Register the function in routing.py:
channel_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", on_receive),
]
The JSON message you send will be stored in message.content which is basically just a python dict.

Laravel PubSubHubbub i have subscribed but couldn't receive updates

I am trying to get real time feed updates using the Pubsubhubbup and Laravel, i have created 2 functions one for subscribe and the other one is a callback function.
when the subscribe function called it worked and the callback function receives a confirmation from the hub and respond with the hub_challenge code, all this works OK but the callback function doesn't receive any feed updates after that although it should receive it from the hub when there are updates but this is not happen !!
can you help to find what is the problem ??
thanks for your time.
the functions
public function subscribe(Feed $feed)
{
$hub_url = "http://pubsubhubbub.appspot.com";
$callback_url = url('feed/getFeedUpdates');
$subscriber = new Subscriber($hub_url, $callback_url);
$subscriber->subscribe($feed->feed_url);
Flash::success('Feed has been saved.');
return redirect('feed');
}
public function getFeedUpdates(Request $request)
{
// Subscribe Confirmation
if ($request->has('hub_mode') && $request->hub_mode == 'subscribe') {
$response = new Response($request->hub_challenge, 200);
$response->header('Content-Type', 'text/plain');
return $response;
} else { // Receive Updates
$updates = file_get_contents("php://input");
// put the updates to the database
}
}

Does javapns support broadcast push notifications?

I googled javapns and nothing show that it support broadcast diffusion.
It there a trick to make it support broadcast?
I am using this code right now, and adding all my available tokens in the call:
try {
PushNotificationPayload payload = PushNotificationPayload.complex();
payload.addAlert("Hello World");
payload.addBadge(1);
payload.addSound("default");
payload.addCustomDictionary("id", "1");
System.out.println(payload.toString());
List<PushedNotification> NOTIFICATIONS = Push
.payload(payload, "D:\\keystore1.p12", "123456", true,
"-------------");
for (PushedNotification NOTIFICATION : NOTIFICATIONS) {
if (NOTIFICATION.isSuccessful()) {
/* APPLE ACCEPTED THE NOTIFICATION AND SHOULD DELIVER IT */
System.out
.println("PUSH NOTIFICATION SENT SUCCESSFULLY TO: "
+ NOTIFICATION.getDevice().getToken());
/* STILL NEED TO QUERY THE FEEDBACK SERVICE REGULARLY */
} else {
String INVALIDTOKEN = NOTIFICATION.getDevice().getToken();
/* ADD CODE HERE TO REMOVE INVALIDTOKEN FROM YOUR DATABASE */
/* FIND OUT MORE ABOUT WHAT THE PROBLEM WAS */
Exception THEPROBLEM = NOTIFICATION.getException();
THEPROBLEM.printStackTrace();
/*
* IF THE PROBLEM WAS AN ERROR-RESPONSE PACKET RETURNED BY
* APPLE, GET IT
*/
ResponsePacket THEERRORRESPONSE = NOTIFICATION
.getResponse();
if (THEERRORRESPONSE != null) {
System.out.println(THEERRORRESPONSE.getMessage());
}
}
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
Real Broadcast notification does not exists. IOS Push notification service has only one implementation and it takes token list of clients.
So you have to get tokens of your client, then use your script.

Resources