Monday, March 24, 2014

Power over ethernet (PoE) magnetometer and cloud detector

Combined magnetometer and cloud detector
Combined magnetometer and cloud detector.


To improve the performance and stability of the AuroraWatchNet magnetometers I recently began experimenting with a power over ethernet (PoE) version. With restrictions on power consumption lifted considerable performance improvements are possible. As a result I have developed the magnetometer hardware specifically to support a power over ethernet version. Another instrument I've been developing is a cloud detector. This too should benefit from a power over ethernet version. One problem I encountered was with dew settling on the sensor but fitting a heater is incompatible with battery-powered operation. Since both the magnetometer and cloud detector use almost the same hardware I decided to design an Arduino-compatible 'shield' that could be used to support both systems.

Combined magnetometer and cloud detector hardware

Combined magnetometer and cloud detector PCBs
Printed circuit boards for the sensor shield (left), the IR or humidity sensor (top right)
and fluxgate magnetometer (bottom right). Click for annotated version.
The complete system requires six circuit boards (five for the wireless version). The first is the microcontroller board, I use my Calunium Arduino clone. I hope that in future it will be possible to use an off-the-shelf Arduino Mega2560 instead but the current firmware relies on Calunium's real-time clock to generate the hardware interrupts which control the sampling interval. There is also a sensor shield, the Arduino Ethernet shield (omitted on the battery-powered wireless version), and one board for each of the sensors (fluxgate magnetometer, IR temperature and humidity).

The sensor shield is based on the existing design and retains the option of battery-powered operation with radio communication. The magnetometer sensor and analogue-to-digital converter must be powered at 5V, which requires a level-shifting circuit when the microcontroller is powered from 3.3V, which is the case when operating from batteries. For power over ethernet use the microcontroller must also operate at 5V for compatibility with the Arduino Ethernet shield so the level shifting is not required. It is kept however as it provides buffering between the two circuit boards; 1.5m is a considerable distance for an I2C bus. The cloud detector uses a non-contact infra-red temperature sensor operating at 3.3V so a level-shifting circuit is required for PoE operation where the microcontroller is connected to 5V. (I've ignored the fact that a 5V version of the sensor exists since it isn't readily available in the UK). The sensor shield allows a humidity sensor to be connected so that estimates of the clear sky and cloudy sky temperatures can be made. As before, an on-board LM61 temperature sensor monitors the system temperature. The new sensor shield also adds a header to fit an Embedded Adventures lightning sensor module. I don't have one of these at the moment so I can't be certain it will work and there is no software support for it in the existing firmware. Fitting it at the same time as the cloud detector sensors will require long break-away headers to be soldered to the bottom of the lightning sensor module.

Fluxgate magnetometer sensor PCB
Fluxgate magnetometer sensor mounted on its sensor PCB.
Click for annotated version.

The fluxgate sensor is fitted on its own PCB which contains the analogue to digital converter. For PoE operation a linear voltage regulator is used to convert from 9V to the 5V supply it requires. For battery operation a MAX619 DC-DC charge pump boosts the battery voltage to 5V. Almost all of the temperature variation can be removed by placing the PCB at the bottom of a 1m length of soil pipe. The pipe is buried to a depth of 0.85m with its axis vertical. In the magnetometer-only system the microcontroller, sensor shield and ethernet shield (or batteries for the wireless version) are fitted onto a wooden frame to hold them into the top part of the tube. Positioning the rest of the system away from the fluxgate sensor helps to avoid unwanted effects from any ferro-magnetic components (such as the batteries), it also aids access and enables wireless data transmission.

Humidity sensor PCB
Honeywell HIH6131 humidity sensor mounte on its sensor PCB.
The same PCB design is also used for the MLX90614 IR temperature sensor.
Click for annotated version.

The enclosure design used for the magnetometer isn't suitable for the cloud detector so the prototype cloud detector used a standard IP65 rated box, with the IR temperature sensor pointing upwards to view the sky. The humidity sensor was fitted above a breather hole in the bottom of the box. This concept will continue to be used for the cloud detector; the IR temperature sensor and humidity sensor are fitted to separate PCBs in the top and bottom of the box. To minimise costs the IR temperature and humidity sensors use the same PCB design. The mechanical design of the cloud detector part is something I'd like to improve upon, particularly to reduce the number of PCBs used. However the differing sensor requirements may prevent this.

