• Tiada Hasil Ditemukan

I had my conflicts eased throughout this research and managed to finish this project in the timescale given

N/A
N/A
Protected

Academic year: 2022

Share "I had my conflicts eased throughout this research and managed to finish this project in the timescale given"

Copied!
82
0
0

Tekspenuh

(1)

ON-BOARD DATA HANDLING FOR CUBESAT USING RASPBERRY PI

by

MUHAMMAD HAKIIM BIN ZAINUDIN

Thesis submitted in fulfilment of the requirements for Bachelor Degree of Aerospace Engineering (Honours) (Aerospace Engineering)

(2)

1 Endorsement

I, Muhammad Hakiim Bin Zainudin hereby declare that I have checked and revised the whole draft of dissertation as required by my supervisor.

MUHAMMAD HAKIIM BIN ZAINUDIN

DR SITI HARWANI BINTI MD YUSOFF

Date:

DR NORIZHAM BIN ABDUL RAZAK

Date:

(3)

2

DECLARATION

This thesis is a result of my own investigation, except where otherwise stated and has not previously been accepted in substance for any degree and is not being concurrently submitted in candidature for any other degree.

MUHAMMAD HAKIIM BIN ZAINUDIN

Date:

(4)

3

ACKNOWLEDGEMENT

First and foremost, I would express my sincere gratitude to Allah S.W.T that he granted me a good health during this project. I had my conflicts eased throughout this research and managed to finish this project in the timescale given.

Next, I would like to thank my supervisor, Puan Siti Harwani Binti Md for supporting me through this 9-month period with his knowledge. Without Puan Siti Harwani’s encouragement and support, I would not have managed to complete this research.

Apart from that, I would like to thank Dr Norilmi Amilia Ismail who provided helps in understanding the project at an early stage. I also want to thank my friends who together in this MySat project. They helped me a lot in helping me to configure what I need to do.

They also share their experience and knowledge with me without any limitation in order to complete this project together.

Lastly, I feel indebted to my parents Mr Salleh Hudin and Mrs Mazmin throughout this research. Since I am this eldest sibling in the house I had a few responsibilities on my younger siblings. Understanding the importance of this project, my parents gave me full freedom during this period of time and did not insist me in helping them by getting back to hometown when I am busy.

(5)

4

ON-BOARD DATA HANDLING FOR CUBESAT USING RASPBERRY PI

Abstract

Outer space is such a mysterious place, full of questions, and we humans tend to seek for the answers. That’s why human develop space exploration. From this development, satellite was born. The development of satellite alone help human in many ways. Satellite has become a device that very important to human in so many fields. Nowadays, satellite has evolved, to smaller size, and cheaper in price. It is called CubeSat. A CubeSat is a small cube with size of 1U which is 10cm x 10cm x 10 cm, and consist of power supply, on-board controller, payload and transmitter. On-board data handling helps to control the satellite automatically. It also helps a satellite to gather various data from payload and collect information about the condition of the satellite. There’s a lot of data handling being developed right now such as Arduino, Raspberry Pi and Basic-X24. Arduino and Basic X-24 widely used in CubeSat on-board data handling but Raspberry Pi still in development. Raspberry Pi hold a lot of potential to become one of the on-board data handling for CubeSat. There’s only a few of CubeSat that contain Raspberry Pi that really go to space such as Pi-Sat. Raspberry Pi can be said a lot more powerful in term of processing power but has a few problems in the development to launch in space because Raspberry Pi not generally build to go to space. Raspberry Pi always need a modification to sustain harsh environment of space.

(6)

5

PAPAN PENGENDALIAN DATA UNTUK CUBESAT MENGGUNAKAN RASPBERRY PI

Abstrak

Ruang angkasa merupakan tempat yang misteri dan penuh dengan tanda tanya. Kita manusia yang selalu cenderung mencari jawapan. Oleh sebab itu, manusia cuba memajukan penerokaan ruang angkasa. Dari perkembangan ini, satelit dilahirkan.

Perkembangan satelit semata-mata membantu manusia dalam pelbagai cara. Satelit telah menjadi alat yang sangat penting untuk manusia dalam banyak bidang. Pada dewasa ini, satelit telah mengecil, kepada saiz yang lebih kecil, dan harga yang lebih murah. Ia dipanggil CubeSat. A CubeSat adalah kiub kecil dengan saiz 1U iaitu 10cm x 10cm x 10 cm, dan terdiri daripada bekalan kuasa, pengawal di atas kapal, muatan dan pemancar.

Papan pengendalian data membantu mengendalikan satelit secara automatik. Ia juga membantu satelit untuk mengumpulkan pelbagai data dari muatan dan mengumpulkan maklumat mengenai keadaan satelit. Terdapat banyak papan pengendalian data yang sedang dimajukan sekarang seperti Arduino, Raspberry Pi dan Basic-X24. Arduino dan Basic X-24 digunakan secara meluas dalam pengendalian data papan atas CubeSat tetapi masih dalam pembangunan. Raspberry Pi mempunyai banyak potensi untuk menjadi salah satu pengendalian data di papan atas untuk CubeSat. Terdapat hanya beberapa CubeSat yang mengandungi Raspberry Pi yang benar-benar pergi ke angkasa seperti Pi- Sat. Raspberry Pi boleh dikatakan jauh lebih berkuasa dari segi kuasa pemprosesan tetapi mempunyai beberapa masalah dalam pembangunan untuk melancarkan ruang angkasa kerana Raspberry Pi tidak biasanya dibina untuk pergi ke ruang angkasa. Raspberry Pi sentiasa memerlukan pengubahsuaian kerana angkasa merupakan persekitaran yang bahaya.

(7)

6

Table of content

Abstract 4

Abstrak 5

Table of content 6

List of figures 7

List of tables 8

Chapter 1 9

Introduction 9

1.0 Background 9

1.1 Problem statement 13

1.2 Objective 14

Chapter 2 16

Literature review 16

2.1 Mission 16

2.2 On-board computer 17

2.3 Impact of ionosphere 19

Chapter 3 23

Methodology 23

3.1 Approach 23

3.2 Raspberry Pi preparation for My-Sat 25

3.3 Flowchart 28

Chapter 4 39

Results and discussion 39

4.0 Results 39

4.1 Discussion 43

Chapter 5 48

Conclusion and recommendation 48

5.1 Conclusion 48

5.2 Recommendation 48

5.3 Future works 49

References 50

Appendices A – Algorithm 52

(8)

7 List of figures

Figure 1.1: The number of small satellites sent into the orbit in recent years(Wekerle et

al., 2017) 11

Figure 1.2: CubeSat mission category(Wekerle et al., 2017) 12

Figure 1.3: The location of the ionosphere 13

Figure 2.1: Raspberry Pi board 18

Figure 2.2: Mechanisms for Heavy Ion and Proton single event upset effects 21

Figure 3.1: Block diagram of the CubeSat 23

Figure 3.2: Project flowchart target 24

Figure 3.3: ADS1115 Analog to digital converter for Raspberry Pi 26 Figure 3.4: The commands to install Adafruit ADS1x15 Python library 27 Figure 3.5: List of the GPIO pins on the Raspberry Pi 28

Figure 3.6: The main flow of the algorithm 29

Figure 3.7: Boot flowchart 30

Figure 3.8: Deployment flow chart 31

Figure 3.9: Task list flow chart 32

Figure 3.10: Housekeeping flow chart 34

