This is the code that has been used. The IP that is used is on the same WiFi network to which my laptop is connected. Only the last digit is different.
#include <Ethernet.h>
#include<SPI.h>
#include <PubSubClient.h>
byte mac[] = { 0x12, 0xED, 0xBA, 0xFE, 0x2E, 0xED };
String macstr="12edbafe2eed";
byte ip[] = {192,16,1,1};
EthernetClient ethClient;
char servername[]="99elnd.messaging.internetofthings.ibmcloud.com";
PubSubClient client(servername, 1883,ethClient);
void setup()
{
Serial.begin(9600);
Serial.println("Arduino MQTT v.1.2");
Ethernet.begin(mac,ip);
}
void loop()
{
char clientStr[33];
String clientName = String("d:99elnd:arduno_mitul:12edbafe2ee2");
clientName.toCharArray(clientStr,33);
char token[] = "mituliot7450";
while (!client.connected()) {
Serial.println("Reconnecting client … ");
client.connect(clientStr, "use-token-auth", token);
}
String data = "{\"d\": {\"TEST\":";
data+=random(10);
data+="} }";
char jsonStr[33];
data.toCharArray(jsonStr,33);
char topicStr[33];
String topicName = String("iot-2/evt/status/fmt/json");
topicName.toCharArray(topicStr,33);
Serial.print("attempt to send");
Serial.print(jsonStr);
Serial.print("to");
Serial.println(topicStr);
if (client.publish(topicStr,jsonStr))
Serial.println("successfully sent");
else
Serial.println("unsuccessfully sent");
Serial.println("Disconnecting client … ");
client.disconnect();
delay(5000);
}
The serial monitor prints:
Arduino MQTT v.1.2
Reconnecting client …
Reconnecting client …
Reconnecting client …
Reconnecting client …
Reconnecting client …
Its slightly strange you are using 192,16,1,1 as your IP. Typically x.x.x.1 is the default gateway for a given network. If that is the case in your network, then there will be an IP conflict and your device will not have Internet connectivity. This appears to be the case as the credentials from your sketch do work, but there is no record of that device ever even attempting to connect prior to my testing.
You could use DHCP instead which is probably more portable as in the hello world client example here:
http://www.tweaking4all.com/hardware/arduino/arduino-ethernet-data-pull/
or try using the IP address of your laptop (while that is disconnected of course) if indeed your laptop is also using static IP assignment. I've found that, if the gateway and the DHCP server are one and the same device, it will not route traffic for an IP it has not supplied via DHCP, even if it is a valid and unused IP address. You have to limit the range of addresses the DHCP server can dish out in order to free up some to be used in static assignment.
Looks like maybe you are passing the wrong token for authentication - I see some authentication errors in the Watson-IoT log. Please confirm you are passing the correct authentication token that was generated when you registered the device.
Related
I have this binding socket:
Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
mainSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0));
And I need to know when an extern client is connected and disconnected from my servicies( ftp, database server, app server, etc).
thank for advance.
What I have tried:
I tried with these methods but, did not work for me.
mainSocket.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0), new AsyncCallback(ClientConnected), null);
mainSocket.BeginDisconnect(true, new AsyncCallback(ClientDisconnected), null);
private void ClientDisconnected(IAsyncResult ar)
{
// here get some client info like Ip
}
private void ClientConnected(IAsyncResult ar)
{
// here get some client info like Ip
}
I need some help please. Thanks.
BeginConnect() and BeginDisconnect() are asynchronous operations. They are not events you can subscribe to.
BeginConnect() is for a client socket to asynchronously open a new connection to a server. BeginDisconnect() asynchronously closes an open socket.
To detect clients connecting to your server, you need to use Accept(), BeginAccept()/EndAccept(), or AcceptAsync() to accept inbound connections coming into your server socket. You will be given a new Socket for each accepted client to use for communicating with them.
There is no event for a client disconnecting from a server. If a client disconnects, pending/subsequent send/receive operations involving that client will fail. You need to handle those failures when they occur. For instance, if a client disconnects gracefully, a read operation from the client will end as successful with 0 bytes reported. But if the client disconnects abnormally, a read operation will end as failed with an error code reported.
I'm writing in Python software that runs on my Windows (and Linux) PC, while the PC is connected via LAN (with or without a router) to a second device.
The second device sends UDP multicast packets to a known multicast group address and port.
The software in the computer is configured to be part of the same multicast group.
This is working OK as long as both my computer and the server network configuration are on the same sub-net.
Now, most of the times I will don't know the IP of the device in advance and I'll be connecting my computer directly to the server point-to-point. (Imagine the software that comes with IP security cameras that allows you to discover or know the IP of the camera when connecting directly to them with out knowing it in advance and without being in the same sub-net). E.g my computer has IP 169.x.x.x/24 and the server has IP 10.1.1.100 but I do not know the server IP in advance.
For reasons out of my control, the device cannot be configured to be a DHCP server so it cannot assign IP to my computer and cannot use DNS.
How can I receive the UDP multicast packets without raw capture?
This is my current code for the socket configuration that is working when both the computer and the server have the same sub-net. Ex 10.1.1.100/16 and 10.1.1.60/16 but needs to work also as mentioned above.
class MulticastSocket(object):
"""Sends UDP packets to multicast addressses."""
def __init__(self, bind_ip=None):
self._create(bind_ip)
def _create(self, bind_ip):
self.bind_addr = bind_ip
# chosen arbitrary from IANA's Scoped Multicast Range
# https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml#unicast-prefix-based
self.multicast_group = '239.6.2.86'
self.multicast_port = 6286
"""Creates a multicast UDP socket"""
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self._sock.settimeout(6)
ttl = 2
self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
self._sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.bind_addr))
membership_request = struct.pack('4s4s', socket.inet_aton(self.multicast_group),
socket.inet_aton(self.bind_addr))
self._sock.setsockopt(
socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership_request)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if sys.platform == 'linux':
bind_addr = self.multicast_group
else:
bind_addr = self.bind_addr if self.bind_addr else ''
self._sock.bind((bind_addr, self.multicast_port))
def get(self):
"""use to get the socket object to work with the select as select only accept sockets objects"""
return self._sock
def send(self, msg):
return self._sock.sendto(msg, (self.multicast_group, self.multicast_port))
def recv(self, len):
try:
response = self._sock.recvfrom(len)
return response
except socket.timeout:
return "", ""
def close(self):
self._sock.close()
I want to discover the deices which are running a specified service exposed to the local network, but I don't know how to.
For example I want local IP address and port number of the devices running service '_googlecast._tcp.'.
Is there any way to achieve this in Flutter ?
Thanks in advance
Check multicast DNS package: A Dart package to do service discovery over multicast DNS (mDNS), Bonjour, and Avahi.
Essentially, create a mDNS Client and get PTR record for the service, as:
const String name = '_googlecast._tcp.local';
final MDnsClient client = MDnsClient();
await client.start();
// Get the PTR recod for the service.
await for (PtrResourceRecord ptr in client
.lookup<PtrResourceRecord>(ResourceRecordQuery.serverPointer(name))) {
// Use the domainName from the PTR record to get the SRV record,
// which will have the port and local hostname.
// Note that duplicate messages may come through, especially if any
// other mDNS queries are running elsewhere on the machine.
await for (SrvResourceRecord srv in client.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(ptr.domainName))) {
// Domain name will be something like "io.flutter.example#some-iphone.local._dartobservatory._tcp.local"
final String bundleId =
ptr.domainName; //.substring(0, ptr.domainName.indexOf('#'));
print('Dart observatory instance found at '
'${srv.target}:${srv.port} for "$bundleId".');
}
}
client.stop();
print('Done.');
I'm using STM32 with ESp8266 using latest AT Command Firmware V2
Also i'm including https://github.com/nimaltd/ESP8266
Which helps parse at commands
I can connect to my router access point and my local tcp server but when sending GET requests i receive nothing on my local
const char* host = "192.168.1.9";
while(!Wifi_TcpIp_StartTcpConnection(0,host,3437,10)){
char buffer[] = "Unable to connect to TCP Backend\r\n";
HAL_UART_Transmit(&huart1,buffer,sizeof(buffer),HAL_MAX_DELAY);
};
uint8_t req ="GET /opaaa HTTP/1.1\r\n"; Wifi_TcpIp_SendDataTcp(0,sizeof(req),&req); //success but i receive nothing
Assuming the TCP communication works properly (you can connect to the server, send and receive data) and that the host you connect to serves HTTP on that port, the issue I can see with your request is that you're missing an additional CRLF at the end, like so:
char *req = "GET /opaaa HTTP/1.1\r\n\r\n";
Wifi_TcpIp_SendDataTcp(0, strlen(req), (uint8_t*)req);
This signifies the end of HTTP headers that you're sending. In your original case, the server may still be waiting for more headers and therefore holding with sending the response back to you.
I also suggest to clean up the sending code, one way of which I've pasted above - you were assigning a string to a single byte uint8_t variable.
I want to setup a datastreaming server in Processing, so the Client sends a String to the Server and the Server answeres it. For example Client - Server "Cupcake" then Server - Client "Cupcakce sounds funny" so the Server answeres the string. I tried this with the UDP library and opened the port on the server. But when the server had to answer the Clinet it did'nt work, because I can't open the client's ports. Any solutions?
Sounds like you need two-way communication.
Using UDP you would need two sketches that are both UDP servers and clients.
e.g.
sketch #1 listens on port 12000
sketch #1 sends data on port 12001
sketch #2 listens on port 12001
sketch #2 sends data on port 12000
You can also use TCP sockets.
As the Server you can use Examples > Libraries > Network > ChatServer
I'm surprised there's no ChatClient example, but you can get away with something like this:
import javax.swing.*;
import processing.net.*;
int port = 10002;
Client myClient;
void setup()
{
size(400, 400);
textFont(createFont("SanSerif", 16));
myClient = new Client(this, "localhost", port); // Starts a client on port 10002
background(0);
}
void draw()
{
background(0);
text("client - press ENTER to type\nconnected:"+myClient.active(), 15, 45);
}
void keyReleased() {
if (keyCode == ENTER) {
String message = JOptionPane.showInputDialog(null, "message: ", "TCP Client messaging", JOptionPane.QUESTION_MESSAGE);
println(message);
if (myClient.active() && message != null) {
myClient.write(message);
}
}
}
Note: The server must be running before the client so the client can connect.
Be sure to checkout the difference between UDP and TCP protocols to work out which one makes most sense to use in your case (especially if you pan to use more clients).
Another option worth looking into is WebSockets. This would allow you to have a WebSocket server in Processing and the client could either be another Processing sketch or simply any browser with WebSocket support(e.g. most modern)