For a combined system I plan to use the soil pipe to house the fluxgate sensor but locate the rest of the electronics in a separate box following the design of the prototype cloud detector.

Does it work?

I've not yet deployed a system outside but testing indicates the new printed circuit boards work as intended when used in power over ethernet mode. Battery-powered operation on this new version has not yet been tested.

Design files

The design files (hardware, firmware and software) are open source and can all be downloaded from the Github repository. A PDF version of the user manual describing how to construct and operate the magnetometer can be downloaded from http://aurorawatch.lancs.ac.uk/manual.pdf. At the time of writing only instructions to build the original FLC100 shield are included. Instructions to build the combined sensor shield described above will be added in due course.


Wednesday, February 12, 2014

Performance comparison of power over ethernet (PoE) and battery magnetometers

Introduction

I've been working to improve the performance and stability of the AuroraWatchNet magnetometers. It's apparent that both measurement noise and stability are considerably improved when the sensor is powered continually. Unfortunately with the sensor powered continually the batteries last for only a few weeks. I have therefore been testing a power over ethernet (PoE) version of the magnetometer. The hardware is essentially the same but the addition of the Arduino Ethernet shield requires the microcontroller to operate from 5V. Operating voltage is easily changed on my Calunium microcontroller board. With the power restrictions lifted the sampling interval can also be reduced. The test system has been operating reliably for almost two months, sampling every 5 seconds. With some minor configuration changes sampling every second is possible although I am not convinced the trade-off in measurement noise is worthwhile.

Performance comparison

Below is a plot comparing one hour of data from the new power over ethernet system with two of the existing battery-powered wireless models already in operation. The PoE system is on the same site as LAN1 but located nearer parked cars. I chose this period because it was free of man-made disturbances. I adjusted the baselines so that the plots overlap.Only the H component of the magnetic field is shown.

Power over ethernet compared with existing AWN magnetometers
Click for larger version.

The graph shows that the power over ethernet version has much smaller measurement errors; it can probably operate with ~0.1nT accuracy compared to ~10nT for the battery-powered version. It's such an improvement that I found the measurement accuracy was being limited by the available resolution of the analogue-to-digital converter. The battery-powered versions derive the sample value from the median of 15 samples (taken as a burst over 4 seconds) to reduce noise. To improve the resolution for the PoE version it operates by taking the mean of 15 samples. Further improvement to the resolution may be possible by taking advantage of the programmable gain amplifier that is built into the analogue-to-digital converter.

Let's see how it compares against some observatory-grade measurements. The plot below shows the same interval but this time uses data from the British Geological Survey magnetometers at Eskdalemuir and Hartland. I obtained the data from the SAMNET data archive at Lancaster University, where the data has already been converted into HEZ magnetic coordinates. AuroraWatchNet also operates with HEZ magnetic coordinates, although usually the E and Z sensors are not present. As before, the baselines have been adjusted so that the plots overlap.


PoE magnetometer compared with BGS magnetometers
Click for larger version.


The similarity between the different traces is striking. Some differences are to be expected since Eskdalemuir is approximately 140km north of Lancaster and Hartland is 350km SSW of Lancaster. This interval is interesting because it shows Pi2 pulsations, starting at about 01:15 and ending around 01:30. The period of the pulsations are about 90 to 120 seconds.

Conclusions

For a home-built citizen-science magnetometer which probably costs 25 times less than its observatory grade cousin I'm very happy with its performance. The detection of Pi2 pulsations means a low-cost magnetometer can now notify of substorm onset, not just the arrival of geomagnetic storms. A network of such devices has interesting possibilities for the study of magnetic field line resonances.

You might wonder why anyone would want to buy an observatory grade instrument, there are good reasons. At present I am relying on the sensor manufacturer's calibration, whilst an observatory grade instrument would be supplied with an official calibration certificate. The observatory instrument would also have better long-term baseline stability, lower temperature variation and higher cadence. Calibration is an issue I hope to tackle at a later date. For space-weather monitoring only short-term variations are of interest and
the better performance provided by an observatory system may not be needed.

Data credits

The Sub-Auroral Magnetometer Network data (SAMNET) is operated by the Space Plasma Environment and Radio Science (SPEARS) group, Department of Physics, Lancaster UniversityHartland and Eskdalemuir data is provided courtesy of the British Geological Survey.