Figure 3.11: Electric Power Subsystem flow chart 35

Figure 3.12: Communication flow chart 36

Figure 3.13: Safe mode flow chart 37

Figure 4.1: The configuration files lines that consist of the variable 39

Figure 4.2: The result of i2c detect 43

(9)

8 List of tables

Table 1.1: Types of small satellites and their weight 10

(10)

9 Chapter 1

Introduction

1.0 Background

A satellite is an artificial object which has been intentionally placed into orbit. Such objects are sometimes called artificial satellites to distinguish them from natural satellites such as the Earth's Moon.

On 4 October 1957, the Soviet Union launched the world's first artificial satellite, called Sputnik 1. The Sputnik 1 launched into low Earth orbit for the technology demonstration(Swenson, 1997). This event marked the beginning of satellite era. Since then, about 6,600 satellites from more than 40 countries have been launched.

Approximately 500 operational satellites are in low-Earth orbit, 50 are in medium-Earth orbit (at 20,000 km), and the rest are in geostationary orbit (at 36,000 km). A few large satellites have been launched in parts and assembled in orbit. Over a dozen space probes have been placed into orbit around other bodies and become artificial satellites to the Moon, Mercury, Venus, Mars, Jupiter, Saturn, a few asteroids, a comet and the Sun.

The satellite has been used for ages to gain and collect information that we can’t normally get from the ground. Satellites are used for many purposes. There are various types of satellite include astronomy satellites, atmospheric satellites, communication satellites, navigation satellites, spy satellites, remote sensing satellites, search and rescue satellites, space exploration satellites, and weather satellites. Besides, International Space Stations

(11)

10

and human spacecraft in orbit are also satellites. In modern days, satellites are a very important device without a majority of human realizing it.

As time goes on, satellite becomes smaller and simpler. Researchers start to develop new kind of satellite which is small and simple enough to make. This development leads to introduce new kind of satellite such as Mini-satellite, Nano-satellite, micro-satellite and pico-satellite.

Table 1.1: Types of small satellites and their weight

Satellites Wet mass

Mini-satellite 101 – 500 kg

Microsatellite 11 – 100 kg

Nano-satellite 1 – 10 kg

Pico-satellite ≤ 1 kg

The CubeSat is a miniaturized satellite type for space research and application. The CubeSat is made up of one or more 10 x 10 x 10 cm cubic units. It all started in 1999, California Polytechnic State University (Cal Poly) and Stanford University developed CubeSat specifications to promote and develop the skills necessary for creating small satellites intended for low Earth orbit operations. Professors Jordi Puig-Suari of Cal Poly and Bob Twiggs of Stanford also proposed a reference design for the CubeSat. Their mission was to enable graduate students to design, build, test and operate limited capabilities of artificial satellites within the limited time and financial constraints of a graduate degree program. In June 2003, the first CubeSats launched and were placed into orbit on a Russian Eurockot(Bethesda MD (SPX), 2016). Nowadays, CubeSat has been built by a hobbyist, students, researchers, and even entrepreneur. CubeSat has evolved

(12)

11

from its original mission which is to act as a tool to help teach students about the process involved in developing, launching, and operating spacecraft. One of the driven factors is the price. The cost to build a satellite also has decreased a lot than it used to be. CubeSat is a small device and much simpler satellite which helps a lot of researchers to build a CubeSat in doing their research in the space without using a lot of money. There are many projects that used CubeSat to gain data from the space. With the existence of CubeSat, students in university also can build their own satellite without costing university or college huge amount of money.

Figure 1.1: The number of small satellites sent into the orbit in recent years(Wekerle et al., 2017)

This figure 1.1 shows how small satellites increasing popularity in the recent years.

Starting from 2007 the number of Nanosatellite has increased drastically. CubeSat also categorized into Nanosatellite(Wekerle et al., 2017).

(13)

12

Figure 1.2: CubeSat mission category(Wekerle et al., 2017)

Figure 1.2 shows the mission of the CubeSat that has been sent to space in recent years.

Small satellites have been used majorly for research and development.(Wekerle et al., 2017) This project also categorized into research and development, and scientific research.

University Sains Malaysia also plans to build a CubeSat and launch it to space.

University Sains Malaysia collaborates with ANGKASA (National Co-operative Movement of Malaysia) in developing and launching this CubeSat into space. This CubeSat named MySat. MySat will be the first CubeSat from Malaysia to be launched into space. MySat mission is to measure the amount of electron in ionosphere. Based on figure 2, Ionosphere is the ionized part of the Earth’s upper atmosphere, about 50 km to 250 km altitude.

(14)

13

Figure 1.3: The location of the ionosphere

At first, many will question University Sains Malaysia on why we even need to calculate the amount of electron in the ionosphere and what will we get by doing this. In 1960s, ionosphere disturbances regarding with earthquakes were identified. Kim and Pulinets et al suggested that there will be disturbance of electron density based on strong vertical electric field at the earth’s surface. Basically, we can predict the occurrence of earthquake in certain places by using this CubeSat.

1.1 Problem statement

The CubeSat cannot operate with hardware alone. Users also cannot operate the CubeSat manually because of the distance between the CubeSat and the users. This means that CubeSat needs to operate automatically. It needs a subsystem that in charge of the hardware such as payload, sensor, and power supply. This subsystem also will schedule the tasks of the CubeSat. These tasks will be made by using programming.

(15)

14

This subsystem also needs testing to make sure it works perfectly according to the plan.

Before launching the CubeSat, the functionality of the hardware and the software needs to be tested to make sure it can operate smoothly and achieve the missions. All the subsystems will be compiled into a system and the functionality of the software will be tested.

1.2 Objective

To build the subsystem to control My-Sat called on-board data handling based on Raspberry Pi. Raspberry Pi will be the main on-board computer that will be in charge to control other subsystems in the My-Sat such as Electric Power System (EPS), payload, sensors and communication subsystem. In developing on-board data handling for CubeSat, a program is needed to control all the subsystem in the CubeSat. On-board data handling can be called the brain of any satellite. On-board data handling the main function is to communicate through all the subsystems to make sure a mission run successfully. Its significant role is to store the data collected from the subsystems and payload and compile them to send back to the ground. The data that has been stored in the on-board data handling are consist of payload data, housekeeping data and telecommands data. The coding also responsible for scheduling the tasks of the My-Sat.

This functionality of the coding also will be tested when the subsystems are ready.

In the same time, the on-board computer also needs to collect the information of the satellite. This task is known as housekeeping. Housekeeping data is crucial to monitor the condition of the satellite and how it operates in its daily life. On-board data handling to analyze the situation of the voltage and current supply because of it essential to keep the satellite works in the safe condition.

(16)

15

This strategy may save the satellite from being a shortage of electrical power. It helps the satellite to keep working within a wide range of electric supply. Besides, the satellite does not always operate at its best condition because at some point the satellite will go through the condition where there is no sunlight that reaches the satellite. This condition will affect the satellite because many simple satellites powered up by solar panels. This condition also normal to the satellite. It is called an eclipse. With on-board data handling that has been programmed, this problem can be tackled easily thus prolonged the satellite operation life. This is also one of the on-board data handling responsibilities.

(17)

16 Chapter 2

Literature review

2.1 Mission

