Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FamicomDumperConnection.cs « FamicomDumperConnection - github.com/ClusterM/famicom-dumper-client.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9a7fbed5539ae75728237b8e7df9c185ed3edba5 (plain)
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
using FTD2XX_NET;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Management;

namespace com.clusterrr.Famicom.DumperConnection
{
    public class FamicomDumperConnection : MarshalByRefObject, IDisposable, IFamicomDumperConnection
    {
        const int PortBaudRate = 250000;
        const ushort DefaultmaxReadPacketSize = 1024;
        const ushort DefaultmaxWritePacketSize = 1024;
        const byte Magic = 0x46;
        const string DeviceName = "Famicom Dumper/Programmer";

        public string PortName { get; set; }
        public bool Verbose { get; set; } = false;
        public int Timeout { get; set; }
        public byte ProtocolVersion { get; private set; } = 0;

        private SerialPort serialPort = null;
        private FTDI d2xxPort = null;
        private Thread readingThread;
        private int commRecvPos;
        private byte commRecvCommand;
        private byte commRecvCrc;
        private bool commRecvError;
        private int commRecvLength;
        private List<byte> recvBuffer = new List<byte>();
        private bool dumperInitOk = false;
        private bool cpuReadDone = false;
        private int cpuWriteDoneCounter = 0;
        private bool ppuReadDone = false;
        private bool ppuWriteDone = false;
        private byte[] prgRecvData, chrRecvData;
        private byte[] mirroring;
        private bool resetAck = false;
        private ushort maxReadPacketSize = DefaultmaxReadPacketSize;
        private ushort maxWritePacketSize = DefaultmaxWritePacketSize;

        enum Command
        {
            COMMAND_PRG_STARTED = 0,
            COMMAND_CHR_STARTED = 1,
            COMMAND_ERROR_INVALID = 2,
            COMMAND_ERROR_CRC = 3,
            COMMAND_ERROR_OVERFLOW = 4,
            COMMAND_PRG_INIT = 5,
            COMMAND_CHR_INIT = 6,
            COMMAND_PRG_READ_REQUEST = 7,
            COMMAND_PRG_READ_RESULT = 8,
            COMMAND_PRG_WRITE_REQUEST = 9,
            COMMAND_PRG_WRITE_DONE = 10,
            COMMAND_CHR_READ_REQUEST = 11,
            COMMAND_CHR_READ_RESULT = 12,
            COMMAND_CHR_WRITE_REQUEST = 13,
            COMMAND_CHR_WRITE_DONE = 14,
            COMMAND_PHI2_INIT = 15,
            COMMAND_PHI2_INIT_DONE = 16,
            COMMAND_MIRRORING_REQUEST = 17,
            COMMAND_MIRRORING_RESULT = 18,
            COMMAND_RESET = 19,
            COMMAND_RESET_ACK = 20,
            COMMAND_PRG_EPROM_WRITE_REQUEST = 21,
            COMMAND_CHR_EPROM_WRITE_REQUEST = 22,
            COMMAND_EPROM_PREPARE = 23,
            COMMAND_PRG_FLASH_ERASE_REQUEST = 24,
            COMMAND_PRG_FLASH_WRITE_REQUEST = 25,
            COMMAND_CHR_FLASH_ERASE_REQUEST = 26,
            COMMAND_CHR_FLASH_WRITE_REQUEST = 27,
            COMMAND_TEST_SET = 32,
            COMMAND_TEST_RESULT = 33,
            COMMAND_COOLBOY_READ_REQUEST = 34,
            COMMAND_COOLBOY_ERASE_REQUEST = 35,
            COMMAND_COOLBOY_WRITE_REQUEST = 36,
            COMMAND_COOLGIRL_ERASE_SECTOR_REQUEST = 37,
            COMMAND_COOLGIRL_WRITE_REQUEST = 38,
            COMMAND_PRG_CRC_READ_REQUEST = 39,
            COMMAND_CHR_CRC_READ_REQUEST = 40,
            COMMAND_BOOTLOADER = 0xFE,
            COMMAND_DEBUG = 0xFF
        }

        public enum MemoryAccessMethod
        {
            CoolboyGPIO,
            Direct
        }

        public FamicomDumperConnection(string portName = null)
        {
            this.PortName = portName;
            Timeout = 10000;
        }