Sunday, October 27, 2013

Magnetometer progress report: link indicator LED

I recently added a new feature to the magnetometer remote sensor unit firmware. To help indicate when it is within radio communication range of the base unit an LED is turned on at the start of a message communication. When the sensor unit receives the acknowledgement from the base unit of successful message receipt the LED is switched off. In normal operation the LED should blink briefly every 30 seconds, after each sampling interval. If the LED remains on it indicates a problem with the radio link. For the initial installation the sampling time can be reduced to 5 seconds for to obtain faster feedback of whether communication is successful or not.

Improvements for battery-powered operation

Indicating link errors by using an LED is convenient during installation but the power wasted after installation is not compatible with battery-powered operation. To save power the LED is used only the first 15 minutes of operation. Only user-initiated reset actions (power on or reset switch pressed) cause the LED to be used, resets from by the watchdog timer or brown-out detector are ignored. The cause of the reset is detected by examining the microcontroller's status register (MCUSR).


Communication timeout feature added

I've also added a timeout which detects when communication has been lost for an extended period. The microcontroller system is rebooted in the hope that the error is recoverable. Loss of communication, along with low battery status, can also be sensed and reported by running the latest version of the data plotting software on the Raspberry Pi. If either error is detected a message can be sent via email, Twitter or Facebook.


Saturday, October 19, 2013

Cloud detector: a review of progress so far

The hardware

My cloud detector has been running outside for over 5 months now. Overall I'm very pleased with how it works. The battery-powered hardware is based on the AuroraWatchNet magnetometer design, which uses my own Calunium microcontroller development board. The remote sensor board and fluxgate sensor are omitted. I've added a Melexis MLX90614 non-contact infra-red thermometer to measure the sky temperature. Clear skies should give low temperatures whilst clouds are expected to have warmer temperatures, although still colder than the ambient temperature. The MLX90614 also outputs the sensor temperature, which should be close to the ambient temperature. I also added a Honeywell HIH-6131-021 humidity sensor which has an I2C interface. Do not confuse with the similar sounding version which has an SPI interface! The HIH-6130 also provides and ambient temperature measurement. To avoid direct contact with water the humidity sensor is placed at the bottom of the enclosure with a hole underneath to expose it to air. This hole also functions as a breather hole and ensures that the internal pressure matches atmospheric pressure. Since this hole was drilled there have not been any more incidents of water ingress.

The Calunium board is running a firmware is a modified version of the magnetometer firmware. It communicates with the Raspberry Pi data logger using an 868MHz radio link, with the same signed communication protocol used by AuroraWatchNet. This means I can use the data recording software from AuroraWatchNet. It also inherits the signed over-the-air firmware update capability. In principle it should be possible to combine both magnetometer and cloud detector functions in one unit.

I started off using the 90°  field-of-view version of the non-contact IR thermometer but later switched to theMLX90614ESF-DCH-000-TU-ND variant which features a 12° field of view. Its greater height meant it was easier to fit into the cable grommet housing. However I think the FOV is too narrow and I plan to switch back to the original sensor when I have time.

Data processing

The data processing and plotting now uses the auroraplot library for Python, which I developed to process the AuroraWatchNet magnetometer data. On the graphs I plot the sky temperature measured by the non-contact IR thermometer and the ambient temperature measured by the humidity sensor. For monitoring purposes I also plot the sensor temperature of the IR thermometer (marked as "detector temperature"); this should be similar to the ambient temperature but its exposed position makes it more likely to undergo solar heating and radiative cooling. For good measure I also plot the system temperature, which is measured by an LM61 temperature sensor connected to the ATmega1284P's analogue to digital converter. This measurement is noisy but useful to check the system doesn't overheat on sunny summer days.

The plan is to estimate the upper and lower bounds that I would expect for the sky temperature, and from that derive an estimate of the cloud cover. I initially expected that with complete cloud cover the sky temperature would match that the lifted condensation level, which I estimate using the ambient temperature and relative humidity. I soon saw temperatures higher than the LCL temperature. Research literature indicates that the clouds can act as a mirror at long IR wavelengths and thus the expected temperature should include an effect of ground temperature too. On the plots this is shown as the effective cloud temperature. The clear sky temperature is derived from results found in research literature but none of the equations tried so far have been a great match. Other researchers have fitted parameters for their specific location (including altitude) by comparison with visual measurements. I have yet to try this but daily measurements are made at the nearby Hazelrigg Weather Station. The graphs are too cluttered for production use but help me to understand what is happening.