Earthquake is a dangerous natural phenomenon that can affect many lives and manage to destroy building and infrastructure when it happens. Try to imagine if we can predict when and where an earthquake will occur, we can evacuate people and save them before it happens. There are some ways in detecting the earthquake, and one of them is analyzing ionosphere. DEMETER is a microsatellite that has been sent to space to study the ionosphere. The resulting conclusion made in DEMETER team publications suggests that there are real and obvious perturbations of electric and magnetic fields and electrons density in the ionosphere connected with the seismic activity, but they are rather weak and at the present stage of data processing could only be identified with the help of statistical analysis, because many other phenomena can perturb the ionosphere and generate similar and even greater disturbances there. Other conclusion points out that these perturbations may also occur within a few hours and a few days before an EQ and mostly in the close vicinity of the EQ epicentre (Korepanov, 2016). The electromagnetic waves directly propagating from the EQ epicentre have not been observed, in contrast to suggestions advanced in many papers. But the changes in wave propagation above the epicentres were confirmed and this was attributed to variations of ionospheric plasma density.

(18)

17

CubeSat is a cheap way to send satellite to space for space mission, science project or education purpose. CubeSats considerably decrease the cost and complexity of development and launch as compared to robust traditional satellites with redundant subsystems, as evidenced by observed dramatic increase in number of CubeSat launches over the last decade (Poghosyan and Golkar, 2017). It also has a few limitations by using CubeSat, power is one of them for 1U CubeSat. But, currently, power generation on 3U CubeSats can easily reach up to 20–30 W by using deployable solar panels. There also a huge range of battery with high capacity such as high energy density lithium ion and lithium polymer batteries that can be utilized as primary or secondary power source for CubeSat missions (Poghosyan and Golkar, 2017). Communication also become one of the problem for CubeSat. Early CubeSat missions used VHF and UHF radio frequency which provide low data rates as 1.2 and 9.6 Kbps. CubeSat nowadays, can achieve higher data rates up to few Mbps through S-band communication systems such as DICE 1.5U CubeSat. There’s CubeSat that can achieve 40 Mbps data rates.

2.2 On-board computer

For this project, we try to implement Raspberry Pi as on-board data handling for this CubeSat. In recent years, Raspberry Pi has make step forward to send Raspberry Pi into space. A few researchers trying to send raspberry Pi into space, such as using Raspberry Pi with high altitude balloon to capture the image of earth.(Anand and Rajesh, 2016) Raspberry Pi also made a program to encourage students and researchers to send Raspberry Pi to International Space Station. The program called Astro Pi. This show their initiative to send Raspberry Pi to space (Honess and Quinlan, 2017). Raspberry Pi also has been used in NASA CubeSat, 1.2U Pi-Sat for capturing earth picture. NASA stats that Raspberry Pi could be very low-cost CubeSat platform. Raspberry Pi also popular

(19)

18

with open source platform, that can minimize time in making the CubeSat. Arduino also popular with open source software. On the other hand, using open source hobbyist boards in CubeSats is a challenge itself. They will have to withstand the harsh environmental conditions during launch and in space, namely radiation, high vacuum, extreme temperatures, vibrations, etc. On top of that, power available on a CubeSat is sparse – a limitation that is usually not of much concern for terrestrial electronics (Scholz and Juang, 2015).

Raspberry Pi looks like a simple device and it is cheap. It is available in the market only for 35 dollars. Despite having low price, Raspberry Pi processor quite powerful to become microcontroller for CubeSat. Its flexibility also convenient for users.

To build cheap CubeSat, Raspberry Pi was chosen to be the on-board data handling.

Although, there is a lot cheaper microcontroller in a market such as Arduino.

Figure 2.1: Raspberry Pi board

Originally, Arduino is a microcontroller but in the same time, Arduino is not as fast as Raspberry Pi. It has 4 processor cores. Multiple cores allowed the system to handle multiple threads in a time. It also has promising clock speed which 1.4 GHz. For small

(20)

19

board it considered to be good. Based on its powerful components, it is hard to turn down the possibility for Raspberry Pi to become leading on-board data handling for CubeSat.

Raspberry Pi also easy to use even for people that does not know how to operate microcontroller before. After the power and HDMI has been plugged in this device can operate on the go. The installation of the software also is not hard. SD card is used to install the software, if someone wants to use multiple software, it can be changed by merely changing the SD card. Raspberry Pi consists of GPIO pins and ground pins. These pins will connect Raspberry Pi to the other subsystems such as electric power system (EPS), payload, transmitter and watchdog.

It has wide range of programming language that can be used with Raspberry Pi such as C, C++, and Python. The usual software for the Raspberry Pi is the Raspbian which can run C language and Python. It is not a limitation to stick with the Raspbian.

There is a lot more software for Raspberry Pi that can be tried. Python language has top the charts in recent years over other programming languages such as C, C++ and Java and is widely used by the programmers in various applications. Many programmers nowadays use python because of its versatility features and produce fewer programming codes. There’s many benefits of python that makes it popular now. Python also tried

As everyone knows, space has a harsh environment. It is hard to ensure the computer will operate reliably for certain period.

2.3 Impact of ionosphere

Ionosphere is the layer of the earth’s atmosphere that is ionized by solar and cosmic radiation.(Zolesi and Cander, 2014) This ionization is becoming big problem when transmitting a radio wave and electronics part in the CubeSat. The ionization of the Ionosphere is divided by two categories, which is during the day and the night. During

(21)

20

the day, the high energy from the sun and the cosmic rays, the atoms located in ionosphere have been stripped of one or more of its electrons, this phenomenon also called ionized. Because of the electron being stripped away from them, the atoms in ionosphere will be positively charged. The stripped or ionized electron will act as free particles.

This situation will make ionosphere have high energy. During the night, the absence of the Sun does not mean there is no ionization happen. Besides, ionosphere will be ionized by cosmic rays, but it will be not as strong as the energy of the Sun. Comic ray origin is from various sources throughout the galaxy and the universe such as neutron stars, supernova, radio galaxies, quasars and even black holes.

Although ionosphere has complicated situation, it also serves a significant role to the Earth which is protecting Earth from the most intense forms of space weather. (Zell, 2013) It also helps in radio propagation, by producing waveguide which the radio signals can bounce and make their way to the ground.(Kelley, 1989)

Another phenomenon produced by the sun is coronal mass ejection. This phenomenon is solar explosions propel burst of particles and electromagnetic fluctuations into Earth’s atmosphere. The particles burst by coronal mass ejection can collide with electronics on-board and disrupt its system. In this case, coronal mass ejection does not directly affect the satellite in ionosphere, but it can increase the number of free electrons in ionosphere.(Fox, 2013)

Besides, cosmic radiation also can cause problem to the on-board of the CubeSat.

First, cosmic radiation may interfere with transistors and will bit-flip the computer memory. Bit-flipping is algorithmic manipulation of binary digits. Bit-flipping also

(22)

21

known as soft error. Bit-flip is a situation where the state of single binary bit has changed from 0 to 1 or 1 to 0. A negative environmental impact is one of the factors for bit-flip.

Increasing hit, lowering the voltage and cosmic radiation can lead to bit-flip. Although, bit-flip sounds simple it can cause a huge problem to the CubeSat as a whole. It can corrupt saved data and causing instability in the whole system.(Myrland, 2013) It means, if bit-flip happen in on-board data handling the CubeSat may not perform well or becomes a failure.

