1 // Copyright 2014 Olivier Gillet.
2 //
3 // Author: Olivier Gillet (ol.gillet@gmail.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // THE SOFTWARE.
22 //
23 // See http://creativecommons.org/licenses/MIT/ for more information.
24 
25 #include "stmlib/dsp/dsp.h"
26 #include "stmlib/system/bootloader_utils.h"
27 #include "stmlib/system/system_clock.h"
28 
29 #include "elements/drivers/codec.h"
30 #include "elements/drivers/leds.h"
31 #include "elements/drivers/pots_adc.h"
32 #include "elements/drivers/switch.h"
33 #include "elements/drivers/system.h"
34 
35 #include "elements/meter.h"
36 
37 #include "stm_audio_bootloader/qpsk/packet_decoder.h"
38 #include "stm_audio_bootloader/qpsk/demodulator.h"
39 
40 #include <cstring>
41 
42 using namespace elements;
43 using namespace stmlib;
44 using namespace stm_audio_bootloader;
45 
46 const double kSampleRate = 48000.0;
47 const double kModulationRate = 6000.0;
48 const double kBitRate = 12000.0;
49 const uint32_t kStartAddress = 0x08008000;
50 
51 Codec codec;
52 Demodulator demodulator;
53 Leds leds;
54 Meter meter;
55 PacketDecoder decoder;
56 PotsAdc pots;
57 Switch push_switch;
58 
59 int __errno;
60 
61 // Default interrupt handlers.
62 extern "C" {
63 
NMI_Handler()64 void NMI_Handler() { }
HardFault_Handler()65 void HardFault_Handler() { while (1); }
MemManage_Handler()66 void MemManage_Handler() { while (1); }
BusFault_Handler()67 void BusFault_Handler() { while (1); }
UsageFault_Handler()68 void UsageFault_Handler() { while (1); }
SVC_Handler()69 void SVC_Handler() { }
DebugMon_Handler()70 void DebugMon_Handler() { }
PendSV_Handler()71 void PendSV_Handler() { }
72 
73 }
74 
75 extern "C" {
76 
77 enum UiState {
78   UI_STATE_WAITING,
79   UI_STATE_RECEIVING,
80   UI_STATE_ERROR,
81   UI_STATE_WRITING
82 };
83 
84 volatile bool switch_released = false;
85 volatile UiState ui_state;
86 volatile int32_t gain = 4096;
87 volatile uint8_t pot_index = 0;
88 
UpdateLeds()89 void UpdateLeds() {
90   leds.set_gate(true);
91   switch (ui_state) {
92     case UI_STATE_WAITING:
93       leds.set_gate(system_clock.milliseconds() & 128);
94       break;
95 
96     case UI_STATE_RECEIVING:
97       leds.set_gate(system_clock.milliseconds() & 32);
98       {
99         int32_t peak = meter.peak();
100         if (peak < 16384) {
101           leds.set_exciter(peak >> 6);
102           leds.set_resonator(0);
103         } else {
104           leds.set_exciter(255);
105           leds.set_resonator((peak - 16384) >> 6);
106         }
107       }
108       break;
109 
110     case UI_STATE_ERROR:
111       {
112         bool on = system_clock.milliseconds() & 64;
113         leds.set_exciter(on ? 0 : 255);
114         leds.set_resonator(on ? 255 : 0);
115       }
116       break;
117 
118     case UI_STATE_WRITING:
119       {
120         leds.set_exciter(255);
121         leds.set_resonator(0);
122       }
123       break;
124   }
125   leds.Write();
126 }
127 
SysTick_Handler()128 void SysTick_Handler() {
129   system_clock.Tick();
130   pots.Scan();
131   if (pots.last_read() == POT_EXCITER_BLOW_LEVEL) {
132     int32_t gain_raw = pots.value(POT_EXCITER_BLOW_LEVEL) >> 1;
133     gain = gain_raw * gain_raw >> 16;
134   }
135   push_switch.Debounce();
136   if (push_switch.released()) {
137     switch_released = true;
138   }
139   UpdateLeds();
140 }
141 
142 }
143 
144 size_t discard_samples = 8000;
145 
FillBuffer(Codec::Frame * input,Codec::Frame * output,size_t n)146 void FillBuffer(Codec::Frame* input, Codec::Frame* output, size_t n) {
147   for (size_t i = 0; i < n; ++i) {
148     input[i].r = Clip16(static_cast<int32_t>(input[i].r) * gain >> 12);
149   }
150   meter.Process(input, n);
151   while (n--) {
152     if (!discard_samples) {
153       demodulator.PushSample(2048 + (input->r >> 4));
154     } else {
155       --discard_samples;
156     }
157     *output = *input;
158     ++output;
159     ++input;
160   }
161 }
162 
163 static size_t current_address;
164 static uint16_t packet_index;
165 static uint32_t kSectorBaseAddress[] = {
166   0x08000000,
167   0x08004000,
168   0x08008000,
169   0x0800C000,
170   0x08010000,
171   0x08020000,
172   0x08040000,
173   0x08060000,
174   0x08080000,
175   0x080A0000,
176   0x080C0000,
177   0x080E0000
178 };
179 const uint32_t kBlockSize = 16384;
180 const uint16_t kPacketsPerBlock = kBlockSize / kPacketSize;
181 uint8_t rx_buffer[kBlockSize];
182 
ProgramPage(const uint8_t * data,size_t size)183 void ProgramPage(const uint8_t* data, size_t size) {
184   FLASH_Unlock();
185   FLASH_ClearFlag(
186       FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
187       FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR| FLASH_FLAG_PGSERR);
188   for (int32_t i = 0; i < 12; ++i) {
189     if (current_address == kSectorBaseAddress[i]) {
190       FLASH_EraseSector(i * 8, VoltageRange_3);
191     }
192   }
193   const uint32_t* words = static_cast<const uint32_t*>(
194       static_cast<const void*>(data));
195   for (size_t written = 0; written < size; written += 4) {
196     FLASH_ProgramWord(current_address, *words++);
197     current_address += 4;
198   }
199 }
200 
Init()201 void Init() {
202   System sys;
203   sys.Init(false);
204   leds.Init();
205   meter.Init(48000);
206   push_switch.Init();
207   if (!codec.Init(48000, CODEC_PROTOCOL_PHILIPS, CODEC_FORMAT_16_BIT)) { }
208   if (!codec.Start(&FillBuffer)) { }
209   sys.StartTimers();
210   pots.Init();
211 }
212 
InitializeReception()213 void InitializeReception() {
214   decoder.Init(20000);
215   demodulator.Init(
216       kModulationRate / kSampleRate * 4294967296.0,
217       kSampleRate / kModulationRate,
218       2.0 * kSampleRate / kBitRate);
219   demodulator.SyncCarrier(true);
220   decoder.Reset();
221   current_address = kStartAddress;
222   packet_index = 0;
223   ui_state = UI_STATE_WAITING;
224 }
225 
main(void)226 int main(void) {
227   InitializeReception();
228   Init();
229 
230   bool exit_updater = !push_switch.pressed_immediate();
231 
232   while (!exit_updater) {
233     bool error = false;
234 
235     if (demodulator.state() == DEMODULATOR_STATE_OVERFLOW) {
236       error = true;
237     } else {
238       demodulator.ProcessAtLeast(32);
239     }
240 
241     while (demodulator.available() && !error && !exit_updater) {
242       uint8_t symbol = demodulator.NextSymbol();
243       PacketDecoderState state = decoder.ProcessSymbol(symbol);
244       switch (state) {
245         case PACKET_DECODER_STATE_OK:
246           {
247             ui_state = UI_STATE_RECEIVING;
248             memcpy(
249                 rx_buffer + (packet_index % kPacketsPerBlock) * kPacketSize,
250                 decoder.packet_data(),
251                 kPacketSize);
252             ++packet_index;
253             if ((packet_index % kPacketsPerBlock) == 0) {
254               ui_state = UI_STATE_WRITING;
255               ProgramPage(rx_buffer, kBlockSize);
256               decoder.Reset();
257               demodulator.SyncCarrier(false);
258             } else {
259               decoder.Reset();
260               demodulator.SyncDecision();
261             }
262           }
263           break;
264         case PACKET_DECODER_STATE_ERROR_SYNC:
265         case PACKET_DECODER_STATE_ERROR_CRC:
266           error = true;
267           break;
268         case PACKET_DECODER_STATE_END_OF_TRANSMISSION:
269           exit_updater = true;
270           break;
271         default:
272           break;
273       }
274     }
275     if (error) {
276       ui_state = UI_STATE_ERROR;
277       switch_released = false;
278       while (!switch_released);  // Polled in ISR
279       InitializeReception();
280     }
281   }
282   codec.Stop();
283   pots.DeInit();
284   Uninitialize();
285   JumpTo(kStartAddress);
286   while (1) { }
287 }
288