Hello I am new to this but I am developing a client to Mosquitto broker.
It works fine, but I want to know how could I add the Sender Id to the message.
i.e. Message From "Client1" : "LightON"
This is how I handle the subscription
private void Form1_Load_1(object sender, EventArgs e)
{
try
{
IPAddress HostIP;
HostIP = IPAddress.Parse(textBox1.Text);
clientSub = new MqttClient(HostIP);
clientSub.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(EventPublished);
}
catch (InvalidCastException ex)
{
MessageBox.Show("ERROR ON LOAD" + ex.ToString());
}
}
The Publish Event is :
private void EventPublished(Object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
{
try
{
SetText("Recevied Message..");
SetText("The Topic is:" + e.Topic);
SetText("*Message: " + System.Text.UTF8Encoding.UTF8.GetString(e.Message));
SetText("");
}
catch (InvalidCastException ex)
{
}
}
And I am using the M2mqtt library.
The only way to do this is to add it to the message payload yourself.
There is no concept of a publisher id in the MQTT headers. Client IDs are only to identify clients to the broker, not end to end.
Related
I am developing a windows form to function as a modbus tcp Master Simulator.I am using NModbus library.
I want to connect to multiple slaves simultaneously and do the read and write operation,does the NModbus library supports this kind of implementation? and if so how?.
Currently i am able to connect to single slave device and do the read/write operations,but i am stuck on how to the same with multiple slaves though.
Should i use the threading Concept to achieve the same.
Here is my code to connect to single slave device and do the read/write operation.
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
TcpClient masterTcpClient = new TcpClient(txtIP.Text, 502);
master = ModbusIpMaster.CreateIp(masterTcpClient);
MessageBox.Show("Connected");
}
catch (SystemException error)
{
MessageBox.Show(error.Message);
}
}
private void btnReadCoil_Click(object sender, EventArgs e)
{
try
{
byte slaveID = 255;
ushort startAddress = Convert.ToUInt16(txtStartaddress.Text);
ushort numInputs = Convert.ToUInt16(txtSize.Text);
bool[] inputs = master.ReadCoils(slaveID, startAddress, numInputs);
AnswerFromServer.Items.Clear();
for (int i = 0; i < inputs.Length; i++)
{
AnswerFromServer.Items.Add(Convert.ToInt16(inputs[i]));
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Exception Reading values from Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnWriteSingleRegister_Click(object sender, EventArgs e)
{
try
{
byte slaveID = 255;
ushort RegisterAddress = Convert.ToUInt16(txtStartaddress.Text);
ushort value = Convert.ToUInt16(txtSingleValue.Text);
master.WriteSingleRegister(slaveID, RegisterAddress, value);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Exception writing values to Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Can any one please help me with this one?
create another instance of this socket and maintain it.
TcpClient masterTcpClient_Two = new TcpClient(txtIPTwo.Text, 502);
Here i have how i accept the call but when someon is calling to me it is rejecting here is what i have tried but still don't works outgoing calls are working but incoming not can you help me? there is 1 point that it is alawys showing me call state busy
static void call_CallStateChanged(object sender, CallStateChangedArgs e)
{
Console.WriteLine("Call state: {0}.", e.State);
if (e.State == CallState.Answered)
SetupDevices();
}
static void RegisterAccount(SIPAccount account)
{
try
{
phoneLine = softphone.CreatePhoneLine(account);
phoneLine.RegistrationStateChanged += line_RegStateChanged;
softphone.IncomingCall += softphone_IncomingCall;
softphone.RegisterPhoneLine(phoneLine);
}
catch (Exception ex)
{
MessageBox.Show("Error during SIP registration: " + ex);
}
What I have tried:
static void softphone_IncomingCall(object sender, VoIPEventArgs e)
{
call = e.Item;
call.CallStateChanged += call_CallStateChanged;
call.Answer();
}
I've setup a openfire server in a vm, and its accessible from internet(I've done the port-forwarding to point to the ip of the vm).
I can chat using spark so openfire is working perfectly.
Now I am trying to connect my c# app to the server and I am getting error.
Code :
private void button1_Click(object sender, System.EventArgs e)
{
try
{
using (var client = new XmppClient("192.168.0.109", "pbc92", "12345"))
{
try
{
client.Connect();
client.StatusChanged += client_StatusChanged;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void client_StatusChanged(object sender, S22.Xmpp.Im.StatusEventArgs e)
{
MessageBox.Show(e.Jid.ToString());
}
The error :
Try with Sharp.Xmpp, it is a fork of the currently frozen S22.Xmpp.
https://github.com/pgstath/Sharp.Xmpp
i have build a chat application that uses UDP and TCP sockets, first let me walk you through the mechanism of the app:
from the android device i send a UDP packet to a group address which has multiple windows devices listening to it, when the windows device receives the packet, it checks whether it has the same phone number or not so i use the phone number as a unique key to identify the device then if it has the same phone number that I've send the packet with, it will respond with a key says: "ImReadyNow" sent through a TCP socket and that will make the android device accept the connection and act as a server for that windows device, i had similar problems when i first start making that app, the respond key from the windows device was returned with some rubbish data before and after it and i solved that problem by attaching a key to that massage and i split it after releasing so that old problem that i was facing was when a windows device sends "Hello" the android device receives
"????Hello" i solved this one by attaching a key to the first of the massage so
i'll receives "????$#!Hello" then i'll split the received string into two parts and displays the massage only, and that works fine for me till, i notice that sometimes the android device receives rubbish data only and that occurs randomly like if windows device sends "hello" then "hi" then "hello"
i may receives the first two massages right but the third one will received as "?????"
and as i told you it occurs randomly so does any one know why is this happening?
after debugging br.readLine() method does sometimes return "????" and this occurs as i said randomly.
here is the code that i'm using:
private class ChatClientThread extends Thread {
#Override
public void run() {
/*Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream=null;*/
// clientSocket=null;
try {
String data=EmpPhoneNumber;
DatagramChannel channel = DatagramChannel.open();
DatagramSocket socket = channel.socket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(52276));
socket.setBroadcast(true);
InetAddress group = InetAddress.getByName(
"224.0.1.2");
System.out.println("HELLO");
System.out.println(data);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
group, 52276);
serverSocket=new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(4125));
int i=0;
while(i<=30){
Thread.sleep(200);
socket.send(packet);
i++;
}
while(true){
clientSocket = serverSocket.accept();
BufferedReader br= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
strAcceptConnection= br.readLine();
System.out.println(strAcceptConnection);
if(!strAcceptConnection.contains("$#!")){
updateTextView("<font color=\"#0000A0\"> <b>"+empNameChat+": </b></font>"+"Error in recieving msg");
}else{
String parts[]= strAcceptConnection.split("[$#!]+");
if(!parts[1].equals("ImReadyNoW")){
updateTextView("<font color=\"#0000A0\"> <b>"+empNameChat+": </b></font>"+parts[2]);
}}}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
EmpDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(EmpDetails.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
EmpDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(EmpDetails.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
} finally {
EmpDetails.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
}
public void sendMessage(View view) {
final String msg= et.getText().toString();
et.setText("");
new Thread(new Runnable() {
public void run() {
Socket sock= null;
try {
sock= new Socket(clientSocket.getInetAddress().getHostAddress(), 4125);
Log.v("str", "send sock: "+sock.getInetAddress().getHostAddress()+sock.isConnected()+Integer.toString(sock.getPort()));
} catch (UnknownHostException e) {
Log.v("ERRORTAG", ""+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.v("ERRORTAG", ""+e.getMessage());
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
try {
DataOutputStream out= new DataOutputStream(sock.getOutputStream());
if(!msg.equals("")){
out.writeUTF("XX$#!"+MainActivity.empIdFromD+"$#!"+msg);
out.flush();
updateTextView("<font color=\"#800000\"> <b>"+"You"+": </b></font>" + msg);}
}
catch (IOException e) {
Log.v("ERRORTAG", ""+e.getMessage());
e.printStackTrace();
}
}
}).start();
}
public void updateTextView(String message) {
final String msg= message;
uiHandle.post(new Runnable() {
public void run() {
textView.setMovementMethod(new ScrollingMovementMethod());
Log.v("TAG", "updating textview");
//textView.append(msg+"\n");
textView.append(Html.fromHtml(msg));
textView.append("\n");
Log.v("TAG", "updated textview");
ScrollView sc= (ScrollView)findViewById(R.id.scrollView1);
sc.fullScroll(View.FOCUS_DOWN);
}
});
}
how does the received string look like:
LogCat:
PS. on the other side the windows device receives all of the massages correctly.
When I try to send a notification from my server I receive this message: "Invalid token size"
From this thread, PushSharp doesn't send notifications, I found out that it might be because I'm trying to use a Sandbox cert to the the production server or vice versa but I don't think so as I don't have any production certificate setup.
I then exported the APNs Development Certificate (.p12) and use that one on the server (as required by PushSharp).
I have exported the .p12 file again to make sure that the certificate is the actual one but with no luck.
I'm using the "Sandbox" flag as well.
Here is the C# code that I'm using:
static class APN
{
static PushBroker push = new PushBroker();
static byte[] appleCert = File.ReadAllBytes(#"C:\Certs\PineAppPushDev.p12");
static public void StartAPN()
{
Console.WriteLine("Starting APN ...");
/* Event listeners */
push.OnChannelException += broker_OnChannelException;
push.OnNotificationFailed += broker_OnNotificationFailed;
push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "*****"));
}
static private void broker_OnChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, System.Exception error)
{
Console.WriteLine("broker_OnChannelException:");
Console.WriteLine("PushChannel: " + pushChannel.ToString());
Console.WriteLine("Error: " + error.ToString());
}
static private void broker_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, System.Exception error)
{
Console.WriteLine("broker_OnNotificationFailed:");
Console.WriteLine("Notification: " + notification.ToString());
Console.WriteLine("Error: " + error.ToString());
}
static public void SendAPN(string message, string deviceID)
{
Console.WriteLine("SendAPN");
Console.WriteLine("DeviceID: " + deviceID.ToString());
try
{
push.QueueNotification(new AppleNotification()
.ForDeviceToken(deviceID)
.WithAlert(message));
}
catch (Exception ex)
{
Console.WriteLine("ERROR: APN.SendAPN(): " + ex.ToString());
}
}
}
Not sure what I'm missing, any help is highly appreciated!