Cosmic rays and solar flares also can cause a single event latch-up (SEL). Single event latch-up is a hard error. Single event latch-up happened when energetic particles causing single event upsets. Single event upset (SEU) is a change of state caused by one ionizing particle strike a sensitive node in a microelectronic device. Ionizing particle example is ions, electrons and photons. Single event latch-up results in an abnormal high- current state. These errors can be cleared by power toggling the device. If this action does not happen soon enough the device will suffer permanent damage.(Nashville, 2012)

Figure 2.2: Mechanisms for Heavy Ion and Proton single event upset effects

(23)

22

As we know, the ionosphere is an area full of radiation or ionized particles. If the CubeSat components exposed to the surrounding, there is no guarantee that the CubeSat can operate anymore. The cosmic radiations in the ionosphere make things worse as it can affect the on-board computer of the CubeSat. There a few solutions to avoid ionized particles affect the CubeSat components. First, by using radiation-hardened electronic components, this problem can be solved easily.(Ødegaard and Skavhaug, 2013) However, for building CubeSat, budget limitations are much stricter than high reliability system. As this solution need a huge amount of money to be made, so there is a possibility that this solution is not good enough. To solve this problem by changing the board structure is also expensive.(Myrland, 2013) By using off-the-shelf CubeSat, this problem can be avoided as the structure is effective in reducing the radiation. This off-the-shelf CubeSat also one of the way to solve this problem cheaply. In this project the CubeSat was made in our own laboratory, hopefully it can withstand cosmic radiation and solar flare as well as off-the-shelf CubeSat.

(24)

23 Chapter 3

Methodology

3.1 Approach

The approach of writing an algorithm can be called a strategy. As lack of strategy may lead someone to write the algorithm that is not necessary for a mission or the objective of the project.

The project flowchart can be referred in figure 3.2. First, the mission, objective and requirement need to be well defined. The mission definition is the starting point of how to approach the project. As mission, objective and requirement are defined, the algorithm will be written simply to achieve the mission and objective alongside the requirement so there will be no mistake when writing the algorithm. The connection of the subsystem with on-board data handling showed in figure 3.1.

Figure 3.1: Block diagram of the CubeSat

C&DH

Antenna release

Transceiver

GPIO Data memory

Watchdog

Payload

Power relays

Comm

I2C SPI

USART

(25)

24

Figure 3.2: Project flowchart target

(26)

25

The developed algorithm must be able to execute nominal operation schedule, send a command to get health data from subsystems, collect each subsystems data, and process, format and store the collected telemetry data. After the algorithm is developed, it needs to go through a verification process to ensure the program functionality meets the requirement that has been set. The algorithm that been developed divided into four categories. The first category that needs to be developed is antenna deployment subsystem. Antenna deployment subsystem will fully depend on the real-time operating system and will deploy at the time that was set in the algorithm. The second category is communication subsystem or also known as a beacon. This subsystem also depends on the real-time operating system and follow the requirement that has been set in the algorithm. The communication subsystem allows CubeSat to interact with ground station whether to look the status of the CubeSat or transfer the data that has been collected to Earth. This subsystem plays a crucial part in saving the power used by CubeSat. The third category is the main part of the on-board data handling which is to ensure that the board can communicate with other subsystems, collect telemetry data and store the data in on-board data handling storage.

3.2 Raspberry Pi preparation for My-Sat

Raspberry Pi needs to be prepared before it can operate as on-board data handling for the CubeSat. Raspberry Pi alone is not suitable to become on-board data handling for My-Sat for certain reasons. First, Electric Power System (EPS) and payload need to be connected to on-board data handling through the analogue pin, but Raspberry Pi does not provide this option to the user. To overcome this problem, the provide GPIO pins must be converted into analogue pins using analogue to digital converter.

(27)

26

They are two types of analogue to digital converter that available in the market which is MCP3008 and ADS1115. The MCP3008 is a cheap 10-bit with 8-channel analogue to digital converter. While the ADS1115 is a great analogue to digital converters that are easy to use with the Raspberry Pi by using its I2C communication bus. The ADS1115 is a higher precision 16-bit ADC with 4 channels. ADS1115 have a programmable gain from 2/3x to 16x, thus it can amplify small signals and read them with higher precision. The ADS1115 is chosen to be used for this project because of its precision.

Figure 3.3: ADS1115 Analog to digital converter for Raspberry Pi Before wiring the ADS1115 to the Raspberry Pi, make sure to enable the I2C on the Raspberry Pi. First, install kernel support for the I2C. This can be made by using

“Raspi-Config”. “Sudo Raspi-config” is a command to go to Raspberry Pi software configuration tool. By doing so, the menu will pop up. Then, choose ‘interfacing option’

(28)

27

and ‘advanced option’. Choose menu ‘I2C’. After confirming the choice that has been made, Raspberry Pi need to reboot. After that, the kernel installation for I2C is done.

After enabling I2C, it is ready to install the Adafruit ADS1x15 Python library.

The Adafruit ADS1x15 Python library is taken from Github. This step can be done by writing this code in figure 3.4 into the ‘terminal’.

Figure 3.4: The commands to install Adafruit ADS1x15 Python library The ADS1115 connected to the Raspberry Pi by connecting “VDD” pin to the

“P1-01 (3.3V)”, “GND” to the “P1-09 (GND)”, “SCL” to the “P1-05 (I2C SCL)” and

“SDA” to the “P1-03 (I2C SDA)”. The Raspberry Pi pins can be referred in figure 3.5.

(29)

28

Figure 3.5: List of the GPIO pins on the Raspberry Pi 3.3 Flowchart

The flow chart is a beginning before making a system. The flowchart is a type of diagram to show an algorithm, workflow or the process. It also a simplified version of the algorithm, workflow, or process of the system. Flowcharts are used in various fields.

(30)

29

Figure 3.6: The main flow of the algorithm

The simple way to show how the algorithm works is by using a flowchart. The general flow for this algorithm is after booting process, the system will verify the antenna deployment. If the antenna is deployed, it will continue to run tasks that have been scheduled and if the antenna still not deployed, it will hibernate for the time that has been set, then deployed the antenna. This general flow of this algorithm showed in figure 3.6.

(31)

30

Figure 3.7: Boot flowchart

As we know, the system will run many processes. Figure 3.7 shows in detail how booting process going to be run. The booting process will require the setup of the hardware. In this case, the booting process of the software mainly depends on the watchdog counter. That is why the system needs to update the reset counter and reset cause, every time it boots. After the software and hardware finishing up the booting process, it will return to the main loop in figure 3.6.

(32)

31

Figure 3.8: Deployment flow chart

The verification of the antenna also has its own flow. This flow is shown in figure 3.8. The verification process made by reading the deployment status. This deployment status will be stored in the My-Sat storage. If there is the deployment status that already been written in the system, it will be considered the task is done and it will return to main.

In the same time, if there is no deployment status that proved the antenna has been deployed, it will write the deployment status as not deployed and return to main. The deployment status is important in this system to make sure that the antenna only deployed once in its lifetime. This is because My-Sat does not have a retractable antenna.

(33)

32

Figure 3.9: Task list flow chart

Next, the tasks will be run as scheduled. The tasks that My-Sat needs to run are Electric Power System (EPS) task, housekeeping task, and communication task. The

(34)

33

schedule for this task shown in figure 3.9. As mentioned before, the bootup of the software will depend on the watchdog timer. Thus, the watchdog timer task will be among the first to be run to make sure other tasks follow the timer strictly. Then, it will create store data task. Store data task mainly about to check the storage part of the My- Sat. If there is any problem with the storage part, it will clear all the data in the storage and rebooting the task. Next, the system will run housekeeping task.

