Browsed by
Tag: C#

Read data from a P1 port of a smart meter using a Netduino

Read data from a P1 port of a smart meter using a Netduino

Netduino P1 port connectionWhen you own a smart meter (in Dutch it’s called slimme meter), you probably know that these meters have a port for reading the meter’s data. This port is called the P1 port. This article will describe how you can connect to the P1 port and read the data coming from the meter using a Netduino Plus 2.

The first thing to do is connection the P1 port to the Netduino. The P1 port is a standard RJ11 socket. The P1 port is a half duplex serial port, with signals on TTL-level (0-5V) and with 4 pins connected. The RJ11 connector schema below will show the pins with the signal on each pin. As soon as the RTS-pin gets voltage, a data package will be send through the RxD pin. As long the RTS-pin has voltage, every 10 seconds data will be send.RJ11 connector

Normally serial ports on TTL-level will have an inverted signal. For the P1 port that’s not the case. Therefore you cannot connect the P1 port directly to the Netduino, but you will have to invert the signal first.

The schema below shows how to connect the P1 port to the Netduino using a HD74LS04P Signal Inverter IC. The Signal Invert IC contains 6 inverters, but only 2 are used.

P1 port schema

Once you have the hardware connected, you can start programming.

Opening the P1 port

You will need to use the following port settings to be able to read the P1 port’s data: baud rate: 9600, data bits: 7, parity: Even and stop bits: 1. Below the code for opening the port. In the above schema the P1 port is connected to the Netduino using connector D2, which means COM2.

[code]
string comPort = SerialPorts.COM2;
int baudRate = 9600;
int dataBits = 7;
var stopBits = StopBits.One;
var parity = Parity.Even;

// Create serial port
var serialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBits);

// Open serial port
serialPort.Open();
[/code]

Reading the data

Below you will find an example of the message as read from a P1 port. The first line will give information about the meter. As you can see, my meter is a ‘ISKRA ME382’. In a next article I will describe what the other message lines mean. A message will always start with a ‘/’ and end with a ‘!’.

/ISk5\2ME382-1003

0-0:96.1.1(4B413650303035313332363238353133)
1-0:1.8.1(00357.909*kWh)
1-0:1.8.2(00253.970*kWh)
1-0:2.8.1(00000.000*kWh)
1-0:2.8.2(00000.000*kWh)
0-0:96.14.0(0001)
1-0:1.7.0(0000.55*kW)
1-0:2.7.0(0000.00*kW)
0-0:17.0.0(0999.00*kW)
0-0:96.3.10(1)
0-0:96.13.1()
0-0:96.13.0()
!

The code below will show how you can read the message form the P1 port. The first method will use an infinite loop to continuously read the ports data. After a message was received, the code will pause a while before continuing reading the next message.

[code]
private static void ReadDataFromP1Port(SerialPort serialPort)
{
while (true)
{
if (serialPort.BytesToRead > 0)
{
var msg = ReadMessageFromSerialPort(serialPort);

if (msg != string.Empty)
{
// Wait a while before continuing
Thread.Sleep(_TimeToWaitBeforePressingNextMessageInMilliSeconds);
}
}
}
}
[/code]

The next method will show how the message coming from the P1 port is processed and how the readable message is composed. Because the Netduino Plus 2 handles the serial port a bit different than a Netduino 2, it is necessary to remove the parity bit (see ‘& 127‘) from the incoming byte. If you do not remove the parity bit, your data will be garbage.