Example plots

Below are a selection of plots. You can see the entire archive (from 2013-07-14) at http://aurorawatch.lancs.ac.uk/testing/cloudwatch/test2/.

cloud_detector_20130903
Cloud detector data for 2013-09-03. The asterisk (*) indicates derived parameters (ie not directly measured).
The figure above include most of the effects that can be identified. After midnight there is thick cloud, which later clears for short periods. At around 0300 UT I think it must have rained, the sky temperature is almost identical to the detector temperature and the variability is much reduced. Whilst the sensor is wet no sensible conclusions about cloud cover can be drawn. At about 0700 UT the sensor clears of water and the sky temperature falls indicating clearer skies. The rest of the day is dry, with heavy cloud cover until 1400 UT. At around 1700 UT the skies are completely clear. The clear sky estimate is too low for this time. At 2000 UT the clouds return, with some clear patches.


Cloud detector, 2013-09-28
Cloud detector data for 2013-09-28 showing the effect of clear skies.
The figure above shows an almost completely cloud-free day. The higher variability in the sky temperature measurements between 1200-1600 UT corresponds to similar effects in the humidity data (shown below); both are direct measurements made by different sensors.

Relative humidity, 2013-09-28
Humidity data for 2013-09-28. Notice how the higher variability occurs at the same times as the sky temperature measurements.

Dew

During summer operation dew has not been a problem but now that the nights are colder I have noticed effects which I believe are due to the formation of dew on the sensor. In the first plot below the sky temperature apparently rises from around 2230 UT. The rise is smooth and during this period the ambient temperature is falling, which overnight is often a sign of clear skies. After midnight (second plot) the sky temperature increases slightly before falling sharply around 0630 UT. Sunrise on this day was 0622 UT.

Cloud detector, 2013-10-05Cloud detector, 2013-10-06
This pair of plots is believed to show dew formation on the sensor.


Conclusions

I know from the informal comparisons with visual cloud cover that I regularly make the cloud detector does generally work very well. It does not function during wet periods. As anticipated dew is becoming a problem during the colder nights and a dew heater will be required for reliable winter operation. Future development will be to add a heater, which will need a wired connection to the cloud detector. Once a wired connection is made the radio link appears superfluous so I plan to investigate the options for power-over-ethernet. The Arduino ethernet shield is one possibility, although its compatibility with 3.3V operation has not been established.

Thursday, September 26, 2013

Auroraplot: data processing software for AuroraWatchNet

With the dispatch of the AuroraWatch schools' magnetometers imminent I have implemented a  Python  toolkit to process the data. The numpy and matplotlib modules are used extensively. The toolkit provides an API to load data and perform various processing actions on it, such as plotting data. The concept is influenced by my previous Multi-instrument Analysis toolbox for Matlab. In addition to the loading and processing of magnetic field data auroraplot allows other data types to be added later.

Loading data

Data can be loaded with arbitrary start and end times very simply:

md = ap.load_data('AURORAWATCHNET', 'LAN1', 'MagData',
                  np.datetime64('2013-09-20T12:00:00+0000'),
                  np.datetime64('2013-09-21T12:00:00+0000'))


In this case the selected portion of data crosses midnight and two data files must be loaded, concatenated and trimmed to get the desired time range. This is performed automatically by auroraplot, the user need not be concerned with the format of the files or where they are located. It is even possible for the files to be downloaded on-the-fly using FTP or HTTP transfer protocols.

load_data returns an object (of type MagData) to the user containing the actual magnetic field data and various other metadata, such as a timestamp for each sample and the data units. Each object can store more multiple data channels but all data points must share the same timestamps, be of the same type and share the same units. Therefore it is not possible to store operating temperatures (units °C) in an object holding magnetic field strength (units tesla). The operating temperature data can be accessed as:

td = ap.load_data('AURORAWATCHNET', 'LAN1', 'TemperatureData',
                  np.datetime64('2013-09-20T12:00:00+0000'),
                  np.datetime64('2013-09-21T12:00:00+0000'))