The housekeeping task was shown in detail in figure 3.10. As mentioned before, housekeeping data just to make sure we know the condition of the satellite. Housekeeping data mainly consists of taking reading of temperature, voltage and current supply to the on-board data handling, and ping timer. The reading that has been taken will be stored in the storage. This data will be sent to the ground when ground station contacted the My- Sat.

(35)

34

Figure 3.10: Housekeeping flow chart

After that, the task for Electric Power System (EPS) will be run. This task also showed in detail in the figure 3.11. This task to read the current power level of the Electric

(36)

35

Power System (EPS) of the My-Sat. By using this reading, the system can evaluate more on the power usage of the My-Sat. Then, the system will create communication server task. This task will control the transmitter to contact with ground station. Lastly, the system will run the payload interface task. Here is the task to run the payload to collect data and save into the storage.

Figure 3.11: Electric Power Subsystem flow chart

(37)

36

Figure 3.12: Communication flow chart

Communication task based on figure 3.12, shows how the communication subsystem works. Communication subsystem controlled the transmitter by controlling how many minutes it will be turned on before receiving a signal from the ground. If My- Sat received a signal from the ground station, it will send housekeeping and telemetry data that has been collected by My-Sat. After every transmission that happens, the system will write the log in the system that states My-Sat has sent the data to the ground station.

(38)

37

If there is no signal received by My-Sat, the task will be delayed for some time that has been set.

Figure 3.13: Safe mode flow chart

As mentioned before, My-Sat system also equipped with safe power system when an emergency happens. The flow chart for this task showed in figure 3.13. When the safe

(39)

38

power system is turned on, it will read the power level of the Electric Power System (EPS). If the reading shows it still low on power to run the My-Sat, it will stay on safe power level. In this condition, the system will be in sleep mode. It will try to contact the ground station to inform the condition to the ground station. In the same time, if My-Sat failed to contact the ground station it will stay in safe power level until the power supply becomes stable again.

(40)

39 Chapter 4

Results and discussion

4.0 Results

Algorithms to control the CubeSat was made by dividing the algorithms into 4 sections which are configuration, modes, servers, and types. First, the configuration file for python is used to ease the programmer when they want to change something in the source codes. This configuration file allows the user to change or manipulate variables without using a source file. Even someone who does not know about python or any programming language also can change the variables in the configuration file.

Figure 4.1: The configuration files lines that consist of the variable From the configuration file based on figure 4.1, we can see the variables that have been set is only watchdog timeout. In this case watchdog timeout means, after the time that has been set it will reset and start counting again.

‘Modes’ consist of base, deployment, safe mode, and machine state. Modes are where the mission was defined. Deployment modes using time, socket, logging, and DateTime library. Time is important in the deployment of the antenna because the antenna will be released after a certain amount of times that has been set. This is to avoid any accidents during launching the CubeSat into space. In this algorithm, the time set for

(41)

40

antenna deployment is 15 minutes. This time can be manually changed in the algorithm.

The 15 minutes was set just to make sure My-Sat has enough time to deploy antenna after launched. The algorithm for deployment mode can be referred to Appendix B. The system also will write into logging info before and after antenna deployment. This is to make sure that we can track the deployment process. In the same time, it will also start the boot time of the system.

The algorithm command also depends on the message. This is because we cannot normally input the command. In a simple way, the system itself will generate the command in term of the message, then it will be processed by servers. This is to make sure, that the system can run automatically without waiting for input.

While waiting for 15 minutes, the system will sleep to avoid power wastage. After antenna deployed, it will update the status with using ‘logging.info’. ‘Print’ also can be used in this situation, but ‘print’ command will not save each command or each step the program takes. While using ‘logging’, it will keep each step it has taken, so the user can check it whenever they want. After antenna has been deployed, the transmitter will have to will have to wait 30 minutes before it is going to turn on and waiting for the ground to contact the CubeSat. This 30 minutes time also can be changed in the coding. The 30 minutes mark is not fixed but it must be after antenna was deployed.

Safe mode module is to ensure there is no power wastage as power has an essential part of the CubeSat and it is very limited. This module will consist of log and time library. Same as before, logging will keep user up to date and know more detail about what happened in the CubeSat. It will attempt to take data from the Electric Power Subsystem (EPS) via the server. If the voltage supplied to the on-board computer is low, the server will generate the command via a message that the state of the system is low

(42)

41

then the ‘safe mode’ will be run after generates another command. In this mode, the system will turn on the transmitter for 5 minutes to try contact the ground station to receive telemetry packet from the ground if available. It will only attempt 1 try to contact the ground. The power level is taken from the ‘power socket path’ and evaluated.

Different than the other servers. The state machine is the "driver" that drives the other servers. The ‘state machine’ algorithm is the one that responds to switch phases into ‘safe’ state upon receiving a command from the system. This ensures the state machine doesn't keep running if we end up in a bad state. It also will flush the memory to simulate the first run. This also means that it can only move one phase every ping delay.

The servers for this system will act as a system translation layer between everything else and the hardware. The servers for this system consist of a base server, communication server, watchdog server, log server, socket, storage server and power server.

The watchdog server will boot other servers one by one. It will start ‘cdh’ server first, then ‘comms’ server, ‘power’ server, ‘storage’ server and lastly will run ‘state machine’ mode. This server also will run checksum in purpose to detect errors. If the watchdog timer fails to start, it will reboot the server again and again. It also will check the server ping for 60 seconds. Again, the 60 seconds mark is not fix and can be changed.

If the ping receive is correct it will run the server as usual but if not, it will show that there is an error in the system. In this system, ping literally controls the flow of the program. The watchdog server also ensures every server start according the flow. After the watchdog server started, it will sleep for 5 seconds then check other servers whether they are alive or not. It will attempt to restarting servers which are failed to boot. It also

(43)

42

will check whether other servers responding to the ping or not. The processes will keep updated in ‘log’ server. This server essential to the modes which refer the watchdog as their timer. If the watchdog timer is wrong, the subsystem will run without proper timing.

Communication or ‘comm’ server will interact with the ‘deployment’ mode in extending the antenna and turn on the transmitter. This is where the message produced in ‘deployment’ mode will be processed.

Next, power server will control the Electric Power System (EPS) after it gets the message or command from the ‘safe mode’. It also will check the PING whether to run or to reboot. If there is a problem with the server, it will keep rebooting and keep the data as log data. If there is a command to turn the system into ‘safe’ mode, it will send the command to other servers that the system will turn into safe mode.

Storage server will manage the storage in the My-Sat. It will also act as a database for storing state. First, the server will fix the object maximum size is 128 mebibyte (MiB).

It will also check the storage whether the data can be stored or not.

In the type segment, there is a list of command prompts that will be processed by the system. It also to ensure that the program run following what a programmer wants to.

It will make the program a little bit safer.

Before transfer the coding to the on-board computer, the testing of the other components that were added which is analogue to digital converter and real-time clock need to be done. Real-time clock testing is simple. This component can be tested by using I2C. Write the code in the terminal ‘sudo i2c detect -y 1’.

(44)

43

Figure 4.2: The result of i2c detect

When this kind of result pops up it means that I2C can detect the real-time clock.

The same goes for the analogue to digital converter.

4.1 Discussion

