Skip to main content

em100/
device.rs

1//! Core EM100 device structure and operations
2
3use crate::chips::ChipDesc;
4use crate::error::{Error, Result};
5use crate::fpga;
6use crate::sdram;
7use crate::spi;
8use crate::system;
9use crate::usb;
10use nusb::transfer::{Bulk, In, Out};
11use nusb::{Endpoint, MaybeFuture};
12use std::cell::RefCell;
13use std::time::Duration;
14
15/// EM100 USB Vendor ID
16pub const VENDOR_ID: u16 = 0x04b4;
17/// EM100 USB Product ID  
18pub const PRODUCT_ID: u16 = 0x1235;
19
20/// USB bulk transfer timeout in milliseconds
21pub const BULK_SEND_TIMEOUT: Duration = Duration::from_millis(5000);
22
23/// Hardware versions
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[repr(u8)]
26pub enum HwVersion {
27    /// Early EM100Pro (hardware version 0xff)
28    Em100ProEarly = 0xff,
29    /// EM100Pro (hardware version 0x04)
30    Em100Pro = 0x04,
31    /// EM100Pro-G2 (hardware version 0x06)
32    Em100ProG2 = 0x06,
33    /// Unknown hardware version
34    Unknown = 0x00,
35}
36
37impl From<u8> for HwVersion {
38    fn from(v: u8) -> Self {
39        match v {
40            0xff => HwVersion::Em100ProEarly,
41            0x04 => HwVersion::Em100Pro,
42            0x06 => HwVersion::Em100ProG2,
43            _ => HwVersion::Unknown,
44        }
45    }
46}
47
48impl std::fmt::Display for HwVersion {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        match self {
51            HwVersion::Em100ProEarly => write!(f, "EM100Pro (early)"),
52            HwVersion::Em100Pro => write!(f, "EM100Pro"),
53            HwVersion::Em100ProG2 => write!(f, "EM100Pro-G2"),
54            HwVersion::Unknown => write!(f, "Unknown"),
55        }
56    }
57}
58
59/// Hold pin states
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
61pub enum HoldPinState {
62    #[default]
63    Float = 0x2,
64    Low = 0x0,
65    Input = 0x3,
66}
67
68impl std::str::FromStr for HoldPinState {
69    type Err = Error;
70
71    fn from_str(s: &str) -> Result<Self> {
72        match s.to_uppercase().as_str() {
73            "FLOAT" => Ok(HoldPinState::Float),
74            "LOW" => Ok(HoldPinState::Low),
75            "INPUT" => Ok(HoldPinState::Input),
76            _ => Err(Error::InvalidArgument(format!(
77                "Invalid hold pin state: {}",
78                s
79            ))),
80        }
81    }
82}
83
84impl std::fmt::Display for HoldPinState {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        match self {
87            HoldPinState::Float => write!(f, "float"),
88            HoldPinState::Low => write!(f, "low"),
89            HoldPinState::Input => write!(f, "input"),
90        }
91    }
92}
93
94/// EM100 device structure
95pub struct Em100 {
96    /// USB bulk OUT endpoint
97    pub endpoint_out: RefCell<Endpoint<Bulk, Out>>,
98    /// USB bulk IN endpoint
99    pub endpoint_in: RefCell<Endpoint<Bulk, In>>,
100    /// MCU firmware version
101    pub mcu: u16,
102    /// FPGA firmware version
103    pub fpga: u16,
104    /// Device serial number
105    pub serial_no: u32,
106    /// Hardware version
107    pub hw_version: HwVersion,
108}
109
110/// USB endpoint addresses
111const ENDPOINT_OUT: u8 = 0x01;
112const ENDPOINT_IN: u8 = 0x82;
113
114impl Em100 {
115    /// Open an EM100 device
116    ///
117    /// If bus and device are specified, opens the device at that location.
118    /// If serial_number is specified, opens the device with that serial number.
119    /// Otherwise, opens the first EM100 device found.
120    pub fn open(bus: Option<u8>, device: Option<u8>, serial_number: Option<u32>) -> Result<Self> {
121        let (endpoint_out, endpoint_in) = if let (Some(bus), Some(dev)) = (bus, device) {
122            // Find device by bus:device
123            Self::open_by_bus_device(bus, dev)?
124        } else if let Some(serial) = serial_number {
125            // Find device by serial number - need to open each and check
126            Self::open_by_serial(serial)?
127        } else {
128            // Open first available device
129            Self::open_first()?
130        };
131
132        let mut em100 = Em100 {
133            endpoint_out: RefCell::new(endpoint_out),
134            endpoint_in: RefCell::new(endpoint_in),
135            mcu: 0,
136            fpga: 0,
137            serial_no: 0,
138            hw_version: HwVersion::Unknown,
139        };
140
141        em100.init()?;
142        Ok(em100)
143    }
144
145    fn open_first() -> Result<(Endpoint<Bulk, Out>, Endpoint<Bulk, In>)> {
146        for device in nusb::list_devices().wait()? {
147            if device.vendor_id() == VENDOR_ID && device.product_id() == PRODUCT_ID {
148                let dev = device.open().wait()?;
149                let interface = dev.claim_interface(0).wait()?;
150                let endpoint_out = interface.endpoint::<Bulk, Out>(ENDPOINT_OUT)?;
151                let endpoint_in = interface.endpoint::<Bulk, In>(ENDPOINT_IN)?;
152                return Ok((endpoint_out, endpoint_in));
153            }
154        }
155        Err(Error::DeviceNotFound)
156    }
157
158    fn open_by_bus_device(bus: u8, dev: u8) -> Result<(Endpoint<Bulk, Out>, Endpoint<Bulk, In>)> {
159        for device in nusb::list_devices().wait()? {
160            if device.busnum() == bus && device.device_address() == dev {
161                if device.vendor_id() == VENDOR_ID && device.product_id() == PRODUCT_ID {
162                    let usb_dev = device.open().wait()?;
163                    let interface = usb_dev.claim_interface(0).wait()?;
164                    let endpoint_out = interface.endpoint::<Bulk, Out>(ENDPOINT_OUT)?;
165                    let endpoint_in = interface.endpoint::<Bulk, In>(ENDPOINT_IN)?;
166                    return Ok((endpoint_out, endpoint_in));
167                } else {
168                    return Err(Error::InvalidArgument(format!(
169                        "USB device on bus {:03}:{:02} is not an EM100pro",
170                        bus, dev
171                    )));
172                }
173            }
174        }
175        Err(Error::DeviceNotFound)
176    }
177
178    fn open_by_serial(serial: u32) -> Result<(Endpoint<Bulk, Out>, Endpoint<Bulk, In>)> {
179        for device in nusb::list_devices().wait()? {
180            if device.vendor_id() == VENDOR_ID && device.product_id() == PRODUCT_ID {
181                let usb_dev = device.open().wait()?;
182                let interface = usb_dev.claim_interface(0).wait()?;
183                let endpoint_out = interface.endpoint::<Bulk, Out>(ENDPOINT_OUT)?;
184                let endpoint_in = interface.endpoint::<Bulk, In>(ENDPOINT_IN)?;
185                let mut em100 = Em100 {
186                    endpoint_out: RefCell::new(endpoint_out),
187                    endpoint_in: RefCell::new(endpoint_in),
188                    mcu: 0,
189                    fpga: 0,
190                    serial_no: 0,
191                    hw_version: HwVersion::Unknown,
192                };
193
194                // Try to init and check serial
195                if em100.init().is_ok() && em100.serial_no == serial {
196                    // Re-extract the endpoints (can't return from a moved em100)
197                    let endpoint_out = em100.endpoint_out.into_inner();
198                    let endpoint_in = em100.endpoint_in.into_inner();
199                    return Ok((endpoint_out, endpoint_in));
200                }
201            }
202        }
203        Err(Error::DeviceNotFound)
204    }
205
206    /// Initialize the device
207    fn init(&mut self) -> Result<()> {
208        // nusb handles kernel driver detachment and interface claiming automatically
209
210        // Check device status
211        if !self.check_status()? {
212            return Err(Error::StatusUnknown);
213        }
214
215        // Get version information
216        self.get_version()?;
217
218        // Get device info (serial number, hardware version)
219        self.get_device_info()?;
220
221        Ok(())
222    }
223
224    /// Check device status by reading SPI flash ID
225    fn check_status(&self) -> Result<bool> {
226        let id = spi::get_spi_flash_id(self)?;
227        // Check for Micron M25P16 or MX77L12850F
228        Ok(id == 0x202015 || id == 0xc27518)
229    }
230
231    /// Get firmware version information
232    fn get_version(&mut self) -> Result<()> {
233        let (mcu, fpga) = system::get_version(self)?;
234        self.mcu = mcu;
235        self.fpga = fpga;
236        Ok(())
237    }
238
239    /// Get device serial number and hardware version
240    fn get_device_info(&mut self) -> Result<()> {
241        let mut data = [0u8; 256];
242        spi::read_spi_flash_page(self, 0x1fff00, &mut data)?;
243
244        self.serial_no = (data[5] as u32) << 24
245            | (data[4] as u32) << 16
246            | (data[3] as u32) << 8
247            | data[2] as u32;
248        self.hw_version = HwVersion::from(data[1]);
249        Ok(())
250    }
251
252    /// Start or stop emulation
253    pub fn set_state(&self, run: bool) -> Result<()> {
254        fpga::write_fpga_register(self, 0x28, if run { 1 } else { 0 })?;
255        Ok(())
256    }
257
258    /// Get current emulation state
259    pub fn get_state(&self) -> Result<bool> {
260        let state = fpga::read_fpga_register(self, 0x28)?;
261        Ok(state != 0)
262    }
263
264    /// Set address mode (3 or 4 byte)
265    pub fn set_address_mode(&self, mode: u8) -> Result<()> {
266        if mode != 3 && mode != 4 {
267            return Err(Error::InvalidArgument(format!(
268                "Invalid address mode: {}",
269                mode
270            )));
271        }
272        fpga::write_fpga_register(self, 0x4f, if mode == 4 { 1 } else { 0 })?;
273        Ok(())
274    }
275
276    /// Get current hold pin state
277    pub fn get_hold_pin_state(&self) -> Result<HoldPinState> {
278        let val = fpga::read_fpga_register(self, 0x2a)?;
279        match val {
280            0 => Ok(HoldPinState::Low),
281            2 => Ok(HoldPinState::Float),
282            3 => Ok(HoldPinState::Input),
283            _ => Err(Error::InvalidResponse),
284        }
285    }
286
287    /// Set hold pin state
288    pub fn set_hold_pin_state(&self, state: HoldPinState) -> Result<()> {
289        // Read and acknowledge current state
290        let val = fpga::read_fpga_register(self, 0x2a)?;
291        fpga::write_fpga_register(self, 0x2a, (1 << 2) | val)?;
292
293        // Read again
294        let _ = fpga::read_fpga_register(self, 0x2a)?;
295
296        // Set desired state
297        fpga::write_fpga_register(self, 0x2a, state as u16)?;
298
299        // Verify
300        let new_val = fpga::read_fpga_register(self, 0x2a)?;
301        if new_val != state as u16 {
302            return Err(Error::OperationFailed(format!(
303                "Failed to set hold pin state. Expected {:?}, got {}",
304                state, new_val
305            )));
306        }
307
308        Ok(())
309    }
310
311    /// Set chip type for emulation
312    pub fn set_chip_type(&mut self, chip: &ChipDesc) -> Result<()> {
313        let fpga_voltage = if self.fpga & 0x8000 != 0 { 1800 } else { 3300 };
314
315        // Check if we need to switch FPGA voltage
316        for entry in chip.init.iter().take(chip.init_len) {
317            if entry[0] != 0x11 || entry[1] != 0x04 {
318                continue;
319            }
320
321            let chip_voltage = ((entry[2] as u16) << 8) | (entry[3] as u16);
322
323            let req_voltage = match chip_voltage {
324                1601 | 1800 if fpga_voltage == 3300 => Some(18),
325                3300 if fpga_voltage == 1800 => Some(33),
326                _ => None,
327            };
328
329            if let Some(voltage) = req_voltage {
330                if !self.set_fpga_voltage(voltage)? {
331                    return Err(Error::OperationFailed(format!(
332                        "The current FPGA firmware ({:.1}V) does not support {} {} ({:.1}V)",
333                        fpga_voltage as f32 / 1000.0,
334                        chip.vendor,
335                        chip.name,
336                        chip_voltage as f32 / 1000.0
337                    )));
338                }
339            }
340            break;
341        }
342
343        // Send init sequence
344        for entry in chip.init.iter().take(chip.init_len) {
345            usb::send_cmd(self, entry)?;
346        }
347
348        // Set FPGA registers
349        fpga::write_fpga_register(self, 0xc4, 0x01)?;
350        fpga::write_fpga_register(self, 0x10, 0x00)?;
351        fpga::write_fpga_register(self, 0x81, 0x00)?;
352
353        Ok(())
354    }
355
356    /// Set FPGA voltage (18 for 1.8V, 33 for 3.3V)
357    pub fn set_fpga_voltage(&mut self, voltage_code: u8) -> Result<bool> {
358        fpga::fpga_reconfigure(self)?;
359
360        let mut cmd = [0u8; 16];
361        cmd[0] = 0x24;
362        if voltage_code == 18 {
363            cmd[2] = 7;
364            cmd[3] = 0x80;
365        }
366        usb::send_cmd(self, &cmd)?;
367
368        // Must wait 2s before issuing any other USB command
369        std::thread::sleep(Duration::from_secs(2));
370
371        // Verify
372        self.get_version().ok();
373        let actual = if self.fpga & 0x8000 != 0 { 18 } else { 33 };
374
375        if actual != voltage_code {
376            return Ok(false);
377        }
378
379        Ok(true)
380    }
381
382    /// Set serial number
383    pub fn set_serial_no(&mut self, serial: u32) -> Result<()> {
384        let mut data = [0u8; 512];
385        spi::read_spi_flash_page(self, 0x1fff00, &mut data[..256])?;
386
387        let old_serial = (data[5] as u32) << 24
388            | (data[4] as u32) << 16
389            | (data[3] as u32) << 8
390            | data[2] as u32;
391
392        if old_serial == serial {
393            return Ok(());
394        }
395
396        data[2] = serial as u8;
397        data[3] = (serial >> 8) as u8;
398        data[4] = (serial >> 16) as u8;
399        data[5] = (serial >> 24) as u8;
400
401        if old_serial != 0xffffffff {
402            // Preserve magic
403            spi::read_spi_flash_page(self, 0x1f0000, &mut data[256..512])?;
404            spi::unlock_spi_flash(self)?;
405            spi::get_spi_flash_id(self)?;
406            spi::erase_spi_flash_sector(self, 0x1f)?;
407            spi::write_spi_flash_page(self, 0x1f0000, &data[256..512])?;
408        }
409
410        spi::write_spi_flash_page(self, 0x1fff00, &data[..256])?;
411
412        // Re-read serial number
413        self.get_device_info()?;
414
415        Ok(())
416    }
417
418    /// Download data to SDRAM
419    pub fn download(&self, data: &[u8], address: u32) -> Result<()> {
420        sdram::write_sdram(self, data, address)
421    }
422
423    /// Upload data from SDRAM
424    pub fn upload(&self, address: u32, length: usize) -> Result<Vec<u8>> {
425        sdram::read_sdram(self, address, length)
426    }
427
428    /// Get serial number as string
429    pub fn serial_string(&self) -> String {
430        if self.serial_no == 0xffffffff {
431            "N.A.".to_string()
432        } else {
433            let prefix = if self.hw_version == HwVersion::Em100ProEarly {
434                "DP"
435            } else {
436                "EM"
437            };
438            format!("{}{:06}", prefix, self.serial_no)
439        }
440    }
441
442    /// Get device information as structured data
443    pub fn get_info(&self) -> DeviceInfo {
444        let mcu_version = format!("{}.{:02}", self.mcu >> 8, self.mcu & 0xff);
445
446        let fpga_version = match self.hw_version {
447            HwVersion::Em100Pro | HwVersion::Em100ProEarly => {
448                if self.fpga > 0x0033 {
449                    format!(
450                        "{}.{:02} ({})",
451                        (self.fpga >> 8) & 0x7f,
452                        self.fpga & 0xff,
453                        if self.fpga & 0x8000 != 0 {
454                            "1.8V"
455                        } else {
456                            "3.3V"
457                        }
458                    )
459                } else {
460                    format!("{}.{:02}", self.fpga >> 8, self.fpga & 0xff)
461                }
462            }
463            HwVersion::Em100ProG2 => {
464                format!("{}.{:03}", (self.fpga >> 8) & 0x7f, self.fpga & 0xff)
465            }
466            _ => format!("{}.{}", self.fpga >> 8, self.fpga & 0xff),
467        };
468
469        DeviceInfo {
470            mcu_version,
471            fpga_version,
472            hw_version: self.hw_version,
473            serial: self.serial_string(),
474            fpga_voltage: if self.fpga & 0x8000 != 0 { 1800 } else { 3300 },
475        }
476    }
477
478    /// Print device information (CLI convenience)
479    #[cfg(feature = "cli")]
480    pub fn print_info(&self) {
481        let info = self.get_info();
482        println!("MCU version: {}", info.mcu_version);
483        println!("FPGA version: {}", info.fpga_version);
484        println!("Hardware version: {:?}", info.hw_version);
485        println!("Serial number: {}", info.serial);
486    }
487
488    /// Get debug information (voltages and FPGA registers)
489    pub fn get_debug_info(&self) -> Result<DebugInfo> {
490        system::set_led(self, system::LedState::BothOff)?;
491        let v1_2 = system::get_voltage(self, system::GetVoltageChannel::V1_2)?;
492        let e_vcc = system::get_voltage(self, system::GetVoltageChannel::EVcc)?;
493        system::set_led(self, system::LedState::BothOn)?;
494        let ref_plus = system::get_voltage(self, system::GetVoltageChannel::RefPlus)?;
495        let ref_minus = system::get_voltage(self, system::GetVoltageChannel::RefMinus)?;
496        system::set_led(self, system::LedState::RedOn)?;
497        let buffer_vcc = system::get_voltage(self, system::GetVoltageChannel::BufferVcc)?;
498        let trig_vcc = system::get_voltage(self, system::GetVoltageChannel::TriggerVcc)?;
499        system::set_led(self, system::LedState::BothOn)?;
500        let rst_vcc = system::get_voltage(self, system::GetVoltageChannel::ResetVcc)?;
501        let v3_3 = system::get_voltage(self, system::GetVoltageChannel::V3_3)?;
502        system::set_led(self, system::LedState::RedOn)?;
503        let buffer_v3_3 = system::get_voltage(self, system::GetVoltageChannel::BufferV3_3)?;
504        let v5 = system::get_voltage(self, system::GetVoltageChannel::V5)?;
505        system::set_led(self, system::LedState::GreenOn)?;
506
507        let mut fpga_registers = [0u16; 128];
508        for (i, register) in fpga_registers.iter_mut().enumerate() {
509            *register = fpga::read_fpga_register(self, (i * 2) as u8).unwrap_or(0xFFFF);
510        }
511
512        Ok(DebugInfo {
513            voltages: Voltages {
514                v1_2,
515                e_vcc,
516                ref_plus,
517                ref_minus,
518                buffer_vcc,
519                trig_vcc,
520                rst_vcc,
521                v3_3,
522                buffer_v3_3,
523                v5,
524            },
525            fpga_registers,
526        })
527    }
528
529    /// Debug mode - print voltages and FPGA registers (CLI convenience)
530    #[cfg(feature = "cli")]
531    pub fn debug(&self) -> Result<()> {
532        let info = self.get_debug_info()?;
533
534        println!("Voltages:");
535        println!("  1.2V:        {}mV", info.voltages.v1_2);
536        println!("  E_VCC:       {}mV", info.voltages.e_vcc);
537        println!("  REF+:        {}mV", info.voltages.ref_plus);
538        println!("  REF-:        {}mV", info.voltages.ref_minus);
539        println!("  Buffer VCC:  {}mV", info.voltages.buffer_vcc);
540        println!("  Trig VCC:    {}mV", info.voltages.trig_vcc);
541        println!("  RST VCC:     {}mV", info.voltages.rst_vcc);
542        println!("  3.3V:        {}mV", info.voltages.v3_3);
543        println!("  Buffer 3.3V: {}mV", info.voltages.buffer_v3_3);
544        println!("  5V:          {}mV", info.voltages.v5);
545
546        println!("\nFPGA registers:");
547        for i in 0..128 {
548            if i % 8 == 0 {
549                print!("\n  {:04x}: ", i * 2);
550            }
551            print!("{:04x} ", info.fpga_registers[i]);
552        }
553        println!();
554
555        Ok(())
556    }
557}
558
559/// Device information structure
560#[derive(Debug, Clone)]
561pub struct DeviceInfo {
562    pub mcu_version: String,
563    pub fpga_version: String,
564    pub hw_version: HwVersion,
565    pub serial: String,
566    pub fpga_voltage: u16,
567}
568
569/// Voltage readings
570#[derive(Debug, Clone, Copy)]
571pub struct Voltages {
572    pub v1_2: u32,
573    pub e_vcc: u32,
574    pub ref_plus: u32,
575    pub ref_minus: u32,
576    pub buffer_vcc: u32,
577    pub trig_vcc: u32,
578    pub rst_vcc: u32,
579    pub v3_3: u32,
580    pub buffer_v3_3: u32,
581    pub v5: u32,
582}
583
584/// Debug information structure
585#[derive(Debug, Clone)]
586pub struct DebugInfo {
587    pub voltages: Voltages,
588    pub fpga_registers: [u16; 128],
589}
590
591/// List all connected EM100 devices
592pub fn list_devices() -> Result<Vec<(u8, u8, String)>> {
593    let mut devices = Vec::new();
594
595    for device in nusb::list_devices().wait()? {
596        if device.vendor_id() != VENDOR_ID || device.product_id() != PRODUCT_ID {
597            continue;
598        }
599
600        let bus = device.busnum();
601        let addr = device.device_address();
602
603        // Try to get serial number
604        match Em100::open(Some(bus), Some(addr), None) {
605            Ok(em100) => {
606                devices.push((bus, addr, em100.serial_string()));
607            }
608            Err(_) => {
609                devices.push((bus, addr, "unknown".to_string()));
610            }
611        }
612    }
613
614    Ok(devices)
615}