Why doesn't the NetworkUp event fire on the .Net Gadgeteer GHI WiFi RS21 module? - .net-gadgeteer

I'm trying to debug why the event NetworkUp never fires on the WiFi RS21 Gadgeteer module and I've distilled it down to a very simple code listing:
using Microsoft.SPOT;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
namespace NetworkUpTest
{
public partial class Program
{
void ProgramStarted()
{
wifi_RS21.UseDHCP();
wifi_RS21.NetworkUp += wifi_RS21_NetworkUp;
wifi_RS21.NetworkDown += wifi_RS21_NetworkDown;
var scans = wifi_RS21.Interface.Scan("LLOYDREGANS");
if (scans != null && scans.Length > 0)
{
Debug.Print("Joining " + scans[0].SSID);
wifi_RS21.Interface.Join(scans[0], "**********");
}
var giveUpWaitingForTheNetworkUpEvent = new GT.Timer(300000, GT.Timer.BehaviorType.RunOnce);
giveUpWaitingForTheNetworkUpEvent.Tick += giveUpWaitingForTheNetworkUpEvent_Tick;
giveUpWaitingForTheNetworkUpEvent.Start();
}
void wifi_RS21_NetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
{
Debug.Print("NetworkUp");
}
void wifi_RS21_NetworkDown(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
{
Debug.Print("NetworkDown");
}
void giveUpWaitingForTheNetworkUpEvent_Tick(GT.Timer timer)
{
Debug.Print("Give up waiting for the NetworkUp event and try requesting the router homepage");
var request = HttpHelper.CreateHttpGetRequest("http://192.168.1.1/");
request.ResponseReceived += request_ResponseReceived;
request.SendRequest();
}
void request_ResponseReceived(HttpRequest sender, HttpResponse response)
{
Debug.Print("Response received. response.Text.Length = " + response.Text.Length);
}
}
}
Here's the listing from the output window when the program runs (minus the thread exited reports):
Using mainboard GHI Electronics FEZSpider version 1.0
RS9110 firmware version Number is 4.4.5
RS9110 driver version Number is 4.4.5
Joining LLOYDREGANS
NetworkDown
Give up waiting for the NetworkUp event and try requesting the router homepage
Response received. response.Text.Length = 2509
Given that the network is demonstrably up, why is "NetworkDown" the only event that fires from the WiFi RS21 module?

The answer on the GHI forum suggests that the correct events to use are:
Interface.WirelessConnectivityChanged
Interface.NetworkAddressChanged
instead of the exemplar code on GHI's WiFi RS21 Gadgeteer module page.

Related

Unity Mirror - NetworkServer Send Message To Target Client

I'm not sure what I'm doing wrong here but I can't seem to get my message from the server to the client. Here is what I have so far:
protected virtual void RegisterHandlers(bool enable)
{
if (enable)
{
NetworkServer.RegisterHandler<ClientRequestLoadScene>(OnClientRequestedToLoadScene);
NetworkClient.RegisterHandler<ServerRequestLoadScene>(OnServerRequestLoadScene);
}
else
{
NetworkServer.UnregisterHandler<ClientRequestLoadScene>();
NetworkClient.UnregisterHandler<ServerRequestLoadScene>();
}
}
The above is called when the instance starts to register a new handler. Then I have the client call:
ClientRequestLoadScene msg = new ClientRequestLoadScene();
msg.scene = scene;
NetworkClient.Send(msg);
This is received by the server fine. Then the server runs the following:
private void OnClientRequestedToLoadScene(NetworkConnection conn, ClientRequestLoadScene msg)
{
...
...
ServerRequestLoadScene server_msg = new ServerRequestLoadScene();
server_msg.scene = msg.scene;
NetworkServer.SendToClientOfPlayer(conn.identity, msg);
...
...
}
The above message is never received by the client. I have also tried: NetworkServer.SendToAll(msg); and that is never received by the client either. What am I doing wrong?
The issue with the above is with these lines:
server_msg.scene = msg.scene;
NetworkServer.SendToClientOfPlayer(conn.identity, msg);
It needed to be:
server_msg.scene = msg.scene;
conn.Send(server_msg);

Connect MQTTnet with Azure IoT Hub

I have created a device that delivers messages. Now I want to send them to an Azure IoT Hub by using MQTTnet Version 2.4.0 because the .NET target Framework is on Version 4.5 and it is not my decision to change it.
My Question:
Is there any other or better method to do this
What MqttClientOption do I take best
What Parameters to set to which value to connect to the Hub
I have tried almost every combination of values for the ClientId/UserName/Password as described here: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support#using-the-mqtt-protocol-directly-as-a-device
but none of them worked for me
I have tried outside the Project and build a similar device on the current framework and it worked perfectly with the newer version of MQTTnet.
Sadly I don't get any kind of error message only a MqttCommunicationTimedOutException after about 10 seconds.
Thanks for your help I have been stuck at this problem for almost a week.
The following code snippet is a working example of the simulated device1 using the MQTT protocol directly to the Azure IoT Hub via the MQTTnet Version 2.4.0 library:
using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var options = new MqttClientTcpOptions()
{
Server = "myIoTHub.azure-devices.net",
Port = 8883,
ClientId = "device1",
UserName = "myIoTHub.azure-devices.net/device1/api-version=2018-06-30",
Password = "SharedAccessSignature sr=myIoTHub.azure-devices.net%2Fdevices%2Fdevice1&sig=****&se=1592830262",
ProtocolVersion = MQTTnet.Core.Serializer.MqttProtocolVersion.V311,
TlsOptions = new MqttClientTlsOptions() { UseTls = true },
CleanSession = true
};
var factory = new MqttClientFactory();
var mqttClient = factory.CreateMqttClient();
// handlers
mqttClient.Connected += delegate (object sender, EventArgs e)
{
Console.WriteLine("Connected");
};
mqttClient.Disconnected += delegate (object sender, EventArgs e)
{
Console.WriteLine("Disconnected");
};
mqttClient.ApplicationMessageReceived += delegate (object sender, MqttApplicationMessageReceivedEventArgs e)
{
Console.WriteLine(Encoding.ASCII.GetString(e.ApplicationMessage.Payload));
};
mqttClient.ConnectAsync(options).Wait();
// subscribe on the topics
var topicFilters = new[] {
new TopicFilter("devices/device1/messages/devicebound/#", MqttQualityOfServiceLevel.AtLeastOnce),
new TopicFilter("$iothub/twin/PATCH/properties/desired/#", MqttQualityOfServiceLevel.AtLeastOnce),
new TopicFilter("$iothub/methods/POST/#", MqttQualityOfServiceLevel.AtLeastOnce)
};
mqttClient.SubscribeAsync(topicFilters).Wait();
// publish message
var topic = $"devices/device1/messages/events/$.ct=application%2Fjson&$.ce=utf-8";
var payload = Encoding.ASCII.GetBytes("Hello IoT Hub");
var message = new MqttApplicationMessage(topic, payload, MqttQualityOfServiceLevel.AtLeastOnce, false);
mqttClient.PublishAsync(message);
Console.Read();
}
}
}
and the following screen snippet shows an example of the output for updating a desired twin property color and receiving a C2D message:

Connection not working from Android to UWP on desktop - ZeroMq (NetMq)

I tried some examples of ZMQ on C++,C# and Python. I am trying to have Request-Reply pattern to connect Android device to PC running UWP with Xamarin forms.
Below is the Requestor code:
public void HelloWorld()
{
var timer = new Timer(60000);
timer.Start();
timer.Elapsed += (sender, args) =>
{
this.Cancel = true;
timer.Stop();
};
// Create
const string endpoint = "tcp://PC_ip:3245";
using (var request = new RequestSocket())
{
request.Bind(endpoint);
Thread.Sleep(2000);
while (!Cancel)
{
request.SendFrame("Requester says hello");
var reply = request.ReceiveFrameString();
Debug.WriteLine("Gets reply {0}",reply);
}
}
}
Reply socket code:
public void HelloWorld()
{
var timer = new Timer(60000);
const string endpoint = "tcp://PC_ip:3245";
timer.Start();
timer.Elapsed += (sender, args) =>
{
timer.Stop();
Cancel = true;
};
using (var replierSocket = new ResponseSocket())
{
replierSocket.Connect(endpoint);
Thread.Sleep(2000);
while (!Cancel)
{
var replyFromRequester = replierSocket.ReceiveFrameString();
Debug.WriteLine("Got reply {0}", replyFromRequester);
replierSocket.SendFrame("Response socket say hello");
}
}
}
Cancel is boolean
I went through some questions posted on this and added delay and these connection code blocks only trigger after button clicks on app.
While debugging , request.ReceiveFrameString() replierSocket.ReceiveFrameString(); are not even hit.
I am new to network programming , I understand that for REQ/REP pattern the code has to be in particular order which I traced and fixed I believe and turned off firewall on my PC so that firewall wont block my incoming connections from Android device.
PC_ip stands for IPv4 address I got from ipconfig /all for my wifi. I also tried external ip of my machine from sites like whatsmyip.org at ResponseSocket but I still dont get response between devices.
Please let me know what am I doing wrong.
Issue replication repository : GitHub/me/XamZeroMq