On-board data handling usually consists of powerful microcontroller that can handle various threads at one time. At the same time, Raspberry Pi is not a microcontroller such as Arduino, but it is a single board computer. It does not mean that Raspberry Pi cannot run CubeSat but to make it operate as good as another microcontroller, a lot of things need to be tweaked to make it suitable to control a CubeSat.

First, the most important thing is to add a real-time clock for Raspberry Pi. This is because Raspberry Pi does not offer built-in real time clock which is one of the important things in managing program such as CubeSat. CubeSat software needs to strictly follow time schedule that has been set by the programmer. If CubeSat does not follow time schedule, it will cause an accident that can affect launching progress and will affect whole mission itself. In this case, the operating system itself needs to be reliable enough to run the real-time application. A lot of operating systems available for Raspberry Pi for various applications. There’s special operating system in Raspberry Pi

(45)

44

to make a small computer, for playing games, for media purposes and many more. The most popular operating system for Raspberry Pi is Raspbian. Raspbian or General Purposes Operating System original purpose to use for systems or applications that are not time critical. Is it suitable for Raspbian to be ported to control CubeSat? The answer is no. Raspbian usually cannot run the real-time application but NASA proof that they can run their core Flight System using Raspbian which is based on Linux Debian. To make Raspberry Pi operates as a CubeSat, the operating system that can run real-time operating system is essential. There are a few real-time operating systems such as freeRTOS, CibbiOS and VxWorks.

As mentioned above, Raspberry Pi is a single board computer and not microcontroller, it means that Raspberry Pi will not run a program when boot except someone insert the command into it. If there is an accident where the power supply from electric power system (EPS) is not sufficient to run the Raspberry Pi, then it will shut down. After reboot, someone needs to go to the CubeSat and insert a command to make sure the program run again. This problem will affect the whole operation. So, Raspberry Pi system needs to be tweaked a little to avoid a problem like this from happening. The tweaking of the Raspberry Pi is essential to make Raspberry Pi operates efficiently. First, if there is not enough power for Raspberry Pi to turn on, it will shut down. Raspberry Pi used the log in system, so there is no way for it to run the application again. So, the solution is to make the Raspberry Pi auto log in and set to run the application straightforward. This will ensure that the Raspberry Pi only in standby mode without running any application. As we know, Raspberry Pi has a various application that already built in. To improve the performance, checked the applications that are useless and

(46)

45

disable them such as network services, graphical interfaces and games. Disable as many useless services that run on boot to ensure booting process run as smooth as it can.

Raspberry Pi also has a lot of applications that come with the operating system such as built-in games, and Microsoft applications. Applications like this will use a lot of space in the microSD and maybe will run in the background thus will affect the RAM usage and processor power. It also may affect the power usage of the on-board data handling. In a CubeSat, power consumption needs to be minimized as far as we can. By removing the useless applications for the project, the Raspberry Pi can operate at its best without any disturbance. This is one of the ways to turn single-board computer like this into the microcontroller.

The choice of language also important. Usually, CubeSat used C language as on- board data handling or on-board controller programming language. This is because C language can run through the less powerful board which results in low power usage. As we all know, CubeSat has very limited power to be used throughout the CubeSat, so it will be good to reduce as much power consumption as we can. In this case, Raspberry Pi already fix as a board to control the CubeSat so there are a few more programming languages that can be implemented such as C++, C#, and even Python. Python is known as high-level programming languages such as C, C++, PHP, and Java. Python also needs the powerful board to run its programming, and Raspberry Pi can handle the Python well.

In this case, the board will be not a limitation to use Python language.

In modern days, everything is going to open-source approach. We can see the trend in our smartphone, android. Android which is owned by Google was made open source since a long time ago. Programmers can change the coding freely to suit their needs. In CubeSat, this trend already take place without majority of us does not realize

(47)

46

it. One thing that has goes ‘open source’ is the structure of the CubeSat. CubeSat kit already exist in market which ease manufacturer, hobbyist, and even researchers. With CubeSat kit researchers, manufacturers, and hobbyist can reduce a lot of time to make the CubeSat structure. They can focus their time to optimize other aspects such as payload and the data that they want to collect. Same trend has followed the on-board data handling. There already an open-source project for CubeSat just like android. This approach eases many parties as they just need to focus to develop algorithm for the special task that they want to assign to their CubeSat. One of the example is NASA core Flight System that they already release as an open-source project. By doing this, every developer can reduce the time to develop the CubeSat thus can reduce the project time.

For manufacturer it also means they can increase their profit. Open-source approach also can reduce fail CubeSat projects. A recent study shows that 40% launched CubeSat into space are fail. According to study, at least 45% of all satellite that failed can be allocated to electric faults. The electrical power subsystem (EPS) contributes 27% and Command and Data Handling (C&DH) contributes 15% of all satellite failures. According to this study, failure for command and data handling also contribute to huge amount of satellite failure. As the programming for on-board data handling become open source, hopefully the number of failure in satellites will be reduced.

The integrated testing of the CubeSat should be done to validate the software whether it can perform well or need to be repaired. In this project, the integrated testing cannot be done because of certain factors. First, the other subsystems still in developing phase which not allowed on-board data handling to integrate with other subsystems. The my-sat project was done by 4 students which handled different subsystems. Based on the schedule, subsystems will be integrated by week 9. In the same time, everyone has their

(48)

47

own problem in completing each subsystem which makes us behind the schedule. I also had some problems regarding complete the algorithms as I still inexperienced in Python and on-board data handling system which affects my schedule. Besides, the integrated testing also cannot be completed due to lack of components.

(49)

48 Chapter 5

Conclusion and recommendation

5.1 Conclusion

There are many great microcontrollers in the market that suitable for the CubeSat.

Raspberry Pi originally not meant for the CubeSat, but it does not mean this single board computer is not suitable for the CubeSat application. It will be quite interesting to see more CubeSats use the Raspberry Pi as the on-board data handling. In terms of processing power, this small Raspberry Pi sure is a winner. In the same time, Raspberry Pi needs a lot of tweaks to make it run as microcontroller, if not, the Raspberry Pi can become on- board data handling for the CubeSat or the performance will be limited which might affect the performance of CubeSat later. Although, Raspberry Pi is not a popular device to become on-board computer for CubeSat nowadays, but a few organizations already try to put this mini single board computer into the space. NASA also has sent a CubeSat handled by the Raspberry Pi via Pi-Sat and it is huge success. Moreover, NASA also has tested their own open source software for on-board data handling on this Raspberry Pi.

5.2 Recommendation

Raspberry Pi also is a good device with a good price. It can be cheap CubeSat on- board data handling in the future. There are a lot of variances of Raspberry Pi. Raspberry Pi zero is the cheapest one among them. If someone wants to make a cheap CubeSat, this variance of Raspberry Pi is a good choice. Besides, it also can run various operating systems and many programming languages can be used such as C, C++, and Python. As

(50)

49

the trends are going towards open source for the CubeSat, there is a lot of possibilities that Raspberry Pi will become among the best on-board data handling.

5.3 Future works

As we can see from figure 3.2, the project mission is still not accomplished. This is due to certain problems which originated from myself and the team. The integrated testing and the debugging process is essential in ensuring this project a success. The integrated testing of My-Sat needs to be done to make sure software and hardware can work properly. In the same time, there may be a few debugging needed to make sure the system can run smoother and without any flaw.

(51)

50 References

