├── doc └── QMC5883L-Datasheet-1.0.pdf ├── calibration ├── img │ ├── fig1_mobile-screenshot.png │ └── fig2_calibration-graph.png ├── make-random-points ├── README.md ├── 2d-calibration-get-samples └── 2d-calibration-make-calc ├── setup.py ├── README.md ├── py_qmc5883l └── __init__.py └── LICENSE /doc/QMC5883L-Datasheet-1.0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RigacciOrg/py-qmc5883l/HEAD/doc/QMC5883L-Datasheet-1.0.pdf -------------------------------------------------------------------------------- /calibration/img/fig1_mobile-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RigacciOrg/py-qmc5883l/HEAD/calibration/img/fig1_mobile-screenshot.png -------------------------------------------------------------------------------- /calibration/img/fig2_calibration-graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RigacciOrg/py-qmc5883l/HEAD/calibration/img/fig2_calibration-graph.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="py_qmc5883l", 8 | version="0.1.1", 9 | author="Niccolo Rigacci", 10 | author_email="niccolo@rigacci.org", 11 | description="Python driver for the QMC5883L 3-axis magnetic sensor", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/RigacciOrg/py-qmc5883l", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python", 18 | "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)", 19 | "Operating System :: OS Independent", 20 | ], 21 | ) 22 | -------------------------------------------------------------------------------- /calibration/make-random-points: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """Generate some pseudo-random points, aligned onto an ellipse.""" 4 | 5 | import numpy as np 6 | import sys 7 | 8 | A = 3500.0 # Semi-axis A 9 | B = 2600.0 # Semi-axis B 10 | Cx = -687.0 # Center Offset X 11 | Cy = -1380.0 # Center Offset Y 12 | perturb = 400.0 # Random error 13 | 14 | # Ellipse rotation: a positive angle is counter-clockwise. 15 | phi = np.pi * 0.22 # If phi < pi/4 then interpolated A > B 16 | #phi = np.pi * 0.35 # Interpolated A < B 17 | 18 | # Optional command-line argument range 0-100: means rotation 0-pi. 19 | if len(sys.argv) > 1: 20 | phi = np.pi * (float(sys.argv[1]) / 100.0) 21 | 22 | R = np.arange(0, 2*np.pi, 0.05) 23 | x = A * np.cos(R) + Cx + perturb * np.random.rand(len(R)) 24 | y = B * np.sin(R) + Cy + perturb * np.random.rand(len(R)) 25 | 26 | # Rotate all points counter-clockwise around the ellipse center. 27 | for i in range(0, len(x)): 28 | x1 = Cx + np.cos(phi) * (x[i] - Cx) - np.sin(phi) * (y[i] - Cy) 29 | y1 = Cy + np.sin(phi) * (x[i] - Cx) + np.cos(phi) * (y[i] - Cy) 30 | print("%f %f %f" % (x1, y1, 0)) 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python driver for the QMC5883L 3-Axis Magnetic Sensor 2 | 3 | Developed for the **Raspberry Pi**, requires the **python-smbus** package 4 | to access the I2C bus. 5 | 6 | Usage example: 7 | 8 | ```python 9 | import py_qmc5883l 10 | sensor = py_qmc5883l.QMC5883L() 11 | m = sensor.get_magnet() 12 | print(m) 13 | ``` 14 | 15 | The object constructor accepts some arguments, e.g. you can pass this one to 16 | switch the output range to 8 Gauss, for very strong magnetic fields which 17 | can otherwise overflow the sensor: 18 | 19 | ```python 20 | sensor = py_qmc5883l.QMC5883L(output_range=py_qmc5883l.RNG_8G) 21 | ``` 22 | 23 | The class constructor will initialize the sensor and put it into continuous 24 | read mode, where a new reading is available into the registers at the Output 25 | Data Rate (default is 10 Hz). To save power you can put the sensor in standby 26 | mode calling the **QMC5883L.mode_standby()** method. To wakeup the sensor, just 27 | call the **QMC5883L.mode_continuous()** once, and start getting values. 28 | 29 | ## Module installation 30 | 31 | Installing from the source should be as simple as running: 32 | 33 | ``` 34 | python setup.py install 35 | ``` 36 | 37 | Make sure that the install destination directory exists, e.g. for the 38 | Raspbian Stretch distro it is /usr/local/lib/python2.7/dist-packages. 39 | 40 | ## Output Range Scale 41 | 42 | The sensor produces values as 16 bit signed integers, i.e. 43 | numbers between -32768 and 32767. The field range is 44 | programmable with two different values: +/-2 gauss or +/-8 45 | gauss. The natural magnetic field produced by the Earth is 46 | generally between 0.25 and 0.65 gauss, so the 2 G range is 47 | preferable in natural environment. You can expect readings in 48 | the range +/-4000 (about 0.2 gauss). 49 | 50 | If you operate in presence of strong magnetic fields, you can 51 | experience reading overflows (over the 16 bit capabilities), in 52 | this case the driver will generate a warning and you can try to 53 | initialize the sensor in 8 gauss range, as seen above. 54 | 55 | ## Adjust for Magnetic Declination 56 | 57 | If you want that the **QMC5883L.get_bearing()** method return 58 | the current compass bearing adjusted by the *magnetic declination*, 59 | you have to set the **QMC5883L.declination** property. 60 | 61 | ```python 62 | sensor.get_bearing() 63 | # 87.20 64 | sensor.declination = 10.02 65 | sensor.get_bearing() 66 | # 97.22 67 | ``` 68 | 69 | The magnetic declination changes depending on the place and upon 70 | time; there are some web services which give your current value. 71 | 72 | ## Calibration 73 | 74 | Values returned by the magnetic sensor may be altered by several 75 | factors, like misalignment of sensor's axes, asimmetries in the 76 | sensor sensitivity, magnetic fields and magnetic (ferrous) 77 | metals in the proximity of the sensor. 78 | 79 | Into the **[calibration directory](calibration/)** there are 80 | some tools that can be used to perform a simple 2D calibration 81 | using the Earth's magnetic field. 82 | 83 | Once you have obtained the 3x3 calibration matrix, you can set 84 | it into the driver using the **calibration** property and have 85 | it automatically applied when calling the **get_bearing()** 86 | function. 87 | 88 | ```python 89 | sensor.calibration = [[1.030, 0.026, -227.799], 90 | [0.0255, 1.021, 1016.442], 91 | [0.0, 0.0, 1.0]] 92 | sensor.get_bearing() 93 | ``` 94 | 95 | ## Documentation 96 | 97 | Read the **[module source code](py_qmc5883l/__init__.py)** and the 98 | **[chip Datasheet](doc/QMC5883L-Datasheet-1.0.pdf)**. 99 | -------------------------------------------------------------------------------- /calibration/README.md: -------------------------------------------------------------------------------- 1 | # QMC5883L Magnetic Sensor Calibration 2 | 3 | Here we provide some tools that allows a simple calibration of 4 | the magnetic sensor. Actually there are three magnetic sensors 5 | in the QMC5883L chip, each one aligned along the three 6 | orthogonal axes X, Y and Z. In this calibration procedure **we 7 | ignore the Z axis**, and we let the sensor to work with its X-Y 8 | plane perfectly aligned to the Earth's surface. This will reduce 9 | a lot the complexity of gathering the required data and the 10 | complexity of visualizing the calibration data on a graph. 11 | 12 | The tools presented here are designed to be run on a **headless 13 | host** (i.e. without a connected display), using a text-only 14 | remote connection, whereas the tools aimed to do a full 3D 15 | calibration, generally require a realtime 3D graphic animation. 16 | 17 | ## Gathering data with 2d-calibration-get-samples 18 | 19 | 20 | 21 | First of all we need to execute the 22 | **2d-calibration-get-samples** script. It runs by doing a 23 | continuous read of the magnetic sensor and saving several data 24 | points all along the circumference. You need to turn the sensor 25 | all way round and wait for the counter to increment for each one 26 | of the 36 sectors, untill it became an hash **#** sign. 27 | 28 | In an ideal world (no misalignment of the sensor, sensor 29 | sensitivity perfectly simmetric, no deformation of the Earth's 30 | magnetif field) the acquired points **should align perfectly 31 | onto a circumference**, centered on the axes origin. More 32 | likely, the points **will align onto an ellipse with the center 33 | having some offset** from the axes origin. 34 | 35 | When a sufficient number of points are acquired (or when the "Q" 36 | key is pressed, the script will save the gathered data to a file 37 | and exit. The data file will be named 38 | **magnet-data\_YYYYmmdd\_HHMM.txt**. 39 | 40 | ## Executing 2d-calibration-make-calc 41 | 42 | 43 | 44 | This second script will calculate the **geometric 45 | transformation** required to transform the decentered ellipse 46 | into a perfectly centered circle. 47 | 48 | The result will be a **3x3 matrix** of floating point numbers, 49 | that the qmc5883l driver can use to provide a calibrated value 50 | for the **get\_bearing()** function. 51 | 52 | The result will be presented as a **Gnuplot script** which can 53 | be used to visualize the acquired points and the geometric 54 | transformation calculated. 55 | 56 | In details, the Python script will: 57 | 58 | 1. Calculate the **ellipse that best fits the data**, using the 59 | least squares method. 60 | 2. Calculate the **affine transformation matrix** from the 61 | ellipse to the circle with the radius equal to the ellipse major 62 | axis. 63 | 3. Output a **Gnuplot script** which generates a graph with: 64 | * the input **data points**; 65 | * the **fitting ellipse**; 66 | * the **affine transformation** circle; 67 | * the position of an **example point** before and after the 68 | transformation; 69 | * the affine transformation circle, **centered at the 70 | origin**; 71 | 72 | The commands to be executed from the command line are something 73 | like this: 74 | 75 | ``` 76 | 2d-calibration-get-samples 77 | 2d-calibration-make-calc magnet-data_20181018_1711.txt > gnuplot-script 78 | gnuplot gnuplot-script 79 | ``` 80 | 81 | The first lines of the Gnuplot script will contain the 82 | calculated transformation matrix, ready to be used into the 83 | **QMC5883L.calibration** property: 84 | 85 | ``` 86 | #!/usr/bin/gnuplot 87 | # 88 | # The calibration matrix (affine transformation with offset to origin): 89 | # 90 | # [[ 1.03033633e+00 2.55081314e-02 -2.27798862e+02] 91 | # [ 2.55081314e-02 1.02144837e+00 1.01644152e+03] 92 | # [ 0.00000000e+00 0.00000000e+00 1.00000000e+00]] 93 | # 94 | # The same matrix, as a Python array: 95 | # 96 | # sensor.calibration = [[1.0303, 0.0255, -227.7989], 97 | # [0.0255, 1.0214, 1016.4415], 98 | # [0.0, 0.0, 1.0]] 99 | ``` 100 | -------------------------------------------------------------------------------- /calibration/2d-calibration-get-samples: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Read data from a QMC5883L magnetic sensor, covering a full turn 5 | around the Z axis (i.e. on the X-Y plane). During the acquiring 6 | phase, it shows a curses interface to give a feedback on how 7 | many points were acquired and at what turning angle. When enough 8 | data is acquired (or when the "Q" key is pressed), it saves a 9 | text file with the raw "X Y Z" coordinates. 10 | """ 11 | 12 | import curses 13 | import datetime 14 | import math 15 | import textwrap 16 | import time 17 | import signal 18 | import sys 19 | import py_qmc5883l 20 | 21 | __author__ = "Niccolo Rigacci" 22 | __copyright__ = "Copyright 2018 Niccolo Rigacci " 23 | __license__ = "GPLv3-or-later" 24 | __email__ = "niccolo@rigacci.org" 25 | __version__ = "0.1.1" 26 | 27 | # Subdivide the entire circle in sectors, to group samples. 28 | SECTORS_COUNT = 36 29 | # How many samples to get per each sector. 30 | SAMPLES_PER_SECTOR = 50 31 | 32 | # Size of dial, in screen characters. 33 | DIAL_WIDTH = 37 34 | DIAL_HEIGHT = 19 35 | BORDER_X = 4 36 | BORDER_Y = 2 37 | 38 | # Measured values range 39 | SENSOR_MIN_VAL = -32768 40 | SENSOR_MAX_VAL = 32767 41 | 42 | RAW_DATA_FILE = "magnet-data_%s.txt" % (datetime.datetime.now().strftime('%Y%m%d_%H%M'),) 43 | 44 | # ------------------------------------------------------------------------ 45 | # Calculate the size of screen objects. 46 | # ------------------------------------------------------------------------ 47 | DIAL_RADIUS_X = float((DIAL_WIDTH - 1)/ 2.0) 48 | DIAL_RADIUS_Y = float((DIAL_HEIGHT -1) / 2.0) 49 | SECTOR_WIDTH = (2 * math.pi) / SECTORS_COUNT 50 | TOTAL_WIDTH = DIAL_WIDTH + BORDER_X * 2 51 | TOTAL_HEIGHT = DIAL_HEIGHT + BORDER_Y * 2 52 | 53 | # ------------------------------------------------------------------------ 54 | # ------------------------------------------------------------------------ 55 | def print_at(x, y, string, attr=curses.A_NORMAL): 56 | global stdscr 57 | try: 58 | stdscr.addstr(y, x, string, attr) 59 | stdscr.refresh() 60 | except: 61 | pass 62 | 63 | 64 | # ------------------------------------------------------------------------ 65 | # ------------------------------------------------------------------------ 66 | def terminate_handler(sig, frame): 67 | curses.endwin() 68 | sys.exit(1) 69 | 70 | # ------------------------------------------------------------------------ 71 | # Initialize the magnetic sensor and screen curses. 72 | # ------------------------------------------------------------------------ 73 | sensor = py_qmc5883l.QMC5883L() 74 | signal.signal(signal.SIGINT, terminate_handler) 75 | stdscr = curses.initscr() 76 | # Hide the cursor and make getch() non-blocking. 77 | curses.curs_set(0) 78 | curses.noecho() 79 | stdscr.nodelay(1) 80 | stdscr.refresh() 81 | 82 | # Draw a box. 83 | print_at(0, 0, "-" * TOTAL_WIDTH) 84 | print_at(0, TOTAL_HEIGHT - 1, "-" * TOTAL_WIDTH) 85 | for i in range(1, TOTAL_HEIGHT-1): 86 | print_at(0, i, "|") 87 | print_at(TOTAL_WIDTH-1, i, "|") 88 | msg = 'Do a complete rotation of the sensor on the XY plane. When enough samples are acquired, each sector will be marked with an "#".' 89 | print_at(0, TOTAL_HEIGHT+2, textwrap.fill(msg, TOTAL_WIDTH)) 90 | 91 | # Inizialize samples dictionary and print dial on screen. 92 | SAMPLES = {} 93 | for i in range(0, SECTORS_COUNT): 94 | SAMPLES[i] = [] 95 | angle = SECTOR_WIDTH * i 96 | DOT_X = BORDER_X + int(DIAL_RADIUS_X + DIAL_RADIUS_X * math.sin(angle)) 97 | DOT_Y = BORDER_Y + int(DIAL_RADIUS_Y - DIAL_RADIUS_Y * math.cos(angle)) 98 | print_at(DOT_X, DOT_Y, ".") 99 | print_at(BORDER_X + int(DIAL_RADIUS_X), BORDER_Y + int(DIAL_RADIUS_Y), '+') 100 | print_at(BORDER_X + int(DIAL_RADIUS_X), BORDER_Y - 1, 'N') 101 | print_at(BORDER_X + int(DIAL_RADIUS_X), BORDER_Y + DIAL_HEIGHT, 'S') 102 | print_at(BORDER_X + DIAL_WIDTH, BORDER_Y + int(DIAL_RADIUS_Y), 'E') 103 | print_at(BORDER_X - 1, BORDER_Y + int(DIAL_RADIUS_Y), 'W') 104 | 105 | # Loop to acquire data for the entire circumference. 106 | completed_sectors = 0 107 | NEEDLE_X = NEEDLE_Y = 1 108 | while True: 109 | (x, y, z) = sensor.get_magnet_raw() 110 | if x is not None and y is not None: 111 | # Angle on the XY plane from magnetic sensor. 112 | angle = math.atan2(y, x) 113 | if angle < 0: 114 | angle += 2 * math.pi 115 | sector = int(angle / SECTOR_WIDTH) 116 | sampled = len(SAMPLES[sector]) 117 | # Needle angle, rounded to sector center. 118 | needle_angle = ((2 * math.pi) / SECTORS_COUNT) * sector 119 | # Hide compass needle at previous position. 120 | print_at(NEEDLE_X, NEEDLE_Y, " ") 121 | # Print compass needle. 122 | NEEDLE_X = BORDER_X + int(DIAL_RADIUS_X + DIAL_RADIUS_X * 0.8 * math.sin(needle_angle)) 123 | NEEDLE_Y = BORDER_Y + int(DIAL_RADIUS_Y - DIAL_RADIUS_Y * 0.8 * math.cos(needle_angle)) 124 | print_at(NEEDLE_X, NEEDLE_Y, "O", curses.A_REVERSE) 125 | print_at(0, TOTAL_HEIGHT, "(X, Y) = (%s, %s), Compass: %s deg" 126 | % ("{:6d}".format(x), "{:6d}".format(y), "{:5.1f}".format(math.degrees(angle)))) 127 | if sampled < SAMPLES_PER_SECTOR: 128 | DOT_X = BORDER_X + int(DIAL_RADIUS_X + DIAL_RADIUS_X * math.sin(needle_angle)) 129 | DOT_Y = BORDER_Y + int(DIAL_RADIUS_Y - DIAL_RADIUS_Y * math.cos(needle_angle)) 130 | SAMPLES[sector].append([x, y, z]) 131 | sampled += 1 132 | completed = int(10 * (float(sampled) / SAMPLES_PER_SECTOR)) 133 | if completed < 10: 134 | completed = str(completed) 135 | attr = curses.A_NORMAL 136 | else: 137 | completed = '#' 138 | attr = curses.A_REVERSE 139 | print_at(DOT_X, DOT_Y, completed, attr) 140 | if sampled >= SAMPLES_PER_SECTOR: 141 | completed_sectors += 1 142 | if completed_sectors >= SECTORS_COUNT: 143 | break 144 | time.sleep(0.10) 145 | time.sleep(0.05) 146 | key = stdscr.getch() 147 | if key == ord('q'): 148 | break 149 | curses.endwin() 150 | 151 | # Print raw values. 152 | with open(RAW_DATA_FILE, "w") as f: 153 | for i in range(0, SECTORS_COUNT): 154 | if len(SAMPLES[i]) > 0: 155 | for s in SAMPLES[i]: 156 | line = "%.1f %.1f %.1f" % (s[0], s[1], s[2]) 157 | f.write(line + "\n") 158 | print(u'Raw data written to file "%s"' % (RAW_DATA_FILE,)) 159 | -------------------------------------------------------------------------------- /py_qmc5883l/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Python driver for the QMC5883L 3-Axis Magnetic Sensor. 4 | 5 | Usage example: 6 | 7 | import py_qmc5883l 8 | sensor = py_qmc5883l.QMC5883L() 9 | m = sensor.get_magnet() 10 | print(m) 11 | 12 | you will get three 16 bit signed integers, representing the values 13 | of the magnetic sensor on axis X, Y and Z, e.g. [-1257, 940, -4970]. 14 | """ 15 | 16 | import logging 17 | import math 18 | import time 19 | import smbus 20 | 21 | __author__ = "Niccolo Rigacci" 22 | __copyright__ = "Copyright 2018 Niccolo Rigacci " 23 | __license__ = "GPLv3-or-later" 24 | __email__ = "niccolo@rigacci.org" 25 | __version__ = "0.1.4" 26 | 27 | DFLT_BUS = 1 28 | DFLT_ADDRESS = 0x0d 29 | 30 | REG_XOUT_LSB = 0x00 # Output Data Registers for magnetic sensor. 31 | REG_XOUT_MSB = 0x01 32 | REG_YOUT_LSB = 0x02 33 | REG_YOUT_MSB = 0x03 34 | REG_ZOUT_LSB = 0x04 35 | REG_ZOUT_MSB = 0x05 36 | REG_STATUS_1 = 0x06 # Status Register. 37 | REG_TOUT_LSB = 0x07 # Output Data Registers for temperature. 38 | REG_TOUT_MSB = 0x08 39 | REG_CONTROL_1 = 0x09 # Control Register #1. 40 | REG_CONTROL_2 = 0x0a # Control Register #2. 41 | REG_RST_PERIOD = 0x0b # SET/RESET Period Register. 42 | REG_CHIP_ID = 0x0d # Chip ID register. 43 | 44 | # Flags for Status Register #1. 45 | STAT_DRDY = 0b00000001 # Data Ready. 46 | STAT_OVL = 0b00000010 # Overflow flag. 47 | STAT_DOR = 0b00000100 # Data skipped for reading. 48 | 49 | # Flags for Status Register #2. 50 | INT_ENB = 0b00000001 # Interrupt Pin Enabling. 51 | POL_PNT = 0b01000000 # Pointer Roll-over. 52 | SOFT_RST = 0b10000000 # Soft Reset. 53 | 54 | # Flags for Control Register 1. 55 | MODE_STBY = 0b00000000 # Standby mode. 56 | MODE_CONT = 0b00000001 # Continuous read mode. 57 | ODR_10HZ = 0b00000000 # Output Data Rate Hz. 58 | ODR_50HZ = 0b00000100 59 | ODR_100HZ = 0b00001000 60 | ODR_200HZ = 0b00001100 61 | RNG_2G = 0b00000000 # Range 2 Gauss: for magnetic-clean environments. 62 | RNG_8G = 0b00010000 # Range 8 Gauss: for strong magnetic fields. 63 | OSR_512 = 0b00000000 # Over Sample Rate 512: less noise, more power. 64 | OSR_256 = 0b01000000 65 | OSR_128 = 0b10000000 66 | OSR_64 = 0b11000000 # Over Sample Rate 64: more noise, less power. 67 | 68 | 69 | class QMC5883L(object): 70 | """Interface for the QMC5883l 3-Axis Magnetic Sensor.""" 71 | def __init__(self, 72 | i2c_bus=DFLT_BUS, 73 | address=DFLT_ADDRESS, 74 | output_data_rate=ODR_10HZ, 75 | output_range=RNG_2G, 76 | oversampling_rate=OSR_512): 77 | 78 | self.address = address 79 | self.bus = smbus.SMBus(i2c_bus) 80 | self.output_range = output_range 81 | self._declination = 0.0 82 | self._calibration = [[1.0, 0.0, 0.0], 83 | [0.0, 1.0, 0.0], 84 | [0.0, 0.0, 1.0]] 85 | chip_id = self._read_byte(REG_CHIP_ID) 86 | if chip_id != 0xff: 87 | msg = "Chip ID returned 0x%x instead of 0xff; is the wrong chip?" 88 | logging.warning(msg, chip_id) 89 | self.mode_cont = (MODE_CONT | output_data_rate | output_range 90 | | oversampling_rate) 91 | self.mode_stby = (MODE_STBY | ODR_10HZ | RNG_2G | OSR_64) 92 | self.mode_continuous() 93 | 94 | def __del__(self): 95 | """Once finished using the sensor, switch to standby mode.""" 96 | self.mode_standby() 97 | 98 | def mode_continuous(self): 99 | """Set the device in continuous read mode.""" 100 | self._write_byte(REG_CONTROL_2, SOFT_RST) # Soft reset. 101 | self._write_byte(REG_CONTROL_2, INT_ENB) # Disable interrupt. 102 | self._write_byte(REG_RST_PERIOD, 0x01) # Define SET/RESET period. 103 | self._write_byte(REG_CONTROL_1, self.mode_cont) # Set operation mode. 104 | 105 | def mode_standby(self): 106 | """Set the device in standby mode.""" 107 | self._write_byte(REG_CONTROL_2, SOFT_RST) 108 | self._write_byte(REG_CONTROL_2, INT_ENB) 109 | self._write_byte(REG_RST_PERIOD, 0x01) 110 | self._write_byte(REG_CONTROL_1, self.mode_stby) # Set operation mode. 111 | 112 | def _write_byte(self, registry, value): 113 | self.bus.write_byte_data(self.address, registry, value) 114 | time.sleep(0.01) 115 | 116 | def _read_byte(self, registry): 117 | return self.bus.read_byte_data(self.address, registry) 118 | 119 | def _read_word(self, registry): 120 | """Read a two bytes value stored as LSB and MSB.""" 121 | low = self.bus.read_byte_data(self.address, registry) 122 | high = self.bus.read_byte_data(self.address, registry + 1) 123 | val = (high << 8) + low 124 | return val 125 | 126 | def _read_word_2c(self, registry): 127 | """Calculate the 2's complement of a two bytes value.""" 128 | val = self._read_word(registry) 129 | if val >= 0x8000: # 32768 130 | return val - 0x10000 # 65536 131 | else: 132 | return val 133 | 134 | def get_data(self): 135 | """Read data from magnetic and temperature data registers.""" 136 | i = 0 137 | [x, y, z, t] = [None, None, None, None] 138 | while i < 20: # Timeout after about 0.20 seconds. 139 | status = self._read_byte(REG_STATUS_1) 140 | if status & STAT_OVL: 141 | # Some values have reached an overflow. 142 | msg = ("Magnetic sensor overflow.") 143 | if self.output_range == RNG_2G: 144 | msg += " Consider switching to RNG_8G output range." 145 | logging.warning(msg) 146 | if status & STAT_DOR: 147 | # Previous measure was read partially, sensor in Data Lock. 148 | x = self._read_word_2c(REG_XOUT_LSB) 149 | y = self._read_word_2c(REG_YOUT_LSB) 150 | z = self._read_word_2c(REG_ZOUT_LSB) 151 | continue 152 | if status & STAT_DRDY: 153 | # Data is ready to read. 154 | x = self._read_word_2c(REG_XOUT_LSB) 155 | y = self._read_word_2c(REG_YOUT_LSB) 156 | z = self._read_word_2c(REG_ZOUT_LSB) 157 | t = self._read_word_2c(REG_TOUT_LSB) 158 | break 159 | else: 160 | # Waiting for DRDY. 161 | time.sleep(0.01) 162 | i += 1 163 | return [x, y, z, t] 164 | 165 | def get_magnet_raw(self): 166 | """Get the 3 axis values from magnetic sensor.""" 167 | [x, y, z, t] = self.get_data() 168 | return [x, y, z] 169 | 170 | def get_magnet(self): 171 | """Return the horizontal magnetic sensor vector with (x, y) calibration applied.""" 172 | [x, y, z] = self.get_magnet_raw() 173 | if x is None or y is None: 174 | [x1, y1] = [x, y] 175 | else: 176 | c = self._calibration 177 | x1 = x * c[0][0] + y * c[0][1] + c[0][2] 178 | y1 = x * c[1][0] + y * c[1][1] + c[1][2] 179 | return [x1, y1] 180 | 181 | def get_bearing_raw(self): 182 | """Horizontal bearing (in degrees) from magnetic value X and Y.""" 183 | [x, y, z] = self.get_magnet_raw() 184 | if x is None or y is None: 185 | return None 186 | else: 187 | b = math.degrees(math.atan2(y, x)) 188 | if b < 0: 189 | b += 360.0 190 | return b 191 | 192 | def get_bearing(self): 193 | """Horizontal bearing, adjusted by calibration and declination.""" 194 | [x, y] = self.get_magnet() 195 | if x is None or y is None: 196 | return None 197 | else: 198 | b = math.degrees(math.atan2(y, x)) 199 | if b < 0: 200 | b += 360.0 201 | b += self._declination 202 | if b < 0.0: 203 | b += 360.0 204 | elif b >= 360.0: 205 | b -= 360.0 206 | return b 207 | 208 | def get_temp(self): 209 | """Raw (uncalibrated) data from temperature sensor.""" 210 | [x, y, z, t] = self.get_data() 211 | return t 212 | 213 | def set_declination(self, value): 214 | """Set the magnetic declination, in degrees.""" 215 | try: 216 | d = float(value) 217 | if d < -180.0 or d > 180.0: 218 | logging.error(u'Declination must be >= -180 and <= 180.') 219 | else: 220 | self._declination = d 221 | except: 222 | logging.error(u'Declination must be a float value.') 223 | 224 | def get_declination(self): 225 | """Return the current set value of magnetic declination.""" 226 | return self._declination 227 | 228 | def set_calibration(self, value): 229 | """Set the 3x3 matrix for horizontal (x, y) magnetic vector calibration.""" 230 | c = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] 231 | try: 232 | for i in range(0, 3): 233 | for j in range(0, 3): 234 | c[i][j] = float(value[i][j]) 235 | self._calibration = c 236 | except: 237 | logging.error(u'Calibration must be a 3x3 float matrix.') 238 | 239 | def get_calibration(self): 240 | """Return the current set value of the calibration matrix.""" 241 | return self._calibration 242 | 243 | declination = property(fget=get_declination, 244 | fset=set_declination, 245 | doc=u'Magnetic declination to adjust bearing.') 246 | 247 | calibration = property(fget=get_calibration, 248 | fset=set_calibration, 249 | doc=u'Transformation matrix to adjust (x, y) magnetic vector.') 250 | -------------------------------------------------------------------------------- /calibration/2d-calibration-make-calc: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Read magnetic sensor data (pair of "X Y" coordinates) from a file, then: 5 | 6 | 1) Calculate the ellipse that best fits the data, using the least 7 | squares method. 8 | 2) Calculate the affine transformation matrix from the ellipse 9 | to the circle with the radius equal to the ellipse major axis. 10 | 3) Output a Gnuplot script which generates a graph with: 11 | * the input data points; 12 | * the fitting ellipse; 13 | * the affine transformation circle; 14 | * the position of an example point before and after the 15 | transformation; 16 | * the affine transformation circle, centered at the origin; 17 | 18 | Requires the python-numpy package. 19 | 20 | Web References: 21 | * Fitting an Ellipse to a Set of Data Points 22 | http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html 23 | * Circle affine transformation 24 | https://math.stackexchange.com/questions/619037/circle-affine-transformation 25 | * How to fit a 2D ellipse to given points 26 | https://stackoverflow.com/questions/47873759/how-to-fit-a-2d-ellipse-to-given-points 27 | * Fitting an ellipse to a set of data points in python (nan values in axes) 28 | https://stackoverflow.com/questions/39693869/fitting-an-ellipse-to-a-set-of-data-points-in-python 29 | 30 | Releases 31 | 32 | 2020-06-11 - Released version 0.2.0 33 | * Added an alternative method in fit_ellipse() to avoid sqrt of negative 34 | numbers in some weird cases, causing nan values for ellipse axes. 35 | * Fixed a potential problem calcluating MAX_SCALE 36 | """ 37 | 38 | import os.path 39 | import json 40 | import numpy as np 41 | from numpy.linalg import eig, inv 42 | import sys 43 | 44 | __author__ = "Niccolo Rigacci" 45 | __copyright__ = "Copyright 2018 Niccolo Rigacci " 46 | __license__ = "GPLv3-or-later" 47 | __email__ = "niccolo@rigacci.org" 48 | __version__ = "0.2.0" 49 | 50 | if len(sys.argv) > 1: 51 | RAW_DATA_FILE = sys.argv[1] 52 | else: 53 | print(u"Usage: %s {raw_data_file}" % (os.path.basename(sys.argv[0]))) 54 | sys.exit(1) 55 | 56 | # Take a point of the ellipse to show affine transformation to circle. 57 | # This is the counter-clockwise angle from the X positive axis. 58 | if len(sys.argv) > 2: 59 | TEST_PHI = 2 * np.pi * float(sys.argv[2]) / 100.0 60 | else: 61 | TEST_PHI = np.pi * 0.3 62 | 63 | # Measured values range. 64 | SENSOR_MIN_VAL = -32768 65 | SENSOR_MAX_VAL = 32767 66 | 67 | # Name of the image generated by Gnuplot. 68 | if RAW_DATA_FILE[-4] == u'.': 69 | OUTPUT_PNG = RAW_DATA_FILE[0:-4] + u'.png' 70 | else: 71 | OUTPUT_PNG = RAW_DATA_FILE + u'.png' 72 | 73 | 74 | def read_data_file(): 75 | """Read a file with "x y" data lines. Return two lists with x and 76 | y values, plus the min/max values for x and y.""" 77 | global SENSOR_MAX_VAL, SENSOR_MIN_VAL 78 | min_x = min_y = SENSOR_MAX_VAL 79 | max_x = max_y = SENSOR_MIN_VAL 80 | x = [] 81 | y = [] 82 | with open(RAW_DATA_FILE, 'r') as f: 83 | for line in f: 84 | values = line.strip().split() 85 | data_x = float(values[0]) 86 | data_y = float(values[1]) 87 | x.append(data_x) 88 | y.append(data_y) 89 | if data_x < min_x: 90 | min_x = data_x 91 | if data_x > max_x: 92 | max_x = data_x 93 | if data_y < min_y: 94 | min_y = data_y 95 | if data_y > max_y: 96 | max_y = data_y 97 | return x, y, min_x, min_y, max_x, max_y 98 | 99 | 100 | def fit_ellipse(x, y, use_abs=True): 101 | """Return the best fit ellipse from two numpy.ndarray 102 | (multidimensional arrays) of vertices.""" 103 | x = x[:, np.newaxis] 104 | y = y[:, np.newaxis] 105 | D = np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x))) 106 | S = np.dot(D.T, D) 107 | C = np.zeros([6,6]) 108 | C[0, 2] = C[2, 0] = 2; C[1, 1] = -1 109 | E, V = eig(np.dot(inv(S), C)) 110 | if use_abs: 111 | n = np.argmax(np.abs(E)) 112 | else: 113 | # Use this if semi axes are invalid (sqrt of negative). 114 | n = np.argmax(E) 115 | a = V[:, n] 116 | return a 117 | 118 | 119 | def ellipse_center(a): 120 | """Return the coordinates of the ellipse center.""" 121 | b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] 122 | num = b*b-a*c 123 | x0=(c*d-b*f)/num 124 | y0=(a*f-b*d)/num 125 | return np.array([x0, y0]) 126 | 127 | 128 | def ellipse_semi_axes_length(a): 129 | """Return the lenght of both semi-axes of the ellipse.""" 130 | b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] 131 | up = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g) 132 | down1=(b*b-a*c)*( (c-a)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) 133 | down2=(b*b-a*c)*( (a-c)*np.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a)) 134 | if (up/down1) >= 0 and (up/down2) >= 0: 135 | res1=np.sqrt(up/down1) 136 | res2=np.sqrt(up/down2) 137 | else: 138 | res1 = None 139 | res2 = None 140 | return np.array([res1, res2]) 141 | 142 | def ellipse_angle_of_rotation(a): 143 | """Return the rotation angle (in radians) of the ellipse axes. 144 | A positive angle means counter-clockwise rotation.""" 145 | b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] 146 | return 0.5*np.arctan(2*b/(a-c)) 147 | 148 | 149 | def affine_matrix(a, b, phi, to_origin=False): 150 | """Matrix for affine transformation from ellipse to circle.""" 151 | if a >= b: 152 | # Affine transformation to circle with R = A (major axis). 153 | ab_ratio = float(a) / float(b) 154 | cos_phi = np.cos(phi) 155 | sin_phi = np.sin(phi) 156 | else: 157 | # Swap A and B axis: transformation to circle with R = B (major axis). 158 | ab_ratio = float(b) / float(a) 159 | cos_phi = np.cos(phi+np.pi/2) 160 | sin_phi = np.sin(phi+np.pi/2) 161 | # R1 and R2: matrix to rotate the ellipse orthogonal to the axes and back. 162 | # T1 and T2: matrix to translate the ellipse to the origin and back. 163 | # D: matrix to scale ellipse to circle. 164 | R1 = np.array([[cos_phi, sin_phi, 0], [-sin_phi, cos_phi, 0], [0, 0, 1]], dtype=float) 165 | R2 = np.array([[cos_phi, -sin_phi, 0], [sin_phi, cos_phi, 0], [0, 0, 1]], dtype=float) 166 | T1 = np.array([[1, 0, -cx], [0, 1, -cy], [0, 0, 1]], dtype=float) 167 | T2 = np.array([[1, 0, cx], [0, 1, cy], [0, 0, 1]], dtype=float) 168 | D = np.array([[1, 0, 0], [0, ab_ratio, 0], [0, 0, 1]], dtype=float) 169 | if to_origin: 170 | # Transformation shifted to axes origin. 171 | return np.matmul(np.matmul(np.matmul(R2, D), R1), T1) 172 | else: 173 | # Transformation centered with the ellipse. 174 | return np.matmul(np.matmul(np.matmul(np.matmul(T2, R2), D), R1), T1) 175 | 176 | 177 | # Read data from file. 178 | x, y, min_x, min_y, max_x, max_y = read_data_file() 179 | MAX_SCALE = int(max(abs(min_x), abs(max_x), abs(min_y), abs(max_y)) / 500.0 * 750.0) 180 | 181 | # Convert lists x and y into Numpy N-dimensional arrays. 182 | x_arr = np.fromiter(x, np.float) 183 | y_arr = np.fromiter(y, np.float) 184 | 185 | # Calculate the ellipse which best fits the data. 186 | warning = '' 187 | ellipse = fit_ellipse(x_arr, y_arr) 188 | [cx, cy] = ellipse_center(ellipse) 189 | [a, b] = ellipse_semi_axes_length(ellipse) 190 | phi = ellipse_angle_of_rotation(ellipse) 191 | # If semi axes are invalid, try a different method. 192 | if a == None or b == None: 193 | warning = "Invalid semi axes detected: using fit_ellipse() without np.abs()." 194 | ellipse = fit_ellipse(x_arr, y_arr, use_abs=False) 195 | [cx, cy] = ellipse_center(ellipse) 196 | [a, b] = ellipse_semi_axes_length(ellipse) 197 | phi = ellipse_angle_of_rotation(ellipse) 198 | 199 | # Calculate the coordinates of semi-axes vertices. 200 | ax = cx + a * np.cos(phi) 201 | ay = cy + a * np.sin(phi) 202 | bx = cx + b * np.cos(phi + np.pi/2) 203 | by = cy + b * np.sin(phi + np.pi/2) 204 | 205 | # Calculate the affine transformation matrix: 206 | # centered with the best fitting ellipse... 207 | M = affine_matrix(a, b, phi, to_origin=False) 208 | # centered on the origin... 209 | M1 = affine_matrix(a, b, phi, to_origin=True) 210 | 211 | # Take P1: an example point to be transformed. 212 | x1 = cx + a*np.cos(TEST_PHI)*np.cos(phi) - b*np.sin(TEST_PHI)*np.sin(phi) 213 | y1 = cy + a*np.cos(TEST_PHI)*np.sin(phi) + b*np.sin(TEST_PHI)*np.cos(phi) 214 | P1 = np.array([x1, y1, 1], dtype=float) 215 | P1.shape = (3,1) 216 | 217 | # Calculate P2: the affine transformation of the example point. 218 | P2 = np.matmul(M, P1) 219 | x2 = P2[0, 0] 220 | y2 = P2[1, 0] 221 | 222 | # Output the Gnuplot recipe. 223 | GNUPLOT_SCRIPT = u"""#!/usr/bin/gnuplot 224 | # 225 | # The calibration matrix (affine transformation with offset to origin): 226 | # 227 | # %s 228 | # 229 | # The same matrix, as a Python array: 230 | # 231 | # sensor.calibration = %s 232 | # 233 | # %s 234 | # 235 | input_data = "%s" 236 | set output "%s" 237 | circle_size = %d * 0.02 238 | raw_data_color = "#28e828" 239 | ellipse_color = "#38a838" 240 | affine_offset_color = "#d0d0d0" 241 | affine_centered_color = "#c020c0" 242 | set term png size 1200, 1200 font "Helvetica,18" 243 | set style line 100 lc rgb raw_data_color lw 1 244 | set style line 300 lc rgb ellipse_color lw 3 245 | set style line 400 lc rgb affine_offset_color lw 3 246 | set style line 500 lc rgb affine_centered_color lw 3 247 | set style fill transparent solid 0.50 248 | set title "QMC5883L Magnetic Sensor X-Y Plane Calibration" 249 | set size ratio 1 250 | set xzeroaxis 251 | set yzeroaxis 252 | set xrange [-%d:%d] 253 | set yrange [-%d:%d] 254 | set label 40 center at graph 0.5,char 1.5 \\ 255 | "Ellipse center (x, y) = (%d, %d), Semi-axis (a, b) = (%d, %d), Rotation = %.1f°" 256 | set bmargin 5 257 | set object 20 ellipse center %.2f,%.2f size %.2f,%.2f angle %.2f \\ 258 | front fillstyle empty border lc rgb ellipse_color lw 3 259 | set object 10 circle center %.2f,%.2f size %.2f \\ 260 | front fillstyle empty border lc rgb affine_offset_color lw 3 261 | set object 30 circle center 0,0 size %.2f \\ 262 | front fillstyle empty border lc rgb affine_centered_color lw 3 263 | plot input_data using 1:2:(circle_size) with circles linestyle 100 \\ 264 | title "Raw Data", \\ 265 | " 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------