python-intan 0.0.2__py3-none-any.whl → 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
intan/__init__.py CHANGED
@@ -1,42 +1,42 @@
1
1
  """
2
- python-intan: A Python package for reading and visualizing data from Intan Technologies' RHD2000 series of integrated circuits.
3
-
4
- Subpackages
5
- -----------
6
- io --- Reading and writing Intan data files
7
- plotting --- Plotting and visualization
8
- control --- UART and TCP communication helpers
9
- processing --- Signal processing functions
2
+ Intan: Python interface for reading, processing, and visualizing data
3
+ from Intan Technologies' RHD2000 and RHS2000 acquisition systems.
4
+
5
+ This package includes modules for:
6
+ - Reading and parsing `.rhd` and `.rhs` files
7
+ - Streamed acquisition via TCP/IP from the Intan RHX software
8
+ - Visualization of high-density EMG or LFP signals
9
+ - Configuration and device control
10
10
  """
11
11
 
12
+ __version__ = "0.0.3"
13
+ __author__ = "Jonathan Shulgach"
14
+ __email__ = "jshulgac@andrew.cmu.edu"
15
+ __license__ = "MIT"
16
+ __url__ = "https://github.com/jshulgach/intan-python"
17
+ __description__ = "Python interface for streaming, parsing, and analyzing Intan Technologies RHX files"
18
+
12
19
  import importlib as _importlib
13
20
 
14
21
  submodules = [
22
+ # 'decomposition',
23
+ 'applications',
15
24
  'io',
16
25
  'plotting',
17
- 'control',
26
+ # 'control',
18
27
  'processing',
28
+ 'interface',
29
+ 'samples',
30
+ # 'stream',
19
31
  ]
20
32
 
21
33
  __all__ = submodules + [
22
- 'LowLevelCallable',
23
- 'test',
24
- 'show_config',
34
+ #'LowLevelCallable',
35
+ #'tests',
36
+ #'show_config',
25
37
  '__version__',
26
38
  ]
27
39
 
28
40
 
29
41
  def __dir__():
30
42
  return __all__