Battery voltage (data type VoltageData) can be accessed in a similar same way.

Plotting data

High-level plot functions enable the data be be plotted very simply, for the magnetic field data loaded previously

md.plot()


will produce a matplotlib figure with a title and the axes labelled with the correct units. Temperature and voltage data are plotted in the same way.

I have created some tools to make working with numpy's datetime64 and timedelta64 objects more convenient, including rounding functions (round, ceil and floor) which round to an interval. They are useful for finding the start of an hour, or the end of a day. I have also created Locator and Formatter classes to sensibly label time axes using datetime64 times and timedelta64 intervals. Tick marks are located on the nearest second, minute, hour, day, month or year boundary (or multiple thereof) depending on the time interval being displayed. Thanks to matplotlib's structure the labels are automatically regenerated with the most appropriate time units when a plot is zoomed.

Other operations

Quiet-day curves

Other operations include the generation of quiet-day curves. These are the curves from which we measure geomagnetic activity and are of critical importance for AuroraWatch UK. There are are not flat but have a daily variation caused by the equatorial electrojet. The empirical algorithm selects the days (typically 5) with the least geomagnetic activity. A truncated Fourier series is used to guarantee that the quiet-day curves are cyclic, with the start and end points having the same magnitude and slope. This is essential otherwise our rolling plots would show up the discontinuities in the QDC at midnight, and would falsely cause step changes in the geomagnetic activity. An example QDC is shown below.

qdc
Quiet-day curve for magnetometer at Lancaster ,UK. This is derived from recorded data
and clearly shows the Sq current system caused by the equatorial electrojet.

From this we can see that even on a geomagnetically quiet day we would expect a 30nT variation in field strength seen by the magnetometer. The AuroraWatch threshold for minor geomagnetic activity is 50nT so this shows the importance of using a quiet-day curve instead of a flat line when calculating geomagnetic activity.

Stack plots

Stack plots (also called magnetograms) are a convenient representation for magnetic field data from a set of magnetometers separated in latitude.Data from the northernmost instruments is placed at the top and that from the southernmost at the bottom. An example stackplot is shown below:

20130920
Stackplot showing data from two Lancaster stations and from Ormskirk.
The magnetometer at Ormskirk is operated by the Met Office as part of a test. The stackplots will be more interesting as the network grows.

Open source

The source code is available under a BSD-type license from Github.You will need python, along with the numpy (version 1.7), matplotlib and scipy python modules.auroraplot has been tested under Debian Linux (64 bit version) and Raspbian on the Raspberry Pi.


Thursday, August 8, 2013

Securing your SSH server against brute force password attacks

If you run an SSH server open to the whole internet you'll soon notice many attempts to break into your system using random username and password combinations. This 'noise' in the log files is annoying and might mean you miss an important message. If you are unlucky or use a common username and password your system might be compromised by one of these brute force attacks.

One method to drastically reduce the number of cracking attempts is to restrict access to the SSH server by IP address. This can done be done either by editing the SSH config file or by using configuring iptables. However this method requires valid users to have static IP addresses, something which most home users don't have. In many cases public key authentication is a better choice.

Use public key authentication

A better method to stop attackers from using random username and passwords is to switch off password authentication entirely and require public key authentication instead. Attackers will not be able to try random username/password combinations and will not create 'noise' in the log files. Valid users will still be able to connect.

To describe how this can be set up assume we wish to protect a computer with a static IP address called server. We wish to access it from another system called laptop, (which may be using a dynamic IP address). The account on server that we will access is dave. We'll assume that the SSH configuration file is /etc/ssh/sshd_config. Adjust these names to suit your setup.

Firstly, on laptop create a public/private key pair.
ssh-keygen -t dsa

A passphrase is not required although it is a good idea. On server make sure a ~/.ssh directory exists with the correct permissions:
mkdir ~dave/.ssh
chmod go= ~dave/.ssh

Using your favourite editor (emacs of course) paste the contents of the public key into the ~dave/.ssh/authorized_keys file on server. Putty users may find the instructions at http://www.howtoforge.com/ssh_key_based_logins_putty helpful. Check that you can log into server without requiring your password. If you are going to configure server remotely ensure you can log in without needing your password, otherwise you will lock yourself out! If you set a passphrase you will need to type that.

Configure the server

