Hardware components | ||||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
Software apps and online services | ||||||
| ||||||
| ||||||
| ||||||
| ||||||
|
I recently purchased a Raspberry pi 2 and it occurred to me that any tutorial i see is requiring either some web service built using signal R or controlling it inside local network with the raspberry pi 2 acting as a server.I wanted to do actual Device to Host communication across networks which could have support for multitudes of device communicating without much coding(in the future) .Hence i wanted to find some way in which a beginner enthusiast can start up development and communication on the IOT field without going to much into code development and deployment of web services .Hence i came across the idea of controlling my Raspberry pi using MQTT .
You can refer the hardware setup for the MS Blinky app sample as a starting point
Enjoy coding and please don't forget to give any feedback good or bad :)
Note:-
1)One can further expand this functionality and can create interfacing apps for Android etc.
Links
For my purpose i am using free MQTT provider cloudAMQP
MQTT tutorials
https://www.rabbitmq.com/getstarted.html
https://www.rabbitmq.com/tutorials/tutorial-five-dotnet.html
Disclaimer.
I do not take any consequence from damage resulting from following instructions directly /Indirectly.Please take it up at your own risk !
MqttClient cl;
string sendTopic = "<devname>" ;
string[] reciveTopic = { "<devname>" };
//this is to demonstrate diffrent reposnes sent to diffrent requests
string diffResponse1="resp1", diffResponse2="resp2";
Boolean run = true;
String instanceid = "";
Windows.Devices.Gpio.GpioController ioControll = Windows.Devices.Gpio.GpioController.GetDefault();
Windows.Devices.Gpio.GpioPin pin;
//you can use cloud amqp for free MQTT hosting service
cl = new MqttClient("<free cloud client server >", 1883, false, MqttSslProtocols.None);
cl.Connect("<devname>", "<username>:<username>", "<password>", true, 100);
byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE };
cl.Subscribe(reciveTopic, qosLevels);
cl.MqttMsgPublishReceived += Cl_MqttMsgPublishReceived;
instanceid = Guid.NewGuid().ToString();
pin = ioControll.OpenPin(5);
pin.SetDriveMode(Windows.Devices.Gpio.GpioPinDriveMode.Output);
Timer publishing logic
C#Task.Run(async () =>
{
try
{
while (true)
{
if (run)
{
CommunicationMessage commMsg = new CommunicationMessage();
String resp = diffResponse1;
commMsg.id = instanceid;
commMsg.msg = resp;
publishMessage(sendTopic, SerializeIt(commMsg));
}
await Task.Delay(TimeSpan.FromMinutes(15));
}
}
catch (Exception)
{
// throw;
}
});
Logic to listen and respond on device
C# private async Task LedOn()
{
try
{
if (ioControll != null)
{
pin.Write(Windows.Devices.Gpio.GpioPinValue.High);
}
}
catch (Exception)
{
}
}
private async Task LedOff()
{
try
{
if (ioControll != null)
{
pin.Write(Windows.Devices.Gpio.GpioPinValue.Low);
}
}
catch (Exception)
{
}
}
private void Cl_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
if(e.Message!=null && !String.IsNullOrWhiteSpace(Encoding.UTF8.GetString(e.Message)))
{
CommunicationMessage mrcv= deserializeIt(e.Message);
if(mrcv.id!=instanceid)
{
if (mrcv.msg.Equals("ledon"))
{
CommunicationMessage commMsg = new CommunicationMessage();
commMsg.id = instanceid;
commMsg.msg = diffResponse1;
publishMessage(sendTopic, SerializeIt(commMsg));
LedOn();
}
else if (mrcv.msg.Equals("ledoff"))
{
CommunicationMessage commMsg = new CommunicationMessage();
commMsg.id = instanceid;
commMsg.msg = diffResponse2;
publishMessage(sendTopic, SerializeIt(commMsg));
LedOff();
}
else if (mrcv.msg.Equals("stop"))
{
run = false;
LedOff();
}
else
{
run = true;
}
}
}
}
public void publishMessage(String topic, byte[] message)
{
try
{
cl.Publish(topic,message);
}
catch (Exception)
{
}
}
public byte[] SerializeIt(Object obj)
{
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, obj);
return ms.ToArray();
}
public CommunicationMessage deserializeIt(byte[] b)
{
MemoryStream ms = new MemoryStream(b);
JsonSerializer serializer = new JsonSerializer();
BsonReader reader = new BsonReader(ms);
CommunicationMessage rcv = serializer.Deserialize<CommunicationMessage>(reader);
return rcv;
}
Windows 8.1 phone logic
C# public sealed partial class MainPage : Page
{
MqttClient cl;
string[] sendTopic = { "<devname>" };
string reciveTopic = "<devname>" ;
string diffResponse1 = "resp1", diffResponse2 = "resp2";
String instanceid = "";
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
try
{
//Server could be cloudAmqp
cl = new MqttClient("<mqtt server>", <portnumber>, false, MqttSslProtocols.None);
cl.Connect("<phone queue name>", "<username>:<username>", "<password>", true, 100);
byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE };
cl.Subscribe(sendTopic, qosLevels);
cl.MqttMsgPublishReceived += Cl_MqttMsgPublishReceived;
instanceid = Guid.NewGuid().ToString(); //this is so that we identiify and not respond to our own echo
}
catch (Exception)
{
}
}
private async void Cl_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// throw new NotImplementedException();
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
try
{
if (e.Message != null && !String.IsNullOrWhiteSpace(Encoding.UTF8.GetString(e.Message, 0, e.Message.Count())))
{
CommunicationMessage recvMsg = deserializeIt(e.Message);
if(recvMsg.id!=instanceid)
{
String text = recvMsg.msg;
//testOP.Text += text + "\n";//can display text output in a text field
}
}
}
catch (Exception)
{
}
});
}
private void ButtonLedOn_Tapped(object sender, TappedRoutedEventArgs e)
{
CommunicationMessage commMsg = new CommunicationMessage();
commMsg.id = instanceid;
commMsg.msg = "ledon";
publishMessage(reciveTopic, SerializeIt(commMsg));
}
private void ButtonLedOff_Tapped(object sender, TappedRoutedEventArgs e)
{
CommunicationMessage commMsg = new CommunicationMessage();
commMsg.id = instanceid;
commMsg.msg = "ledoff";
publishMessage(reciveTopic,SerializeIt(commMsg));
}
private void ButtonStop_Tapped(object sender, TappedRoutedEventArgs e)
{
CommunicationMessage commMsg = new CommunicationMessage();
commMsg.id = instanceid;
commMsg.msg = "stop";
publishMessage(reciveTopic, SerializeIt(commMsg));
}
private void ButtonRun_Tapped(object sender, TappedRoutedEventArgs e)
{
CommunicationMessage commMsg = new CommunicationMessage();
commMsg.id = instanceid;
commMsg.msg = "run";
publishMessage(reciveTopic, SerializeIt(commMsg));
}
public void publishMessage(String topic, byte[] message)
{
try
{
cl.Publish(topic, message);
}
catch (Exception)
{
}
}
public byte[] SerializeIt(Object obj)
{
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
// serialize product to BSON
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, obj);
return ms.ToArray();
}
public CommunicationMessage deserializeIt(byte[] b)
{
MemoryStream ms = new MemoryStream(b);
JsonSerializer serializer = new JsonSerializer();
BsonReader reader = new BsonReader(ms);
CommunicationMessage rcv = serializer.Deserialize<CommunicationMessage>(reader);
return rcv;
}
}
<StackPanel Orientation="Vertical">
<Button Content="led on" HorizontalAlignment="Stretch" Tapped="ButtonLedOn_Tapped">
</Button>
<Button Content="led off" HorizontalAlignment="Stretch" Tapped="ButtonLedOff_Tapped">
</Button>
<!--this is to control optional timer code -->
<Button Content="Stop" HorizontalAlignment="Stretch" Tapped="ButtonStop_Tapped">
</Button>
<!--this is to control optional timer code -->
<Button Content="Run" HorizontalAlignment="Stretch" Tapped="ButtonRun_Tapped">
</Button>
</StackPanel>
Comments