31
-
32
-
33
- def __getattr__(name):
34
- if name in submodules:
35
- return _importlib.import_module(f'scipy.{name}')
36
- else:
37
- try:
38
- return globals()[name]
39
- except KeyError:
40
- raise AttributeError(
41
- f"Module 'scipy' has no attribute '{name}'"
42
- )
@@ -0,0 +1,439 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-intan
3
+ Version: 0.0.3
4
+ Summary: Python interface and utilities for working with Intan RHX devices and electrophysiology data
5
+ Author-email: Jonathan Shulgach <jshulgac@andrew.cmu.edu>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Neuro-Mechatronics-Interfaces/python-intan
8
+ Keywords: intan,emg,neurotech,signal processing,biomedical
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: numpy>=1.26.0
13
+ Requires-Dist: scipy==1.14.1
14
+ Requires-Dist: matplotlib
15
+ Requires-Dist: pandas
16
+ Requires-Dist: PySerial
17
+ Requires-Dist: scikit-learn
18
+ Requires-Dist: tqdm
19
+ Requires-Dist: tensorflow==2.19.0
20
+ Requires-Dist: seaborn
21
+ Requires-Dist: pyyaml
22
+ Requires-Dist: PyQt5
23
+ Requires-Dist: pyqtgraph
24
+ Requires-Dist: pylsl
25
+ Provides-Extra: docs
26
+ Requires-Dist: sphinx; extra == "docs"
27
+ Requires-Dist: sphinx-autodoc-typehints; extra == "docs"
28
+ Requires-Dist: myst-parser; extra == "docs"
29
+ Dynamic: license-file
30
+
31
+ ![Logo](https://raw.githubusercontent.com/neuro-mechatronics-interfaces/python-intan/main/docs/figs/logo.png)
32
+
33
+ # Python Intan
34
+
35
+ [![Docs](https://img.shields.io/badge/docs-online-blue.svg)](https://neuro-mechatronics-interfaces.github.io/python-intan/)
36
+ [![Python](https://img.shields.io/badge/python-3.10+-blue)](https://www.python.org/)
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
38
+ [![PyPI version](https://badge.fury.io/py/python-intan.svg)](https://badge.fury.io/py/python-intan)
39
+ [![Downloads](https://pepy.tech/badge/python-intan)](https://pepy.tech/project/python-intan)
40
+
41
+ **python-intan** is a comprehensive Python package for working with Intan Technologies RHX systems and electrophysiology data. From file loading to real-time streaming, signal processing to machine learning, hardware integration to GUI applications—everything you need for EMG/neural data analysis in one package.
42
+
43
+ ---
44
+
45
+ ## ✨ Key Features
46
+
47
+ - 📁 **File I/O**: Load `.rhd`, `.rhs`, `.dat`, `.csv`, and `.npz` files with ease
48
+ - 🔴 **Real-time Streaming**: TCP interface for live data acquisition from RHX devices
49
+ - 🎛️ **Signal Processing**: Filtering, normalization, RMS, feature extraction
50
+ - 🤖 **Machine Learning**: Complete gesture classification pipeline with TensorFlow
51
+ - 📊 **Visualization**: Waterfall plots, real-time plotting, GUI applications
52
+ - 🔌 **Hardware Integration**: LSL support, Raspberry Pi Pico, robotic control
53
+ - 🖥️ **GUI Applications**: EMG viewer, trial selector, gesture pipeline interface
54
+ - 🚀 **Performance**: GPU acceleration, optimized for real-time applications
55
+
56
+ ---
57
+
58
+ ## 📚 Quick Links
59
+
60
+ - [**Documentation**](https://neuro-mechatronics-interfaces.github.io/python-intan/) - Full guides and API reference
61
+ - [**Examples**](https://github.com/Neuro-Mechatronics-Interfaces/python-intan/tree/main/examples) - 60+ code examples
62
+ - [**FAQ**](https://neuro-mechatronics-interfaces.github.io/python-intan/info/faqs.html) - Frequently asked questions
63
+ - [**Contributing**](CONTRIBUTING.md) - How to contribute
64
+ - [**Changelog**](CHANGELOG.md) - Version history
65
+
66
+ ---
67
+
68
+ ## 📦 Installation
69
+
70
+ ### From PyPI (Recommended)
71
+
72
+ ```bash
73
+ pip install python-intan
74
+ ```
75
+
76
+ ### From Source (Latest Features)
77
+
78
+ ```bash
79
+ git clone https://github.com/Neuro-Mechatronics-Interfaces/python-intan.git
80
+ cd python-intan
81
+ pip install -e .
82
+ ```
83
+
84
+ ### With Virtual Environment
85
+
86
+ ```bash
87
+ # Using conda
88
+ conda create -n intan python=3.10
89
+ conda activate intan
90
+ pip install python-intan
91
+
92
+ # Or using venv
93
+ python -m venv intan
94
+ source intan/bin/activate # Windows: intan\Scripts\activate
95
+ pip install python-intan
96
+ ```
97
+
98
+ ### GPU Support (Optional)
99
+
100
+ For faster machine learning training:
101
+
102
+ ```bash
103
+ pip install tensorflow[and-cuda] nvidia-cudnn-cu12
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 🚀 Getting Started
109
+
110
+ ### Load and Visualize EMG Data
111
+
112
+ ```python
113
+ import intan
114
+
115
+ # Load .rhd file (opens file picker)
116
+ result = intan.io.load_rhd_file()
117
+
118
+ # Or specify path directly
119
+ result = intan.io.load_rhd_file('path/to/file.rhd')
120
+
121
+ # Access data
122
+ emg_data = result['amplifier_data'] # Shape: (channels, samples)
123
+ fs = result['frequency_parameters']['amplifier_sample_rate']
124
+ t = result['t_amplifier']
125
+
126
+ # Quick filtering
127
+ emg_filtered = intan.processing.notch_filter(emg_data, fs, f0=60)
128
+ emg_filtered = intan.processing.filter_emg(emg_filtered, 'bandpass', fs,
129
+ lowcut=10, highcut=500)
130
+
131
+ # Visualize
132
+ intan.plotting.waterfall(emg_filtered, range(64), t,
133
+ plot_title='Filtered EMG Data')
134
+ ```
135
+
136
+ ### Real-time Streaming from RHX Device
137
+
138
+ ```python
139
+ from intan.interface import IntanRHXDevice
140
+
141
+ # Connect to device
142
+ device = IntanRHXDevice()
143
+ device.enable_wide_channel(range(64))
144
+ device.start_streaming()
145
+
146
+ # Stream data
147
+ timestamps, data = device.stream(duration_sec=1.0)
148
+ print(f"Acquired data shape: {data.shape}")
149
+
150
+ device.close()
151
+ ```
152
+
153
+ ### Train a Gesture Classifier
154
+
155
+ ```python
156
+ from intan.ml import ModelManager
157
+ import numpy as np
158
+
159
+ # Load training data
160
+ data = np.load('training_data.npz')
161
+ X_train, y_train = data['features'], data['labels']
162
+
163
+ # Train model
164
+ manager = ModelManager()
165
+ model, pca, scaler = manager.train_model(X_train, y_train,
166
+ model_type='CNN', epochs=50)
167
+
168
+ # Save for later use
169
+ manager.save_model('gesture_model.keras')
170
+ ```
171
+
172
+ ### Real-time Gesture Recognition
173
+
174
+ ```python
175
+ from intan.interface import IntanRHXDevice
176
+ from intan.ml import EMGRealTimePredictor
177
+ import tensorflow as tf
178
+
179
+ # Load trained model
180
+ model = tf.keras.models.load_model('gesture_model.keras')
181
+
182
+ # Initialize device
183
+ device = IntanRHXDevice(num_channels=128)
184
+ device.start_streaming()
185
+
186
+ # Create predictor
187
+ predictor = EMGRealTimePredictor(device, model, pca, mean, std, label_names)
188
+ predictor.run_prediction_loop()
189
+
190
+ # Get predictions
191
+ while True:
192
+ prediction = predictor.get_prediction()
193
+ if prediction:
194
+ print(f"Gesture: {prediction['label']} ({prediction['confidence']:.1%})")
195
+ ```
196
+
197
+ ### Lab Streaming Layer (LSL) Integration
198
+
199
+ ```python
200
+ from intan.interface import IntanRHXDevice, LSLPublisher
201
+
202
+ # Start device
203
+ device = IntanRHXDevice(num_channels=64)
204
+ device.start_streaming()
205
+
206
+ # Publish to LSL
207
+ publisher = LSLPublisher(name='IntanEMG', stream_type='EMG',
208
+ channel_count=64, sample_rate=4000)
209
+
210
+ while True:
211
+ _, data = device.stream(n_frames=40)
212
+ publisher.push_chunk(data.T)
213
+ ```
214
+
215
+ ---
216
+
217
+ ## 🗂️ Package Structure
218
+
219
+ ```text
220
+ intan/
221
+ ├── io/ # File loading (.rhd, .dat, .csv, .npz)
222
+ ├── interface/ # RHX device, LSL, hardware interfaces
223
+ ├── processing/ # Signal processing and filtering
224
+ ├── ml/ # Machine learning pipeline
225
+ ├── plotting/ # Visualization utilities
226
+ ├── applications/ # GUI applications
227
+ ├── decomposition/ # PCA, ICA decomposition
228
+ └── samples/ # Sample data utilities
229
+
230
+ examples/
231
+ ├── Read_Files/ # File loading examples
232
+ ├── RHXDevice/ # Device streaming examples
233
+ ├── LSL/ # Lab Streaming Layer examples
234
+ ├── gesture_classifier/ # ML training and prediction
235
+ ├── applications/ # GUI application demos
236
+ ├── 3D_printed_arm_control/ # Robotic control integration
237
+ └── interface/ # Hardware interfacing examples
238
+ ```
239
+
240
+ ---
241
+
242
+ ## 🎯 Use Cases
243
+
244
+ ### 📊 Data Analysis
245
+ - Load and analyze `.rhd` recordings
246
+ - Batch process multiple files
247
+ - Extract specific time segments
248
+ - Generate publication-quality figures
249
+
250
+ ### 🔴 Real-time Applications
251
+ - Live EMG visualization
252
+ - Online gesture recognition
253
+ - Closed-loop control systems
254
+ - Synchronized multi-modal recording
255
+
256
+ ### 🤖 Machine Learning
257
+ - Train gesture classifiers
258
+ - Real-time prediction
259
+ - Cross-session validation
260
+ - Transfer learning
261
+
262
+ ### 🔬 Research
263
+ - Impedance testing
264
+ - Signal quality monitoring
265
+ - Protocol automation
266
+ - Custom experimental setups
267
+
268
+ ---
269
+
270
+ ## 📖 Documentation
271
+
272
+ Comprehensive documentation is available at [neuro-mechatronics-interfaces.github.io/python-intan](https://neuro-mechatronics-interfaces.github.io/python-intan/)
273
+
274
+ **Key Sections:**
275
+ - [Installation Guide](https://neuro-mechatronics-interfaces.github.io/python-intan/info/installation.html)
276
+ - [Loading Files](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/loading_data.html)
277
+ - [Real-time Streaming](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/live_plotting.html)
278
+ - [Signal Processing](https://neuro-mechatronics-interfaces.github.io/python-intan/info/signal_processing.html)
279
+ - [Gesture Classification](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/gesture_classification.html)
280
+ - [LSL Integration](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/lsl_streaming.html)
281
+ - [GUI Applications](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/gui_applications.html)
282
+ - [Hardware Control](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/hardware_control.html)
283
+ - [FAQ](https://neuro-mechatronics-interfaces.github.io/python-intan/info/faqs.html)
284
+ - [API Reference](https://neuro-mechatronics-interfaces.github.io/python-intan/intan_api/modules.html)
285
+
286
+ ---
287
+
288
+ ## 🎓 Examples
289
+
290
+ The `examples/` directory contains 60+ working examples organized by category:
291
+
292
+ ```bash
293
+ # File loading
294
+ python examples/Read_Files/load_rhd_demo.py
295
+
296
+ # Real-time streaming
297
+ python examples/RHXDevice/scrolling_live.py
298
+
299
+ # Gesture classification pipeline
300
+ python examples/gesture_classifier/1a_build_training_dataset_rhd.py
301
+ python examples/gesture_classifier/2_train_model.py
302
+ python examples/gesture_classifier/3d_predict_from_device_realtime.py
303
+
304
+ # GUI applications
305
+ python examples/applications/run_emg_viewer.py
306
+ python examples/applications/gesture_pipeline_gui.py
307
+
308
+ # LSL streaming
309
+ python examples/LSL/lsl_waveform_viewer.py
310
+ python examples/LSL/lsl_rms_barplot.py
311
+ ```
312
+
313
+ See the [Examples Documentation](https://neuro-mechatronics-interfaces.github.io/python-intan/examples/introduction.html) for complete guides.
314
+
315
+ ---
316
+
317
+ ## 🛠️ Supported Hardware
318
+
319
+ - **Intan RHX Controllers**: RHD USB Interface Board, RHD Recording Controller
320
+ - **Amplifiers**: RHD2000 series (RHD2132, RHD2164, RHD2216, etc.)
321
+ - **Stimulation**: RHS2000 series amplifiers
322
+ - **Peripherals**: Raspberry Pi Pico, servo controllers, IMU sensors
323
+ - **Integration**: Lab Streaming Layer (LSL) compatible devices
324
+
325
+ ---
326
+
327
+ ## 🤝 Contributing
328
+
329
+ We welcome contributions! Whether it's:
330
+
331
+ - 🐛 Bug reports
332
+ - ✨ Feature requests
333
+ - 📝 Documentation improvements
334
+ - 🧪 New examples
335
+ - 🔧 Code contributions
336
+
337
+ Please see our [Contributing Guide](CONTRIBUTING.md) for details.
338
+
339
+ **Ways to contribute:**
340
+ - Report bugs or request features via [GitHub Issues](https://github.com/Neuro-Mechatronics-Interfaces/python-intan/issues)
341
+ - Submit pull requests with improvements
342
+ - Share your use cases and examples
343
+ - Help answer questions in discussions
344
+ - Improve documentation
345
+
346
+ ---
347
+
348
+ ## 📝 Citation
349
+
350
+ If you use this package in your research, please cite:
351
+
352
+ ```bibtex
353
+ @software{Shulgach_Python_Intan_2025,
354
+ author = {Shulgach, Jonathan and Murphy, Max and Foy, Adrian},
355
+ title = {{Python Intan Package}},
356
+ year = {2025},
357
+ month = {01},
358
+ version = {0.0.3},
359
+ url = {https://github.com/Neuro-Mechatronics-Interfaces/python-intan},
360
+ note = {Neuromechatronics Lab, Carnegie Mellon University}
361
+ }
362
+ ```
363
+
364
+ ---
365
+
366
+ ## 📄 License
367
+
368
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
369
+
370
+ **MIT License means:**
371
+ - ✅ Commercial use
372
+ - ✅ Modification
373
+ - ✅ Distribution
374
+ - ✅ Private use
375
+
376
+ ---
377
+
378
+ ## 🙏 Acknowledgments
379
+
380
+ Developed by the [Neuromechatronics Lab](https://www.meche.engineering.cmu.edu/faculty/neuromechatronics-lab.html) at Carnegie Mellon University.
381
+
382
+ **Core Contributors:**
383
+ - Jonathan Shulgach
384
+ - Max Murphy
385
+ - Adrian Foy
386
+
387
+ **Special Thanks:**
388
+ - Intan Technologies for hardware and support
389
+ - The open-source neuroscience community
390
+
391
+ ---
392
+
393
+ ## 📧 Contact & Support
394
+
395
+ - **Documentation**: [neuro-mechatronics-interfaces.github.io/python-intan](https://neuro-mechatronics-interfaces.github.io/python-intan/)
396
+ - **Issues**: [GitHub Issues](https://github.com/Neuro-Mechatronics-Interfaces/python-intan/issues)
397
+ - **Email**: jshulgac@andrew.cmu.edu
398
+ - **Lab Website**: [Neuromechatronics Lab](https://www.meche.engineering.cmu.edu/faculty/neuromechatronics-lab.html)
399
+
400
+ ---
401
+
402
+ ## 🚦 Status & Roadmap
403
+
404
+ **Current Version: 0.0.3** (January 2025)
405
+
406
+ ### Completed ✅
407
+ - [x] File loading (.rhd, .dat, .csv, .npz)
408
+ - [x] Real-time TCP streaming from RHX
409
+ - [x] Signal processing pipeline
410
+ - [x] Machine learning (CNN, LSTM, Dense models)
411
+ - [x] Real-time gesture recognition
412
+ - [x] Lab Streaming Layer integration
413
+ - [x] GUI applications (EMG viewer, trial selector, gesture pipeline)
414
+ - [x] Hardware integration (Pico, robotic arms, IMU)
415
+ - [x] Comprehensive documentation and examples
416
+
417
+ ### In Progress 🚧
418
+ - [ ] Performance benchmarking suite
419
+ - [ ] Extended LSL marker synchronization
420
+ - [ ] Additional ML model architectures
421
+ - [ ] Mobile device integration
422
+
423
+ ### Planned 📋
424
+ - [ ] Public training datasets
425
+ - [ ] Cloud integration for distributed processing
426
+ - [ ] Advanced impedance testing tools
427
+ - [ ] Multi-language support (MATLAB, Julia wrappers)
428
+
429
+ See [CHANGELOG.md](CHANGELOG.md) for detailed version history.
430
+
431
+ ---
432
+
433
+ <p align="center">
434
+ <b>⭐ If you find this package useful, please consider giving it a star on GitHub! ⭐</b>
435
+ </p>
436
+
437
+ <p align="center">
438
+ Made with ❤️ by the Neuromechatronics Lab
439
+ </p>
@@ -0,0 +1,6 @@
1
+ intan/__init__.py,sha256=dkVJG-UkEqVxonW6TmCAR05lEq2mbitPDD-SCz4xHXc,1032
2
+ python_intan-0.0.3.dist-info/licenses/LICENSE,sha256=acfOQeocdtaKmGd_-tdY3yOUSrxP9_nX4q2xv7G9RR0,1099
3
+ python_intan-0.0.3.dist-info/METADATA,sha256=zkBY38oZXYtZToG9krja9GF9FfUBMFbf7BdBLuyR2I4,13969
4
+ python_intan-0.0.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ python_intan-0.0.3.dist-info/top_level.txt,sha256=P-ybm93eLvEAjcZnvltPlz6ghXTfMSb0ttfh9G_tBkI,6
6
+ python_intan-0.0.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.3.1)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
intan/control/__init__.py DELETED
@@ -1 +0,0 @@
1
- from ._messaging import PicoMessager, TCPClient, RingBuffer
@@ -1,171 +0,0 @@
1
- import time
2
- import socket
3
- import serial
4
- import numpy as np
5
- from statistics import mode, StatisticsError
6
- import collections
7
-
8
-
9
- class PicoMessager:
10
- """Class for managing serial communication with a Raspberry Pi Pico."""
11
-
12
- def __init__(self, port='COM13', baudrate=9600, buffer_size=1, verbose=False):
13
- """Initializes the PicoMessager.
14
-
15
- Args:
16
- port (str): The serial port to connect to (e.g., 'COM13').
17
- baudrate (int): The baud rate for serial communication.
18
- buffer_size (int): The number of past gestures to keep in the buffer.
19
- verbose (bool): Whether to print incoming messages automatically.
20
- """
21
- self.port = port
22
- self.baudrate = baudrate
23
- self.buffer = collections.deque(maxlen=buffer_size)
24
- self.current_gesture = None # Keep track of the current gesture being sent
25
- self.verbose = verbose
26
- self.running = True # To control the connection
27
-
28
- # Connect to the Pico via serial
29
- try:
30
- self.serial_connection = serial.Serial(self.port, self.baudrate, timeout=1)
31
- print(f"Connected to Pico on {self.port} at {self.baudrate} baud.")
32
- except serial.SerialException as e:
33
- print(f"Error connecting to Pico: {e}")
34
- self.serial_connection = None
35
-
36
- def dump_output(self, mute=False):
37
- """Reads all available bytes from the serial connection and prints them.
38
-
39
- This function reads all incoming messages from the Pico until there are no more bytes left.
40
- """
41
- if self.serial_connection and self.serial_connection.is_open:
42
- try:
43
- if self.serial_connection.in_waiting > 0:
44
- incoming_message = self.serial_connection.readline().decode().strip()
45
- if incoming_message and not mute:
46
- print(f"Message from Pico: {incoming_message}")
47
- except serial.SerialException as e:
48
- print(f"Error reading message: {e}")
49
-
50
- def update_gesture(self, new_gesture):
51
- """Updates the gesture buffer and sends the most common gesture if it changes.
52
-
53
- Args:
54
- new_gesture (str): The newly detected gesture.
55
- """
56
- # Update the gesture buffer
57
- self.buffer.append(new_gesture)
58
-
59
- # Find the most common gesture in the buffer
60
- try:
61
- most_common_gesture = mode(self.buffer)
62
- except StatisticsError:
63
- # If mode cannot be determined, continue without change
64
- most_common_gesture = None
65
-
66
- # If the most common gesture changes, update current_gesture and send the new message
67
- if most_common_gesture and most_common_gesture != self.current_gesture:
68
- self.current_gesture = most_common_gesture
69
- self.send_message(self.current_gesture)
70
-
71
- def send_message(self, message):
72
- """Sends a message to the Pico over serial.
73
-
74
- Args:
75
- message (str): The message to send.
76
- """
77
- if self.serial_connection and self.serial_connection.is_open:
78
- try:
79
- formatted_message = f"{message};" # Add terminator character to the message
80
- self.serial_connection.write(formatted_message.encode())
81
- print(f"Sent message to Pico: {formatted_message}")
82
- except serial.SerialException as e:
83
- print(f"Error sending message: {e}")
84
- else:
85
- print("Serial connection not available or not open.")
86
-
87
- def close_connection(self):
88
- """Closes the serial connection to the Pico and stops the background listener."""
89
- # Stop the background thread
90
- self.running = False
91
-
92
- if self.serial_connection and self.serial_connection.is_open:
93
- self.serial_connection.close()
94
- print("Closed connection to Pico.")
95
-
96
-
97
- class TCPClient:
98
- """ Class for managing TCP connections to the Intan system."""
99
- def __init__(self, name, host, port, buffer=1024):
100
- """Initializes the TCPClient.
101
-
102
- Args:
103
- name (str): Name of the client.
104
- host (str): The IP address of the host to connect to.
105
- port (int): The port number to connect to.
106
- buffer (int): The buffer size for receiving data.
107
- """
108
- self.name = name
109
- self.host = host
110
- self.port = port
111
- self.buffer = buffer
112
- self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
113
- self.s.settimeout(5) # Timeout after 5 seconds if no data received
114
-
115
- def connect(self):
116
- """Connects to the host server."""
117
- self.s.setblocking(True)
118
- self.s.connect((self.host, self.port))
119
- self.s.setblocking(False)
120
-
121
- def send(self, data, wait_for_response=False):
122
- """Sends data to the host server and optionally waits for a response."""
123
- # convert data to bytes if it is not already
124
- if not isinstance(data, bytes):
125
- data = data.encode()
126
- self.s.sendall(data)
127
- time.sleep(0.01)
128
-
129
- if wait_for_response:
130
- return self.read()
131
-
132
- def read(self, bytes=None):
133
- """ Reads and returns bytes by the buffer size unless specified """
134
- if bytes is None:
135
- return self.s.recv(self.buffer)
136
- else:
137
- return self.s.recv(bytes)
138
-
139
- def close(self):
140
- self.s.close()
141
-
142
-
143
- class RingBuffer:
144
- """Fixed-size ring buffer for storing recent data up to max number of samples."""
145
-
146
- def __init__(self, num_channels, size_max=4000):
147
- self.max = size_max
148
- self.samples = collections.deque(maxlen=size_max) # Stores (timestamp, data)
149
- self.num_channels = num_channels
150
-
151
- def append(self, t, x):
152
- """Adds a new sample to the buffer, automatically removing the oldest if full."""
153
- x = np.array(x, dtype=np.float32).reshape(1, -1) # Ensure it remains multi-channel
154
- self.samples.append((t, x))
155
-
156
- def get_samples(self, n=1):
157
- """Returns the last n samples from the buffer as NumPy arrays."""
158
- if len(self.samples) < n:
159
- raise ValueError("Requested more samples than available in the buffer.")
160
-
161
- recent_samples = list(self.samples)[-n:] # Get last n elements
162
- timestamps, data = zip(*recent_samples) # Separate timestamps and data
163
-
164
- # Convert to NumPy arrays and ensure shape is correct
165
- data_array = np.vstack(data) # Stack samples to shape (n, num_channels)
166
-
167
- return data_array, np.array(timestamps)
168
-
169
- def is_full(self):
170
- """Checks if the buffer is at max capacity."""
171
- return len(self.samples) == self.max