Anand, P. and Rajesh, D. (2016) ‘World Journal of Engineering WJERT HIGH ALTITUDE BALLOON FOR PHOTOGRAMMETRY AND’, 2(3), pp. 201–209.

Bethesda MD (SPX) (2016) History of the CubeSat. Available at:

http://www.spacedaily.com/reports/History_of_the_CubeSat_999.html (Accessed: 14 May 2018).

Fox, K. C. (2013) ‘Impacts of Strong Solar Flares’. Brian Dunbar. Available at:

https://www.nasa.gov/mission_pages/sunearth/news/flare-impacts.html (Accessed: 14 May 2018).

Honess, D. and Quinlan, O. (2017) ‘Astro Pi: Running your code aboard the International Space Station’, Acta Astronautica. Pergamon, 138, pp. 43–52. doi:

10.1016/j.actaastro.2017.05.023.

Kelley, M. C. (1989) The Earth’s Ionosphere. Plasma physics and electrodynamics, International Geophysics Series. Academic Press. doi: 10.1016/S0074-6142(09)60228- X.

Korepanov, V. (2016) ‘Possibility to detect earthquake precursors using cubesats’, Acta Astronautica. Pergamon, 128, pp. 203–209. doi: 10.1016/j.actaastro.2016.07.031.

Myrland, J. (2013) ‘On-Board Controller & Data Handling’, (February).

Nashville, T. (2012) ‘SINGLE EVENT LATCHUP: HARDENING STRATEGIES, TRIGGERING MECHANISMS, AND TESTING CONSIDERATIONS’. Available at:

https://etd.library.vanderbilt.edu/available/etd-11032012-

225718/unrestricted/dodds_dissertation_FINAL.pdf (Accessed: 14 May 2018).

(52)

51

Ødegaard, K. A. and Skavhaug, A. (2013) ‘Simple Methods for Error Detection and Correction for Low-Cost Nano Satellites’. Available at: https://hal.archives-

ouvertes.fr/hal-00848615/document (Accessed: 14 May 2018).

Poghosyan, A. and Golkar, A. (2017) ‘CubeSat evolution: Analyzing CubeSat capabilities for conducting science missions’, Progress in Aerospace Sciences.

Pergamon, 88, pp. 59–83. doi: 10.1016/j.paerosci.2016.11.002.

Scholz, A. and Juang, J. N. (2015) ‘Toward open source CubeSat design’, Acta Astronautica. Pergamon, 115, pp. 384–392. doi: 10.1016/j.actaastro.2015.06.005.

Swenson, G. W. (1997) ‘Looking back: sputnik’, IEEE Potentials, 16(1), pp. 36–40.

doi: 10.1109/45.565615.

Wekerle, T. et al. (2017) ‘Status and trends of smallsats and their launch vehicles - An up-to-date review’, Journal of Aerospace Technology and Management, 9(3), pp. 269–

286. doi: 10.5028/jatm.v9i3.853.

Zolesi, B. and Cander, L. R. (2014) Ionospheric prediction and forecasting, Ionospheric Prediction and Forecasting. doi: 10.1007/978-3-642-38430-1.

(53)

52 Appendices A – Algorithm

Deployment mode import time import socket import pickle import logging import datetime

from types.datagram import Msg, RequestType from servers.fast_socket import FastSocket from modes.base_mode import Mode

from types.cmd_types import CommsCmd, StorageCmd SOCKET_PATH = '/tmp/mode/deployment'

COMMS_SOCKET_PATH = '/tmp/comms' STORAGE_SOCKET_PATH = '/tmp/storage' logging.basicConfig(level=logging.INFO) class Deployment(Mode):

def start(self):

DEPLOY_WAIT = 1

Logging.info('Waiting {} secs to deploy antenna...'.format(DEPLOY_WAIT)) time.sleep(DEPLOY_WAIT)

self.deploy_antenna()

uptime, boot_count = self.update_boot_status()

logging.info('Boot count {}, previous uptime {}'.format(boot_count, uptime))

(54)

53 BEACON_WAIT = 1

logging.info('Waiting {} secs to begin beacon...'.format(BEACON_WAIT)) self.beacon()

Msg(RequestType.COMMAND_LIST, [StorageCmd.STORE, 'DEPLOYED', 1]

).send(SOCKET_PATH, STORAGE_SOCKET_PATH) def update_boot_status(self) -> (float, int):

Msg(RequestType.COMMAND_LIST, [StorageCmd.STORE, 'LAUNCH', True]

).send(SOCKET_PATH, STORAGE_SOCKET_PATH) boot_count = Msg(RequestType.COMMAND_LIST, [StorageCmd.LOAD, 'BOOT_COUNT']

).send_and_recv(SOCKET_PATH, STORAGE_SOCKET_PATH).data

boot_count = boot_count or 0 boot_count += 1

Msg(RequestType.COMMAND_LIST,

[StorageCmd.STORE, 'BOOT_COUNT', boot_count]

).send(SOCKET_PATH, STORAGE_SOCKET_PATH) uptime = Msg(RequestType.COMMAND_LIST,

[StorageCmd.LOAD, 'UPTIME']

).send_and_recv(SOCKET_PATH, STORAGE_SOCKET_PATH).data

(55)

54 Msg(RequestType.COMMAND_LIST, [StorageCmd.STORE, 'UPTIME', 0]

).send(SOCKET_PATH, STORAGE_SOCKET_PATH) return uptime, boot_count

def fail(self):

pass

def deploy_antenna(self) -> bool:

return Msg(

RequestType.COMMAND, CommsCmd.EXTEND_ANT,

).send_and_recv(SOCKET_PATH, COMMS_SOCKET_PATH, timeout=60 * 5) def beacon(self) -> bool:

return Msg(

RequestType.COMMAND, CommsCmd.SEND_TLM_PKT,

).send_and_recv(SOCKET_PATH, COMMS_SOCKET_PATH, timeout=60 * 5)

if __name__ == '__main__':

Deployment().start()

(56)

55 Safe mode

import logging import time

from types.datagram import Msg, RequestType

from types.cmd_types import PowerCmd, CommsCmd, StorageCmd from servers.fast_socket import FastSocket

from modes.base_mode import Mode SOCKET_PATH = '/tmp/mode/detumble' COMMS_SOCKET_PATH = '/tmp/comms' ADCS_SOCKET_PATH = '/tmp/adcs' POWER_SOCKET_PATH = '/tmp/power' STORAGE_SOCKET_PATH = '/tmp/storage' logging.basicConfig(level=logging.INFO) class Safe(Mode):

def start(self):

time.sleep(3) low_power = Msg(

RequestType.COMMAND, PowerCmd.LOW_POWER

).send_and_recv(SOCKET_PATH, POWER_SOCKET_PATH).data try:

ground_cmd = Msg(

RequestType.COMMAND,

(57)

56 CommsCmd.RECV_TLM_PKT

).send_and_recv(SOCKET_PATH, COMMS_SOCKET_PATH, timeout=5) except:

pass

if not low_power:

send_beacon = Msg(

RequestType.COMMAND, CommsCmd.SEND_TLM_PKT

).send_and_recv(SOCKET_PATH, COMMS_SOCKET_PATH).data did_deploy = Msg(

RequestType.COMMAND_LIST, [StorageCmd.LOAD, 'DEPLOYED']

).send_and_recv(SOCKET_PATH, STORAGE_SOCKET_PATH).data if not did_deploy:

from modes.deployment import Deployment return Deployment

return Safe

if __name__ == '__main__':