        /// <summary>
        /// Method to obtain list of Linux USB devices
        /// </summary>
        /// <returns>Array of usb devices </returns>
        private static string[] GetLinuxUsbDevices()
        {
            return Directory.GetDirectories("/sys/bus/usb/devices").Where(d => File.Exists(Path.Combine(d, "dev"))).ToArray();
        }

        /// <summary>
        /// Method to get serial port path for specified USB converter
        /// </summary>
        /// <param name="deviceSerial">Serial number of USB to serial converter</param>
        /// <returns>Path of serial port</returns>
        private static string LinuxDeviceToPort(string device)
        {
            var subdirectories = Directory.GetDirectories(device);
            foreach (var subdir in subdirectories)
            {
                var subsubdirectories = Directory.GetDirectories(subdir);
                var ports = subsubdirectories.Where(d => Path.GetFileName(d).StartsWith("tty"));
                if (ports.Any())
                    return $"/dev/{Path.GetFileName(ports.First())}";
            }
            return null;
        }

        /// <summary>
        /// Method to get serial port path for specified USB converter
        /// </summary>
        /// <param name="deviceSerial">Serial number of USB to serial converter</param>
        /// <returns>Path of serial port</returns>
        private static string LinuxDeviceSerialToPort(string deviceSerial)
        {
            var devices = GetLinuxUsbDevices().Where(d =>
            {
                var serialFile = Path.Combine(d, "serial");
                return File.Exists(serialFile) && File.ReadAllText(serialFile).Trim() == deviceSerial;
            });
            if (!devices.Any()) return null;
            var device = devices.First();
            return LinuxDeviceToPort(device);
        }

        public void Open()
        {
            dumperInitOk = false;
            ProtocolVersion = 0;
            maxReadPacketSize = DefaultmaxReadPacketSize;
            maxWritePacketSize = DefaultmaxWritePacketSize;

            string portName = PortName;
            if (string.IsNullOrEmpty(portName) || portName.ToLower() == "auto")
            {
                if (!IsRunningOnMono()) // Is it running on Windows?
                {
                    // Using Windows FTDI driver to determine serial number
                    FTDI myFtdiDevice = new FTDI();
                    uint ftdiDeviceCount = 0;
                    FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
                    // FTDI serial number autodetect
                    ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
                    // Check status
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                        throw new IOException("Failed to get number of devices (error " + ftStatus.ToString() + ")");

                    // If no devices available, return
                    if (ftdiDeviceCount == 0)
                        throw new IOException("Failed to get number of devices (error " + ftStatus.ToString() + ")");

                    // Allocate storage for device info list
                    FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];

                    // Populate our device list
                    ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);

                    portName = null;
                    if (ftStatus == FTDI.FT_STATUS.FT_OK)
                    {
                        var dumpers = ftdiDeviceList.Where(d => d.Description == DeviceName);
                        if (!dumpers.Any())
                            throw new IOException($"{DeviceName} not found");
                        portName = dumpers.First().SerialNumber;
                    }
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                        throw new IOException("Failed to get FTDI devices (error " + ftStatus.ToString() + ")");
                }
                else
                {
                    // Linux?
                    var devices = GetLinuxUsbDevices();
                    var dumpers = devices.Where(d =>
                    {
                        var productFile = Path.Combine(d, "product");
                        return File.Exists(productFile) && File.ReadAllText(productFile).Trim() == DeviceName;
                    });
                    if (!dumpers.Any())
                        throw new IOException($"{DeviceName} not found");
                    portName = LinuxDeviceToPort(dumpers.First());
                }
                Console.WriteLine($"Autodetected USB device serial number: {portName}");
            }