Photon matchmaking - Join or create a room using in Unity with an SQL lobby

I am trying to implement skill based matchmaking using Photon in Unity. It seems
I got most of this code from the documentation and it works but not well.
The problem is that you can't use JoinOrCreate() with the sql lobby type so my logic here is try and find a room, if it fails create one.
void init()
{
_client = Game.Context.GetComponent<SocketConnectionManager>().client;
joinRoom();
}
public void joinRoom()
{
TypedLobby sqlLobby = new TypedLobby("skillLobby", LobbyType.SqlLobby);
string sqlLobbyFilter = "C0 BETWEEN 100 AND 200";
_client.OpJoinRandomRoom(null, MatchMaker.MaxPlayers, MatchmakingMode.FillRoom, sqlLobby, sqlLobbyFilter);
}
public void createRoom()
{
RoomOptions o = new RoomOptions();
o.MaxPlayers = MatchMaker.MaxPlayers;
o.CustomRoomProperties = new Hashtable() { { "C0", Game.Me.getInt("trophies") } };
o.CustomRoomPropertiesForLobby = new string[] { "C0" }; // this makes "C0" available in the lobby
TypedLobby sqlLobby = new TypedLobby("skillLobby", LobbyType.SqlLobby);
_client.OpCreateRoom("", o, sqlLobby);
}
private void onEvent(EventData obj)
{
if (_client.CurrentRoom != null)
{
if (_client.CurrentRoom.PlayerCount >= _client.CurrentRoom.MaxPlayers)
{
// sweet I am good to go.
}
}
else
{
createRoom();
}
}
The problem is this is pretty unreliable. Say two players try to find a game at the same time they will both search fail and then both create. Now I have two players sitting in empty rooms instead of playing each other.
Any ideas on a better system?
Thanks all.
Thank you for choosing Photon!
First of all, there are few things that you should understand about Photon:
you can't use JoinOrCreate() with the sql lobby type
This is not correct.
Where did you read such thing?
Did you test this yourself? What did you test exactly?
onEvent (LoadBalancingClient.OnEventAction) callback cannot be used to be notified of a failed join random room operation. Instead, you should make use of the LoadBalancingClient.OnOpResponseAction callback, as follows:
private void OnOpResponse(OperationResponse operationResponse)
{
switch (operationResponse.Code)
{
case OperationCode.JoinRandomGame:
if (operationResponse.ReturnCode == ErrorCode.NoMatchFound)
{
createRoom();
}
break;
}
}
To detect a join event inside a room (local or remote player entered a room):
private void onEvent(EventData eventData)
{
switch (eventData.Code)
{
case EventCode.Join:
int actorNr = (int)eventData[ParameterCode.ActorNr];
PhotonPlayer originatingPlayer = this.GetPlayerWithId(actorNr);
if (originatingPlayer.IsLocal)
{
}
else
{
}
break;
}
}
To answer your question:
Say two players try to find a game at the same time they will both
search fail and then both create.
Any ideas on a better system?
No.
This issue happens only during the development phase where you use a few clients to run some tests. Once you have enough user base you won't notice this issue.

How to make sockets work in xamarin?

In the Answer to this question Here:Server Client Application with .NET and Xamarin
the person who answered said: "On Xamarin.Android you can use all of the regular .Net socket classes"
I tried using the code in example of the Microsoft documentation and i had no errors but application just is just displaying like that on the phone:
If I delete the socket code it would display the page normally.My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Net;
using System.Net.Sockets;
namespace App14
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
var label = new Label() { Text = "searching for a connection" };
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
label.Text = "Found a Connection";
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
label.Text = "Text received" + data;
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public Page2 ()
{
StartListening();
Title = "Sign in page";
InitializeComponent();
}
private void page2_click(object sender,EventArgs e)
{
Navigation.PushAsync(new Page1(), true);
}
}
}
Xaml File code:
Why is this?.and can you please provide an example of client mobile or server mobile socket
You are blocking the UI Thread with your StartListening call, since it has a infinite while loop.
The label you create in the while loop is never added as content on the page. Hence the text you add to it will never be shown. You already have a label defined with the name l on the page. In this case you could just use that to add text:
l.Text = "hello";
As commented, you should start your socket listening code on another thread to not block you UI. This could be as simple as writing Task.Run(() => StartListening());. Make sure you understand what this does and possibly how you cancel this Task again when navigating away from the page or during App lifecycle.
If you try to Connect from your mobile with the correct ip address and port number of the Listener when both devices are in the same LAN it should work. If one of the devices is behind a different LAN router/modem you won't be able to connect because the router will block all incoming connections unless you use a port routing mechanism like UPnP.