Safe().start()

(58)

57 State machine mode

import os import pickle

from modes.safe_mode import Safe

from servers import storage_server, base_server from types.datagram import Msg, RequestType import logging

TESTING = True

SOCKET_PATH = '/tmp/state_machine' logging.basicConfig(level=logging.INFO)

class StateMachineHandler(base_server.Handler):

state = Safe def handle(self):

msg = pickle.loads(self.request.recv(1024)) self.handle_default(msg)

if msg.req_type == RequestType.PING:

self.state = self.state().start()

logging.info('Transitioning to state {}'.format(self.state)) def clean_db():

import os import shelve try:

(59)

58 os.unlink(storage_server.DB_PATH) except OSError:

pass

with shelve.open(storage_server.DB_PATH, 'c'):

pass

def start_server():

logging.info('Initializing State Machine server...') if os.path.exists(SOCKET_PATH):

logging.warn('Detected stale socket, removing to start server...') os.remove(SOCKET_PATH)

if TESTING:

clean_db()

server = base_server.Server( SOCKET_PATH, StateMachineHandler

) try:

server.serve_forever() finally:

os.remove(SOCKET_PATH) if __name__ == '__main__':

start_server()

(60)

59 Base server

import logging import socketserver import sys

import threading import os

import pickle import logging

from types.datagram import Msg, RequestType logging.basicConfig(level=logging.DEBUG) class Handler(socketserver.BaseRequestHandler):

def handle_default(self, msg):

logging.debug('{} received {} from {}'.format(

self.server.server_address, msg.req_type, self.client_address)) if msg.req_type == RequestType.RESTART:

logging.error('{} going down for restart'.format(

self.SOCKET_PATH))

self.server._BaseServer__shutdown_request = True return True

elif msg.req_type == RequestType.PING:

self.request.sendall(

pickle.dumps(Msg(RequestType.PING_RESP, None)), ) return True

elif msg.req_type == RequestType.COMMAND:

(61)

60

print('Executing command: {}'.format(msg.data)) return False

elif msg.req_type == RequestType.COMMAND_LIST:

print('Executing command: {} with args {}'.format(msg.data[0], msg.data[1:])) return False

class Server(socketserver.UnixStreamServer):

def handle_error(self, request, client_address):

super(request, client_address)

logging.error('Request {}\n could not be handled,' ' terminating server...'.format(

request)) sys.exit(5)

def start_server(): logging.info('Initializing CDH server...') if os.path.exists(SOCKET_PATH):

logging.warn('Detected stale socket, removing to start server...') os.remove(SOCKET_PATH)

server = socketserver.UnixStreamServer(SOCKET_PATH, CDHHandler) try:

server.serve_forever() finally:

os.remove(SOCKET_PATH) if __name__ == '__main__':

start_server()

(62)

61 CDH server

import logging import socketserver import sys

import threading import os

import pickle import logging

from servers import base_server

from types.datagram import Msg, RequestType SOCKET_PATH = '/tmp/cdh'

logging.basicConfig(level=logging.INFO) class CDHHandler(base_server.Handler):

def handle(self):

msg = pickle.loads(self.request.recv(1024)) if self.handle_default(msg):

return True def start_server():

logging.info('Initializing CDH server...') if os.path.exists(SOCKET_PATH):

logging.warn('Detected stale socket, removing to start server...') os.remove(SOCKET_PATH)

(63)

62 server = base_server.Server(

SOCKET_PATH, CDHHandler )

try:

server.serve_forever() finally:

os.remove(SOCKET_PATH) if __name__ == '__main__':

start_server()

(64)

63 Comms server

import logging import socketserver import sys

import threading import os

import pickle import time import logging

from servers import base_server

from types.datagram import Msg, RequestType from types.cmd_types import CommsCmd

SOCKET_PATH = '/tmp/comms'

logging.basicConfig(level=logging.INFO)

class CommsHandler(base_server.Handler):

def deploy_antenna(self) -> bool:

time.sleep(1) return True

(65)

64 def beacon(self) -> bool:

time.sleep(1) return True

def handle(self):

msg = pickle.loads(self.request.recv(1024)) if self.handle_default(msg):

return

if msg.data == CommsCmd.EXTEND_ANT:

result = self.deploy_antenna()

logging.info('antenna deployment result: {}'.format(result)) self.request.sendall(

pickle.dumps(Msg(RequestType.DATA, result)), )

elif msg.data == CommsCmd.SEND_TLM_PKT:

result = self.beacon()

logging.info('Beacon result: {}'.format(result)) self.request.sendall(

pickle.dumps(Msg(RequestType.DATA, result)) )

(66)

65 def start_server():

logging.info('Initializing COMMS server...') if os.path.exists(SOCKET_PATH):

logging.warn('Detected stale socket, removing to start server...') os.remove(SOCKET_PATH)

server = base_server.Server(

SOCKET_PATH, CommsHandler )

try:

server.serve_forever() finally:

os.remove(SOCKET_PATH) if __name__ == '__main__':

start_server()

(67)

66 Fast socket server

import socket import os import logging class FastSocket:

def __init__(self, src, dest, timeout=30):

self.src = src self.dest = dest

self.timeout = timeout def __enter__(self):

self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if os.path.exists(self.src):

os.unlink(self.src) try:

self.sock.bind(self.src)

self.sock.settimeout(self.timeout) self.sock.connect(self.dest) except Exception as e:

logging.error(

'Could not bind or connect {}->{}'.format(self.src, self.dest)) return self.sock

def __exit__(self, *args):

self.sock.close()

(68)

67 Log server

import logging import socketserver import sys

import threading import os

import pickle import logging

from servers import base_server

from types.datagram import Msg, RequestType, LogRequest from types.cmd_types import LogCmd

SOCKET_PATH = '/tmp/log' LOG_DIR = '/tmp/logs'

LOG_PATH = LOG_DIR + '/log'

logging.basicConfig(level=logging.INFO) class LogHandler(base_server.Handler):

def handle(self):

msg = pickle.loads(self.request.recv(2 ** 20)) if self.handle_default(msg):

return True

if isinstance(msg.data, list):

cmd = msg.data[0]

if cmd == LogCmd.ADD_LINES:

(69)

68 level = msg.data[1]

source self.logger def write(self, lines):

print(

Rujukan

DOKUMEN BERKAITAN

Company specific determinants or factors that influence the adoption of RBA approach by internal auditors were identified by Castanheira, Rodrigues & Craig (2009) in

Over the past decade, some electric power facility such as electrical rotating machine, transformer and reactor will be injected harmonic current into power distribution

In recent years, research efforts are ongoing to use glycerol as a platform for chemical synthesis. This route has been driven by a surplus glycerol available on the market with

The effect of catalytic activity for TiO 2 nanoparticles (NPs) or various annealed TiO 2 NTs and various experimental parameters including the use of various organic dyes

Moreover, due to their rigidity, CMS membranes can retain their stability in aggressive (vapor or solvents, and nonoxidizing acids or bases) and adverse (high temperature and

25. I am willing to spend extra time to be involved in my child’s language learning. I am never tired of helping my child develop his/her second language. I will always be

In this project, we will be implementing an image feature extraction method called Centre-Symmetric Local Binary Pattern (CS-LBP) in a low-cost computer called the

In this project, will be used as an ultrasonic sensor network to detect the level of water in major rivers prone to flooding.. Ultrasonic sensors will be placed in containers such