-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ft8.tsx
407 lines (298 loc) · 12.5 KB
/
Ft8.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import React, { useState, useEffect } from 'react'
import { StatusBar } from 'expo-status-bar'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import useCachedResources from './hooks/useCachedResources'
import useColorScheme from './hooks/useColorScheme'
import Navigation from './navigation'
import { Button, View, TextInput } from 'react-native'
import WebView from 'react-native-webview'
import { useWebViewMessage } from 'react-native-react-bridge'
import ApiPoker from './apiPoker.js'
import { StorageAccessFramework } from 'expo-file-system'
import { Buffer } from '@craftzdog/react-native-buffer'
import { Audio } from 'expo-av'
import * as MediaLibrary from 'expo-media-library'
import * as FileSystem from 'expo-file-system'
import { FFmpegKit } from 'ffmpeg-kit-react-native'
import { useDispatch, useSelector } from 'react-redux'
import { store } from './state/store'
import {
addDebugField,
removeDebugField,
removeDebugFields
} from './state/reducers/debugReducer'
import {
fetchTimeFromGNSS,
initializeTime
} from './state/reducers/timeReducer'
// Globals
let permissions: any
let uri: any
let createdFilename: any
let recordingUri // RECORDING FRO MEXPO
// For performance measurements
let start_meas: any
let middle_meas: any
let end_meas: any
const bufferFrom16Array = (array16: any) => {
const buf = []
let wi = 0
for (let i = 0; i < array16.length; i++) {
buf[wi] = array16[i] >> 8
wi++
buf[wi] = array16[i]
wi++
}
return Buffer.from(buf)
}
// Used by file2audio
const array16FromBuffer = (buffer: any) => {
const arr = []
const arrayLength = 350000
for (let i = 0; i < arrayLength; i++) {
arr.push(
(buffer[i] << 8) | (buffer[i + 1])
)
// Increase index by one since we are processing 16 bit (byte) values.
// If increment would be just one by for loop, step would be 1 byte.
i++
if (i === arrayLength - 1) {
break
}
}
return new Uint16Array(arr)
}
const saveAndPlayDecodedMessage = async (dataArray: any) => {
middle_meas = performance.now()
FileSystem.writeAsStringAsync(
`${FileSystem.cacheDirectory}/encoded_message_out.wav`, // If file does not exist, it creates it, otherwise, overwrites it
bufferFrom16Array(new Uint16Array(dataArray)).toString('base64'), // Get data buffer
{ encoding: 'base64' } // Very imporant one since, we are writing it as a string
)
.then(async (writedStatus) => {
const { sound } = await Audio.Sound.createAsync(
{ uri: `${FileSystem.cacheDirectory}/encoded_message_out.wav` }
)
// For performance analysis
end_meas = performance.now()
console.log(`Call to start to receved took ${middle_meas - start_meas} milliseconds.`)
console.log(`Call to start to writed file took ${end_meas - start_meas} milliseconds.`)
// Play encoded ft8 audio
await sound.playAsync()
})
.catch(e => console.log(`Could not write a file, err: ${e.message}`))
}
export default function Ft8() {
const dispatch = useDispatch()
const selector = useSelector((state: any) => state.debug)
const tests = useSelector((state: any) => state.time)
const counter = null
// console.log('TESTS', tests)
// useEffect(() => {
// // dispatch(fetchTimeFromGNSS())
// console.log('DISPATCHGIN')
// dispatch(initializeTime())
// // setTimeout(() => {
// // dispatch(
// // fetchTimeFromGNSS()
// // )
// // }, 3000)
// }, [dispatch])
// SetTimeout accuracy test
// const cTime = Date.now()
// counter = setTimeout(() => {
// console.log('accuracy' ,(Date.now() - 1000) - cTime)
// }, 1000)
// const [time, setTime] = useState(Math.floor(Date.now() / 1000))
// setInterval(() => setTime(Math.floor(Date.now() / 1000)))
// useEffect(() => {
// console.log('acc', time)
// }, [time])
const [messageInput, setMessageInput] = useState('CQ OH9KR KP26')
const [recording, setRecording] = useState()
const [receivedMessages, setReceivedMessages] = useState([])
const [debugData, setDegubData] = useState({random: ''})
// For creating debug field
const [localFieldName, setLocalFieldName] = useState('')
const [localFieldValue, setLocalFieldValue] = useState('')
// START RECORDING AUDIO
const onPressRecord = async () => {
// EXCPO AV
try {
console.log('Requesting permissions..')
const recPermissions = await Audio.requestPermissionsAsync() // TODO move this out of here. Should ask @startup
console.log('Permissions over', recPermissions)
await Audio.setAudioModeAsync({})
console.log('Starting recording..')
const { recording } = await Audio.Recording.createAsync({
isMeteringEnabled: true,
android: {
extension: '.mp4',
outputFormat: Audio.AndroidOutputFormat.MPEG_4,
audioEncoder: Audio.AndroidAudioEncoder.DEFAULT,
sampleRate: 12000, // 44100, = expo defulat
numberOfChannels: 1,
bitRate: 128000,
},
ios: {
extension: '.m4a',
outputFormat: Audio.IOSOutputFormat.MPEG4AAC,
audioQuality: Audio.IOSAudioQuality.MAX,
sampleRate: 44100,
numberOfChannels: 2,
bitRate: 128000,
linearPCMBitDepth: 16,
linearPCMIsBigEndian: false,
linearPCMIsFloat: false,
},
web: {
mimeType: 'audio/webm',
bitsPerSecond: 128000,
},
})
setRecording(recording)
console.log('Recording started')
} catch (err) {
console.error('Failed to start recording', err)
}
}
const onPressStopRecord = async () => {
start_meas = performance.now()
console.log('Stopping recording..')
setRecording(undefined)
await recording.stopAndUnloadAsync()
recordingUri = recording.getURI()
console.log('Recording stopped and stored at', recordingUri)
const sourceFile = recordingUri
const destinationFile = 'file:///data/user/0/com.rantakangas.ft8shack/cache/Audio/myConversion22.wav' // fileForConvertedRecord
console.log('sourceFile', sourceFile, '& destinationFile', destinationFile)
FFmpegKit
.execute(`-i ${sourceFile} -acodec pcm_u8 -ar 12000 -ac 1 -c:a pcm_s16le ${destinationFile}`)
.then(async (session) => {
console.log(209, 'Converting successfully completed!', session)
// Optional, just for debugging if the original decode_ft8 works
// MediaLibrary.saveToLibraryAsync(destinationFile)
// console.log("saved to library maybe async DESTINATIONFILE =====" , destinationFile)
// DECODE FT8 FROM DESTINATION FILE
const testFile = await StorageAccessFramework.readAsStringAsync(destinationFile, {
encoding: 'base64',
length: 350000
})
emit({ type: 'DECODE_FT8', data: array16FromBuffer(Buffer.from(testFile, 'base64')) })
console.log('Deleting recoded audio')
await StorageAccessFramework.deleteAsync(destinationFile, { idempotent: true })
console.log(`Deleted file: "${destinationFile}"`)
})
.catch(async (err) => {
console.log(`FFmpeg errored!! #: ${err.message} ::: ${err}`)
console.log('...still, deleting recoded audio')
await StorageAccessFramework.deleteAsync(destinationFile, { idempotent: true })
console.log(`Deleted file: "${destinationFile}"`)
})
}
useEffect(() => {
(async () => {
// uri = StorageAccessFramework.getUriForDirectoryInRoot('Pictures')
// console.debug("uri ", uri)
// permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync(uri)
const mediaPermissions = await MediaLibrary.requestPermissionsAsync()
})()
}, [])
// useWebViewMessage hook create props for WebView and handle communication
// The argument is callback to receive message from React
const { ref, onMessage, emit } = useWebViewMessage((message: any) => {
// console.log("@App reeived msg from WebView! Msg is=", message);
if (message.type === 'saveAndPlayDecodedMessage') {
saveAndPlayDecodedMessage(message.data, setDegubData)
} else if (message.type === 'showContent') {
setReceivedMessages(message.data)
}
if (message.type === 'LOG') console.log(message.data)
})
const isLoadingComplete = useCachedResources()
const colorScheme = useColorScheme()
if (!isLoadingComplete) {
return null
} else {
return (
<SafeAreaProvider>
<Navigation colorScheme={colorScheme} />
{
receivedMessages.map(message => <TextInput
key={message.text}
value={`${message.score}dB, ${message.freq}Hz, ${message.time}s, ${message.text}`}>
</TextInput>)
}
{/* Do not show this since it only for poking WebAssemvbly */}
<View>
<WebView
incognito={true}
ref={ref}
// Pass the source code of React App
source={{ html: ApiPoker }}
onMessage={onMessage}
/>
</View>
<TextInput
value={JSON.stringify(
selector
)}
placeholder={'Something should be here'}
/>
<TextInput
value={ JSON.stringify(debugData) }
placeholder={'Logs Are Here'}
/>
<TextInput
value={messageInput}
placeholder={'Message here'}
onChangeText={setMessageInput}
>
</TextInput>
<TextInput
value={ localFieldName }
placeholder={'Field Name'}
onChangeText={setLocalFieldName}
/>
<TextInput
value={ localFieldValue }
placeholder={'Field Value'}
onChangeText={setLocalFieldValue}
/>
<Button
title="Test store"
onPress={() => {
dispatch(addDebugField({
fieldName: localFieldName,
fieldValue: localFieldValue
}))
} }
/>
<Button
title="Remove one store"
onPress={() => {
dispatch(removeDebugField(localFieldName))
} }
/>
<Button
title="Remove all store"
onPress={() => {
dispatch(removeDebugFields())
} }
/>
<Button
title="TX"
onPress={() => {
start_meas = performance.now()
emit({ type: 'ENCODE_FT8', data: messageInput })
} }
/>
<Button
title={recording ? 'Stop Recording' : 'Start Recording'}
onPress={recording ? onPressStopRecord : onPressRecord}
/>
<StatusBar />
</SafeAreaProvider>
)
}
}