The key requirement for the server configuration is that by default password authentication is turned off. Find the line in /etc/ssh/sshd_config which sets password authentication. Make sure it is set to
PasswordAuthentication no
If necessary remove any leading # character. Whilst editting /etc/ssh/sshd_config its a good idea to disable empty passwords and root logins, ensure the following lines are set
PermitEmptyPasswords no
PermitRootLogin no
If you need empty passwords or root logins from specific hosts this can be overridden later.


Enable password authentication for trusted hosts

Once password authentication is disabled users on a multi-user system will have a problems copying their keys to grant them access! Exceptions can be made for trusted static IP addresses so that users can copy their public key. Assume we trust all IP addresses in the subnet 192.168.1.0/24. Passwords can then be enabled by simply adding the following lines to the end of /etc/ssh/sshd_config
Match Address 192.168.1.0/24
PasswordAuthentication yes

Enable root logins

Suppose a root login using password authentication is required for one host only (192.168.1.123). Add the following lines to /etc/ssh/sshd_config
Match Address 192.168.1.123
PasswordAuthentication yes
PermitRootLogin yes

Summary

These simple steps keep your SSH server accessible from everywhere but greatly reduce the likelihood of a successful brute force attack. The Match keyword requires openssh version 4.4 or later.

Thursday, May 30, 2013

Cloud detector: first data

Annotated plot for 2013-05-30.
The cloud detector has been operating outside for a few days now. The plot above is an example of the data I am getting, annotations added manually! The ambient temperature is the temperature of the sensor. In reality this may be a little warmer than ambient when it is exposed to direct sunlight. The sky temperature is the object temperature from the sensor. It is an average over its field of view, and in the absence of clouds it is also averaged in height. From the plot a number of features can be identified:

Clear sky
With no clouds to reflect back thermal radiation the sky temperature for a clear sky is very low, typically < -10°C. This results in a large difference (> 20°C) between ambient and sky temperatures.


Overcast sky
With the presence of clouds most thermal radiation is not lost to space but reflected back to Earth and the sensor. The difference between ambient and sky temperatures is small (< 10°C). With a uniform cloud coverage the variation in the difference is small.


Cloudy sky
A sky with partial cloud cover has an intermediate difference in ambient and sky temperatures. The cumulus clouds resulted in a large variation of the temperature difference, caused by the more sensitive central viewing area observing alternately clear sky and cloud. Complete coverage by a thin layer of cloud is expected to give an intermediate temperature difference but low variability.


Wet sensor
When the sensor is wet with rain the sky temperature is measured incorrectly since the water is not transparent to long-wave infra-red radiation and matches the ambient temperature. As wet weather implies cloud this is not a major problem although I have concerns over the time taken for the sensor to dry off.


Dew
The formation of dew is observed in the evening as the ambient temperature falls. The difference between ambient and sky temperature is reduced to less than 10°C.

Future work

Early operation shows that dew is a problem and can indicate cloud when the sky is actually clear. I have considered creative solutions such as painting the top of the box white and the bottom black in order to minimise heat lost to the sky and maximise heat absorbed from the ground. I expect this will only delay the onset when dew becomes a problem, not eliminate it. The only viable solution is to heat the sensor slightly (~2°C) above ambient, which means moving away from battery-powered operation. If a cable is used for power then wireless communications makes little sense, power-over-ethernet seems the way forward. A heated sensor will also reduce the drying time after rainfall.

I still have some concerns regarding waterproofing around the sensor. I have ordered the MLX90614ESF-DCH-000-TU-ND which features a 12° field of view. This narrower view is obtained by fitting a refractive germanium lens above the sensor. The TO-39 package has been modified to be taller than standard to accommodate the lens. The additional height should mean that the top of the sensor is above the cable gland. Water should not collect so easily and it should be possible to use silicone sealant without accidentally coating the sensor window.

Previously I tried pointing the sensor downwards and using a metal surface as a mirror to view the sky. The experiment was not successful and I think this was in part due to the wide field of  view of the sensor (90°) preventing a clear upward view without also observing the ground or enclosure. It will be worthwhile repeating the experiment with the narrow field of view sensor.

I only have basic plotting routines at present. The goal is to produce a cloud cover index, varying between 0 indicating no cloud and 1 indicating complete cloud cover. The index will be used as the basis for sending alerts.