            if (portName.ToUpper().StartsWith("COM") || IsRunningOnMono())
            {
                if (IsRunningOnMono() && !portName.StartsWith("/dev/tty"))
                {
                    // Need to convert serial number to port address
                    var ttyPath = LinuxDeviceSerialToPort(portName);
                    if (string.IsNullOrEmpty(ttyPath))
                        throw new IOException($"Device with serial number {portName} not found");
                    portName = ttyPath;
                    Console.WriteLine($"Autodetected USB device path: {portName}");
                }
                // Port specified 
                SerialPort sPort;
                sPort = new SerialPort();
                sPort.PortName = portName;
                sPort.WriteTimeout = 5000; sPort.ReadTimeout = -1;
                sPort.BaudRate = PortBaudRate;
                sPort.Parity = Parity.None;
                sPort.DataBits = 8;
                sPort.StopBits = StopBits.One;
                sPort.Handshake = Handshake.None;
                sPort.DtrEnable = false;
                sPort.RtsEnable = false;
                sPort.NewLine = Environment.NewLine;
                sPort.Open();
                serialPort = sPort;
            }
            else
            {
                // It's Windows and serial number specified
                // Using Windows FTDI driver
                FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
                // Create new instance of the FTDI device class
                FTDI myFtdiDevice = new FTDI();
                // Open first device in our list by serial number
                ftStatus = myFtdiDevice.OpenBySerialNumber(portName);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    throw new IOException("Failed to open device (error " + ftStatus.ToString() + ")");
                // Set data characteristics - Data bits, Stop bits, Parity
                ftStatus = myFtdiDevice.SetTimeouts(300000, 5000);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    throw new IOException("Failed to set timeouts (error " + ftStatus.ToString() + ")");
                ftStatus = myFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    throw new IOException("Failed to set data characteristics (error " + ftStatus.ToString() + ")");
                // Set flow control
                ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0x11, 0x13);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    throw new IOException("Failed to set flow control (error " + ftStatus.ToString() + ")");
                // Set up device data parameters
                ftStatus = myFtdiDevice.SetBaudRate(PortBaudRate);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    throw new IOException("Failed to set Baud rate (error " + ftStatus.ToString() + ")");
                d2xxPort = myFtdiDevice;
            }

            if (readingThread != null)
                readingThread.Abort();
            readingThread = new Thread(readThread);
            readingThread.Start();
        }

        public void Close()
        {
            if (serialPort != null)
            {
                if (serialPort.IsOpen)
                    serialPort.Close();
                serialPort = null;
            }
            if (d2xxPort != null)
            {
                if (d2xxPort.IsOpen)
                    d2xxPort.Close();
                d2xxPort = null;
            }
            if (readingThread != null)
            {
                readingThread.Abort();
                readingThread = null;
            }
        }

        void readThread()
        {
            try
            {
                while (serialPort != null)
                {
                    try
                    {
                        int c = serialPort.ReadByte();
                        if (c >= 0)
                            RecvProceed((byte)c);
                    }
                    catch (TimeoutException) { }
                }
                while (d2xxPort != null)
                {
                    try
                    {
                        UInt32 numBytesAvailable = 0;
                        FTDI.FT_STATUS ftStatus;
                        do
                        {
                            ftStatus = d2xxPort.GetRxBytesAvailable(ref numBytesAvailable);
                            if (ftStatus != FTDI.FT_STATUS.FT_OK)
                                throw new IOException("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                            Thread.Sleep(10);
                        } while (numBytesAvailable == 0);
                        var data = new byte[numBytesAvailable];
                        UInt32 numBytesRead = 0;
                        ftStatus = d2xxPort.Read(data, numBytesAvailable, ref numBytesRead);
                        if (ftStatus != FTDI.FT_STATUS.FT_OK)
                            throw new IOException("Failed to read data (error " + ftStatus.ToString() + ")");
                        foreach (var b in data)
                            RecvProceed(b);
                    }
                    catch (TimeoutException) { }
                }
            }
            catch (ThreadAbortException) { }
            catch (IOException)
            {
                Close();
                //Console.WriteLine("Port closed: " + ex.Message);
            }
            finally
            {
                readingThread = null;
            }
        }

        void CalcRecvCRC(byte inbyte)
        {
            int j;
            for (j = 0; j < 8; j++)
            {
                byte mix = (byte)((commRecvCrc ^ inbyte) & 0x01);
                commRecvCrc >>= 1;
                if (mix != 0)
                    commRecvCrc ^= 0x8C;
                inbyte >>= 1;
            }
        }

        void RecvProceed(byte data)
        {
            if (commRecvError && data != Magic) return;
            commRecvError = false;
            if (commRecvPos == 0)
            {
                commRecvCrc = 0;
                recvBuffer.Clear();
            }

            CalcRecvCRC(data);
            int l = commRecvPos - 4;
            switch (commRecvPos)
            {
                case 0:
                    if (data != Magic)
                    {
                        OnError();
                    }
                    break;
                case 1:
                    commRecvCommand = data;
                    break;
                case 2:
                    commRecvLength = data;
                    break;
                case 3:
                    commRecvLength |= data << 8;
                    break;
                default:
                    if (l < commRecvLength)
                    {
                        recvBuffer.Add(data);
                    }
                    else if (l == commRecvLength)
                    {
                        if (commRecvCrc == 0)
                        {
                            DataReceived((Command)commRecvCommand, recvBuffer.ToArray());
                        }
                        else
                        {
                            commRecvError = true;
                            OnError();
                            //comm_start(COMMAND_ERROR_CRC, 0);
                        }
                        commRecvPos = 0;
                        return;
                    }
                    break;
            }
            commRecvPos++;
        }

        void DataReceived(Command command, byte[] data)
        {
            //Console.WriteLine("Received command: " + command);
            switch (command)
            {
                case Command.COMMAND_PRG_STARTED:
                    dumperInitOk = true;
                    if (data.Length >= 1)
                        ProtocolVersion = data[0];
                    if (data.Length >= 3)
                        maxReadPacketSize = (ushort)(data[1] | (data[2] << 8));
                    if (data.Length >= 5)
                        maxWritePacketSize = (ushort)(data[3] | (data[4] << 8));
                    break;
                case Command.COMMAND_PRG_READ_RESULT:
                    OnCpuReadResult(data);
                    break;
                case Command.COMMAND_PRG_WRITE_DONE:
                    OnCpuWriteDone();
                    break;
                case Command.COMMAND_CHR_READ_RESULT:
                    OnPpuReadResult(data);
                    break;
                case Command.COMMAND_CHR_WRITE_DONE:
                    OnPpuWriteDone();
                    break;
                case Command.COMMAND_MIRRORING_RESULT:
                    OnMirroring(data);
                    break;
                case Command.COMMAND_RESET_ACK:
                    OnResetAck();
                    break;
                case Command.COMMAND_DEBUG:
                    ShowDebugInfo(data);
                    break;
            }
        }

        void ShowDebugInfo(byte[] data)
        {
            foreach (var b in data)
                Console.Write("{0:X2} ", b);
        }

        void SendData(Command command, byte[] data)
        {
            byte[] buffer = new byte[data.Length + 5];
            buffer[0] = Magic;
            buffer[1] = (byte)command;
            buffer[2] = (byte)(data.Length & 0xFF);
            buffer[3] = (byte)((data.Length >> 8) & 0xFF);
            Array.Copy(data, 0, buffer, 4, data.Length);

            byte crc = 0;
            for (var i = 0; i < buffer.Length - 1; i++)
            {
                byte inbyte = buffer[i];
                for (int j = 0; j < 8; j++)
                {
                    byte mix = (byte)((crc ^ inbyte) & 0x01);
                    crc >>= 1;
                    if (mix != 0)
                        crc ^= 0x8C;
                    inbyte >>= 1;
                }
            }
            buffer[buffer.Length - 1] = crc;
            //foreach (var b in buffer) Console.Write(", 0x{0:X2}", b);
            if (serialPort != null)
                serialPort.Write(buffer, 0, buffer.Length);
            if (d2xxPort != null)
            {
                uint numBytesWritten = 0;
                var ftStatus = d2xxPort.Write(buffer, buffer.Length, ref numBytesWritten);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    throw new IOException("Failed to write to device (error " + ftStatus.ToString() + ")");
            }
        }

        public bool DumperInit()
        {
            if (Verbose)
                Console.Write("Dumper initialization... ");

            dumperInitOk = false;
            for (int i = 0; i < 300; i++)
            {
                SendData(Command.COMMAND_PRG_INIT, new byte[0]);
                Thread.Sleep(50);
                if (dumperInitOk)
                {
                    if (Verbose)
                        Console.WriteLine("OK");
                    return true;
                }
            }
            if (Verbose)
                Console.WriteLine("failed");
            return false;
        }

        public byte[] ReadCpu(ushort address, int length)
            => ReadCpu(address, length, MemoryAccessMethod.Direct);

        public byte[] ReadCpu(ushort address, int length, MemoryAccessMethod flashType)
        {
            if (Verbose)
                Console.Write($"Reading 0x{length:X4}B <= 0x{address:X4} @ CPU...");
            var result = new List<byte>();
            while (length > 0)
            {
                result.AddRange(ReadCpuBlock(address, Math.Min(maxReadPacketSize, length), flashType));
                address += maxReadPacketSize;
                length -= maxReadPacketSize;
            }
            if (Verbose && result.Count <= 32)
            {
                foreach (var b in result)
                    Console.Write($" {b:X2}");
            }
            else if (Verbose)
                Console.WriteLine(" OK");
            return result.ToArray();
        }

        private byte[] ReadCpuBlock(ushort address, int length, MemoryAccessMethod flashType = MemoryAccessMethod.Direct)
        {
            var buffer = new byte[4];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            cpuReadDone = false;
            switch (flashType)
            {
                case MemoryAccessMethod.Direct:
                    SendData(Command.COMMAND_PRG_READ_REQUEST, buffer);
                    break;
                case MemoryAccessMethod.CoolboyGPIO:
                    SendData(Command.COMMAND_COOLBOY_READ_REQUEST, buffer);
                    break;
            }
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (cpuReadDone) return prgRecvData;
            }
            throw new IOException("Read timeout");
        }

        public ushort ReadCpuCrc(ushort address, int length)
        {
            if (Verbose)
                Console.Write($"Reading CRC of 0x{length:X4}b of 0x{address:X4} @ CPU...");
            var buffer = new byte[4];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            cpuReadDone = false;
            SendData(Command.COMMAND_PRG_CRC_READ_REQUEST, buffer);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (cpuReadDone)
                {
                    var crc = (ushort)(prgRecvData[0] | (prgRecvData[1] * 0x100));
                    if (Verbose)
                        Console.WriteLine($" {crc:X4}");
                    return crc;
                }
            }
            throw new IOException("Read timeout");
        }

        public void WriteCpu(ushort address, byte data)
            => WriteCpu(address, new byte[] { data });

        public void WriteCpu(ushort address, byte[] data)
        {
            if (Verbose)
            {
                if (data.Length <= 32)
                {
                    Console.Write($"Writing ");
                    foreach (var b in data)
                        Console.Write($"0x{b:X2} ");
                    Console.Write($"=> 0x{address:X4} @ CPU...");
                }
                else
                {
                    Console.Write($"Writing 0x{data.Length:X4}B => 0x{address:X4} @ CPU...");
                }
            }
            int wlength = data.Length;
            int pos = 0;
            while (wlength > 0)
            {
                var wdata = new byte[Math.Min(maxWritePacketSize, wlength)];
                Array.Copy(data, pos, wdata, 0, wdata.Length);
                WriteCpuBlock(address, wdata);
                address += maxWritePacketSize;
                pos += maxWritePacketSize;
                wlength -= maxWritePacketSize;
            }
            if (Verbose)
                Console.WriteLine(" OK");
            return;
        }

        private void WriteCpuBlock(ushort address, byte[] data)
        {
            int length = data.Length;
            var buffer = new byte[4 + length];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            Array.Copy(data, 0, buffer, 4, length);
            cpuWriteDoneCounter = 0;
            SendData(Command.COMMAND_PRG_WRITE_REQUEST, buffer);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (cpuWriteDoneCounter != 0) return;
            }
            throw new IOException("Write timeout");
        }

        public void EraseCpuFlash(MemoryAccessMethod flashType)
        {
            switch (flashType)
            {
                case MemoryAccessMethod.CoolboyGPIO:
                    SendData(Command.COMMAND_COOLBOY_ERASE_REQUEST, new byte[0]);
                    break;
                case MemoryAccessMethod.Direct:
                    SendData(Command.COMMAND_COOLGIRL_ERASE_SECTOR_REQUEST, new byte[0]);
                    break;
            }
            cpuWriteDoneCounter = 0;
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (cpuWriteDoneCounter != 0) return;
            }
            throw new IOException("Write timeout");
        }

        public void WriteCpuFlash(ushort address, byte[] data, MemoryAccessMethod flashType = MemoryAccessMethod.Direct, bool accelerated = false)
        {
            if (Verbose)
            {
                if (data.Length <= 32)
                {
                    Console.Write($"Writing ");
                    foreach (var b in data)
                        Console.Write($"0x{b:X2} ");
                    Console.Write($"=> 0x{address:X4} @ CPU flash ({flashType})...");
                }
                else
                {
                    Console.Write($"Writing 0x{data.Length:X4}B => 0x{address:X4} @ CPU flash ({flashType})...");
                }
            }
            int wlength = data.Length;
            int pos = 0;
            int writeCounter = 0;
            cpuWriteDoneCounter = 0;
            while (wlength > 0)
            {
                var wdata = new byte[Math.Min(maxWritePacketSize, wlength)];
                Array.Copy(data, pos, wdata, 0, wdata.Length);
                if (ContainsNotFF(data))
                {
                    WriteCpuFlashBlock(address, wdata, !accelerated, flashType);
                    writeCounter++;
                    if (accelerated)
                        Thread.Sleep(40);
                }
                address += maxWritePacketSize;
                pos += maxWritePacketSize;
                wlength -= maxWritePacketSize;
                //Console.WriteLine("{0} / {1}", writeCounter, prgWriteDoneCounter);
            }
            if (accelerated)
            {
                for (int t = 0; t < Timeout; t += 5)
                {
                    Thread.Sleep(5);
                    if (cpuWriteDoneCounter >= writeCounter)
                        return;
                }
                throw new IOException("Write timeout");
            }
            if (Verbose)
                Console.WriteLine(" OK");
        }

        private static bool ContainsNotFF(byte[] data)
        {
            foreach (var b in data)
                if (b != 0xFF) return true;
            return false;
        }

        private void WriteCpuFlashBlock(ushort address, byte[] data, bool wait, MemoryAccessMethod flashType)
        {
            int length = data.Length;
            var buffer = new byte[4 + length];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            Array.Copy(data, 0, buffer, 4, length);
            if (wait)
                cpuWriteDoneCounter = 0;
            switch (flashType)
            {
                case MemoryAccessMethod.CoolboyGPIO:
                    SendData(Command.COMMAND_COOLBOY_WRITE_REQUEST, buffer);
                    break;
                case MemoryAccessMethod.Direct:
                    SendData(Command.COMMAND_COOLGIRL_WRITE_REQUEST, buffer);
                    break;
            }
            if (wait)
            {
                for (int t = 0; t < Timeout; t += 5)
                {
                    Thread.Sleep(5);
                    if (cpuWriteDoneCounter != 0) return;
                }
                throw new IOException("Write timeout");
            }
        }

        public byte[] ReadPpu(ushort address, int length)
        {
            if (Verbose)
                Console.Write($"Reading 0x{length:X4}B <= 0x{address:X4} @ PPU...");
            var result = new List<byte>();
            while (length > 0)
            {
                result.AddRange(ReadPpuBlock(address, Math.Min(maxReadPacketSize, length)));
                address += maxReadPacketSize;
                length -= maxReadPacketSize;
            }
            if (Verbose && result.Count <= 32)
            {
                foreach (var b in result)
                    Console.Write($" {b:X2}");
                Console.WriteLine();
            }
            else if (Verbose)
                Console.WriteLine(" OK");
            return result.ToArray();
        }

        public byte[] ReadPpuBlock(ushort address, int length)
        {
            var buffer = new byte[4];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            ppuReadDone = false;
            SendData(Command.COMMAND_CHR_READ_REQUEST, buffer);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (ppuReadDone)
                    return chrRecvData;
            }
            throw new IOException("Read timeout");
        }

        public ushort ReadPpuCrc(ushort address, int length)
        {
            if (Verbose)
                Console.Write($"Reading CRC of 0x{length:X4}b of 0x{address:X4} @ PPU...");
            var buffer = new byte[4];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            ppuReadDone = false;
            SendData(Command.COMMAND_CHR_CRC_READ_REQUEST, buffer);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (ppuReadDone)
                {
                    var crc = (ushort)(chrRecvData[0] | (chrRecvData[1] * 0x100));
                    if (Verbose)
                        Console.WriteLine($" {crc:X4}");
                    return crc;
                }
            }
            throw new IOException("Read timeout");
        }

        public void WritePpu(ushort address, byte data)
            => WritePpu(address, new byte[] { data });

        public void WritePpu(ushort address, byte[] data)
        {
            if (Verbose)
            {
                if (data.Length <= 32)
                {
                    Console.Write($"Writing ");
                    foreach (var b in data)
                        Console.Write($"0x{b:X2} ");
                    Console.Write($"=> 0x{address:X4} @ PPU...");
                }
                else
                {
                    Console.Write($"Writing 0x{data.Length:X4}B => 0x{address:X4} @ PPU...");
                }
            }
            if (data.Length > maxWritePacketSize) // Split packets
            {
                int wlength = data.Length;
                int pos = 0;
                while (wlength > 0)
                {
                    var wdata = new byte[Math.Min(maxWritePacketSize, wlength)];
                    Array.Copy(data, pos, wdata, 0, wdata.Length);
                    WritePpu(address, wdata);
                    address += maxWritePacketSize;
                    pos += maxWritePacketSize;
                    wlength -= maxWritePacketSize;
                }
                if (Verbose)
                    Console.WriteLine(" OK");
                return;
            }

            int length = data.Length;
            var buffer = new byte[4 + length];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            Array.Copy(data, 0, buffer, 4, length);
            ppuWriteDone = false;
            SendData(Command.COMMAND_CHR_WRITE_REQUEST, buffer);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (ppuWriteDone) return;
            }
            throw new IOException("Write timeout");
        }

        public void WritePpuEprom(ushort address, byte[] data)
        {
            if (data.Length > maxWritePacketSize) // Split packets
            {
                int wlength = data.Length;
                int pos = 0;
                while (wlength > 0)
                {
                    var wdata = new byte[Math.Min(maxWritePacketSize, wlength)];
                    Array.Copy(data, pos, wdata, 0, wdata.Length);
                    WritePpuEprom(address, wdata);
                    address += maxWritePacketSize;
                    pos += maxWritePacketSize;
                    wlength -= maxWritePacketSize;
                }
                return;
            }

            int length = data.Length;
            var buffer = new byte[4 + length];
            buffer[0] = (byte)(address & 0xFF);
            buffer[1] = (byte)((address >> 8) & 0xFF);
            buffer[2] = (byte)(length & 0xFF);
            buffer[3] = (byte)((length >> 8) & 0xFF);
            Array.Copy(data, 0, buffer, 4, length);
            ppuWriteDone = false;
            SendData(Command.COMMAND_CHR_EPROM_WRITE_REQUEST, buffer);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (ppuWriteDone) return;
            }
            throw new IOException("Write timeout");
        }

        public bool[] GetMirroring()
        {
            if (Verbose)
                Console.Write("Reading mirroring... ");
            mirroring = null;
            SendData(Command.COMMAND_MIRRORING_REQUEST, new byte[0]);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (mirroring != null)
                {
                    if (Verbose)
                    {
                        foreach (var b in mirroring)
                            Console.Write($"{b} ");
                        Console.WriteLine();
                    }
                    return mirroring.Select(v => v != 0).ToArray();
                }
            }
            throw new IOException("Read timeout");
        }

        /// <summary>
        /// Simulate reset (M2 goes to Z-state for a second)
        /// </summary>
        public void Reset()
        {
            resetAck = false;
            SendData(Command.COMMAND_RESET, new byte[0]);
            for (int t = 0; t < Timeout; t += 5)
            {
                Thread.Sleep(5);
                if (resetAck) return;
            }
            throw new IOException("Read timeout");
        }

        public void Bootloader()
        {
            SendData(Command.COMMAND_BOOTLOADER, new byte[0]);
        }

        private void OnCpuReadResult(byte[] data)
        {
            prgRecvData = data;
            cpuReadDone = true;
        }

        private void OnCpuWriteDone()
        {
            cpuWriteDoneCounter++;
        }

        private void OnPpuReadResult(byte[] data)
        {
            chrRecvData = data;
            ppuReadDone = true;
        }

        private void OnPpuWriteDone()
        {
            ppuWriteDone = true;
        }

        private void OnMirroring(byte[] mirroring)
        {
            this.mirroring = mirroring;
        }

        private void OnResetAck()
        {
            resetAck = true;
        }

        private void OnError()
        {
        }

        private static bool IsRunningOnMono()
        {
            return Type.GetType("Mono.Runtime") != null;
        }

        public override object InitializeLifetimeService()
        {
            return null; // Infinity
        }

        public void Dispose()
        {
            Close();
        }
    }
}