[code]
private static string ReadMessageFromSerialPort(SerialPort serialPort)
{
// Init
string msg = string.Empty;
int singleByte = 0;

// Read the message
while (serialPort.CanRead && singleByte != _StopChar && msg.Length < _ProtectAgainstOverflow) { // Read byte and remove parity bit // Without removing the parity bit, the message will contain garbage on a Netduino Plus 2 singleByte = serialPort.ReadByte() & 127; // Add character to message msg += (char)singleByte; } // Flush the serial port serialPort.Flush(); // If loop was exited without the last character being the stop character, the message was invalid, so return an emtpy message if (singleByte != _StopChar) { return string.Empty; } // Return the message return msg; } [/code] These are the used variables [code] private static int _StopChar = 33; // = ! private static int _TimeToWaitBeforePressingNextMessageInMilliSeconds = 8000; private static int _ProtectAgainstOverflow = 600; [/code]

Netduino plus 2: First steps

Netduino plus 2: First steps

NetduinoI while ago I bought a Netduino plus 2. This open-source electronics prototyping platform is based on the .Net Micro Framework. The advantage of the plus 2 is, the presence of a network connection. This  connection makes it possible to connect the Netduino to the internet.

After setting up the development environment (Visual C# 2010, .Net Micro Framework, .Net Micro Framework Toolbox and Netduino SDK) to programming can start.

Netduino Plus 2

In this post I will show some code I used for my first steps into progamming the Netduino. The program will use the on-board button and LED.  When the button is pressed, a URL will be called and when the response from the URL is ok, the LED will blink.

This is the C# code which will run on the Netduino

[code]

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using Toolbox.NETMF.NET;

namespace ButtonPress
{
public class Program
{
private const string _Server = "example.com";

public static void Main()
{
// Initialize onboard LED
var led = new OutputPort(Pins.ONBOARD_LED, false);

// Initialize onboard button
var button = new InputPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled);

while (true)
{
// Read button state
var buttonPressed = button.Read();

// If the button was pressed, send info to URL
if (buttonPressed)
{
// Send information
var ack = SendInformation2Url();

// If send was ok, blink LED once
if (ack)
{
BlinkLED(led, 1);
}
else // otherwise blink LED 3 times
{
BlinkLED(led, 3);
}
}
}
}
}
[/code]

Code for calling a URL

[code]
// Send information to URL
private static bool SendInformation2Url()
{
var result = false;

var socket = new IntegratedSocket(_Server, 80);
var session = new HTTP_Client(socket);

var response = session.Get("/buttonpress.php");
if (response.ResponseCode == 200)
{
result = true;
}

return result;
}
[/code]

The code for blinking the LED

[code]
// Blink the LED
private static void BlinkLED(OutputPort led, int count)
{
for (int i = 0; i < count; i++)
{
led.Write(true);
Thread.Sleep(250);
led.Write(false);
Thread.Sleep(250);
}
}
[/code]

This is the code behind the buttonpress.php:

[code]
<?php
$fp = fopen(‘buttonspress.log’, ‘a’);
fprintf($fp, "%s: button was pressed\n", date(‘Y-m-d H:i:s’));
fclose($fp);
?>
[/code]

This is all the code you need for reading the on-board button state, calling a URL and letting the on-board LED blink.

Generate XML-file from your internal data

Generate XML-file from your internal data

Are you a .Net programmer and ever wanted to write your internal data to an XML-file without wanting to do the writing yourself? Well here’s some example code which can be useful for you.

First some classes representing the internal data.

[csharp]
using System.Collections.ObjectModel;

namespace XmlSerializer
{
public class DataContainer
{
public JustSomeData Data1;
public Collection Data2;
}
}
[/csharp]
[csharp]
namespace XmlSerializer
{
public class SomeMoreData
{
public long Id;
public string Name;
public int Age;
}
}
[/csharp]

The internal data will be written to a XML-file using the XmlSerializer. The following code shows a method which will initialize the internal data and will write this data to a XML-file.

[csharp highlight=”41,42-51″]
private void ShowXmlSerialization()
{
#region Init

// Main data
var dataContainer = new DataContainer();
dataContainer.Data2 = new Collection<SomeMoreData>();

#endregion Init

#region Generate some data

// Just some data
var justSomeData = new JustSomeData()
{
Id = 1,
Code = "Demo",
Description = "Just some demo data"
};

// Add it to the main data
dataContainer.Data1 = justSomeData;

// Some more data
dataContainer.Data2.Clear();
for (int i = 1; i <= 5; i++)
{
var someMoreData = new SomeMoreData();

someMoreData.Id = i;
someMoreData.Name = string.Format("Name {0}", i);
someMoreData.Age = i * 3 + i * 10;

dataContainer.Data2.Add(someMoreData);
}

#endregion Generate some data

#region Serialize

// Serialize the data
var serializer = new System.Xml.Serialization.XmlSerializer(dataContainer.GetType());

#endregion Serialize

#region Write to file

// Write it to file
var filename = "JustSomeData.xml";
Stream writer = new FileStream(filename, FileMode.Create);
serializer.Serialize(writer, dataContainer);

#endregion Write to file
}
[/csharp]

The generated XML-file will look like:

[xml]
<?xml version="1.0"?>
<DataContainer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Data1>
<Id>1</Id>
<Code>Demo</Code>
<Description>Just some demo data</Description>
</Data1>
<Data2>
<SomeMoreData>
<Id>1</Id>
<Name>Name 1</Name>
<Age>13</Age>
</SomeMoreData>
<SomeMoreData>
<Id>2</Id>
<Name>Name 2</Name>
<Age>26</Age>
</SomeMoreData>
<SomeMoreData>
<Id>3</Id>
<Name>Name 3</Name>
<Age>39</Age>
</SomeMoreData>
<SomeMoreData>
<Id>4</Id>
<Name>Name 4</Name>
<Age>52</Age>
</SomeMoreData>
<SomeMoreData>
<Id>5</Id>
<Name>Name 5</Name>
<Age>65</Age>
</SomeMoreData>
</Data2>
</DataContainer>
[/xml]