text
stringlengths
41
20k
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** stage1.cpp -- This is the implementation file for the stage1 module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "stage1.h" //Definition of addsub method void stage1::addsub() { double a; double b; a = in1.read(); b = in2.read(); sum.write(a+b); diff.write(a-b); } // end of addsub method
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** stage1.cpp -- This is the implementation file for the stage1 module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "stage1.h" //Definition of addsub method void stage1::addsub() { double a; double b; a = in1.read(); b = in2.read(); sum.write(a+b); diff.write(a-b); } // end of addsub method
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** stage1.cpp -- This is the implementation file for the stage1 module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "stage1.h" //Definition of addsub method void stage1::addsub() { double a; double b; a = in1.read(); b = in2.read(); sum.write(a+b); diff.write(a-b); } // end of addsub method
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #include "systemc.h" #include "tlm.h" using namespace sc_core; using namespace tlm; //----------------------------------------------------------------------------- // Title: UVMC Connection Example - Hierarchical Connection, SC side // // This example illustrates how to make hierarchical UVMC connections, i.e. how // to promote a ~port~, ~export~, ~imp~, or ~socket~ from a child component to // a parent that resides in the other language. In effect, we are using a // component written in SV as the implementation for a component in SC. // See <UVMC Connection Example - Hierarchical Connection, SV side> to see // the SC portion of the example. // // (see UVMC_Connections_SCwrapsSV.png) // // By hiding the SV implementation, we create what appears to be a pure SC-based // testbench, just like the <UVMC Connection Example - Native SC to SC>. // However, the SC producer is implemented in SV and uses UVMC to make a // behind-the-scenes connection. // // This example illustates good programming principles by exposing only standard // TLM interfaces to the user. The implementation of those interfaces is hidden // and therefore can change (or be implemented in another language) without // affecting end user code. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Class: producer // // Our ~producer~ module is merely a wrapper around an SV-side implementation, // but users of this producer will not be aware of that. The producer does not // actually instantiate a SV component. It simply promotes the socket in the // SV producer to a corresponding socket in the SC producer. From the outside, // the SC producer appears as an ordinary SC component with a TLM2 socket as // its public interface. //----------------------------------------------------------------------------- //(begin inline source) #include "uvmc.h" using namespace uvmc; #include "packet.h" class producer: public sc_module { public: sc_port<tlm_blocking_put_if<packet> > out; SC_CTOR(producer) : out("out") { uvmc_connect_hier(out,"sv_out"); } }; //(end inline source) //----------------------------------------------------------------------------- // Group: sc_main // // The ~sv_main~ top-level module below creates and starts the SV portion of this // example. It instantiates our "pure" SC producer and consumer, binds their // sockets to complete the local connection, then starts SC simulation. // // Notice that the code is identical to that used in the // <UVMC Connection Example - Native SC to SC> example. From the SC user's // perspective, there is no difference between the two testbenches. We've // hidden the UVMC implementation details from the user. //----------------------------------------------------------------------------- //(begin inline source) #include "consumer.h" int sc_main(int argc, char* argv[]) { producer prod("prod"); consumer cons("cons"); prod.out.bind(cons.in); sc_start(-1); return 0; }; //(end inline source)
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_convolution) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_convolution) { SC_METHOD(convolution); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void convolution() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { temporal += data_a_in[m][n].read() * data_b_in[i - m][j - n].read(); } } data_out[i][j] = temporal; } } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_convolution) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_convolution) { SC_METHOD(convolution); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void convolution() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { temporal += data_a_in[m][n].read() * data_b_in[i - m][j - n].read(); } } data_out[i][j] = temporal; } } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_convolution) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_convolution) { SC_METHOD(convolution); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void convolution() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { temporal += data_a_in[m][n].read() * data_b_in[i - m][j - n].read(); } } data_out[i][j] = temporal; } } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_convolution) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_convolution) { SC_METHOD(convolution); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void convolution() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { temporal += data_a_in[m][n].read() * data_b_in[i - m][j - n].read(); } } data_out[i][j] = temporal; } } } };
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** in_class_initialization.cpp : Showcase for in-class initialization macros Original Author: Roman I. Popov, Intel *****************************************************************************/ #include <systemc.h> #ifdef USE_PIMPL_ADDER #include "adder_int_5_pimpl.h" #else #include "adder.h" #endif const int TEST_SIZE = 10; template <typename T, int N_INPUTS> struct adder_tester : sc_module { sc_in<bool> SC_NAMED(clock); sc_in<bool> SC_NAMED(reset); sc_in<T> SC_NAMED(res); sc_vector<sc_out<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(adder_tester){} private: // In-class initialization of SC_CTHREAD, second parameter is clock edge, // third parameter is arbitrary initialization code SC_CTHREAD_IMP(adder_tester_cthread, clock.pos(), { async_reset_signal_is(reset, true); } ) { wait(); for (int ii = 0; ii < TEST_SIZE; ++ii) { T ref_res = 0; for (int jj = 0; jj < N_INPUTS; ++jj) { T input = ii + jj; ref_res += input; din[jj] = input; } wait(); cout << "RES: " << res << " REFERENCE: " << ref_res << "\n"; sc_assert(res == ref_res); } sc_stop(); } }; template <typename T, int N_INPUTS> struct testbench : sc_module { sc_clock SC_NAMED(clock, 10, SC_NS); sc_signal<bool> SC_NAMED(reset); sc_signal<T> SC_NAMED(res); sc_vector<sc_signal<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(testbench) {} private: // SC_NAMED_WITH_INIT allows to specify arbitrary initialization code after member declaration // for example you can bind module ports here adder_tester<T, N_INPUTS> SC_NAMED_WITH_INIT(tester_inst) { tester_inst.clock(clock); tester_inst.reset(reset); tester_inst.res(res); tester_inst.din(din); } #ifdef USE_PIMPL_ADDER adder_int_5_pimpl SC_NAMED_WITH_INIT(adder_inst) #else adder<T, N_INPUTS> SC_NAMED_WITH_INIT(adder_inst) #endif { adder_inst.res(res); adder_inst.din(din); } SC_THREAD_IMP(reset_thread, sensitive << clock.posedge_event();) { reset = 1; wait(); reset = 0; } }; int sc_main(int argc, char **argv) { testbench<int, 5> SC_NAMED(tb_inst); sc_start(); return 0; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (ALU) { sc_in <sc_int<8>> in1; // A sc_in <sc_int<8>> in2; // B sc_in <bool> c; // Carry Out // in this project, this signal is always 1 // ALUOP // has 5 bits by merging: opselect (4bits) and first LSB bit of opcode (1bit) sc_in <sc_uint<5>> aluop; sc_in <sc_uint<3>> sa; // Shift Amount sc_out <sc_int<8>> out; // Output /* ** module global variables */ // SC_CTOR (ALU){ SC_METHOD (process); sensitive << in1 << in2 << aluop; } void process () { sc_int<8> a = in1.read(); sc_int<8> b = in2.read(); bool cin = c.read(); sc_uint<5> op = aluop.read(); sc_uint<3> sh = sa.read(); switch (op){ case 0b00000 : out.write(a); break; case 0b00001 : out.write(++a); break; case 0b00010 : out.write(a+b); break; case 0b00011 : out.write(a+b+cin); break; case 0b00100 : out.write(a-b); break; case 0b00101 : out.write(a-b-cin); break; case 0b00110 : out.write(--a); break; case 0b00111 : out.write(b); break; case 0b01000 : case 0b01001 : out.write(a&b); break; case 0b01010 : case 0b01011 : out.write(a|b); break; case 0b01100 : case 0b01101 : out.write(a^b); break; case 0b01110 : case 0b01111 : out.write(~a); break; case 0b10000 : case 0b10001 : case 0b10010 : case 0b10011 : case 0b10100 : case 0b10101 : case 0b10110 : case 0b10111 : out.write(a>>sh); break; default: out.write(a<<sh); break; } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_multiplier) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_multiplier) { SC_METHOD(multiplier); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void multiplier() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read()); } } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_multiplier) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_multiplier) { SC_METHOD(multiplier); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void multiplier() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read()); } } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_multiplier) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_multiplier) { SC_METHOD(multiplier); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void multiplier() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read()); } } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 SC_MODULE(matrix_multiplier) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(matrix_multiplier) { SC_METHOD(multiplier); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { sensitive << data_a_in[i][j]; sensitive << data_b_in[i][j]; } } } void multiplier() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read()); } } } };
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017 Cadence Design Systems, Inc. All rights reserved worldwide. // // The code contained herein is the proprietary and confidential information // of Cadence or its licensors, and is supplied subject to a previously // executed license and maintenance agreement between Cadence and customer. // This code is intended for use with Cadence high-level synthesis tools and // may not be used with other high-level synthesis tools. Permission is only // granted to distribute the code as indicated. Cadence grants permission for // customer to distribute a copy of this code to any partner to aid in designing // or verifying the customer's intellectual property, as long as such // distribution includes a restriction of no additional distributions from the // partner, unless the partner receives permission directly from Cadence. // // ALL CODE FURNISHED BY CADENCE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, AND CADENCE SPECIFICALLY DISCLAIMS ANY WARRANTY OF NONINFRINGEMENT, // FITNESS FOR A PARTICULAR PURPOSE OR MERCHANTABILITY. CADENCE SHALL NOT BE // LIABLE FOR ANY COSTS OF PROCUREMENT OF SUBSTITUTES, LOSS OF PROFITS, // INTERRUPTION OF BUSINESS, OR FOR ANY OTHER SPECIAL, CONSEQUENTIAL OR // INCIDENTAL DAMAGES, HOWEVER CAUSED, WHETHER FOR BREACH OF WARRANTY, // CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE. // //////////////////////////////////////////////////////////////////////////////// #include <systemc.h> // SystemC definitions #include "system.h" // Top-level System module header file static System * m_system = NULL; // The pointer that holds the top-level System module instance. void esc_elaborate() // This function is required by Stratus to support SystemC-Verilog { // cosimulation. It instances the top-level module. m_system = new System( "system" ); } void esc_cleanup() // This function is called at the end of simulation by the { // Stratus co-simulation hub. It should delete the top-level delete m_system; // module instance. } int sc_main( int argc, char ** argv ) // This function is called by the SystemC kernel for pure SystemC simulations { esc_initialize( argc, argv ); // esc_initialize() passes in the cmd-line args. This initializes the Stratus simulation // environment (such as opening report files for later logging and analysis). esc_elaborate(); // esc_elaborate() (defined above) creates the top-level module instance. In a SystemC-Verilog // co-simulation, this is called during cosim initialization rather than from sc_main. sc_start(); // Starts the simulation. Returns when a module calls esc_stop(), which finishes the simulation. // esc_cleanup() (defined above) is automatically called before sc_start() returns. return 0; // Returns the status of the simulation. Required by most C compilers. }
#include <systemc.h> class sc_mutexx : public sc_prim_channel { public: sc_event _free; bool _locked; // blocks until mutex could be locked void lock() { while( _locked ) { wait( _free ); } _locked = true; } // returns false if mutex could not be locked bool trylock() { if( _locked ) return false; else return true; } // unlocks mutex void unlock() { _locked = false; _free.notify(); } // constructor sc_mutexx(){ // _locked = false; } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" SC_MODULE(scalar_logistic_function) { sc_in_clk clock; sc_in<int> data_in; sc_out<int> data_out; SC_CTOR(scalar_logistic_function) { SC_METHOD(logistic_function); sensitive << clock.pos(); sensitive << data_in; } void logistic_function() { data_out.write(data_in.read()); } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" SC_MODULE(scalar_logistic_function) { sc_in_clk clock; sc_in<int> data_in; sc_out<int> data_out; SC_CTOR(scalar_logistic_function) { SC_METHOD(logistic_function); sensitive << clock.pos(); sensitive << data_in; } void logistic_function() { data_out.write(data_in.read()); } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" SC_MODULE(scalar_logistic_function) { sc_in_clk clock; sc_in<int> data_in; sc_out<int> data_out; SC_CTOR(scalar_logistic_function) { SC_METHOD(logistic_function); sensitive << clock.pos(); sensitive << data_in; } void logistic_function() { data_out.write(data_in.read()); } };
/******************************************************************************* * clkgen.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Emulates the clocks on the ESP32. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "Arduino.h" #include "clkgen.h" void clkgen::gen() { bool lvl = false; while(true) { apb_clk.write(lvl); lvl = !lvl; del1cycle(); } }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" SC_MODULE(scalar_logistic_function) { sc_in_clk clock; sc_in<int> data_in; sc_out<int> data_out; SC_CTOR(scalar_logistic_function) { SC_METHOD(logistic_function); sensitive << clock.pos(); sensitive << data_in; } void logistic_function() { data_out.write(data_in.read()); } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_state_vector_state_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_state_vector_state_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_state_vector_state_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_state_vector_state_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_multiplier_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_multiplier vector_multiplier("VECTOR_MULTIPLIER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_multiplier.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_multiplier.data_a_in[i](data_a_in[i]); vector_multiplier.data_b_in[i](data_b_in[i]); vector_multiplier.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_multiplier_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_multiplier vector_multiplier("VECTOR_MULTIPLIER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_multiplier.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_multiplier.data_a_in[i](data_a_in[i]); vector_multiplier.data_b_in[i](data_b_in[i]); vector_multiplier.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_multiplier_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_multiplier vector_multiplier("VECTOR_MULTIPLIER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_multiplier.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_multiplier.data_a_in[i](data_a_in[i]); vector_multiplier.data_b_in[i](data_b_in[i]); vector_multiplier.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_multiplier_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_multiplier vector_multiplier("VECTOR_MULTIPLIER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_multiplier.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_multiplier.data_a_in[i](data_a_in[i]); vector_multiplier.data_b_in[i](data_b_in[i]); vector_multiplier.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** stimulus.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "stimulus.h" void stimulus::entry() { cycle++; // sending some reset values if (cycle<4) { reset.write(true); input_valid.write(false); } else { reset.write(false); input_valid.write( false ); // sending normal mode values if (cycle%10==0) { input_valid.write(true); sample.write( (int)send_value1 ); cout << "Stimuli : " << (int)send_value1 << " at time " /* << sc_time_stamp() << endl; */ << sc_time_stamp().to_double() << endl; send_value1++; }; } }
#include <systemc.h> #include <string> using namespace sc_core; using namespace std; SC_MODULE(IDE) { // Declare inputs and outputs if needed }; SC_MODULE(PCIx) { // Declare inputs and outputs if needed }; SC_MODULE(ESATA) { public: sc_in<bool> clk; sc_out<std::string> path; void write(const std::string& path) { // Write logic goes here } void read_permissions() { // Read permissions logic goes here } void thread_process() { wait(); write(/* Your path */); read_permissions(); } }; SC_MODULE(ETH) { public: sc_in<bool> clk; sc_in<unsigned char*> ethData; sc_out<std::string> encryptionKey; void thread_process() { wait(); // Replace this line with your actual Ethernet signal transmission logic sendEthernetSignal(ethData, encryptionKey); } }; SC_MODULE(bootmsgs) : sc_module("bootmsgs") { QUIETELSECLASS(bootmsgs, "bootmsgs"); SC_HAS_PROCESS(bootmsgs); bootmsgs(sc_module_name name) : sc_module(name) { IDE ide("ide"); PCIx pci("/PCI@0xC0000471e/PCIe_X2_1.0"); ESATA esata("esata"); ETH eth("eth"); sensitive << clk.pos(); idesign(ide, pci, esata); idesign(pci, esata); idesign(esata, eth); clk.register_close(_clock()); printf("0x%x, %p\n", 0xED4401EU + static_cast<unsigned int>(System::getVersion()), &System::driverManagementApplication); printf("0x%x, %p\n", 0xFF18103U, &System::driverManagementApplication); printf("0x%x, %p\n", 0xA1835CBU, &System::bootManager); printf("0x%x, %p\n", 0xC000014U, &System::IPXE); printf("0x%x, %p\n", 0x2FFF27BU, &System::bootOptions); printf("0x%x, %p\n", 0xC51813AU, &System::sysinfo, postinfo, biosinfo, disks); printf("0x%x, %p\n", 0x10183EDU, "Unix network time error !!"); printf("0x%x, %p\n", 0xFE018E4U, "Unix network time sync failure !!", &System::kernelversion, pkgmanagerversion, jreversion, javaversion, jdkversion, debuggerversion, *all); eth.write("AgoyoaFY6TTAOY887sTSFTakujmhGAKH.ksgLHSlauhsfoFAYKGCgcVJHVulfugCgcJGCHGKcgh/.,,/.><M$?@N$M@#n4/23n$<M$N#2/.,me.,M?><>,mS/aMS:las;amS:?<Y!@Pu#H!:kb3?!@mne !@?#>m"); }; int main(int argc, char **argv) { sc_init(argc, argv); bootmsgs bootMsgs("bootmsgs"); sc_start(100, SC_NS); return sc_finish(); }
// Copyright 2020 Glenn Ramalho - RFIDo Design // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This code was based off the work from Espressif Systems covered by the // License: // // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <systemc.h> #include "esp32-hal.h" #include "clockpacer.h" //Undocumented!!! Get chip temperature in Farenheit //Source: https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_int_temp_sensor/ESP32_int_temp_sensor.ino uint8_t temprature_sens_read(); float temperatureRead() { return (temprature_sens_read() - 32) / 1.8; } /* We need to use the C prototype style so that the weak alias will work. */ extern "C" { void __yield(); } void __yield() { /* We do a wait, as that hands the control back to the SystemC Scheduler, * which is also handling our FreeRTOS scheduler. */ wait(clockpacer.get_cpu_period()); } void yield() __attribute__ ((weak, alias("__yield"))); /* This is something often used inside the model and drivers for the model. */ void del1cycle() { if (clockpacer.is_thread()) clockpacer.wait_next_cpu_clk(); } #if CONFIG_AUTOSTART_ARDUINO /* extern TaskHandle_t loopTaskHandle; extern bool loopTaskWDTEnabled; void enableLoopWDT(){ if(loopTaskHandle != NULL){ if(esp_task_wdt_add(loopTaskHandle) != ESP_OK){ log_e("Failed to add loop task to WDT"); } else { loopTaskWDTEnabled = true; } } } void disableLoopWDT(){ if(loopTaskHandle != NULL && loopTaskWDTEnabled){ loopTaskWDTEnabled = false; if(esp_task_wdt_delete(loopTaskHandle) != ESP_OK){ log_e("Failed to remove loop task from WDT"); } } } void feedLoopWDT(){ esp_err_t err = esp_task_wdt_reset(); if(err != ESP_OK){ log_e("Failed to feed WDT! Error: %d", err); } } */ #endif /* void enableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_add(idle_0) != ESP_OK){ log_e("Failed to add Core 0 IDLE task to WDT"); } } void disableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_delete(idle_0) != ESP_OK){ log_e("Failed to remove Core 0 IDLE task from WDT"); } } #ifndef CONFIG_FREERTOS_UNICORE void enableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_add(idle_1) != ESP_OK){ log_e("Failed to add Core 1 IDLE task to WDT"); } } void disableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_delete(idle_1) != ESP_OK){ log_e("Failed to remove Core 1 IDLE task from WDT"); } } #endif */ /* BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, const BaseType_t xCoreID ){ #ifndef CONFIG_FREERTOS_UNICORE if(xCoreID >= 0 && xCoreID < 2) { return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); } else { #endif return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); #ifndef CONFIG_FREERTOS_UNICORE } #endif } */ /* micros and millis get the current time from the SystemC simulation time * instead of the CPU. */ unsigned long int micros() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000000); } unsigned long int millis() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000); } /* Delay does a SystemC wait. */ void delay(uint32_t del) { wait(del, SC_MS); } /* For the delayMicroseconds we do the same thing. We definitely do not want * the busy-wait loop that the original code uses. It bogs down too much the * simulation. */ void delayMicroseconds(uint32_t del) { wait(del, SC_US); } /* Not sure why these are here, but they do nothing, so they can remain here. */ void initVariant() __attribute__((weak)); void initVariant() {} void init() __attribute__((weak)); void init() {} bool verifyOta() __attribute__((weak)); bool verifyOta() { return true; } #ifdef CONFIG_BT_ENABLED //overwritten in esp32-hal-bt.c bool btInUse() __attribute__((weak)); bool btInUse(){ return false; } #endif /* void initArduino() { #ifdef CONFIG_APP_ROLLBACK_ENABLE const esp_partition_t *running = esp_ota_get_running_partition(); esp_ota_img_states_t ota_state; if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) { if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) { if (verifyOta()) { esp_ota_mark_app_valid_cancel_rollback(); } else { log_e("OTA verification failed! Start rollback to the previous version ..."); esp_ota_mark_app_invalid_rollback_and_reboot(); } } } #endif //init proper ref tick value for PLL (uncomment if REF_TICK is different than 1MHz) //ESP_REG(APB_CTRL_PLL_TICK_CONF_REG) = APB_CLK_FREQ / REF_CLK_FREQ - 1; #ifdef F_CPU setCpuFrequencyMhz(F_CPU/1000000); #endif #if CONFIG_SPIRAM_SUPPORT psramInit(); #endif esp_log_level_set("*", CONFIG_LOG_DEFAULT_LEVEL); esp_err_t err = nvs_flash_init(); if(err == ESP_ERR_NVS_NO_FREE_PAGES){ const esp_partition_t* partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL); if (partition != NULL) { err = esp_partition_erase_range(partition, 0, partition->size); if(!err){ err = nvs_flash_init(); } else { log_e("Failed to format the broken NVS partition!"); } } } if(err) { log_e("Failed to initialize NVS! Error: %u", err); } #ifdef CONFIG_BT_ENABLED if(!btInUse()){ esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); } #endif init(); initVariant(); } */ //used by hal log const char *pathToFileName(const char * path) { size_t i = 0; size_t pos = 0; char * p = (char *)path; while(*p){ i++; if(*p == '/' || *p == '\\'){ pos = i; } p++; } return path+pos; }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #include "systemc.h" #include "tlm.h" #include <vector> #include <iomanip> using namespace sc_core; using namespace tlm; using std::vector; //------------------------------------------------------------------------------ // Title: UVMC Converter Example - SC Adapter Class // // This example demonstrates how to define a custom converter for a transaction // class whose members differ in number, type, and size from the corresponding // transaction definition in SV. This situation can arise in cases where the // transaction types are pre-existing in both SC and SV yet have compatible // content. // // (see UVMC_Converters_SC_UserDefinedAdapter.png) // // Because most SC transactions do not implement the pack and unpack member // functions required by the default converter, a template specialization // definition is required. A template specialization can be defined by hand or // via a <UVMC_UTILS> macro, which defines the same converter specialization // plus the operator<< for the default output stream (cout). This allows you // to print your packet contents using cout << my_packet; // // Template specializations are chosen automatically by the C+ compiler, so // you will not need to specify the converter type explicitly when connecting // via <The Connect Function>. // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Group: User Library // // This section defines a transaction class and generic consumer model. We will // define a converter for this packet, then connect an instance of the consumer // with an SV-side producer using a blocking put interface conveying that // transaction. //------------------------------------------------------------------------------ // (begin inline source) namespace user_lib { class packet { public: short addr_hi; short addr_lo; unsigned int payload[4]; char len; bool write; // 1=write, 0=read }; } // (end inline source) //------------------------------------------------------------------------------ // Group: Conversion code // // This section defines a converter specialization for our 'packet' transaction // type. We can not use the default converter because it delegates to ~pack~ and // ~unpack~ methods of the transaction, which our packet class doesn't have. // // So, we define a converter template specialization for our packet type. Your // transaction converters would implement the same template. // // The definition of a SC-side converter specialization is so regular that a // set of convenient macros have been developed to produce a converter class // definition for you. You would invoke one of the macros from the set, // depending on the number of fields in your transaction class and whether it // inherits from a base class. // See <UVMC Converter Example - SC Converter Class, Macro-Generated> for // for an example of using the <UVMC_UTILS> macros. // // // The corresponding transaction in SV declares the following fields, split // across two classes (one inheriting from the other), in the given order. // //| class packet_base extends uvm_sequence_item: //| typedef enum {WRITE, READ, NOOP} cmd_t; //| cmd_t cmd; //| int addr; //| byte data[$]; //| endclass //| //| class packet: //| int extra_int; //| endclass // // If we could define our SC-side transaction to suit this definition, we'd // mirror the types, declaration order, and even the inheritance hierarchy. // In this example, however, we are faced with having to adapt to a // pre-existing transaction type. // // When writing the converters on the SV and SC side, we can choose three // different ways: // // 1: Let the SC converter pack/unpack normally; implement a custom SV // converter to convert according to how the SC side expects to receive // the bits. // // 2: Let the SV converter pack/unpack normally; implement a SC converter // specialization of the default SC converter to convert according to // how the SV side expects to receive the bits. // // 3: Let the SV converter pack/unpack normally; implement a subtype to // the SC converter specialization to convert according to how the SV // side expects to receive the bits. Specify the custom converter type // when calling uvmc_connect. // // A converter specialization, e.g. ~template <> class uvmc_converter<packet>~, // should be reserved for converting the SC transaction as it is defined, // streaming each field in order and without adaptation. It should not // be used to adapt to a custom mapping on the SV side, as in this example. // For this reason, option 3 is the best. // // The ~packet~ transaction in SV will be packed normally: ~cmd~, ~addr~, // ~data~, and ~extra_int~. The SV packetized bits, assuming 3 bytes in // the data array, looks like this: // //| ____________________________________ //| | cmd | addr |d0|d1|d2|extra_int| //| |________|________|__|__|__|_________| //| 0 32 64 72 80 88 // // In SC, we shall adapt as follows // // - map the 32-bit ~cmd~ from SV to a single ~bool~ in SV // // - map the 32-bit ~addr~ from SV to two ~addr_lo~ and ~addr_hi~ 16-bit // values in SC // // - map the ~data~ byte array data from SV to an integer array in SV // // When dealing with built-in types, you should account for the endianess // of your machine's architecture. This example assumes a little-endian // architecture. // //------------------------------------------------------------------------------ // (begin inline source) #include <vector> #include <iomanip> using std::vector; #include "uvmc.h" using namespace uvmc; using namespace user_lib; struct packet_converter : public uvmc_converter<packet> { static void do_pack(const packet &t, uvmc_packer &packer) { int cmd_tmp; if (t.write) cmd_tmp = 0; else cmd_tmp = 1; packer << cmd_tmp << t.addr_lo << t.addr_hi << (int)(t.len) << t.payload; } static void do_unpack(packet &t, uvmc_packer &packer) { int cmd_tmp; vector<unsigned char> data_tmp; packer >> cmd_tmp >> t.addr_lo >> t.addr_hi >> data_tmp; t.len = data_tmp.size(); if (cmd_tmp == 0) t.write = 1; else if (cmd_tmp == 1) t.write = 0; else cout << "packet cmd from SV side has unsupported value " << cmd_tmp << endl; for (int i=0;i<4;i++) t.payload[i]=0; for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { if ((i*4+j)<t.len) { int b; b = data_tmp[i*4+j] << (8*j); t.payload[i] = t.payload[i] | b; } else { break; } } } } }; UVMC_PRINT_4(packet,addr_hi,addr_lo,len,write) // (end inline source) //------------------------------------------------------------------------------ // Group: Testbench code // // This section defines our testbench environment. In the top-level module, we // instantiate the generic consumer model. We also register the consumer's 'in' // export to have a UVMC connection with a lookup string 'stimulus'. The // SV-side will register its producer's 'out' port with the same 'stimulus' // lookup string. UVMC will match these two strings to complete the cross- // language connection, i.e. the SV producer's ~out~ port will be bound to the // SC consumer's ~in~ export. //------------------------------------------------------------------------------ // (begin inline source) #include "systemc.h" #include "tlm.h" using namespace sc_core; using namespace tlm; // a generic target with a TLM1 put export #include "consumer.cpp" class sc_env : public sc_module { public: consumer<packet> cons; sc_env(sc_module_name nm) : cons("cons") { uvmc_connect<packet_converter>(cons.in,"stimulus"); uvmc_connect<packet_converter>(cons.ap,"checker"); } }; // Define sc_main, the vendor-independent means of starting a // SystemC simulation. int sc_main(int argc, char* argv[]) { sc_env env("env"); sc_start(); return 0; } // (end inline source)
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_memory_matrix_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** reset_signal_is.cpp -- This example shows the use of the method sc_module::reset_signal_is() to provide reset semantics for a clocked thread (SC_CTHREAD). Original Author: Andy Goodrich, Forte Design Systems, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" SC_MODULE(CONSUMER) { SC_CTOR(CONSUMER) { SC_CTHREAD(consumer,m_clk.pos()); reset_signal_is(m_reset,false); } void consumer() { cout << sc_time_stamp() << ": reset" << endl; while (1) { m_ready = true; do { wait(); } while ( !m_valid); cout << sc_time_stamp() << ": " << m_value.read() << endl; } } sc_in_clk m_clk; sc_inout<bool> m_ready; sc_in<bool> m_reset; sc_in<bool> m_valid; sc_in<int> m_value; }; SC_MODULE(PRODUCER) { SC_CTOR(PRODUCER) { SC_CTHREAD(producer,m_clk.pos()); reset_signal_is(m_reset,false); } void producer() { m_value = 0; while (1) { m_valid = true; do { wait(); } while (!m_ready); m_value = m_value + 1; } } sc_in_clk m_clk; sc_in<bool> m_ready; sc_in<bool> m_reset; sc_inout<bool> m_valid; sc_inout<int> m_value; }; SC_MODULE(TESTBENCH) { SC_CTOR(TESTBENCH) : m_consumer("consumer"), m_producer("producer") { SC_CTHREAD(testbench,m_clk.pos()); m_consumer.m_clk(m_clk); m_consumer.m_ready(m_ready); m_consumer.m_reset(m_reset); m_consumer.m_valid(m_valid); m_consumer.m_value(m_value); m_producer.m_clk(m_clk); m_producer.m_ready(m_ready); m_producer.m_reset(m_reset); m_producer.m_valid(m_valid); m_producer.m_value(m_value); } void testbench() { for ( int state = 0; state < 100; state++ ) { m_reset = ( state%20 == 12 ) ? false : true; wait(); } sc_stop(); } sc_in_clk m_clk; CONSUMER m_consumer; PRODUCER m_producer; sc_signal<bool> m_ready; sc_signal<bool> m_reset; sc_signal<bool> m_valid; sc_signal<int> m_value; }; int sc_main(int, char*[]) { sc_clock clock; TESTBENCH testbench("testbench"); testbench.m_clk(clock); sc_start(5000, SC_NS); cout << "Done" << endl; return 0; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (Mux3) { sc_in <bool> sel; sc_in <sc_uint<3>> in0; sc_in <sc_uint<3>> in1; sc_out <sc_uint<3>> out; /* ** module global variables */ SC_CTOR (Mux3){ SC_METHOD (process); sensitive << in0 << in1 << sel; } void process () { if(!sel.read()){ out.write(in0.read()); } else{ out.write(in1.read()); } } };
/* * Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and * University of Bologna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Authors: Germain Haugou, GreenWaves Technologies ([email protected]) */ #include <gv/gvsoc.hpp> #include <algorithm> #include <dlfcn.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <vp/json.hpp> #include "main_systemc.hpp" int main(int argc, char *argv[]) { char *config_path = NULL; bool open_proxy = false; for (int i=1; i<argc; i++) { if (strncmp(argv[i], "--config=", 9) == 0) { config_path = &argv[i][9]; } else if (strcmp(argv[i], "--proxy") == 0) { open_proxy = true; } } if (config_path == NULL) { fprintf(stderr, "No configuration specified, please specify through option --config=<config path>.\n"); return -1; } #ifdef VP_USE_SYSTEMC // In case GVSOC was compiled with SystemC, check if we have at least one SystemC component // and if so, forward the launch to the dedicated SystemC launcher if (requires_systemc(config_path)) { return systemc_launcher(config_path); } #endif gv::GvsocConf conf = { .config_path=config_path }; gv::Gvsoc *gvsoc = gv::gvsoc_new(&conf); gvsoc->open(); gvsoc->start(); if (conf.proxy_socket != -1) { printf("Opened proxy on socket %d\n", conf.proxy_socket); } else { gvsoc->run(); } int retval = gvsoc->join(); gvsoc->stop(); gvsoc->close(); return retval; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** fetch.cpp -- Instruction Fetch Unit. Original Author: Martin Wang, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "fetch.h" #include "directive.h" void fetch::entry() { unsigned addr_tmp=0; unsigned datai_tmp=0; unsigned lock_tmp = 0; addr_tmp = 1; // Now booting from default values reset.write(true); ram_cs.write(true); ram_we.write(false); address.write(addr_tmp); wait(memory_latency); // For data to appear do { wait(); } while ( !((bios_valid == true) || (icache_valid == true)) ); if (stall_fetch.read() == true) { datai_tmp = 0; } else { datai_tmp = ramdata.read(); } cout.setf(ios::hex,ios::basefield); cout << "-----------------------" << endl; cout << "IFU :" << " mem=0x" << datai_tmp << endl; cout << "IFU : pc= " << addr_tmp ; cout.setf(ios::dec,ios::basefield); cout << " at CSIM " << sc_time_stamp() << endl; cout << "-----------------------" << endl; instruction_valid.write(true); instruction.write(datai_tmp); program_counter.write(addr_tmp); ram_cs.write(false); wait(); instruction_valid.write(false); addr_tmp++; wait(); while (true) { if (addr_tmp == 5) { reset.write(false); } if (interrupt.read() == true) { ram_cs.write(true); addr_tmp = int_vectno.read(); ram_we.write(false); wait(memory_latency); datai_tmp = ramdata.read(); printf("IF ALERT: **INTERRUPT**\n"); cout.setf(ios::hex,ios::basefield); cout << "------------------------" << endl; cout << "IFU :" << " mem=0x" << datai_tmp << endl; cout << "IFU : pc= " << addr_tmp ; cout.setf(ios::dec,ios::basefield); cout << " at CSIM " << sc_time_stamp() << endl; cout << "------------------------" << endl; instruction_valid.write(true); instruction.write(datai_tmp); ram_cs.write(false); interrupt_ack.write(true); if (next_pc.read() == true) { addr_tmp++; } wait(); instruction_valid.write(false); interrupt_ack.write(false); wait(); } if (branch_valid.read() == true) { printf("IFU ALERT: **BRANCH**\n"); lock_tmp ++; ram_cs.write(true); addr_tmp = branch_address.read(); ram_we.write(false); wait(memory_latency); do { wait(); } while ( !((bios_valid == true) || (icache_valid == true)) ); datai_tmp = ramdata.read(); cout.setf(ios::hex,ios::basefield); cout << "------------------------" << endl; cout << "IFU :" << " mem=0x" << datai_tmp << endl; cout << "IFU : pc= " << addr_tmp ; cout.setf(ios::dec,ios::basefield); cout << " at CSIM " << sc_time_stamp() << endl; cout << "------------------------" << endl; instruction_valid.write(true); instruction.write(datai_tmp); ram_cs.write(false); if (next_pc.read() == true) { addr_tmp++; } wait(); instruction_valid.write(false); wait(); } else { lock_tmp = 0; ram_cs.write(true); address.write(addr_tmp); ram_we.write(false); wait(memory_latency); // For data to appear do { wait(); } while ( !((bios_valid == true) || (icache_valid == true)) ); datai_tmp = ramdata.read(); cout.setf(ios::hex,ios::basefield); cout << "------------------------" << endl; cout << "IFU :" << " mem=0x" << datai_tmp << endl; cout << "IFU : pc= " << addr_tmp ; cout.setf(ios::dec,ios::basefield); cout << " at CSIM " << sc_time_stamp() << endl; cout << "------------------------" << endl; instruction_valid.write(true); instruction.write(datai_tmp); program_counter.write(addr_tmp); branch_clear.write(false); ram_cs.write(false); if (next_pc.read() == true) { addr_tmp++; } wait(); instruction_valid.write(false); wait(); } if (lock_tmp == 1) { branch_clear.write(true); wait(); } /* Unless you wanted to write to your instruction cache. Usually Instruction cache is read only. // Write memory location first chip_select.write(true); write_enable.write(true); address.write(addr); instruction_write.write(datao); printf("fetch: Data Written = %x at address %x\n", datao, addr); wait(memory_latency); // To make all the outputs appear at the interface // some process functionality not shown here during which chip // chip select is deasserted and bus is tristated chip_select.write(false); instruction_write.write(0); wait(); */ } } // end of entry function
#ifndef IPS_FILTER_TLM_CPP #define IPS_FILTER_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "ips_filter_tlm.hpp" #include "common_func.hpp" #include "important_defines.hpp" void ips_filter_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Called do_when_read_transaction with an address %016llX and length %d", address, data_length); this->img_result = *(Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr); *data = (unsigned char) this->img_result; dbgimgtarmodprint(true, "Returning filter result %f", this->img_result); //memcpy(data, Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr, sizeof(IPS_OUT_TYPE_TB)); } void ips_filter_tlm::do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { IPS_OUT_TYPE_TB* result = new IPS_OUT_TYPE_TB; dbgimgtarmodprint(use_prints, "Called do_when_write_transaction with an address %016llX and length %d", address, data_length); //dbgimgtarmodprint(use_prints, "[DEBUG]: data: %0d, address %0d, data_length %0d, size of char %0d", *data, address, data_length, sizeof(char)); for (int i = 0; i < data_length; i++) { this->img_window[address + i] = (IPS_IN_TYPE_TB) *(data + i); } //dbgimgtarmodprint(use_prints, "[DEBUG]: img_window data: %0f", this->img_window[address]); if (address == 8) { dbgimgtarmodprint(true, "Got full window, starting filtering now"); filter(this->img_window, result); } } #endif // IPS_FILTER_TLM_CPP
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ /* * SystemManager.cpp * * Created on: 07 ott 2016 * Author: daniele */ #include <systemc.h> #include <iostream> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string.h> #include "tl.h" #include "pugixml.hpp" #include "SystemManager.h" using namespace std; using namespace pugi; //////////////////////////// // SBM INDEPENDENT //////////////////////////// // Constructor SystemManager::SystemManager() { VPS = generateProcessInstances(); VCH = generateChannelInstances(); VBB = generateBBInstances(); VPL = generatePhysicalLinkInstances(); mappingPS(); mappingCH(); } // Fill process data structure VPS from xml file (application.xml) vector<Process> SystemManager:: generateProcessInstances(){ vector<Process> vps2; int exp_id = 0; int processId; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(APPLICATION); xml_node instancesPS2 = doc.child("instancesPS"); for (pugi::xml_node xn_process = instancesPS2.first_child(); !xn_process.empty(); xn_process = xn_process.next_sibling()){ Process pi; // Process Name pi.setName(xn_process.child_value("name")); // Process id processId = atoi((char*) xn_process.child_value("id")); pi.setId(processId); // Process Priority pi.setPriority(atoi((char*) xn_process.child_value("priority"))); // Process Criticality pi.setCriticality(atoi((char*) xn_process.child_value("criticality"))); // Process eqGate (HW size) xml_node eqGate = xn_process.child("eqGate"); pi.setEqGate((float)eqGate.attribute("value").as_int()); // Process dataType pi.setDataType(atoi((char*) xn_process.child_value("dataType"))); // Process MemSize (SW Size) xml_node memSize = xn_process.child("memSize"); xml_node codeSize = memSize.child("codeSize"); for (pugi::xml_node processorModel = codeSize.child("processorModel"); processorModel; processorModel = processorModel.next_sibling()) { pi.setCodeSize( processorModel.attribute("name").as_string(), processorModel.attribute("value").as_int() ); } xml_node dataSize = memSize.child("dataSize"); for (pugi::xml_node processorModel = dataSize.child("processorModel"); processorModel; processorModel = processorModel.next_sibling()) { pi.setDataSize( processorModel.attribute("name").as_string(), processorModel.attribute("value").as_int() ); } // Process Affinity xml_node affinity = xn_process.child("affinity"); for (pugi::xml_node processorType = affinity.child("processorType"); processorType; processorType = processorType.next_sibling()) { string processorType_name = processorType.attribute("name").as_string(); float affinity_value = processorType.attribute("value").as_float(); pi.setAffinity(processorType_name, affinity_value); } // Process Concurrency xml_node concurrency = xn_process.child("concurrency"); for (pugi::xml_node xn_cprocessId = concurrency.child("processId"); xn_cprocessId; xn_cprocessId = xn_cprocessId.next_sibling()) { unsigned int process_id_n = xn_cprocessId.attribute("id").as_int(); float process_concurrency_value = xn_cprocessId.attribute("value").as_float(); pi.setConcurrency(process_id_n, process_concurrency_value); } // Process Load xml_node load = xn_process.child("load"); for (pugi::xml_node processorId = load.child("processorId"); processorId; processorId = processorId.next_sibling()) { unsigned int processor_id_n = processorId.attribute("id").as_int(); float process_load_value = processorId.attribute("value").as_float(); pi.setLoad(processor_id_n, process_load_value); } // Process time (init) pi.processTime = sc_time(0, SC_MS); // Process energy (init) pi.setEnergy(0); // Process Communication // TO DO if(processId == exp_id){ vps2.push_back(pi); exp_id++; } else { cout << "XML for application is corrupted\n"; exit(11); } } if(exp_id != NPS){ cout << "XML for application is corrupted (NPS)\n"; exit(11); } doc.reset(); return vps2; } // Fill channel data structure VCH from xml file vector<Channel> SystemManager:: generateChannelInstances() { vector<Channel> vch; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file(APPLICATION); xml_node instancesLL = myDoc.child("instancesLL"); //channel parameters xml_node_iterator seqChannel_it; for (seqChannel_it=instancesLL.begin(); seqChannel_it!=instancesLL.end(); ++seqChannel_it){ xml_node_iterator channel_node_it = seqChannel_it->begin(); Channel ch; char* temp; // CH-NAME string name = channel_node_it->child_value(); ch.setName(name); // CH-ID channel_node_it++; temp = (char*) channel_node_it->child_value(); int id = atoi(temp); ch.setId(id); // writer ID channel_node_it++; temp = (char*) channel_node_it->child_value(); int w_id = atoi(temp); ch.setW_id(w_id); // reader ID channel_node_it++; temp = (char*) channel_node_it->child_value(); int r_id = atoi(temp); ch.setR_id(r_id); // CH-width (logical width) channel_node_it++; temp = (char*) channel_node_it->child_value(); int width = atoi(temp); ch.setWidth(width); ch.setNum(0); vch.push_back(ch); } return vch; } /* * for a given processID, increments the profiling variable * (the number of "loops" executed by the process) */ void SystemManager::PS_Profiling(int processId) { VPS[processId].profiling++; } // Check if a process is allocated on a SPP bool SystemManager::checkSPP(int processId) { return VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType() == "SPP"; } // Return a subset of allocationPS by considering only processes mapped to BB with ID equal to bb_unit_id vector<int> SystemManager::getAllocationPS_BB(int bb_id) { vector<int> pu_alloc; for (unsigned int j = 2; j < allocationPS_BB.size(); j++) // 0 and 1 are the testbench { if (allocationPS_BB[j] == bb_id) pu_alloc.push_back(j); } return pu_alloc; } ///// UPDATE XML Concurrency and Communication void SystemManager::deleteConcXmlConCom() { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML Delete result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); xml_node processes = instancesPS.child("process"); for (int i = 0; i < NPS; i++){ xml_node concom = processes.child("concurrency"); for (pugi::xml_node processorId = concom.child("processId"); processorId; processorId = processorId.next_sibling()) { concom.remove_child(processorId); } xml_node concom2 = processes.child("comunication"); for (pugi::xml_node processorId = concom2.child("rec"); processorId; processorId = processorId.next_sibling()) { concom2.remove_child(processorId); } processes = processes.next_sibling(); } xml_node instancesCH = myDoc.child("instancesLL"); xml_node processesCH = instancesCH.child("logical_link"); for (int i = 0; i < NCH; i++){ xml_node concom3 = processesCH.child("concurrency"); for (pugi::xml_node processorId = concom3.child("channelId"); processorId; processorId = processorId.next_sibling()) { concom3.remove_child(processorId); } processesCH = processesCH.next_sibling(); } myDoc.save_file("./XML/application.xml"); cout << endl; } void SystemManager::updateXmlConCom(float matrixCONC_PS_N[NPS][NPS], unsigned int matrixCOM[NPS][NPS], float matrixCONC_CH_N[NCH][NCH]) { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); for (xml_node_iterator seqProcess_it = instancesPS.begin(); seqProcess_it != instancesPS.end(); ++seqProcess_it){ int Id = atoi(seqProcess_it->child_value("id")); if (seqProcess_it->child("concurrency")){ pugi::xml_node concurrency = seqProcess_it->child("concurrency"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node conc_it = concurrency.append_child("processId"); conc_it.append_attribute("id").set_value(i); conc_it.append_attribute("value").set_value(matrixCONC_PS_N[Id][i]); } } } else{ pugi::xml_node concurrency = seqProcess_it->append_child("concurrency"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node conc_it = concurrency.append_child("processId"); conc_it.append_attribute("id").set_value(i); conc_it.append_attribute("value").set_value(matrixCONC_PS_N[Id][i]); } } } } //method 2: use object/node structure pugi::xml_node instancesCOM = myDoc.child("instancesPS"); for (pugi::xml_node_iterator seqProcess_it = instancesCOM.begin(); seqProcess_it != instancesCOM.end(); ++seqProcess_it){ int Id = atoi(seqProcess_it->child_value("id")); if (seqProcess_it->child("comunication")){ pugi::xml_node comunication = seqProcess_it->child("comunication"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node com_it = comunication.append_child("rec"); com_it.append_attribute("idRec").set_value(i); com_it.append_attribute("value").set_value(matrixCOM[Id][i]); } } } else{ pugi::xml_node comunication = seqProcess_it->append_child("comunication"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node com_it = comunication.append_child("rec"); com_it.append_attribute("idRec").set_value(i); com_it.append_attribute("value").set_value(matrixCOM[Id][i]); } } } } pugi::xml_node instancesLL = myDoc.child("instancesLL"); for (xml_node_iterator seqLink_it = instancesLL.begin(); seqLink_it != instancesLL.end(); ++seqLink_it){ int Id = atoi(seqLink_it->child_value("id")); if (seqLink_it->child("concurrency")){ pugi::xml_node concurrencyL = seqLink_it->child("concurrency"); for (int i = 0; i<NCH; i++){ if (i != Id){ pugi::xml_node concL_it = concurrencyL.append_child("channelId"); concL_it.append_attribute("id").set_value(i); concL_it.append_attribute("value").set_value(matrixCONC_CH_N[Id][i]); } } } else{ pugi::xml_node concurrencyL = seqLink_it->append_child("concurrency"); for (int i = 0; i<NCH; i++){ if (i != Id){ pugi::xml_node concL_it = concurrencyL.append_child("channelId"); concL_it.append_attribute("id").set_value(i); concL_it.append_attribute("value").set_value(matrixCONC_CH_N[Id][i]); } } } } cout << "Saving result: " << myDoc.save_file("./XML/application.xml") << endl; myDoc.reset(); cout << endl; } #if defined(_TIMING_ENERGY_) // Fill VBB data structure from xml file (instancesTL.xml) vector<BasicBlock> SystemManager::generateBBInstances(){ /***************************** * LOAD BASIC BLOCKS *****************************/ char* temp; vector<BasicBlock> vbb; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file("./XML/instancesTL.xml"); xml_node instancesBB = myDoc.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ xml_node_iterator BB_it = seqBB_it->begin(); BasicBlock bb; //BB-ID int id = atoi(BB_it->child_value()); bb.setId(id); //BB-NAME BB_it++; string BBname = BB_it->child_value(); bb.setName(BBname); //BB-TYPE BB_it++; string type = BB_it->child_value(); bb.setType(type); // PROCESSING UNIT BB_it++; vector<ProcessingUnit> vpu; for(xml_node child = seqBB_it->child("processingUnit");child;child= child.next_sibling("processingUnit")){ xml_node_iterator pu_it = child.begin(); ProcessingUnit pu; //PU-NAME string puName = pu_it->child_value(); pu.setName(puName); //PU-ID pu_it++; int idPU = atoi(pu_it->child_value()); pu.setId(idPU); //Processor Type pu_it++; string puType = pu_it->child_value(); pu.setProcessorType(puType); // PU-cost pu_it++; float idCost = (float) atof(pu_it->child_value()); pu.setCost(idCost); //PU-ISA pu_it++; string puISA = pu_it->child_value(); pu.setISA(puISA); // PU-Frequency (MHz) pu_it++; float idFreq = (float) atof(pu_it->child_value()); pu.setFrequency(idFreq); // PU-CC4CS float** array = new float*[5]; //Int8 pu_it++; float idCC4CSminint8 = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxint8 = (float) atof(pu_it->child_value()); //Int16 pu_it++; float idCC4CSminint16 = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxint16 = (float) atof(pu_it->child_value()); //Int32 pu_it++; float idCC4CSminint32 = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxint32 = (float) atof(pu_it->child_value()); //Float pu_it++; float idCC4CSminfloat = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxfloat = (float) atof(pu_it->child_value()); //Tot pu_it++; float idCC4CSmin = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmax = (float) atof(pu_it->child_value()); array[0] = new float[2]; array[0][0] = idCC4CSminint8; array[0][1] = idCC4CSmaxint8; array[1] = new float[2]; array[1][0] = idCC4CSminint16; array[1][1] = idCC4CSmaxint16; array[2] = new float[2]; array[2][0] = idCC4CSminint32; array[2][1] = idCC4CSmaxint32; array[3] = new float[2]; array[3][0] = idCC4CSminfloat; array[3][1] = idCC4CSmaxfloat; array[4] = new float[2]; array[4][0] = idCC4CSmin; array[4][1] = idCC4CSmax; pu.setCC4S(array); // PU-Power (W) pu_it++; float idPow = (float) atof(pu_it->child_value()); pu.setPower(idPow); // PU-MIPS pu_it++; float idMIPS = (float) atof(pu_it->child_value()); pu.setMIPS(idMIPS); // PU-I4CS pu_it++; float idI4CSmin = (float) atof(pu_it->child_value()); pu.setI4CSmin(idI4CSmin); pu_it++; float idI4CSmax = (float) atof(pu_it->child_value()); pu.setI4CSmax(idI4CSmax); // PU-Vdd (V) pu_it++; float idVdd = (float)atof(pu_it->child_value()); pu.setVdd(idVdd); // PU-Idd (A) pu_it++; float idIdd = (float)atof(pu_it->child_value()); pu.setIdd(idIdd); // PU-overheadCS (us) pu_it++; float idOver = (float)atof(pu_it->child_value()); pu.setOverheadCS(sc_time((int)idOver, SC_US)); vpu.push_back(pu); } // LOACL MEMORY bb.setProcessor(vpu); BB_it++; xml_node instancesLM = seqBB_it->child("localMemory"); xml_node_iterator lm_it = instancesLM.begin(); //CODE SIZE int lmCodeSize = (int)atof(lm_it->child_value()); bb.setCodeSize(lmCodeSize); //DATA SIZE lm_it++; int lmDataSize = (int)atof(lm_it->child_value()); bb.setDataSize(lmDataSize); //eQG lm_it++; temp = (char*)lm_it->child_value(); int lmEqG = (int)atof(temp); bb.setEqG(lmEqG); // Comunication BB_it++; xml_node instancesCU = seqBB_it->child("communicationUnit"); xml_node_iterator cu_it = instancesCU.begin(); // TO DO // Free Running time BB_it++; xml_node instancesFRT = seqBB_it->child("loadEstimation"); xml_node_iterator frt_it = instancesFRT.begin(); float lmFreeRunningTime = frt_it->attribute("value").as_float(); bb.setFRT(lmFreeRunningTime); vbb.push_back(bb); } return vbb; } #else /* This method generates a dummy instance of a basic block. Each BB contains more than one processing unit inside. */ vector<BasicBlock> SystemManager::generateBBInstances(){ vector<BasicBlock> vbb; for (int i = 0; i < NBB; i++){ BasicBlock bb; //BB-ID bb.setId(i); //BB-NAME bb.setName("dummy"); //BB-TYPE bb.setType("dummy"); // PROCESSING UNIT vector<ProcessingUnit> vpu; for (int j = 0; j < 4; j++){ // each block contains at most 4 pu ProcessingUnit pu; //PU-NAME pu.setName("dummy"); //PU-ID int idPU = j; pu.setId(idPU); //Processor Type pu.setProcessorType("dummy"); //// PU-cost //pu.setCost(0); //PU-ISA pu.setISA("dummy"); // PU-Frequency (MHz) pu.setFrequency(0); // PU-CC4CS float** array = new float*[5]; //TODO: eliminare **? //Int8 float idCC4CSminint8 = 0; float idCC4CSmaxint8 = 0; //Int16 float idCC4CSminint16 = 0; float idCC4CSmaxint16 = 0; //Int32 float idCC4CSminint32 = 0; float idCC4CSmaxint32 = 0; //Float float idCC4CSminfloat = 0; float idCC4CSmaxfloat = 0; //Tot float idCC4CSmin = 0; float idCC4CSmax = 0; //TODO: ciclo con tutti 0! array[0] = new float[2]; array[0][0] = idCC4CSminint8; array[0][1] = idCC4CSmaxint8; array[1] = new float[2]; array[1][0] = idCC4CSminint16; array[1][1] = idCC4CSmaxint16; array[2] = new float[2]; array[2][0] = idCC4CSminint32; array[2][1] = idCC4CSmaxint32; array[3] = new float[2]; array[3][0] = idCC4CSminfloat; array[3][1] = idCC4CSmaxfloat; array[4] = new float[2]; array[4][0] = idCC4CSmin; array[4][1] = idCC4CSmax; pu.setCC4S(array); // PU-Power (W) pu.setPower(0); // PU-MIPS float idMIPS = 0; pu.setMIPS(idMIPS); // PU-I4CS fl
oat idI4CSmin = 0; pu.setI4CSmin(idI4CSmin); float idI4CSmax = 0; pu.setI4CSmax(idI4CSmax); // PU-Vdd (V) float idVdd = 0; pu.setVdd(idVdd); // PU-Idd (A) float idIdd = 0; pu.setIdd(idIdd); // PU-overheadCS (us) float idOver = 0; pu.setOverheadCS(sc_time((int)idOver, SC_US)); vpu.push_back(pu); } bb.setProcessor(vpu); // LOCAL MEMORY //CODE SIZE bb.setCodeSize(0); //DATA SIZE bb.setDataSize(0); //eQG bb.setEqG(0); // Free Running time float lmFreeRunningTime = 0; bb.setFRT(lmFreeRunningTime); vbb.push_back(bb); } return vbb; } #endif #if defined(_TIMING_ENERGY_) // Fill link data structure VPL from xml file (instancesTL.xml) vector<PhysicalLink> SystemManager:: generatePhysicalLinkInstances() { vector<PhysicalLink> VPL; PhysicalLink l; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file("./XML/instancesTL.xml"); xml_node instancesPL = myDoc.child("instancesPL"); //link parameters xml_node_iterator seqLink_it; for (seqLink_it=instancesPL.begin(); seqLink_it!=instancesPL.end(); ++seqLink_it){ xml_node_iterator link_node_it = seqLink_it->begin(); char* temp; // Link NAME string name = link_node_it->child_value(); l.setName(name); // Link ID link_node_it++; temp = (char*) link_node_it->child_value(); unsigned int id = atoi(temp); l.setId(id); // Link PHYSICAL WIDTH link_node_it++; temp = (char*) link_node_it->child_value(); unsigned int physical_width = atoi(temp); l.setPhysicalWidth(physical_width); // Link TCOMM link_node_it++; temp = (char*) link_node_it->child_value(); float tc = (float) atof(temp); sc_time tcomm(tc, SC_MS); l.setTcomm(tcomm); // Link TACOMM link_node_it++; temp = (char*) link_node_it->child_value(); float tac = (float) atof(temp); sc_time tacomm(tac, SC_MS); l.setTAcomm(tacomm); // Link BANDWIDTH link_node_it++; temp = (char*) link_node_it->child_value(); unsigned int bandwidth = atoi(temp); l.setBandwidth(bandwidth); // Link a2 (coefficient needed to compute energy of the communication) link_node_it++; temp = (char*) link_node_it->child_value(); float a2 = (float) atof(temp); l.seta2(a2); // Link a1 (coefficient needed to compute energy of the communication) link_node_it++; temp = (char*) link_node_it->child_value(); float a1 = (float) atof(temp); l.seta1(a1); VPL.push_back(l); } return VPL; } #else vector<PhysicalLink> SystemManager::generatePhysicalLinkInstances() { vector<PhysicalLink> VPL; for (int i = 0; i < NPL; i++){ PhysicalLink pl; pl.setId(i); pl.setName("dummy"); pl.physical_width=1; // width of the physical link pl.tcomm=sc_time(0, SC_MS); // LP: (bandwidth / phisycal_widht = 1/sec=hz (inverto)) ( per 1000) (non sforare i 5 ms) pl.tacomm=sc_time(0, SC_MS); // LP: tcomm * K (es:K=1) pl.bandwidth=0; // bandwidth in bit/s pl.a2=0; // a2 coefficient of energy curve pl.a1=0; // a1 coefficient of energy curve VPL.push_back(pl); } return VPL; } #endif #if defined(_TIMING_ENERGY_) // Fill allocationPS data structure from xml file void SystemManager:: mappingPS() { int exp_id = 0; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file(MAPPING_PS_BB); xml_node mapping = myDoc.child("mapping"); //mapping parameters (process to processor) xml_node_iterator mapping_it; for (mapping_it=mapping.begin(); mapping_it!=mapping.end(); ++mapping_it){ xml_node_iterator child_mapping_it = mapping_it->begin(); int processId = child_mapping_it->attribute("PSid").as_int(); //string processorName = child_mapping_it->attribute("PRname").as_string(); string bbName = child_mapping_it->attribute("BBname").as_string(); int bbId = child_mapping_it->attribute("value").as_int(); int processingunitID = child_mapping_it->attribute("PUid").as_int(); //added ************** int partitionID = child_mapping_it->attribute("PTid").as_int(); //added ************** if(processId == exp_id){ allocationPS_BB.push_back(bbId); exp_id++; } else { cout << "XML for allocation is corrupted\n"; exit(11); } } } #else void SystemManager::mappingPS(){ for (int j = 0; j<NPS; j++){ int bbId = 0; allocationPS_BB.push_back(bbId); } } #endif #if defined(_TIMING_ENERGY_) // Fill allocationCH_PL data structure from xml file void SystemManager::mappingCH() { int exp_id = 0; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file(MAPPING_LC_PL); xml_node mapping = myDoc.child("mapping"); //mapping parameters (channel to link) xml_node_iterator mapping_it; for (mapping_it=mapping.begin(); mapping_it!=mapping.end(); ++mapping_it){ xml_node_iterator child_mapping_it = mapping_it->begin(); int channelId = child_mapping_it->attribute("CHid").as_int(); string linkName = child_mapping_it->attribute("Lname").as_string(); int linkId = child_mapping_it->attribute("value").as_int(); if(channelId == exp_id){ allocationCH_PL.push_back(linkId); exp_id++; } else { cout << "XML for allocation is corrupted\n"; exit(11); } } } #else void SystemManager::mappingCH(){ for (int j = 0; j < NCH; j++){ int linkId = 0; allocationCH_PL.push_back(linkId); } } #endif ///// OTHER METHODS //////// // Evaluate the simulated time for the execution of a statement /* * for a given processID, returns the simulated time * (the time needed by processor, for the allocated process, to * to execute a statement) */ sc_time SystemManager:: updateSimulatedTime(int processId) { // Id representing process dominant datatype int dataType = VPS[processId].getDataType(); //*********************VPU WAS CHANGED IN VBB********************** float CC4Smin = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement float CC4Smax = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][1]; // Average/max number of clock cycles needed by the PU to execute a C statement // Affinity-based interpolation and round up of CC4CSaff unsigned int CC4Saff = (unsigned int) ceil(CC4Smin + ((CC4Smax-CC4Smin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType())))); float frequency = VBB[allocationPS_BB[processId]].getProcessors()[0].getFrequency(); // Frequency of the processor (MHz) sc_time value((CC4Saff/(frequency*1000)), SC_MS); // Average time (ms) needed to execute a C statement return value; } // The computation depends on the value setted for energyComputation (EPI or EPC) float SystemManager:: updateEstimatedEnergy(int processId) { float J4CS; float P; if(energyComputation == "EPC") { // EPC --> J4CS = CC4CSaff * EPC = CC4CSaff * (P/f) // Id representing process dominant datatype int dataType = VPS[processId].getDataType(); //I HAVE TO ADD A LOOP IN ORDER TO TAKE THE PARAMETERS OF EACH PROCESSOR (?) ********************** float CC4Smin = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement //float CC4Smin = VBB[allocationPS_BB[processId]].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement //float CC4Smax = VBB[allocationPS_BB[processId]].getCC4S()[dataType][1]; float CC4Smax = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][1];// Average/max number of clock cycles needed by the PU to execute a C statement // Affinity-based interpolation float CC4Saff = CC4Smin + ((CC4Smax-CC4Smin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType()))); if(this->checkSPP(processId)) { // if the process is on a SPP (HW) --> P = Vdd * Idd (V*A = W) P = VBB[allocationPS_BB[processId]].getProcessors()[0].getVdd() * VBB[allocationPS_BB[processId]].getProcessors()[0].getIdd(); } else { // if the process is on a GPP/DSP (SW) --> P (W) P = VBB[allocationPS_BB[processId]].getProcessors()[0].getPower(); } // EPC = P/f (W/MHz = uJ) float EPC = P / VBB[allocationPS_BB[processId]].getProcessors()[0].getFrequency(); J4CS = CC4Saff * EPC; // uJ } else { // EPI if(this->checkSPP(processId)) { // if the process is on a SPP (HW) --> J4CS = CC4CSaff * P * (1/f) // Id representing process dominant datatype int dataType = VPS[processId].getDataType(); float CC4Smin = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement float CC4Smax = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][1]; // Average/max number of clock cycles needed by the PU to execute a C statement // Affinity-based interpolation float CC4Saff = CC4Smin + ((CC4Smax-CC4Smin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType()))); // P = Vdd * Idd (V*A = W) P = VBB[allocationPS_BB[processId]].getProcessors()[0].getVdd() * VBB[allocationPS_BB[processId]].getProcessors()[0].getIdd(); J4CS = CC4Saff * (P / VBB[allocationPS_BB[processId]].getProcessors()[0].getFrequency()); // uJ } else { // if the process is on a GPP/DSP (SW) --> J4CS = I4CSaff * EPI = I4CSaff * (P/MIPS) float I4CSmin = VBB[allocationPS_BB[processId]].getProcessors()[0].getI4CSmin(); // Average/min number of assembly instructions to execute a C statement float I4CSmax = VBB[allocationPS_BB[processId]].getProcessors()[0].getI4CSmax(); // Average/max number of assembly instructions to execute a C statement // Affinity-based interpolation float I4CSaff = I4CSmin + ((I4CSmax-I4CSmin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType()))); P = VBB[allocationPS_BB[processId]].getProcessors()[0].getPower(); // Watt // EPI = P/MIPS (uJ/instr) float EPI = P / VBB[allocationPS_BB[processId]].getProcessors()[0].getMIPS(); J4CS = I4CSaff * EPI; // uJ } } return J4CS; } // Increase processTime for each statement void SystemManager:: increaseSimulatedTime(int processId) { VPS[processId].processTime += updateSimulatedTime(processId); // Cumulated sum of the statement execution time } // Increase energy for each statement void SystemManager:: increaseEstimatedEnergy(int processId) { VPS[processId].energy += updateEstimatedEnergy(processId); // Cumulated sum of the statement execution energy } // Increase processTime for the wait of the timers void SystemManager::increaseTimer(int processId, sc_time delta) { VPS[processId].processTime += delta; // Cumulated sum of the statement execution time } // Energy XML Updates void SystemManager::deleteConcXmlEnergy(){ char* temp; int Id; pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML Delete result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); xml_node processes = instancesPS.child("process"); for(int i = 0; i < NPS; i++){ temp = (char*) processes.child_value("id"); Id = atoi(temp); //id process xml_node energy = processes.child("energy"); for (pugi::xml_node processorId = energy.child("processorId"); processorId; processorId = processorId.next_sibling()) { unsigned int processor_id_n = processorId.attribute("id").as_int();// float process_load_value = processorId.attribute("value").as_float();// if(allocationPS_BB[Id] == processor_id_n){ energy.remove_child(processorId); } } processes = processes.next_sibling(); } myDoc.save_file("./XML/application.xml"); cout<<endl; ///////////////////////////////////// pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; pugi::xml_node instancesBB = myDoc2.child("instancesBB"); xml_node basicBlock = instancesBB.child("basicBlock"); for(int i = 0; i < NBB; i++){ temp = (char*) basicBlock.child_value("id"); Id = atoi(temp); //id process xml_node energyEst = basicBlock.child("energyEstimation"); for (pugi::xml_node energyTOT = energyEst.child("energyTOT"); energyTOT; energyTOT = energyTOT.next_sibling()) { unsigned int processor_id_n = energyTOT.attribute("id").as_int();// float energy_value = energyTOT.attribute("value").as_float();// if(Id == allocationPS_BB[2]){ energyEst.remove_child(energyTOT); } } basicBlock = basicBlock.next_sibling(); } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; cout<<endl; } void SystemManager:: updateXmlEnergy() { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); /////////////////////// ENERGY ////////////////////////////// pugi::xml_node instancesPS2 = myDoc.child("instancesPS"); float sumEnergyTot=0; for (xml_node_iterator seqProcess_it2=instancesPS2.begin(); seqProcess_it2!=instancesPS2.end(); ++seqProcess_it2){ int Id = atoi(seqProcess_it2->child_value("id")); if(seqProcess_it2->child("energy")){ pugi::xml_node energy = seqProcess_it2->child("energy"); pugi::xml_node energy_it = energy.append_child("processorId"); energy_it.append_attribute("id").set_value(allocationPS_BB[Id]); energy_it.append_attribute("value").set_value(VPS[Id].getEnergy()); }else{ pugi::xml_node energy = seqProcess_it2->append_child("energy"); pugi::xml_node energy_it = energy.append_child("processorId"); energy_it.append_attribute("id").set_value(allocationPS_BB[Id]); energy_it.append_attribute("value").set_value(VPS[Id].getEnergy()); } sumEnergyTot+=VPS[Id].getEnergy(); } cout << "Saving result: " << myDoc.save_file("./XML/application.xml") << endl; myDoc.reset(); cout<<endl; pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; xml_node instancesBB = myDoc2.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ int Id = atoi(seqBB_it->child_value("id")); ///////////////////// ENERGY //////////////////////// if(Id == allocationPS_BB[2]){ if(seqBB_it->child("energyEstimation")){ pugi::xml_node energyEstimation = seqBB_it->child("energyEstimation"); xml_node entot_node = energyEstimation.append_child("energyTOT"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); entot_node.append_attribute("value").set_value(sumEnergyTot); }else{ pugi::xml_node energyEstimation = seqBB_it->append_child("energyEstimation"); xml_node entot_node = energyEstimation.append_child("energyTOT"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); entot_node.append_attribute("value").set_value(sumEnergyTot); } } } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; } // Load Metrics sc_time SystemManager::getFRT(){ return this->FRT; } void SystemManager::setFRT(sc_time x){ FRT = x; } float* SystemManager:: loadEst(sc_time FRT_n){ for(unsigned i =2; i<VPS.size(); i++){ FRL[i] = (float) ((VPS[i].processTime/VPS[i].profiling)/(FRT_n/VPS[i].profiling)); // } return FRL; } float* SystemManager:: getFRL(){ return this->FRL; } // Load XML Updates void SystemManager::deleteConcXmlLoad(){ char* temp; int Id; pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML Delete result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); xml_node processes = instancesPS.child("process"); for(int i = 0; i < NPS; i++){ temp = (char*) processes.child_value("id"); Id = atoi(temp); //id process xml_node load = processes.child("load"); for (pugi::xml_node processorId = load.child("processorId"); processorId; processorId = processorId.next_sibling()) { unsigned int processor_id_n = processorId.attribute("id").as_int();// float process_load_value = processorId.attribute("value").as_float();// if(allocationPS_BB[Id] == processor_id_n){ load.remove_child(processorId); } } /* xml_node WCET = processes.child("WCET"); for (pugi::xml_node processorId = WCET.child("processorId"); processorId; processorId = processorId.next_sibling()) { WCET.remove_child(processorId); } xml_node Period = processes.child("Period"); for (pugi::xml_node processorId = Period.child("processorId"); processorId; processorId = processorId.next_sibling()) { Period.remove_child(processorId); } xml_node Deadline = processes.child("Deadline"); for (pugi::xml_node processorId = Deadline.child("processorId"); processorId; processorId = processorId.next_sibling()) { Deadline.remove_child(processorId); } */ processes = processes.next_sibling(); } myDoc.save_file("./XML/application.xml"); cout<<endl; pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; pugi::xml_node instancesBB = myDoc2.child("instancesBB"); xml_node basicBlock = instancesBB.child("basicBlock"); for(int i = 0; i < NBB; i++){ temp = (char*) basicBlock.child_value("id"); Id = atoi(temp); //id process xml_node loadEst = basicBlock.child("loadEstimation"); for (pugi::xml_node loadTOT = loadEst.child("FreeRunningTime"); loadTOT; loadTOT = loadTOT.next_sibling()) { unsigned int processor_id_n = loadTOT.attribute("id").as_int();// float energy_value = loadTOT.attribute("value").as_float();// if(Id == allocationPS_BB[2]){ loadEst.remove_child(loadTOT); } } basicBlock = basicBlock.next_sibling(); } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; } void SystemManager:: updateXmlLoad() { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); for (xml_node_iterator seqProcess_it=instancesPS.begin(); seqProcess_it!=instancesPS.end(); ++seqProcess_it){ int Id = atoi(seqProcess_it->child_value("id")); ///////////////////// LOAD //////////////////////////// if(seqProcess_it->child("load")){ pugi::xml_node load = seqProcess_it->child("load"); pugi::xml_node load_it = load.append_child("processorId"); load_it.append_attribute("id").set_value(allocationPS_BB[Id]); load_it.append_attribute("value").set_value(FRL[Id]); }else{ pugi::xml_node load = seqProcess_it->append_child("load"); pugi::xml_node load_it = load.append_child("processorId"); load_it.append_attribute("id").set_value(allocationPS_BB[Id]); load_it.append_attribute("value").set_value(FRL[Id]); } } /////////////////////// WCET ////////////////////////////// ////method 2: use
object/node structure //pugi::xml_node instancesPS2 = myDoc.child("instancesPS"); //for (pugi::xml_node_iterator seqProcess_it=instancesPS2.begin(); seqProcess_it!=instancesPS2.end(); ++seqProcess_it){ // int Id = atoi(seqProcess_it->child_value("id")); // // if(seqProcess_it->child("WCET")){ // pugi::xml_node comunication = seqProcess_it->child("WCET"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node wcet_it = comunication.append_child("processorId"); // double wcet_task = (VPS[Id].processTime.to_seconds()); // wcet_it.append_attribute("id").set_value(i); // wcet_it.append_attribute("value").set_value((wcet_task/VPS[Id].profiling)*1000000.0); // } // } // }else{ // pugi::xml_node WCET = seqProcess_it->append_child("WCET"); // for (int i=0; i<VPU.size(); i++){ // if(i!=Id){ // pugi::xml_node wcet_it = WCET.append_child("processorId"); // double wcet_task = (VPS[Id].processTime.to_seconds()); // wcet_it.append_attribute("id").set_value(i); // wcet_it.append_attribute("value").set_value((wcet_task/VPS[Id].profiling)*1000000.0); // } // } // } //} /////////////////////// PERIOD ////////////////////////////// //pugi::xml_node instancesPS3 = myDoc.child("instancesPS"); //for (xml_node_iterator seqLink_it=instancesPS3.begin(); seqLink_it!=instancesPS3.end(); ++seqLink_it){ // int Id = atoi(seqLink_it->child_value("id")); // // if(seqLink_it->child("Period")){ // pugi::xml_node Period = seqLink_it->child("Period"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node period_it = Period.append_child("processorId"); // period_it.append_attribute("id").set_value(i); // double period_value = (FRT.to_seconds()); // period_it.append_attribute("value").set_value((period_value/VPS[Id].profiling)*1000000.0); // } // } // }else{ // pugi::xml_node Period = seqLink_it->append_child("Period"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node period_it = Period.append_child("processorId"); // period_it.append_attribute("id").set_value(i); // double period_value = (FRT.to_seconds()); // period_it.append_attribute("value").set_value((period_value/VPS[Id].profiling)*1000000.0); // } // } // } //} ///////////////////////// DEADLINE ////////////////////////////// // pugi::xml_node instancesPS4 = myDoc.child("instancesPS"); //for (xml_node_iterator seqLink_it=instancesPS4.begin(); seqLink_it!=instancesPS4.end(); ++seqLink_it){ // int Id = atoi(seqLink_it->child_value("id")); // if(seqLink_it->child("Deadline")){ // pugi::xml_node Deadline = seqLink_it->child("Deadline"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node dead_it = Deadline.append_child("processorId"); // dead_it.append_attribute("id").set_value(i); // double deadline_value = (FRT.to_seconds()); // double dead_tot = (deadline_value/VPS[Id].profiling)*1000000.0; // cout<<"VPS["<<Id<<"].profiling --> "<<VPS[Id].profiling<<endl; // dead_it.append_attribute("value").set_value(dead_tot); // } // } // }else{ // pugi::xml_node Deadline = seqLink_it->append_child("Deadline"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node dead_it = Deadline.append_child("processorId"); // dead_it.append_attribute("id").set_value(i); // double deadline_value = (FRT.to_seconds()); // double dead_tot = (deadline_value/VPS[Id].profiling)*1000000.0; // dead_it.append_attribute("value").set_value(dead_tot); // } // } // } //} cout << "Saving result: " << myDoc.save_file("./XML/application.xml") << endl; myDoc.reset(); cout<<endl; /* pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; xml_node instancesBB = myDoc2.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ int Id = atoi(seqBB_it->child_value("id")); ///////////////////// LOAD //////////////////////////// if(seqBB_it->child("loadEstimation")){ pugi::xml_node loadEstimation = seqBB_it->child("loadEstimation"); xml_node frl_node = loadEstimation.child("FreeRunningTime"); if(!(allocationPS_BB[Id] != Id)) { sc_time local_frt = FRT; //frl_node.attribute("value")=(local_frt.to_double()*1000); //another solution for the number conversion frl_node.attribute("value")=(local_frt.to_seconds()*1000); } }else{ pugi::xml_node loadEstimation = seqBB_it->append_child("loadEstimation"); xml_node frl_node = loadEstimation.append_child("FreeRunningTime"); if(allocationPS_BB[Id] == Id) { sc_time local_frt = FRT; //frl_node.attribute("value")=(local_frt.to_double()*1000); //another solution for the number conversion frl_node.attribute("value")=(local_frt.to_seconds()*1000); } } } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; */ /////////////////////////////////////////////////// pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; xml_node instancesBB = myDoc2.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ int Id = atoi(seqBB_it->child_value("id")); ///////////////////// ENERGY //////////////////////// if(Id == allocationPS_BB[2]){ if(seqBB_it->child("loadEstimation")){ pugi::xml_node energyEstimation = seqBB_it->child("loadEstimation"); xml_node entot_node = energyEstimation.append_child("FreeRunningTime"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); sc_time local_frt = FRT; entot_node.append_attribute("value").set_value(local_frt.to_seconds()*1000); }else{ pugi::xml_node energyEstimation = seqBB_it->append_child("energyEstimation"); xml_node entot_node = energyEstimation.append_child("energyTOT"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); sc_time local_frt = FRT; entot_node.append_attribute("value").set_value(local_frt.to_seconds()*1000); } } } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_summation_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
#include <systemc.h> #include <i2c_controller.h> void i2c_controller::clk_divider() { if(rst) { i2c_clk.write(1); } else { if(counter2 == 1) { bool t = i2c_clk.read(); i2c_clk.write(!t); counter2 = 0; } else { counter2 = counter2 + 1; } } } void i2c_controller::scl_controller() { if(rst) { i2c_scl_enable = 0; } else { if((state == IDLE) | (state == START) | (state == STOP)) { i2c_scl_enable = 0; } else { i2c_scl_enable = 1; } } } void i2c_controller::logic_fsm() { if(rst) { state = IDLE; } else { switch(state) { case IDLE: if(enable == 1) { state = START; saved_addr = (addr,rw); saved_data = data_in; } else { state = IDLE; } break; case START: counter = 7; state = ADDRESS; break; case ADDRESS: if(counter == 0) { state = READ_ACK; } else { counter = counter - 1; } break; case READ_ACK: if(i2c_sda ==(sc_logic) 0) { counter = 7; if(saved_addr[0] == 0) { state = WRITE_DATA; } else { state = READ_DATA; } } else { state = STOP; } break; case WRITE_DATA: if(counter == 0) { state = READ_ACK2; } else { counter = counter - 1; } break; case READ_ACK2: if((i2c_sda == 0) & (enable == 1)) { state = IDLE; } else { state = STOP; } break; case READ_DATA: data_from_slave[counter] = i2c_sda; if(counter == 0) { state = WRITE_ACK; } else { counter = counter - 1; } break; case WRITE_ACK: state = STOP; break; case STOP: state = IDLE; break; } } } void i2c_controller::data_fsm() { if(rst) { write_enable.write(1); i2c_sda.write((sc_logic)1); } else { switch(state) { case IDLE: break; case READ_ACK2: break; case START: write_enable.write(1); i2c_sda.write((sc_logic)0); break; case ADDRESS: { int t = saved_addr[counter]; i2c_sda.write((sc_logic) t); } break; case READ_ACK: i2c_sda.write(sc_logic('Z')); write_enable.write(0); break; case WRITE_DATA: { write_enable.write(1); sc_logic t = saved_data[counter]; i2c_sda.write((sc_logic) t); } break; case WRITE_ACK: i2c_sda.write((sc_logic) 0); write_enable.write(1); break; case READ_DATA: write_enable.write(0); break; case STOP: write_enable.write(1); i2c_sda.write((sc_logic)1); break; } } } void i2c_controller::ready_assign() { if((rst == 0) && (state == IDLE)) { ready.write(1); } else { ready.write(0); } } void i2c_controller::i2c_scl_assign() { if(i2c_scl_enable == 0) { i2c_scl.write((sc_logic)1); } else { i2c_scl.write((sc_logic)i2c_clk); } }
/* * @ASCK */ #include <systemc.h> SC_MODULE (PC) { sc_in <bool> clk; sc_in <sc_uint<14>> prev_addr; sc_out <sc_uint<14>> next_addr; /* ** module global variables */ SC_CTOR (PC){ SC_METHOD (process); sensitive << clk.pos(); } void process () { next_addr.write(prev_addr.read()); } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_state_vector_output_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_controller_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
#include "observer.hpp" #include "objection.hpp" #include "top.hpp" #include "systemc.hpp" #include <iomanip> #include <string> using namespace sc_core; namespace { constexpr char const* const MSGID{ "/Doulos/Example/tracing" }; } Observer_module::Observer_module( sc_module_name instance ) : sc_module( instance ) { SC_HAS_PROCESS( Observer_module ); SC_THREAD( prepare_thread ); SC_THREAD( checker_thread ); actual_export.bind( actual_data ); } void Observer_module::start_of_simulation() { const auto& trace_file { Top_module::trace_file() }; if( trace_file != nullptr ) { auto prefix = std::string(name()) + "."; sc_trace( trace_file, received_value, prefix + "received_value" ); sc_trace( trace_file, expected_value, prefix + "expected_value" ); sc_trace( trace_file, actual_value , prefix + "actual_value" ); sc_trace( trace_file, observed_count, prefix + "observed_count" ); sc_trace( trace_file, failures_count, prefix + "failures_count" ); } } void Observer_module::prepare_thread() { INFO( NONE, "Starting " << __PRETTY_FUNCTION__ ); // Obtain values sent out and convert into expected values for(;;) { wait( expect_port->value_changed_event() ); received_value = expect_port->read(); auto computed_value = ~std::hash<Data_t>{}( received_value ) & ~Data_t(); DEBUG( "Computed " << std::hex << computed_value ); expected_fifo.put( computed_value ); } } void Observer_module::checker_thread() { INFO( NONE, "Starting " << __PRETTY_FUNCTION__ ); for(;;) { expected_value = expected_fifo.get(); // Wait for new expected value { Objection obj{ "Observing" }; // Raise objection on creation wait( actual_data.value_changed_event() ); actual_value = actual_data.read(); ++observed_count; // Do the values match? if( actual_value == expected_value ) { INFO( HIGH, "Good value 0x" << std::hex << actual_value ); } else { REPORT(ERROR, std::hex << "Mismatch got 0x" << actual_value << " != expected 0x" << expected_value ); ++failures_count; } } } } // TAF!
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> ////////////////////////////// GENANN ////////////////// #ifdef __cplusplus extern "C" { #endif #ifndef ann_04_GENANN_RANDOM /* We use the following for uniform random numbers between 0 and 1. * If you have a better function, redefine this macro. */ #define ann_04_GENANN_RANDOM() (((double)rand())/RAND_MAX) #endif struct ann_04_genann; typedef double (*ann_04_genann_actfun)(const struct ann_04_genann *ann, double a); typedef struct ann_04_genann { /* How many inputs, outputs, and hidden neurons. */ int inputs, hidden_layers, hidden, outputs; /* Which activation function to use for hidden neurons. Default: gennann_act_sigmoid_cached*/ ann_04_genann_actfun activation_hidden; /* Which activation function to use for output. Default: gennann_act_sigmoid_cached*/ ann_04_genann_actfun activation_output; /* Total number of weights, and size of weights buffer. */ int total_weights; /* Total number of neurons + inputs and size of output buffer. */ int total_neurons; /* All weights (total_weights long). */ double *weight; /* Stores input array and output of each neuron (total_neurons long). */ double *output; /* Stores delta of each hidden and output neuron (total_neurons - inputs long). */ double *delta; } ann_04_genann; #ifdef __cplusplus } #endif ///////////////////////////////////// GENANN /////////////////////////// #ifndef ann_04_genann_act #define ann_04_genann_act_hidden ann_04_genann_act_hidden_indirect #define ann_04_genann_act_output ann_04_genann_act_output_indirect #else #define ann_04_genann_act_hidden ann_04_genann_act #define ann_04_genann_act_output ann_04_genann_act #endif #define ann_04_LOOKUP_SIZE 4096 double ann_04_genann_act_hidden_indirect(const struct ann_04_genann *ann, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann->activation_hidden(ann, a); } double ann_04_genann_act_output_indirect(const struct ann_04_genann *ann, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann->activation_output(ann, a); } const double ann_04_sigmoid_dom_min = -15.0; const double ann_04_sigmoid_dom_max = 15.0; double ann_04_interval; double ann_04_lookup[ann_04_LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double ann_04_genann_act_sigmoid(const ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if (a < -45.0) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (a > 45.0) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 1; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 1.0 / (1 + exp(-a)); } void ann_04_genann_init_sigmoid_lookup(const ann_04_genann *ann) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const double f = (ann_04_sigmoid_dom_max - ann_04_sigmoid_dom_min) / ann_04_LOOKUP_SIZE; HEPSY_S(ann_04_id) int i; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_interval = ann_04_LOOKUP_SIZE / (ann_04_sigmoid_dom_max - ann_04_sigmoid_dom_min); HEPSY_S(ann_04_id) for (i = 0; i < ann_04_LOOKUP_SIZE; ++i) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_lookup[i] = ann_04_genann_act_sigmoid(ann, ann_04_sigmoid_dom_min + f * i); HEPSY_S(ann_04_id) } } double ann_04_genann_act_sigmoid_cached(const ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) assert(!isnan(a)); HEPSY_S(ann_04_id) if (a < ann_04_sigmoid_dom_min) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann_04_lookup[0]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (a >= ann_04_sigmoid_dom_max) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann_04_lookup[ann_04_LOOKUP_SIZE - 1]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) size_t j = (size_t)((a-ann_04_sigmoid_dom_min)*ann_04_interval+0.5); /* Because floating point... */ HEPSY_S(ann_04_id) if (unlikely(j >= ann_04_LOOKUP_SIZE)) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann_04_lookup[ann_04_LOOKUP_SIZE - 1]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return ann_04_lookup[j]; } double ann_04_genann_act_linear(const struct ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return a; } double ann_04_genann_act_threshold(const struct ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return a > 0; } void ann_04_genann_randomize(ann_04_genann *ann) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) int i; HEPSY_S(ann_04_id) for (i = 0; i < ann->total_weights; ++i) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double r = ann_04_GENANN_RANDOM(); /* Sets weights from -0.5 to 0.5. */ HEPSY_S(ann_04_id) ann->weight[i] = r - 0.5; HEPSY_S(ann_04_id) } } ann_04_genann *ann_04_genann_init(int inputs, int hidden_layers, int hidden, int outputs) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if (hidden_layers < 0) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (inputs < 1) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (outputs < 1) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if (hidden_layers > 0 && hidden < 1) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int total_weights = (hidden_weights + output_weights); HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int size = sizeof(ann_04_genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); HEPSY_S(ann_04_id) ann_04_genann *ret = (ann_04_genann *)malloc(size); HEPSY_S(ann_04_id) if (!ret) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ret->inputs = inputs; HEPSY_S(ann_04_id) ret->hidden_layers = hidden_layers; HEPSY_S(ann_04_id) ret->hidden = hidden; HEPSY_S(ann_04_id) ret->outputs = outputs; HEPSY_S(ann_04_id) ret->total_weights = total_weights; HEPSY_S(ann_04_id) ret->total_neurons = total_neurons; /* Set pointers. */ HEPSY_S(ann_04_id) ret->weight = (double*)((char*)ret + sizeof(ann_04_genann)); HEPSY_S(ann_04_id) ret->output = ret->weight + ret->total_weights; HEPSY_S(ann_04_id) ret->delta = ret->output + ret->total_neurons; HEPSY_S(ann_04_id) ann_04_genann_randomize(ret); HEPSY_S(ann_04_id) ret->activation_hidden = ann_04_genann_act_sigmoid_cached; HEPSY_S(ann_04_id) ret->activation_output = ann_04_genann_act_sigmoid_cached; HEPSY_S(ann_04_id) ann_04_genann_init_sigmoid_lookup(ret); HEPSY_S(ann_04_id) return ret; } void ann_04_genann_free(ann_04_genann *ann) {HEPSY_S(ann_04_id) /* The weight, output, and delta pointers go to the same buffer. */ HEPSY_S(ann_04_id) free(ann); } //genann *genann_read(FILE *in) //genann *genann_copy(genann const *ann) double const *ann_04_genann_run(ann_04_genann const *ann, double const *inputs) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double const *w = ann->weight; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double *o = ann->output + ann->inputs; HEPSY_S(ann_04_id) double const *i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ HEPSY_S(ann_04_id) memcpy(ann->output, inputs, sizeof(double) * ann->inputs); HEPSY_S(ann_04_id) int h, j, k; HEPSY_S(ann_04_id) if (!ann->hidden_layers) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double *ret = o; HEPSY_S(ann_04_id) for (j = 0; j < ann->outputs; ++j) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double sum = *w++ * -1.0; HEPSY_S(ann_04_id) for (k = 0; k < ann->inputs; ++k) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) sum += *w++ * i[k]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) *o++ = ann_04_genann_act_output(ann, sum); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return ret; HEPSY_S(ann_04_id) } /* Figure input layer */ HEPSY_S(ann_04_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double sum = *w++ * -1.0; HEPSY_S(ann_04_id) for (k = 0; k < ann->inputs; ++k) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) sum += *w++ * i[k]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) *o++ = ann_04_genann_act_hidden(ann, sum); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) i += ann->inputs; /* Figure hidden layers, if any. */ HEPSY_S(ann_04_id) for (h = 1; h < ann->hidden_layers; ++h) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double sum = *w++ * -1.0; HEPSY_S(ann_04_id) for (k = 0; k < ann->hidden; ++k) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) sum += *w++ * i[k]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) *o++ = ann_04_genann_act_hidden(ann, sum); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) i += ann->hidden; HEPSY_S(ann_04_id) } double const *ret = o; /* Figure output layer. */ for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = ann_04_genann_act_output(ann, sum); } /* Sanity check that we used all weights and wrote all outputs. */ assert(w - ann->weight == ann->total_weights); assert(o - ann->output == ann->total_neurons); return ret; } //void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) //void genann_write(genann const *ann, FILE *out) /////////////////////// ANN //////////////////////// #define ann_04_NUM_DEV 1 // The equipment is composed of NUM_DEV devices ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_04_MAX_ANN 100 // Maximum MAX_ANN ANN #define ann_04_ANN_INPUTS 2 // Number of inputs #define ann_04_ANN_HIDDEN_LAYERS 1 // Number of hidden layers #define ann_04_ANN_HIDDEN_NEURONS 2 // Number of neurons of every hidden layer #define ann_04_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_04_ANN_EPOCHS 10000 #define ann_04_ANN_DATASET 6 #define ann_04_ANN_LEARNING_RATE 3 // ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_04_MAX_ERROR 0.00756 // 0.009 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_04_nANN = -1 ; // Number of ANN that have been created static ann_04_genann * ann_04_ann[ann_04_MAX_ANN] ; // Now up to MAX_ANN ann //static double ann_04_trainingInput[ann_04_ANN_DATASET][ann_04_ANN_INPUTS] = { {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {0, 0} } ; //static double ann_04_trainingExpected[ann_04_ANN_DATASET][ann_04_ANN_OUTPUTS] = { {0}, {1}, {1}, {0}, {1}, {0} } ; static double ann_04_weights[] = { -3.100438, -7.155774, -7.437955, -8.132828, -5.583678, -5.327152, 5.564897, -12.201226, 11.771879 } ; // static double input[4][3] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // static double output[4] = {0, 1, 1, 0}; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_04_annCheck(int index); static int ann_04_annCreate(int n); //----------------------------------------------------------------------------- // Check the correctness of the index of the ANN //----------------------------------------------------------------------------- int ann_04_annCheck(int index) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if ( (index < 0) || (index >= ann_04_nANN) ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // Create n ANN //----------------------------------------------------------------------------- int ann_04_annCreate(int n) {HEPSY_S(ann_04_id) // If already created, or not legal number, or too many ANN, then error HEPSY_S(ann_04_id) if ( (ann_04_nANN != -1) || (n <= 0) || (n > ann_04_MAX_ANN) ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } // Create the ANN's HEPSY_S(ann_04_id) for ( int i = 0; i < n; i++ ) {HEPSY_S(ann_04_id) // New ANN with ANN_INPUT inputs, ANN_HIDDEN_LAYER hidden layers all with ANN_HIDDEN_NEURON neurons, and ANN_OUTPUT outputs HEPSY_S(ann_04_id) ann_04_ann[i] = ann_04_genann_init(ann_04_ANN_INPUTS, ann_04_ANN_HIDDEN_LAYERS, ann_04_ANN_HIDDEN_NEURONS, ann_04_ANN_OUTPUTS); HEPSY_S(ann_04_id) if( ann_04_ann[i] == 0 ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) for (int j = 0; j < i; j++) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_genann_free(ann_04_ann[j]) ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ann_04_nANN = n ; HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// Create and train n identical ANN ////----------------------------------------------------------------------------- //int annCreateAndTrain(int n) //{ // if ( annCreate(n) != EXIT_SUCCESS ) // return( EXIT_FAILURE ); // // // Train the ANN's // for ( int index = 0; index < nANN; index++ ) // for ( int i = 0; i < ANN_EPOCHS; i++ ) // for ( int j = 0; j < ANN_DATASET; j++ ) // genann_train(ann[index], trainingInput[j], trainingExpected[j], ANN_LEARNING_RATE) ; // // return( EXIT_SUCCESS ); //} //----------------------------------------------------------------------------- // Create n identical ANN and set their weight //----------------------------------------------------------------------------- int ann_04_annCreateAndSetWeights(int n) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if( ann_04_annCreate(n) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } // Set weights HEPSY_S(ann_04_id) for ( int index = 0; index < ann_04_nANN; index++ ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) for ( int i = 0; i < ann_04_ann[index]->total_weights; ++i ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_ann[index]->weight[i] = ann_04_weights[i] ; HEPSY_S(ann_04_id)} HEPSY_S(ann_04_id)} HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // x[2] = x[0] XOR x[1] //----------------------------------------------------------------------------- int ann_04_annRun(int index, double x[ann_04_ANN_INPUTS + ann_04_ANN_OUTPUTS]) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if( ann_04_annCheck(index) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ) ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) x[2] = * ann_04_genann_run(ann_04_ann[index], x) ; HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// ////----------------------------------------------------------------------------- //int annPrintWeights(int index) //{ // if ( annCheck(index) != EXIT_SUCCESS ) // return( EXIT_FAILURE ) ; // // // printf("\n*** ANN index = %d\n", index) ; // for ( int i = 0; i < ann[index]->total_weights; ++i ) // printf("*** w%d = %f\n", i, ann[index]->weight[i]) ; // // return( EXIT_SUCCESS ); //} ////----------------------------------------------------------------------------- //// Run the index-th ANN k time on random input and return the numb
er of error ////----------------------------------------------------------------------------- //int annTest(int index, int k) //{ // int x0; int x1; int y; // double x[2]; // double xor_ex; // int error = 0; // // if ( annCheck(index) != EXIT_SUCCESS ) // return( -1 ); // less than zero errors <==> the ANN isn't correctly created // // for (int i = 0; i < k; i++ ) // { // x0 = rand() % 2; x[0] = (double)x0; // x1 = rand() % 2; x[1] = (double)x1; // y = x0 ^ x1 ; // // xor_ex = * genann_run(ann[index], x); // if ( fabs(xor_ex - (double)y) > MAX_ERROR ) // { // error++ ; // printf("@@@ Error: ANN = %d, step = %d, x0 = %d, x1 = %d, y = %d, xor_ex = %f \n", index, i, x0, x1, y, xor_ex) ; // } // } // // if ( error ) // printf("@@@ ANN = %d: N� of errors = %d\n", index, error) ; // else // printf("*** ANN = %d: Test OK\n",index) ; // return( error ); //} //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void ann_04_annDestroy(void) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if ( ann_04_nANN == -1 ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) for ( int index = 0; index < ann_04_nANN; index++ ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_genann_free(ann_04_ann[index]) ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ann_04_nANN = -1 ; } void mainsystem::ann_04_main() { // datatype for channels cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; ann_xx_dataCollector_payload ann_xx_dataCollector_payload_var; double x[ann_04_ANN_INPUTS + ann_04_ANN_OUTPUTS] ; //int ann_04_index = 1; HEPSY_S(ann_04_id) if( ann_04_annCreateAndSetWeights(ann_04_NUM_DEV) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) // Create and init ANN HEPSY_S(ann_04_id) printf("Error Weights \n"); HEPSY_S(ann_04_id) } //implementation HEPSY_S(ann_04_id) while(1) {HEPSY_S(ann_04_id) // content HEPSY_S(ann_04_id) cleanData_xx_ann_xx_payload_var = cleanData_04_ann_04_channel->read(); HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.dev = cleanData_xx_ann_xx_payload_var.dev; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.step = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.ex_time = cleanData_xx_ann_xx_payload_var.ex_time; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_i = cleanData_xx_ann_xx_payload_var.device_i; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_v = cleanData_xx_ann_xx_payload_var.device_v; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_t = cleanData_xx_ann_xx_payload_var.device_t; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_r = cleanData_xx_ann_xx_payload_var.device_r; HEPSY_S(ann_04_id) x[0] = cleanData_xx_ann_xx_payload_var.x_0; HEPSY_S(ann_04_id) x[1] = cleanData_xx_ann_xx_payload_var.x_1; HEPSY_S(ann_04_id) x[2] = cleanData_xx_ann_xx_payload_var.x_2; //u = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.fault = cleanData_xx_ann_xx_payload_var.fault; //RUN THE ANN... // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ // printf("Step = %u Index = %d ANN error.\n", u, index) ; // }else{ // device[index].fault = x[2] <= 0.5 ? 0 : 1 ; // } //u: cycle num HEPSY_S(ann_04_id) if ( ann_04_annRun(0, x) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) printf("Step = %d Index = %d ANN error.\n", (int)ann_xx_dataCollector_payload_var.step, (int)ann_xx_dataCollector_payload_var.dev) ; HEPSY_S(ann_04_id) } else {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.fault = x[2] <= 0.5 ? 0 : 1 ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ann_04_dataCollector_channel->write(ann_xx_dataCollector_payload_var); HEPSY_P(ann_04_id) } } // END
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_convolution_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_convolution vector_convolution("VECTOR_CONVOLUTION"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_convolution.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_convolution.data_a_in[i](data_a_in[i]); vector_convolution.data_b_in[i](data_b_in[i]); vector_convolution.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> ////////////////////////////// GENANN ////////////////// #ifdef __cplusplus extern "C" { #endif #ifndef ann_01_GENANN_RANDOM /* We use the following for uniform random numbers between 0 and 1. * If you have a better function, redefine this macro. */ #define ann_01_GENANN_RANDOM() (((double)rand())/RAND_MAX) #endif struct ann_01_genann; typedef double (*ann_01_genann_actfun)(const struct ann_01_genann *ann, double a); typedef struct ann_01_genann { /* How many inputs, outputs, and hidden neurons. */ int inputs, hidden_layers, hidden, outputs; /* Which activation function to use for hidden neurons. Default: gennann_act_sigmoid_cached*/ ann_01_genann_actfun activation_hidden; /* Which activation function to use for output. Default: gennann_act_sigmoid_cached*/ ann_01_genann_actfun activation_output; /* Total number of weights, and size of weights buffer. */ int total_weights; /* Total number of neurons + inputs and size of output buffer. */ int total_neurons; /* All weights (total_weights long). */ double *weight; /* Stores input array and output of each neuron (total_neurons long). */ double *output; /* Stores delta of each hidden and output neuron (total_neurons - inputs long). */ double *delta; } ann_01_genann; #ifdef __cplusplus } #endif ///////////////////////////////////// GENANN /////////////////////////// #ifndef ann_01_genann_act #define ann_01_genann_act_hidden ann_01_genann_act_hidden_indirect #define ann_01_genann_act_output ann_01_genann_act_output_indirect #else #define ann_01_genann_act_hidden ann_01_genann_act #define ann_01_genann_act_output ann_01_genann_act #endif #define ann_01_LOOKUP_SIZE 4096 double ann_01_genann_act_hidden_indirect(const struct ann_01_genann *ann, double a) { return ann->activation_hidden(ann, a); } double ann_01_genann_act_output_indirect(const struct ann_01_genann *ann, double a) { return ann->activation_output(ann, a); } const double ann_01_sigmoid_dom_min = -15.0; const double ann_01_sigmoid_dom_max = 15.0; double ann_01_interval; double ann_01_lookup[ann_01_LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double ann_01_genann_act_sigmoid(const ann_01_genann *ann unused, double a) { if (a < -45.0) return 0; if (a > 45.0) return 1; return 1.0 / (1 + exp(-a)); } void ann_01_genann_init_sigmoid_lookup(const ann_01_genann *ann) { const double f = (ann_01_sigmoid_dom_max - ann_01_sigmoid_dom_min) / ann_01_LOOKUP_SIZE; int i; ann_01_interval = ann_01_LOOKUP_SIZE / (ann_01_sigmoid_dom_max - ann_01_sigmoid_dom_min); for (i = 0; i < ann_01_LOOKUP_SIZE; ++i) { ann_01_lookup[i] = ann_01_genann_act_sigmoid(ann, ann_01_sigmoid_dom_min + f * i); } } double ann_01_genann_act_sigmoid_cached(const ann_01_genann *ann unused, double a) { assert(!isnan(a)); if (a < ann_01_sigmoid_dom_min) return ann_01_lookup[0]; if (a >= ann_01_sigmoid_dom_max) return ann_01_lookup[ann_01_LOOKUP_SIZE - 1]; size_t j = (size_t)((a-ann_01_sigmoid_dom_min)*ann_01_interval+0.5); /* Because floating point... */ if (unlikely(j >= ann_01_LOOKUP_SIZE)) return ann_01_lookup[ann_01_LOOKUP_SIZE - 1]; return ann_01_lookup[j]; } double ann_01_genann_act_linear(const struct ann_01_genann *ann unused, double a) { return a; } double ann_01_genann_act_threshold(const struct ann_01_genann *ann unused, double a) { return a > 0; } void ann_01_genann_randomize(ann_01_genann *ann) { int i; for (i = 0; i < ann->total_weights; ++i) { double r = ann_01_GENANN_RANDOM(); /* Sets weights from -0.5 to 0.5. */ ann->weight[i] = r - 0.5; } } ann_01_genann *ann_01_genann_init(int inputs, int hidden_layers, int hidden, int outputs) { if (hidden_layers < 0) return 0; if (inputs < 1) return 0; if (outputs < 1) return 0; if (hidden_layers > 0 && hidden < 1) return 0; const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0; const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs; const int total_weights = (hidden_weights + output_weights); const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ const int size = sizeof(ann_01_genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); ann_01_genann *ret = (ann_01_genann *)malloc(size); if (!ret) return 0; ret->inputs = inputs; ret->hidden_layers = hidden_layers; ret->hidden = hidden; ret->outputs = outputs; ret->total_weights = total_weights; ret->total_neurons = total_neurons; /* Set pointers. */ ret->weight = (double*)((char*)ret + sizeof(ann_01_genann)); ret->output = ret->weight + ret->total_weights; ret->delta = ret->output + ret->total_neurons; ann_01_genann_randomize(ret); ret->activation_hidden = ann_01_genann_act_sigmoid_cached; ret->activation_output = ann_01_genann_act_sigmoid_cached; ann_01_genann_init_sigmoid_lookup(ret); return ret; } void ann_01_genann_free(ann_01_genann *ann) { /* The weight, output, and delta pointers go to the same buffer. */ free(ann); } //genann *genann_read(FILE *in) //genann *genann_copy(genann const *ann) double const *ann_01_genann_run(ann_01_genann const *ann, double const *inputs) { double const *w = ann->weight; double *o = ann->output + ann->inputs; double const *i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ memcpy(ann->output, inputs, sizeof(double) * ann->inputs); int h, j, k; if (!ann->hidden_layers) { double *ret = o; for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->inputs; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_output(ann, sum); } return ret; } /* Figure input layer */ for (j = 0; j < ann->hidden; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->inputs; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_hidden(ann, sum); } i += ann->inputs; /* Figure hidden layers, if any. */ for (h = 1; h < ann->hidden_layers; ++h) { for (j = 0; j < ann->hidden; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_hidden(ann, sum); } i += ann->hidden; } double const *ret = o; /* Figure output layer. */ for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_output(ann, sum); } /* Sanity check that we used all weights and wrote all outputs. */ assert(w - ann->weight == ann->total_weights); assert(o - ann->output == ann->total_neurons); return ret; } //void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) //void genann_write(genann const *ann, FILE *out) /////////////////////// ANN //////////////////////// #define ann_01_NUM_DEV 1 // The equipment is composed of NUM_DEV devices ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_01_MAX_ANN 100 // Maximum MAX_ANN ANN #define ann_01_ANN_INPUTS 2 // Number of inputs #define ann_01_ANN_HIDDEN_LAYERS 1 // Number of hidden layers #define ann_01_ANN_HIDDEN_NEURONS 2 // Number of neurons of every hidden layer #define ann_01_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_01_ANN_EPOCHS 10000 #define ann_01_ANN_DATASET 6 #define ann_01_ANN_LEARNING_RATE 3 // ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_01_MAX_ERROR 0.00756 // 0.009 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_01_nANN = -1 ; // Number of ANN that have been created static ann_01_genann * ann_01_ann[ann_01_MAX_ANN] ; // Now up to MAX_ANN ann //static double ann_01_trainingInput[ann_01_ANN_DATASET][ann_01_ANN_INPUTS] = { {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {0, 0} } ; //static double ann_01_trainingExpected[ann_01_ANN_DATASET][ann_01_ANN_OUTPUTS] = { {0}, {1}, {1}, {0}, {1}, {0} } ; static double ann_01_weights[] = { -3.100438, -7.155774, -7.437955, -8.132828, -5.583678, -5.327152, 5.564897, -12.201226, 11.771879 } ; // static double input[4][3] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // static double output[4] = {0, 1, 1, 0}; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_01_annCheck(int index); static int ann_01_annCreate(int n); //----------------------------------------------------------------------------- // Check the correctness of the index of the ANN //----------------------------------------------------------------------------- int ann_01_annCheck(int index) { if ( (index < 0) || (index >= ann_01_nANN) ) return( EXIT_FAILURE ); return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // Create n ANN //----------------------------------------------------------------------------- int ann_01_annCreate(int n) { // If already created, or not legal number, or too many ANN, then error if ( (ann_01_nANN != -1) || (n <= 0) || (n > ann_01_MAX_ANN) ) return( EXIT_FAILURE ); // Create the ANN's for ( int i = 0; i < n; i++ ) { // New ANN with ANN_INPUT inputs, ANN_HIDDEN_LAYER hidden layers all with ANN_HIDDEN_NEURON neurons, and ANN_OUTPUT outputs ann_01_ann[i] = ann_01_genann_init(ann_01_ANN_INPUTS, ann_01_ANN_HIDDEN_LAYERS, ann_01_ANN_HIDDEN_NEURONS, ann_01_ANN_OUTPUTS); if ( ann_01_ann[i] == 0 ) { for (int j = 0; j < i; j++) ann_01_genann_free(ann_01_ann[j]) ; return( EXIT_FAILURE ); } } ann_01_nANN = n ; return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// Create and train n identical ANN ////----------------------------------------------------------------------------- //int annCreateAndTrain(int n) //{ // if ( annCreate(n) != EXIT_SUCCESS ) // return( EXIT_FAILURE ); // // // Train the ANN's // for ( int index = 0; index < nANN; index++ ) // for ( int i = 0; i < ANN_EPOCHS; i++ ) // for ( int j = 0; j < ANN_DATASET; j++ ) // genann_train(ann[index], trainingInput[j], trainingExpected[j], ANN_LEARNING_RATE) ; // // return( EXIT_SUCCESS ); //} //----------------------------------------------------------------------------- // Create n identical ANN and set their weight //----------------------------------------------------------------------------- int ann_01_annCreateAndSetWeights(int n) { if ( ann_01_annCreate(n) != EXIT_SUCCESS ) return( EXIT_FAILURE ); // Set weights for ( int index = 0; index < ann_01_nANN; index++ ) for ( int i = 0; i < ann_01_ann[index]->total_weights; ++i ) ann_01_ann[index]->weight[i] = ann_01_weights[i] ; return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // x[2] = x[0] XOR x[1] //----------------------------------------------------------------------------- int ann_01_annRun(int index, double x[ann_01_ANN_INPUTS + ann_01_ANN_OUTPUTS]) { if ( ann_01_annCheck(index) != EXIT_SUCCESS ) return( EXIT_FAILURE ) ; x[2] = * ann_01_genann_run(ann_01_ann[index], x) ; return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// ////----------------------------------------------------------------------------- //int annPrintWeights(int index) //{ // if ( annCheck(index) != EXIT_SUCCESS ) // return( EXIT_FAILURE ) ; // // // printf("\n*** ANN index = %d\n", index) ; // for ( int i = 0; i < ann[index]->total_weights; ++i ) // printf("*** w%d = %f\n", i, ann[index]->weight[i]) ; // // return( EXIT_SUCCESS ); //} ////----------------------------------------------------------------------------- //// Run the index-th ANN k time on random input and return the number of error ////----------------------------------------------------------------------------- //int annTest(int index, int k) //{ // int x0; int x1; int y; // double x[2]; // double xor_ex; // int error = 0; // // if ( annCheck(index) != EXIT_SUCCESS ) // return( -1 ); // less than zero errors <==> the ANN isn't correctly created // // for (int i = 0; i < k; i++ ) // { // x0 = rand() % 2; x[0] = (double)x0; // x1 = rand() % 2; x[1] = (double)x1; // y = x0 ^ x1 ; // // xor_ex = * genann_run(ann[index], x); // if ( fabs(xor_ex - (double)y) > MAX_ERROR ) // { // error++ ; // printf("@@@ Error: ANN = %d, step = %d, x0 = %d, x1 = %d, y = %d, xor_ex = %f \n", index, i, x0, x1, y, xor_ex) ; // } // } // // if ( error ) // printf("@@@ ANN = %d: N� of errors = %d\n", index, error) ; // else // printf("*** ANN = %d: Test OK\n",index) ; // return( error ); //} //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void ann_01_annDestroy(void) { if ( ann_01_nANN == -1 ) return ; for ( int index = 0; index < ann_01_nANN; index++ ) ann_01_genann_free(ann_01_ann[index]) ; ann_01_nANN = -1 ; } void mainsystem::ann_01_main() { // datatype for channels cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; ann_xx_dataCollector_payload ann_xx_dataCollector_payload_var; double x[ann_01_ANN_INPUTS + ann_01_ANN_OUTPUTS] ; //int ann_01_index = 1; if ( ann_01_annCreateAndSetWeights(ann_01_NUM_DEV) != EXIT_SUCCESS ){ // Create and init ANN printf("Error Weights \n"); } //implementation HEPSY_S(ann_01_id) while(1) {HEPSY_S(ann_01_id) // content cleanData_xx_ann_xx_payload_var = cleanData_01_ann_01_channel->read(); ann_xx_dataCollector_payload_var.dev = cleanData_xx_ann_xx_payload_var.dev; ann_xx_dataCollector_payload_var.step = cleanData_xx_ann_xx_payload_var.step; ann_xx_dataCollector_payload_var.ex_time = cleanData_xx_ann_xx_payload_var.ex_time; ann_xx_dataCollector_payload_var.device_i = cleanData_xx_ann_xx_payload_var.device_i; ann_xx_dataCollector_payload_var.device_v = cleanData_xx_ann_xx_payload_var.device_v; ann_xx_dataCollector_payload_var.device_t = cleanData_xx_ann_xx_payload_var.device_t; ann_xx_dataCollector_payload_var.device_r = cleanData_xx_ann_xx_payload_var.device_r; x[0] = cleanData_xx_ann_xx_payload_var.x_0; x[1] = cleanData_xx_ann_xx_payload_var.x_1; x[2] = cleanData_xx_ann_xx_payload_var.x_2; //u = cleanData_xx_ann_xx_payload_var.step; ann_xx_dataCollector_payload_var.fault = cleanData_xx_ann_xx_payload_var.fault; //RUN THE ANN... // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ // printf("Step = %u Index = %d ANN error.\n", u, index) ; // }else{ // device[index].fault = x[2] <= 0.5 ? 0 : 1 ; // } //u: cycle num if ( ann_01_annRun(0, x) != EXIT_SUCCESS ){ printf("Step = %d Index = %d ANN error.\n", (int)ann_xx_dataCollector_payload_var.step, (int)ann_xx_dataCollector_payload_var.dev) ; }else{ ann_xx_dataCollector_payload_var.fault = x[2] <= 0.5 ? 0 : 1 ; } ann_01_dataCollector_channel->write(ann_xx_dataCollector_payload_var); HEPSY_P(ann_01_id) } } // END
// ---------------------------------------------------------------------------- // SystemC SCVerify Flow -- sysc_sim_trans.cpp // // HLS version: 10.4b/841621 Production Release // HLS date: Thu Oct 24 17:20:07 PDT 2019 // Flow Packages: HDL_Tcl 8.0a, SCVerify 10.4 // // Generated by: [email protected] // Generated date: Fri Apr 17 23:30:03 EDT 2020 // // ---------------------------------------------------------------------------- // // ------------------------------------- // sysc_sim_wrapper // Represents a new SC_MODULE having the same interface as the original model SysTop_rtl // ------------------------------------- // #ifndef TO_QUOTED_STRING #define TO_QUOTED_STRING(x) TO_QUOTED_STRING1(x) #define TO_QUOTED_STRING1(x) #x #endif // Hold time for the SCVerify testbench to account for the gate delay after downstream synthesis in pico second(s) // Hold time value is obtained from 'top_gate_constraints.cpp', which is generated at the end of RTL synthesis #ifdef CCS_DUT_GATE extern double __scv_hold_time; #else double __scv_hold_time = 0.0; // default for non-gate simulation is zero #endif #ifndef SC_USE_STD_STRING #define SC_USE_STD_STRING #endif #include "../../../../../cmod/lab3/SysTop/SysTop.h" #include <systemc.h> #include <mc_scverify.h> #include <mt19937ar.c> #include "mc_dut_wrapper.h" namespace CCS_RTL { class sysc_sim_wrapper : public sc_module { public: // Interface Ports sc_core::sc_in<bool > clk; sc_core::sc_in<bool > rst; Connections::In<InputSetup::WriteReq, Connections::SYN_PORT > write_req; Connections::In<ac_int<6, false >, Connections::SYN_PORT > start; Connections::In<ac_int<8, true >, Connections::SYN_PORT > weight_in_vec[8]; Connections::Out<ac_int<32, true >, Connections::SYN_PORT > accum_out_vec[8]; // Data objects sc_signal< bool > ccs_rtl_SIG_clk; sc_signal< sc_logic > ccs_rtl_SIG_rst; sc_signal< sc_logic > ccs_rtl_SIG_write_req_val; sc_signal< sc_logic > ccs_rtl_SIG_write_req_rdy; sc_signal< sc_lv<69> > ccs_rtl_SIG_write_req_msg; sc_signal< sc_logic > ccs_rtl_SIG_start_val; sc_signal< sc_logic > ccs_rtl_SIG_start_rdy; sc_signal< sc_lv<6> > ccs_rtl_SIG_start_msg; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_0_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_1_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_2_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_3_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_4_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_5_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_6_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_7_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_0_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_1_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_2_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_3_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_4_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_5_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_6_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_7_rdy; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_0_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_1_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_2_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_3_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_4_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_5_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_6_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_7_msg; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_0_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_1_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_2_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_3_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_4_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_5_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_6_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_7_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_0_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_1_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_2_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_3_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_4_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_5_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_6_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_7_rdy; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_0_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_1_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_2_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_3_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_4_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_5_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_6_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_7_msg; // Named Objects // Module instance pointers HDL::ccs_DUT_wrapper ccs_rtl; // Declare processes (SC_METHOD and SC_THREAD) void update_proc(); // Constructor SC_HAS_PROCESS(sysc_sim_wrapper); sysc_sim_wrapper( const sc_module_name& nm ) : ccs_rtl( "ccs_rtl", TO_QUOTED_STRING(TOP_HDL_ENTITY) ) , clk("clk") , rst("rst") , write_req("write_req") , start("start") , weight_in_vec() , accum_out_vec() , ccs_rtl_SIG_clk("ccs_rtl_SIG_clk") , ccs_rtl_SIG_rst("ccs_rtl_SIG_rst") , ccs_rtl_SIG_write_req_val("ccs_rtl_SIG_write_req_val") , ccs_rtl_SIG_write_req_rdy("ccs_rtl_SIG_write_req_rdy") , ccs_rtl_SIG_write_req_msg("ccs_rtl_SIG_write_req_msg") , ccs_rtl_SIG_start_val("ccs_rtl_SIG_start_val") , ccs_rtl_SIG_start_rdy("ccs_rtl_SIG_start_rdy") , ccs_rtl_SIG_start_msg("ccs_rtl_SIG_start_msg") , ccs_rtl_SIG_weight_in_vec_0_val("ccs_rtl_SIG_weight_in_vec_0_val") , ccs_rtl_SIG_weight_in_vec_1_val("ccs_rtl_SIG_weight_in_vec_1_val") , ccs_rtl_SIG_weight_in_vec_2_val("ccs_rtl_SIG_weight_in_vec_2_val") , ccs_rtl_SIG_weight_in_vec_3_val("ccs_rtl_SIG_weight_in_vec_3_val") , ccs_rtl_SIG_weight_in_vec_4_val("ccs_rtl_SIG_weight_in_vec_4_val") , ccs_rtl_SIG_weight_in_vec_5_val("ccs_rtl_SIG_weight_in_vec_5_val") , ccs_rtl_SIG_weight_in_vec_6_val("ccs_rtl_SIG_weight_in_vec_6_val") , ccs_rtl_SIG_weight_in_vec_7_val("ccs_rtl_SIG_weight_in_vec_7_val") , ccs_rtl_SIG_weight_in_vec_0_rdy("ccs_rtl_SIG_weight_in_vec_0_rdy") , ccs_rtl_SIG_weight_in_vec_1_rdy("ccs_rtl_SIG_weight_in_vec_1_rdy") , ccs_rtl_SIG_weight_in_vec_2_rdy("ccs_rtl_SIG_weight_in_vec_2_rdy") , ccs_rtl_SIG_weight_in_vec_3_rdy("ccs_rtl_SIG_weight_in_vec_3_rdy") , ccs_rtl_SIG_weight_in_vec_4_rdy("ccs_rtl_SIG_weight_in_vec_4_rdy") , ccs_rtl_SIG_weight_in_vec_5_rdy("ccs_rtl_SIG_weight_in_vec_5_rdy") , ccs_rtl_SIG_weight_in_vec_6_rdy("ccs_rtl_SIG_weight_in_vec_6_rdy") , ccs_rtl_SIG_weight_in_vec_7_rdy("ccs_rtl_SIG_weight_in_vec_7_rdy") , ccs_rtl_SIG_weight_in_vec_0_msg("ccs_rtl_SIG_weight_in_vec_0_msg") , ccs_rtl_SIG_weight_in_vec_1_msg("ccs_rtl_SIG_weight_in_vec_1_msg") , ccs_rtl_SIG_weight_in_vec_2_msg("ccs_rtl_SIG_weight_in_vec_2_msg") , ccs_rtl_SIG_weight_in_vec_3_msg("ccs_rtl_SIG_weight_in_vec_3_msg") , ccs_rtl_SIG_weight_in_vec_4_msg("ccs_rtl_SIG_weight_in_vec_4_msg") , ccs_rtl_SIG_weight_in_vec_5_msg("ccs_rtl_SIG_weight_in_vec_5_msg") , ccs_rtl_SIG_weight_in_vec_6_msg("ccs_rtl_SIG_weight_in_vec_6_msg") , ccs_rtl_SIG_weight_in_vec_7_msg("ccs_rtl_SIG_weight_in_vec_7_msg") , ccs_rtl_SIG_accum_out_vec_0_val("ccs_rtl_SIG_accum_out_vec_0_val") , ccs_rtl_SIG_accum_out_vec_1_val("ccs_rtl_SIG_accum_out_vec_1_val") , ccs_rtl_SIG_accum_out_vec_2_val("ccs_rtl_SIG_accum_out_vec_2_val") , ccs_rtl_SIG_accum_out_vec_3_val("ccs_rtl_SIG_accum_out_vec_3_val") , ccs_rtl_SIG_accum_out_vec_4_val("ccs_rtl_SIG_accum_out_vec_4_val") , ccs_rtl_SIG_accum_out_vec_5_val("ccs_rtl_SIG_accum_out_vec_5_val") , ccs_rtl_SIG_accum_out_vec_6_val("ccs_rtl_SIG_accum_out_vec_6_val") , ccs_rtl_SIG_accum_out_vec_7_val("ccs_rtl_SIG_accum_out_vec_7_val") , ccs_rtl_SIG_accum_out_vec_0_rdy("ccs_rtl_SIG_accum_out_vec_0_rdy") , ccs_rtl_SIG_accum_out_vec_1_rdy("ccs_rtl_SIG_accum_out_vec_1_rdy") , ccs_rtl_SIG_accum_out_vec_2_rdy("ccs_rtl_SIG_accum_out_vec_2_rdy") , ccs_rtl_SIG_accum_out_vec_3_rdy("ccs_rtl_SIG_accum_out_vec_3_rdy") , ccs_rtl_SIG_accum_out_vec_4_rdy("ccs_rtl_SIG_accum_out_vec_4_rdy") , ccs_rtl_SIG_accum_out_vec_5_rdy("ccs_rtl_SIG_accum_out_vec_5_rdy") , ccs_rtl_SIG_accum_out_vec_6_rdy("ccs_rtl_SIG_accum_out_vec_6_rdy") , ccs_rtl_SIG_accum_out_vec_7_rdy("ccs_rtl_SIG_accum_out_vec_7_rdy") , ccs_rtl_SIG_accum_out_vec_0_msg("ccs_rtl_SIG_accum_out_vec_0_msg") , ccs_rtl_SIG_accum_out_vec_1_msg("ccs_rtl_SIG_accum_out_vec_1_msg") , ccs_rtl_SIG_accum_out_vec_2_msg("ccs_rtl_SIG_accum_out_vec_2_msg") , ccs_rtl_SIG_accum_out_vec_3_msg("ccs_rtl_SIG_accum_out_vec_3_msg") , ccs_rtl_SIG_accum_out_vec_4_msg("ccs_rtl_SIG_accum_out_vec_4_msg") , ccs_rtl_SIG_accum_out_vec_5_msg("ccs_rtl_SIG_accum_out_vec_5_msg") , ccs_rtl_SIG_accum_out_vec_6_msg("ccs_rtl_SIG_accum_out_vec_6_msg") , ccs_rtl_SIG_accum_out_vec_7_msg("ccs_rtl_SIG_accum_out_vec_7_msg") { // Instantiate other modules ccs_rtl.clk(ccs_rtl_SIG_clk); ccs_rtl.rst(ccs_rtl_SIG_rst); ccs_rtl.write_req_val(ccs_rtl_SIG_write_req_val); ccs_rtl.write_req_rdy(ccs_rtl_SIG_write_req_rdy); ccs_rtl.write_req_msg(ccs_rtl_SIG_write_req_msg); ccs_rtl.start_val(ccs_rtl_SIG_start_val); ccs_rtl.start_rdy(ccs_rtl_SIG_start_rdy); ccs_rtl.start_msg(ccs_rtl_SIG_start_msg); ccs_rtl.weight_in_vec_0_val(ccs_rtl_SIG_weight_in_vec_0_val); ccs_rtl.weight_in_vec_1_val(ccs_rtl_SIG_weight_in_vec_1_val); ccs_rtl.weight_in_vec_2_val(ccs_rtl_SIG_weight_in_vec_2_val); ccs_rtl.weight_in_vec_3_val(ccs_rtl_SIG_weight_in_vec_3_val); ccs_rtl.weight_in_vec_4_val(ccs_rtl_SIG_weight_in_vec_4_val); ccs_rtl.weight_in_vec_5_val(ccs_rtl_SIG_weight_in_vec_5_val); ccs_rtl.weight_in_vec_6_val(ccs_rtl_SIG_weight_in_vec_6_val); ccs_rtl.weight_in_vec_7_val(ccs_rtl_SIG_weight_in_vec_7_val); ccs_rtl.weight_in_vec_0_rdy(ccs_rtl_SIG_weight_in_vec_0_rdy); ccs_rtl.weight_in_vec_1_rdy(ccs_rtl_SIG_weight_in_vec_1_rdy); ccs_rtl.weight_in_vec_2_rdy(ccs_rtl_SIG_weight_in_vec_2_rdy); ccs_rtl.weight_in_vec_3_rdy(ccs_rtl_SIG_weight_in_vec_3_rdy); ccs_rtl.weight_in_vec_4_rdy(ccs_rtl_SIG_weight_in_vec_4_rdy); ccs_rtl.weight_in_vec_5_rdy(ccs_rtl_SIG_weight_in_vec_5_rdy); ccs_rtl.weight_in_vec_6_rdy(ccs_rtl_SIG_weight_in_vec_6_rdy); ccs_rtl.weight_in_vec_7_rdy(ccs_rtl_SIG_weight_in_vec_7_rdy); ccs_rtl.weight_in_vec_0_msg(ccs_rtl_SIG_weight_in_vec_0_msg); ccs_rtl.weight_in_vec_1_msg(ccs_rtl_SIG_weight_in_vec_1_msg); ccs_rtl.weight_in_vec_2_msg(ccs_rtl_SIG_weight_in_vec_2_msg); ccs_rtl.weight_in_vec_3_msg(ccs_rtl_SIG_weight_in_vec_3_msg); ccs_rtl.weight_in_vec_4_msg(ccs_rtl_SIG_weight_in_vec_4_msg); ccs_rtl.weight_in_vec_5_msg(ccs_rtl_SIG_weight_in_vec_5_msg); ccs_rtl.weight_in_vec_6_msg(ccs_rtl_SIG_weight_in_vec_6_msg); ccs_rtl.weight_in_vec_7_msg(ccs_rtl_SIG_weight_in_vec_7_msg); ccs_rtl.accum_out_vec_0_val(ccs_rtl_SIG_accum_out_vec_0_val); ccs_rtl.accum_out_vec_1_val(ccs_rtl_SIG_accum_out_vec_1_val); ccs_rtl.accum_out_vec_2_val(ccs_rtl_SIG_accum_out_vec_2_val); ccs_rtl.accum_out_vec_3_val(ccs_rtl_SIG_accum_out_vec_3_val); ccs_rtl.accum_out_vec_4_val(ccs_rtl_SIG_accum_out_vec_4_val); ccs_rtl.accum_out_vec_5_val(ccs_rtl_SIG_accum_out_vec_5_val); ccs_rtl.accum_out_vec_6_val(ccs_rtl_SIG_accum_out_vec_6_val); ccs_rtl.accum_out_vec_7_val(ccs_rtl_SIG_accum_out_vec_7_val); ccs_rtl.accum_out_vec_0_rdy(ccs_rtl_SIG_accum_out_vec_0_rdy); ccs_rtl.accum_out_vec_1_rdy(ccs_rtl_SIG_accum_out_vec_1_rdy); ccs_rtl.accum_out_vec_2_rdy(ccs_rtl_SIG_accum_out_vec_2_rdy); ccs_rtl.accum_out_vec_3_rdy(ccs_rtl_SIG_accum_out_vec_3_rdy); ccs_rtl.accum_out_vec_4_rdy(ccs_rtl_SIG_accum_out_vec_4_rdy); ccs_rtl.accum_out_vec_5_rdy(ccs_rtl_SIG_accum_out_vec_5_rdy); ccs_rtl.accum_out_vec_6_rdy(ccs_rtl_SIG_accum_out_vec_6_rdy); ccs_rtl.accum_out_vec_7_rdy(ccs_rtl_SIG_accum_out_vec_7_rdy); ccs_rtl.accum_out_vec_0_msg(ccs_rtl_SIG_accum_out_vec_0_msg); ccs_rtl.accum_out_vec_1_msg(ccs_rtl_SIG_accum_out_vec_1_msg); ccs_rtl.accum_out_vec_2_msg(ccs_rtl_SIG_accum_out_vec_2_msg); ccs_rtl.accum_out_vec_3_msg(ccs_rtl_SIG_accum_out_vec_3_msg); ccs_rtl.accum_out_vec_4_msg(ccs_rtl_SIG_accum_out_vec_4_msg); ccs_rtl.accum_out_vec_5_msg(ccs_rtl_SIG_accum_out_vec_5_msg); ccs_rtl.accum_out_vec_6_msg(ccs_rtl_SIG_accum_out_vec_6_msg); ccs_rtl.accum_out_vec_7_msg(ccs_rtl_SIG_accum_out_vec_7_msg); // Register processes SC_METHOD(update_proc); sensitive << clk << rst << write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val << ccs_rtl_SIG_write_req_rdy << write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg << start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val << ccs_rtl_SIG_start_rdy << start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg << weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_weight_in_vec_0_rdy << ccs_rtl_SIG_weight_in_vec_1_rdy << ccs_rtl_SIG_weight_in_vec_2_rdy << ccs_rtl_SIG_weight_in_vec_3_rdy << ccs_rtl_SIG_weight_in_vec_4_rdy << ccs_rtl_SIG_weight_in_vec_5_rdy << ccs_rtl_SIG_weight_in_vec_6_rdy << ccs_rtl_SIG_weight_in_vec_7_rdy << weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << ccs_rtl_SIG_accum_out_vec_0_val << ccs_rtl_SIG_accum_out_vec_1_val << ccs_rtl_SIG_accum_out_vec_2_val << ccs_rtl_SIG_accum_out_vec_3_val << ccs_rtl_SIG_accum_out_vec_4_val << ccs_rtl_SIG_accum_out_vec_5_val << ccs_rtl_SIG_accum_out_vec_6_val << ccs_rtl_SIG_accum_out_vec_7_val << accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << ccs_rtl_SIG_accum_out_vec_0_msg << ccs_rtl_SIG_accum_out_vec_1_msg << ccs_rtl_SIG_accum_out_vec_2_msg << ccs_rtl_SIG_accum_out_vec_3_msg << ccs_rtl_SIG_accum_out_vec_4_msg << ccs_rtl_SIG_accum_out_vec_5_msg << ccs_rtl_SIG_accum_out_vec_6_msg << ccs_rtl_SIG_accum_out_vec_7_msg; // Other constructor statements } ~sysc_sim_wrapper() { } // C++ class functions }; } // end namespace CCS_RTL // // ------------------------------------- // sysc_sim_wrapper // Represents a new SC_MODULE having the same interface as the original model SysTop_rtl // ------------------------------------- // // --------------------------------------------------------------- // Process: SC_METHOD update_proc // Static sensitivity: sensitive << clk << rst << write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val << ccs_rtl_SIG_write_req_rdy << write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg << start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val << ccs_rtl_SIG_start_rdy << start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg << weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_weight_in_vec_0_rdy << ccs_rtl_SIG_weight_in_vec_1_rdy << ccs_rtl_SIG_weight_in_vec_2_rdy << ccs_rtl_SIG_weight_in_vec_3_rdy << ccs
_rtl_SIG_weight_in_vec_4_rdy << ccs_rtl_SIG_weight_in_vec_5_rdy << ccs_rtl_SIG_weight_in_vec_6_rdy << ccs_rtl_SIG_weight_in_vec_7_rdy << weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << ccs_rtl_SIG_accum_out_vec_0_val << ccs_rtl_SIG_accum_out_vec_1_val << ccs_rtl_SIG_accum_out_vec_2_val << ccs_rtl_SIG_accum_out_vec_3_val << ccs_rtl_SIG_accum_out_vec_4_val << ccs_rtl_SIG_accum_out_vec_5_val << ccs_rtl_SIG_accum_out_vec_6_val << ccs_rtl_SIG_accum_out_vec_7_val << accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << ccs_rtl_SIG_accum_out_vec_0_msg << ccs_rtl_SIG_accum_out_vec_1_msg << ccs_rtl_SIG_accum_out_vec_2_msg << ccs_rtl_SIG_accum_out_vec_3_msg << ccs_rtl_SIG_accum_out_vec_4_msg << ccs_rtl_SIG_accum_out_vec_5_msg << ccs_rtl_SIG_accum_out_vec_6_msg << ccs_rtl_SIG_accum_out_vec_7_msg; void CCS_RTL::sysc_sim_wrapper::update_proc() { // none.sc_in field_key=clk:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-685:clk:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-685 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_685; // NPS - LV to hold field ccs_rtl_SIG_clk.write(clk.read()); // none.sc_in field_key=rst:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-686:rst:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-686 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686; // NPS - LV to hold field type_to_vector(rst.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686); // read orig port and type convert ccs_rtl_SIG_rst.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686); // then write to RTL port // none.sc_in field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-725 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725; // NPS - LV to hold field type_to_vector(write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725); // read orig port and type convert ccs_rtl_SIG_write_req_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725); // then write to RTL port // none.sc_out field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-735 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735; vector_to_type(ccs_rtl_SIG_write_req_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735); write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735); // none.sc_in field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-745 sc_lv< 69 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745; // NPS - LV to hold field type_to_vector(write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg.read(),69,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745); // read orig port and type convert ccs_rtl_SIG_write_req_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745); // then write to RTL port // none.sc_in field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-782 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782; // NPS - LV to hold field type_to_vector(start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782); // read orig port and type convert ccs_rtl_SIG_start_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782); // then write to RTL port // none.sc_out field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-792 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792; vector_to_type(ccs_rtl_SIG_start_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792); start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792); // none.sc_in field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-802 sc_lv< 6 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802; // NPS - LV to hold field type_to_vector(start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg.read(),6,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802); // read orig port and type convert ccs_rtl_SIG_start_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839; // NPS - LV to hold field type_to_vector(weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_0_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_1_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_2_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_3_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_4_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_5_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_6_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_7_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849; vector_to_type(ccs_rtl_SIG_weight_in_vec_0_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_1_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_2_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_3_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_4_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_5_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_6_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_7_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 sc_lv< 8 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859; // NPS - LV to hold field type_to_vector(weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_0_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_1_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_2_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_3_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_4_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_5_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_6_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_7_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884; vector_to_type(ccs_rtl_SIG_accum_out_vec_0_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_1_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_2_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_3_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_4_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_5_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_6_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_7_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888; // NPS - LV to hold field type_to_vector(accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_0_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_1_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_2_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in fi
eld_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_3_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_4_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_5_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_6_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_7_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 sc_dt::sc_lv<32 > d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892; vector_to_type(ccs_rtl_SIG_accum_out_vec_0_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[0].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_1_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[1].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_2_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[2].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_3_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[3].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_4_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[4].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_5_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[5].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_6_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[6].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_7_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[7].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); } // Include original testbench file(s) #include "/home/billyk/cs148/hls/lab3/SysTop/../../../cmod/lab3/SysTop/testbench.cpp"
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #ifdef HW_COSIM //#define __GMP_WITHIN_CONFIGURE #endif #define DEBUG_SYSTEMC #define SC_INCLUDE_FX #include "hwcore/tb/pipes/tb_streamcircularlinebuffer.h" #include <cstdlib> #include <iostream> #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "streamcircularlinebuffer_tb"; void flush_io() { std::cout << "flush_io()" << std::flush; } void flush_quick_io() { std::cout << "flush_quick_io()" << std::flush; } int sc_main(int argc, char *argv[]) { if (std::atexit(flush_io) != 0 || std::at_quick_exit(flush_quick_io) != 0) { std::cout << "error setup flush at exit" << std::endl; std::exit(1); } return errors ? 1 : 0; cout << "INFO: Elaborating " << simulation_name << endl; sc_core::sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING); sc_report_handler::set_actions(SC_ID_LOGIC_X_TO_BOOL_, SC_LOG); sc_report_handler::set_actions(SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG); // sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG); // sc_set_time_resolution(1,SC_PS); // sc_set_default_time_unit(1,SC_NS); // ModuleSingle modulesingle("modulesingle_i"); tb_top_streamcircularlinebuffer<sizeof(int) * 8, 3> top("tb_top_streamcircularlinebuffer"); cout << "INFO: Simulating " << simulation_name << endl; sc_time time_out(1000, SC_US); sc_start(time_out); cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string() << std::endl << std::flush; sc_assert(sc_time_stamp() != time_out); // assert(sc_time_stamp()!=sc_max_time()); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl << std::flush; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; } // test2
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_scalar_summation_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_values_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
#include <memory> #include <systemc.h> #include "sc_top.h" int sc_main(int argc, char* argv[]) { if (false && argc && argv) {} Verilated::debug(0); Verilated::randReset(2); Verilated::commandArgs(argc, argv); ios::sync_with_stdio(); const std::unique_ptr<sc_top> u_sc_top{new sc_top("sc_top")}; sc_start(); cout << "done, time = " << sc_time_stamp() << endl; return 0; } #ifdef VL_USER_STOP void vl_stop(const char *filename, int linenum, const char *hier) VL_MT_UNSAFE { sc_stop(); cout << "call vl_stop" << endl; } #endif
/* Print.cpp - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified December 2014 by Ivan Grokhotkov Modified May 2015 by Michael C. Miller - ESP31B progmem support Modified 25 July 2019 by Glenn Ramalho - fixed a small bug */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "Arduino.h" #include <systemc.h> #include "info.h" #include "Print.h" extern "C" { #include "time.h" } // Public Methods ////////////////////////////////////////////////////////////// /* default implementation: may be overridden */ size_t Print::write(const uint8_t *buffer, size_t size) { size_t n = 0; while(size--) { n += write(*buffer++); } return n; } size_t Print::printf(const char *format, ...) { char loc_buf[64]; char * temp = loc_buf; va_list arg; va_list copy; va_start(arg, format); va_copy(copy, arg); int len = vsnprintf(NULL, 0, format, copy); va_end(copy); if (len < 0) { PRINTF_WARN("PRINTF", "vnprintf returned an error."); return 0; } if((unsigned int)len >= sizeof(loc_buf)){ temp = new char[len+1]; if(temp == NULL) { return 0; } } len = vsnprintf(temp, len+1, format, arg); write((uint8_t*)temp, len); va_end(arg); if(temp != loc_buf) { delete[] temp; } return len; } size_t Print::print(const __FlashStringHelper *ifsh) { return print(reinterpret_cast<const char *>(ifsh)); } size_t Print::print(const String &s) { return write(s.c_str(), s.length()); } size_t Print::print(const char str[]) { return write(str); } size_t Print::print(char c) { return write(c); } size_t Print::print(unsigned char b, int base) { return print((unsigned long) b, base); } size_t Print::print(int n, int base) { return print((long) n, base); } size_t Print::print(unsigned int n, int base) { return print((unsigned long) n, base); } size_t Print::print(long n, int base) { if(base == 0) { return write(n); } else if(base == 10) { if(n < 0) { int t = print('-'); n = -n; return printNumber(n, 10) + t; } return printNumber(n, 10); } else { return printNumber(n, base); } } size_t Print::print(unsigned long n, int base) { if(base == 0) { return write(n); } else { return printNumber(n, base); } } size_t Print::print(double n, int digits) { return printFloat(n, digits); } size_t Print::println(const __FlashStringHelper *ifsh) { size_t n = print(ifsh); n += println(); return n; } size_t Print::print(const Printable& x) { return x.printTo(*this); } size_t Print::print(struct tm * timeinfo, const char * format) { const char * f = format; if(!f){ f = "%c"; } char buf[64]; size_t written = strftime(buf, 64, f, timeinfo); print(buf); return written; } size_t Print::println(void) { return print("\r\n"); } size_t Print::println(const String &s) { size_t n = print(s); n += println(); return n; } size_t Print::println(const char c[]) { size_t n = print(c); n += println(); return n; } size_t Print::println(char c) { size_t n = print(c); n += println(); return n; } size_t Print::println(unsigned char b, int base) { size_t n = print(b, base); n += println(); return n; } size_t Print::println(int num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(unsigned int num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(long num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(unsigned long num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(double num, int digits) { size_t n = print(num, digits); n += println(); return n; } size_t Print::println(const Printable& x) { size_t n = print(x); n += println(); return n; } size_t Print::println(struct tm * timeinfo, const char * format) { size_t n = print(timeinfo, format); n += println(); return n; } // Private Methods ///////////////////////////////////////////////////////////// size_t Print::printNumber(unsigned long n, uint8_t base) { char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. char *str = &buf[sizeof(buf) - 1]; *str = '\0'; // prevent crash if called with base == 1 if(base < 2) { base = 10; } do { unsigned long m = n; n /= base; char c = m - base * n; *--str = c < 10 ? c + '0' : c + 'A' - 10; } while(n); return write(str); } size_t Print::printFloat(double number, uint8_t digits) { size_t n = 0; if(isnan(number)) { return print("nan"); } if(isinf(number)) { return print("inf"); } if(number > 4294967040.0) { return print("ovf"); // constant determined empirically } if(number < -4294967040.0) { return print("ovf"); // constant determined empirically } // Handle negative numbers if(number < 0.0) { n += print('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for(uint8_t i = 0; i < digits; ++i) { rounding /= 10.0; } number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long) number; double remainder = number - (double) int_part; n += print(int_part); // Print the decimal point, but only if there are digits beyond if(digits > 0) { n += print("."); } // Extract digits from the remainder one at a time while(digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); n += print(toPrint); remainder -= toPrint; } return n; }
#include <systemc.h> // // Example which is using switch statement to create multiplexer // // .. hwt-autodoc:: // SC_MODULE(SwitchStmHwModule) { // ports sc_in<sc_uint<1>> a; sc_in<sc_uint<1>> b; sc_in<sc_uint<1>> c; sc_out<sc_uint<1>> out; sc_in<sc_uint<3>> sel; // component instances // internal signals void assig_process_out() { switch(sel.read()) { case sc_uint<3>("0b000"): { out.write(a.read()); break; } case sc_uint<3>("0b001"): { out.write(b.read()); break; } case sc_uint<3>("0b010"): { out.write(c.read()); break; } default: out.write(sc_uint<1>("0b0")); } } SC_CTOR(SwitchStmHwModule) { SC_METHOD(assig_process_out); sensitive << a << b << c << sel; // connect ports } };
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "esp32-hal-adc.h" #include "adc_types.h" #include "esp_attr.h" #include "driver/adc.h" #include <systemc.h> #include "info.h" static uint8_t __analogAttenuation = 3;//11db static uint8_t __analogWidth = 3;//12 bits static uint8_t __analogCycles = 8; static uint8_t __analogSamples = 0;//1 sample static uint8_t __analogClockDiv = 1; // Width of returned answer () static uint8_t __analogReturnedWidth = 12; void analogSetWidth(uint8_t bits){ if(bits < 9){ bits = 9; } else if(bits > 12){ bits = 12; } __analogWidth = bits - 9; adc1ptr->set_width(bits); adc2ptr->set_width(bits); } void analogSetCycles(uint8_t cycles){ PRINTF_WARN("ADC", "ADC cycles is not yet supported."); __analogCycles = cycles; } void analogSetSamples(uint8_t samples){ PRINTF_WARN("ADC", "ADC samples is not yet supported."); if(!samples){ return; } __analogSamples = samples - 1; } void analogSetClockDiv(uint8_t clockDiv){ if(!clockDiv){ return; } __analogClockDiv = clockDiv; adc_set_clk_div(clockDiv); } void analogSetAttenuation(adc_attenuation_t attenuation) { adc_atten_t at; int c; switch(attenuation) { /* For most measures, we do a simple conversion of the enums. */ case ADC_0db: at = ADC_ATTEN_DB_0; break; case ADC_2_5db: at = ADC_ATTEN_DB_2_5; break; case ADC_6db: at = ADC_ATTEN_DB_6; break; case ADC_11db: at = ADC_ATTEN_DB_11; break; /* If the value is illegal, we warn the user and assume that we can * simply drop the upper bits, as the original code from the Arduino IDF * does this. */ default: at = (adc_atten_t)((unsigned int)attenuation & (~3U)); PRINTF_WARN("ADC", "Using large Attenuation value, using %s", printatten(at)); break; } /* Now we set the attenuation of every channel */ for(c = 0; c < 8; c = c + 1) adc1_config_channel_atten((adc1_channel_t)c, at); for(c = 0; c < 10; c = c + 1) adc2_config_channel_atten((adc2_channel_t)c, at); } void IRAM_ATTR analogInit(){ static bool initialized = false; if(initialized){ return; } analogSetAttenuation((adc_attenuation_t)__analogAttenuation); analogSetCycles(__analogCycles); analogSetSamples(__analogSamples + 1);//in samples analogSetClockDiv(__analogClockDiv); analogSetWidth(__analogWidth + 9);//in bits /* We switch on the ADC in case it is not on. */ adc_power_on(); initialized = true; } void analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation) { /* This one is a bit different from the above one, but we are following * the Arduino-IDF. */ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0 || attenuation > 3){ return ; } analogInit(); if(channel > 7){ adc2_config_channel_atten((adc2_channel_t)(channel-10), (adc_atten_t)attenuation); } else { adc1_config_channel_atten((adc1_channel_t)channel, (adc_atten_t)attenuation); } } bool IRAM_ATTR adcAttachPin(uint8_t pin){ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return false;//not adc pin } /* Not supported yet int8_t pad = digitalPinToTouchChannel(pin); if(pad >= 0){ uint32_t touch = READ_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG); if(touch & (1 << pad)){ touch &= ~((1 << (pad + SENS_TOUCH_PAD_OUTEN2_S)) | (1 << (pad + SENS_TOUCH_PAD_OUTEN1_S)) | (1 << (pad + SENS_TOUCH_PAD_WORKEN_S))); WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, touch); } } else if(pin == 25){ CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE);//stop dac1 } else if(pin == 26){ CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE);//stop dac2 } */ pinMode(pin, ANALOG); analogInit(); return true; } bool IRAM_ATTR adcStart(uint8_t pin){ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return false;//not adc pin } if(channel > 9){ channel -= 10; adc2ptr->soc((int)channel); } else { adc1ptr->soc((int)channel); } return true; } bool IRAM_ATTR adcBusy(uint8_t pin){ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return false;//not adc pin } if(channel > 7) adc2ptr->busy(); return adc2ptr->busy(); } uint16_t IRAM_ATTR adcEnd(uint8_t pin) { int v; int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return 0;//not adc pin } if(channel > 7){ adc2ptr->wait_eoc(); v = adc2ptr->getraw(); /* If it fails we return 0 */ if (v < 0) return 0; } else { adc1ptr->wait_eoc(); v = adc1ptr->getraw(); /* If it fails we return 0 */ if (v < 0) return 0; } return (uint16_t)v; } uint16_t IRAM_ATTR analogRead(uint8_t pin) { if(!adcAttachPin(pin) || !adcStart(pin)){ return 0; } return adcEnd(pin); } void analogReadResolution(uint8_t bits) { if(!bits || bits > 16){ return; } analogSetWidth(bits); // hadware from 9 to 12 __analogReturnedWidth = bits; // software from 1 to 16 } int hallRead() //hall sensor without LNA { PRINTF_ERROR("ADC", "Hall sensor not yet supported."); return 0; }
/******************************************************************************* * espintr.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for the ESP32 interrupt management. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "info.h" #include "espintr.h" #include "soc/soc.h" #include "esp_intr_alloc.h" #include "Arduino.h" void espintr::initialize() { int i; for (i = 0; i < ESPM_INTR_TABLE; i = i + 1) { table_pro[i] = -1; table_app[i] = -1; } for (i = 0; i < XCHAL_NUM_INTERRUPTS; i = i + 1) { handler_pro[i].fn = NULL; handler_pro[i].arg = NULL; handler_app[i].fn = NULL; handler_app[i].arg = NULL; } } void espintr::catcher() { uint32_t pro_lvl, app_lvl; while(true) { wait(); /* We collect all signals into one set of busses. */ pro_lvl = 0; app_lvl = 0; if (ledc_intr_i.read() && table_pro[ETS_LEDC_INTR_SOURCE] != -1) pro_lvl = pro_lvl | (1<<table_pro[ETS_LEDC_INTR_SOURCE]); if (ledc_intr_i.read() && table_app[ETS_LEDC_INTR_SOURCE] != -1) app_lvl = app_lvl | (1<<table_app[ETS_LEDC_INTR_SOURCE]); /* Once we are done we set the new values for raw and intr. */ raw_pro.write(pro_lvl); intr_pro.write(mask_pro.read() & pro_lvl); raw_app.write(app_lvl); intr_app.write(mask_pro.read() & app_lvl); } } int espintr::get_next(uint32_t edgemask, uint32_t now, uint32_t last) { /* Any bits that are edge triggered, we take the value for last. Any that * are not, we take the inverse of now forcing an edge trigger. */ uint32_t lm = last & edgemask | ~now & ~edgemask; /* Priority NMI */ if ((now & (1<<14))>0) return 14; /* Priority 5 */ if ((now & ~last & (1<<16))>0) return 16; /* Timer style */ if ((now & ~lm & (1<<26))>0) return 26; if ((now & ~lm & (1<<31))>0) return 31; /* Priority 4 */ if ((now & ~lm & (1<<24))>0) return 24; if ((now & ~lm & (1<<25))>0) return 25; if ((now & ~lm & (1<<28))>0) return 28; if ((now & ~lm & (1<<30))>0) return 30; /* Priority 3 */ if ((now & ~last & (1<<11))>0) return 11; /* Profiling */ if ((now & ~last & (1<<15))>0) return 15; /* Timer */ if ((now & ~lm & (1<<22))>0) return 22; if ((now & ~lm & (1<<23))>0) return 23; if ((now & ~lm & (1<<27))>0) return 27; if ((now & ~last & (1<<29))>0) return 29; /* Software */ /* Priority 2 */ if ((now & ~lm & (1<<19))>0) return 19; if ((now & ~lm & (1<<20))>0) return 20; if ((now & ~lm & (1<<21))>0) return 21; /* Priority 1 */ if ((now & ~lm & (1<<0))>0) return 0; if ((now & ~lm & (1<<1))>0) return 1; if ((now & ~lm & (1<<2))>0) return 2; if ((now & ~lm & (1<<3))>0) return 3; if ((now & ~lm & (1<<4))>0) return 4; if ((now & ~lm & (1<<5))>0) return 5; if ((now & ~last & (1<<6))>0) return 6; /* Timer */ if ((now & ~last & (1<<7))>0) return 7; /* Software */ if ((now & ~lm & (1<<8))>0) return 8; if ((now & ~lm & (1<<9))>0) return 9; if ((now & ~lm & (1<<10))>0) return 10; if ((now & ~lm & (1<<12))>0) return 12; if ((now & ~lm & (1<<13))>0) return 13; if ((now & ~lm & (1<<17))>0) return 17; if ((now & ~lm & (1<<18))>0) return 18; return -1; } void espintr::driver_app() { uint32_t last = 0; int nextintr; while(true) { wait(); nextintr = get_next(edge_interrupt_app.read(), intr_app.read(), last); last = intr_app.read(); if (nextintr >= 0 && handler_app[nextintr].fn != NULL) (*handler_pro[nextintr].fn)(handler_pro[nextintr].arg); } } void espintr::driver_pro() { uint32_t last = 0; int nextintr; while(true) { wait(); nextintr = get_next(edge_interrupt_pro.read(), intr_pro.read(), last); last = intr_pro.read(); if (nextintr >= 0 && handler_pro[nextintr].fn != NULL) (*handler_pro[nextintr].fn)(handler_pro[nextintr].arg); } } void espintr::maskupdate() { if (setunset) mask_pro.write(mask_pro.read() | newmask); else mask_pro.write(mask_pro.read() & ~newmask); if (setunset) mask_app.write(mask_app.read() | newmask); else mask_app.write(mask_app.read() & ~newmask); } void espintr::trace(sc_trace_file *tf) { sc_trace(tf, raw_app, raw_app.name()); sc_trace(tf, raw_pro, raw_pro.name()); sc_trace(tf, mask_app, mask_app.name()); sc_trace(tf, mask_pro, mask_pro.name()); sc_trace(tf, intr_app, intr_app.name()); sc_trace(tf, intr_pro, intr_pro.name()); }
/******************************************************************************* * pcnttest.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is the main testbench for the pcnt.ino test. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "pcnttest.h" #include <string> #include <vector> #include "info.h" /********************** * Function: trace() * inputs: trace file * outputs: none * return: none * globals: none * * Traces all signals in the design. For a signal to be traced it must be listed * here. This function should also call tracing in any subblocks, if desired. */ void pcnttest::trace(sc_trace_file *tf) { sc_trace(tf, led, led.name()); sc_trace(tf, rx, rx.name()); sc_trace(tf, tx, tx.name()); sc_trace(tf, pwm0, pwm0.name()); sc_trace(tf, pwm1, pwm1.name()); sc_trace(tf, pwm2, pwm2.name()); sc_trace(tf, pwm3, pwm3.name()); sc_trace(tf, ctrl0, ctrl0.name()); sc_trace(tf, ctrl1, ctrl1.name()); sc_trace(tf, ctrl2, ctrl2.name()); i_esp.trace(tf); } /********************** * Task: serflush(): * inputs: none * outputs: none * return: none * globals: none * * Dumps everything comming from the serial interface. */ void pcnttest::serflush() { i_uartclient.dump(); } /********************** * Task: drivewave(): * inputs: none * outputs: none * return: none * globals: none * * Drives a waveform onto the pwm0 pin. */ void pcnttest::drivewave() { int c; pwm0.write(false); pwm1.write(false); pwm2.write(false); pwm3.write(false); while(true) { ctrl1.write(false); for(c = 0; c < 20; c = c + 1) { wait(1, SC_MS); pwm0.write(true); wait(300, SC_NS); pwm1.write(true); pwm2.write(true); wait(200, SC_NS); pwm0.write(false); wait(300, SC_NS); pwm1.write(false); pwm2.write(false); } ctrl1.write(true); for(c = 0; c < 20; c = c + 1) { wait(1, SC_MS); pwm0.write(true); wait(300, SC_NS); pwm1.write(true); pwm3.write(true); wait(200, SC_NS); pwm0.write(false); wait(300, SC_NS); pwm1.write(false); pwm3.write(false); } } } /******************************************************************************* ** Testbenches ***************************************************************** *******************************************************************************/ void pcnttest::t0(void) { SC_REPORT_INFO("TEST", "Running Test T0."); PRINTF_INFO("TEST", "Waiting for power-up"); ctrl0.write(false); ctrl2.write(false); wait(500, SC_MS); } void pcnttest::testbench(void) { /* Now we check the test case and run the correct TB. */ printf("Starting Testbench Test%d @%s\n", tn, sc_time_stamp().to_string().c_str()); if (tn == 0) t0(); else SC_REPORT_ERROR("TEST", "Test number too large."); sc_stop(); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_scalar_adder_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { scalar_adder scalar_adder("SCALAR_ADDER"); sc_signal<bool> clock; sc_signal<int> data_a_in; sc_signal<int> data_b_in; sc_signal<int> data_out; scalar_adder(clock, data_a_in, data_b_in, data_out); data_a_in = 1; data_b_in = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_a_in + data_b_in = " << data_out.read() << endl; return 0; }
/* * SysPE testbench for Harvard cs148/248 only */ #include "SysPE.h" #include <systemc.h> #include <mc_scverify.h> #include <nvhls_int.h> #include <vector> #define NVHLS_VERIFY_BLOCKS (SysPE) #include <nvhls_verify.h> using namespace::std; #include <testbench/nvhls_rand.h> SC_MODULE (Source) { Connections::Out<SysPE::InputType> act_in; Connections::Out<SysPE::InputType> weight_in; Connections::Out<SysPE::AccumType> accum_in; Connections::In<SysPE::AccumType> accum_out; Connections::In<SysPE::InputType> act_out; Connections::In<SysPE::InputType> weight_out; sc_in <bool> clk; sc_in <bool> rst; bool start_src; vector<SysPE::InputType> act_list{0, -1, 3, -7, 15, -31, 63, -127}; vector<SysPE::AccumType> accum_list{0, -10, 30, -70, 150, -310, 630, -1270}; SysPE::InputType weight_data = 10; SysPE::AccumType accum_init = 0; SysPE::InputType act_out_src; SysPE::AccumType accum_out_src; SC_CTOR(Source) { SC_THREAD(run); sensitive << clk.pos(); async_reset_signal_is(rst, false); SC_THREAD(pop_result); sensitive << clk.pos(); async_reset_signal_is(rst, false); } void run() { SysPE::InputType _act; SysPE::AccumType _acc; act_in.Reset(); weight_in.Reset(); accum_in.Reset(); // Wait for initial reset wait(20.0, SC_NS); wait(); // Write wait to PE weight_in.Push(weight_data); wait(); for (int i=0; i< (int) act_list.size(); i++) { _act = act_list[i]; _acc = accum_list[i]; act_in.Push(_act); accum_in.Push(_acc); wait(); } // for wait(5); }// void run() void pop_result() { weight_out.Reset(); wait(); unsigned int i = 0, j = 0; bool correct = 1; while (1) { SysPE::InputType tmp; if (weight_out.PopNB(tmp)) { cout << sc_time_stamp() << ": Received Output Weight:" << " \t " << tmp << endl; } if (act_out.PopNB(act_out_src)) { cout << sc_time_stamp() << ": Received Output Activation:" << " \t " << act_out_src << "\t| Reference \t" << act_list[i] << endl; correct &= (act_list[i] == act_out_src); i++; } if (accum_out.PopNB(accum_out_src)) { int acc_ref = accum_list[j] + act_list[j]*weight_data; cout << sc_time_stamp() << ": Received Accumulated Output:" << "\t " << accum_out_src << "\t| Reference \t" << acc_ref << endl; correct &= (acc_ref == accum_out_src); j++; } wait(); if (i == act_list.size() && j == act_list.size()) break; }// while if (correct == 1) cout << "Implementation Correct :)" << endl; else cout << "Implementation Incorrect (:" << endl; }// void pop_result() }; SC_MODULE (testbench) { sc_clock clk; sc_signal<bool> rst; Connections::Combinational<SysPE::InputType> act_in; Connections::Combinational<SysPE::InputType> act_out; Connections::Combinational<SysPE::InputType> weight_in; Connections::Combinational<SysPE::InputType> weight_out; Connections::Combinational<SysPE::AccumType> accum_in; Connections::Combinational<SysPE::AccumType> accum_out; NVHLS_DESIGN(SysPE) PE; Source src; SC_HAS_PROCESS(testbench); testbench(sc_module_name name) : sc_module(name), clk("clk", 1, SC_NS, 0.5,0,SC_NS,true), rst("rst"), PE("PE"), src("src") { PE.clk(clk); PE.rst(rst); PE.act_in(act_in); PE.act_out(act_out); PE.weight_in(weight_in); PE.weight_out(weight_out); PE.accum_in(accum_in); PE.accum_out(accum_out); src.clk(clk); src.rst(rst); src.act_in(act_in); src.act_out(act_out); src.weight_in(weight_in); src.weight_out(weight_out); src.accum_in(accum_in); src.accum_out(accum_out); SC_THREAD(run); } void run() { rst = 1; wait(10.5, SC_NS); rst = 0; cout << "@" << sc_time_stamp() << " Asserting Reset " << endl ; wait(1, SC_NS); cout << "@" << sc_time_stamp() << " Deasserting Reset " << endl ; rst = 1; wait(10000,SC_NS); cout << "@" << sc_time_stamp() << " Stop " << endl ; sc_stop(); } }; int sc_main(int argc, char *argv[]) { nvhls::set_random_seed(); testbench my_testbench("my_testbench"); sc_start(); //cout << "CMODEL PASS" << endl; return 0; };
/* Copyright &copy; 2017, Stefan Sicklinger, Munich * * All rights reserved. * * This file is part of STACCATO. * * STACCATO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * STACCATO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with STACCATO. If not, see http://www.gnu.org/licenses/. */ #include "FeUmaElement.h" #include "Material.h" #include "Message.h" #include "MathLibrary.h" #ifdef USE_SIMULIA_UMA_API #include <ads_CoreFESystemC.h> #include <ads_CoreMeshC.h> #include <uma_System.h> #include <uma_SparseMatrix.h> #include <uma_ArrayInt.h> #include <uma_IncoreMatrix.h> #endif #include <iostream> #include <stdio.h> #include <iomanip> //XML #include "MetaDatabase.h" FeUmaElement::FeUmaElement(Material *_material) : FeElement(_material) { /*nodeToDofMap = MetaDatabase::getInstance()->nodeToDofMapMeta; nodeToGlobalMap = MetaDatabase::getInstance()->nodeToGlobalMapMeta; int numNodes = nodeToGlobalMap.size(); totalDOFs = 0; for (std::map<int, std::vector<int>>::iterator it = nodeToDofMap.begin(); it != nodeToDofMap.end(); ++it) { totalDOFs += it->second.size(); } mySparseSDReal = new MathLibrary::SparseMatrix<double>(totalDOFs, true, true); std::cout << " >> UMA Element Created with TotalDoFs: " << totalDOFs << std::endl;*/ } FeUmaElement::~FeUmaElement() { } void FeUmaElement::computeElementMatrix(const double* _eleCoords) { /*bool matdisp = false; bool fileexp = false; std::string simFileK = MetaDatabase::getInstance()->simFile + "_X1.sim"; const char * simFileStiffness = simFileK.c_str(); std::string simFileM = MetaDatabase::getInstance()->simFile + "_X2.sim"; const char * simFileMass = simFileM.c_str(); std::string simFileStrD = MetaDatabase::getInstance()->simFile + "_X3.sim"; const char * simFileSD = simFileStrD.c_str(); bool structDampingExists = false; std::ifstream ifile(simFileSD); if (ifile) structDampingExists = true; stiffnessUMA_key = "GenericSystem_stiffness"; massUMA_key = "GenericSystem_mass"; structuralDampingUMA_key = "GenericSystem_structuralDamping"; #ifdef USE_SIMULIA_UMA_API //DebugSIM(stiffnessUMA_key, simFileStiffness, matdisp, fileexp); //DebugSIM(massUMA_key, simFileMass, matdisp, fileexp); ImportSIM(stiffnessUMA_key, simFileStiffness, matdisp, fileexp); ImportSIM(massUMA_key, simFileMass, matdisp, fileexp); ImportSIM(structuralDampingUMA_key, simFileSD, matdisp, fileexp); #endif*/ } #ifdef USE_SIMULIA_UMA_API void FeUmaElement::PrintMatrix(const uma_System &system, const char *matrixName, bool _printToScreen, bool _printToFile) { /*char * mapTypeName[] = { "DOFS", "NODES", "MODES", "ELEMENTS", "CASES", "Unknown" }; if (!system.HasMatrix(matrixName)) { return; printf("\nSparse matrix %s not found\n", matrixName); } uma_SparseMatrix smtx; system.SparseMatrix(smtx, matrixName); if (!smtx) { printf("\nSparse matrix %s cannot be not accessed\n", matrixName); return; } printf(" Matrix %s - sparse type\n", matrixName); printf(" domain: rows %s, columns %s\n", mapTypeName[smtx.TypeRows()], mapTypeName[smtx.TypeColumns()]); printf(" size: rows %i, columns %i, entries %i", smtx.NumRows(), smtx.NumColumns(), smtx.NumEntries()); if (smtx.IsSymmetric()) printf("; symmetric"); printf("\n"); uma_SparseIterator iter(smtx); int row, col; double val; if (_printToScreen) { int count = 0; int lastRow = 0; for (iter.First(); !iter.IsDone(); iter.Next(), count++) { iter.Entry(row, col, val); if (row != lastRow) printf("\n"); if (row != col) printf(" %2i,%-2i:%g", row, col, val); else printf(" *%2i,%-2i:%g", row, col, val); lastRow = row; } printf("\n"); // Map column DOFS to user nodes and dofs if (smtx.TypeColumns() != uma_Enum::DOFS) return; printf("\n map columns [column: node-dof]:"); uma_ArrayInt nodes; smtx.MapColumns(nodes, uma_Enum::NODES); // test array std::vector<int> ldofs; smtx.MapColumns(ldofs, uma_Enum::DOFS); // test vector for (int col = 0; col < nodes.Size(); col++) { if (col % 10 == 0) printf("\n"); printf(" %3i:%3i-%1i", col, nodes[col], ldofs[col]); } printf("\n"); } if (_printToFile) { std::ofstream myfile; myfile.open(std::string(matrixName) +".mtx"); std::cout << ">>> Writing file to: " << std::string(matrixName) + ".mtx" << std::endl; myfile.precision(std::numeric_limits<double>::digits10 + 1); myfile << std::scientific; for (iter.First(); !iter.IsDone(); iter.Next()) { iter.Entry(row, col, val); myfile << row << " " << col << " " << val << std::endl; } myfile.close(); }*/ } #endif void FeUmaElement::DebugSIM(const char* _matrixkey, const char* _fileName, bool _printToScreen, bool _printToFile) { #ifdef USE_SIMULIA_UMA_API /*std::cout << ">>> Debug SIM File: " << _fileName << " UMA Key: " << _matrixkey << std::endl; uma_System system(_fileName); if (system.IsNull()) { std::cout << ">>> Error: System not defined.\n"; } if (system.Type() != ads_GenericSystem) { std::cout << "Error: Struc. Damping Not a Generic System.\n"; } PrintMatrix(system, _matrixkey, _printToScreen, _printToFile);*/ #endif } void FeUmaElement::ImportSIM(const char* _matrixkey, const char* _fileName, bool _printToScreen, bool _printToFile) { #ifdef USE_SIMULIA_UMA_API /*std::cout << ">>> Import SIM File: " << _fileName << " UMA Key: " << _matrixkey << std::endl; bool flag = false; std::ifstream ifile(_fileName); if (!ifile) { if (std::string(_matrixkey) == structuralDampingUMA_key) { std::cout << " > StructuralDamping file not found and hence skipped." << std::endl; flag = true; } else { std::cout << " > File not found." << std::endl; exit(EXIT_FAILURE); } } if (!flag) { uma_System system(_fileName); if (system.IsNull()) { std::cout << ">> Error: System not defined.\n"; } if (system.Type() != ads_GenericSystem) { std::cout << ">> Error: Not a Generic System.\n"; } extractData(system, _matrixkey, _printToScreen, _printToFile); }*/ #endif } #ifdef USE_SIMULIA_UMA_API void FeUmaElement::extractData(const uma_System &system, const char *matrixName, bool _printToScreen, bool _printToFile) { /*char * mapTypeName[] = { "DOFS", "NODES", "MODES", "ELEMENTS", "CASES", "Unknown" }; // Check for matrix existence if (!system.HasMatrix(matrixName)) { std::cout << " >> Sparse matrix " << matrixName << " not found\n"; exit(EXIT_FAILURE); } // Load the matrix uma_SparseMatrix smtx; system.SparseMatrix(smtx, matrixName); if (!smtx) { std::cout << " >> Sparse matrix " << matrixName << " cannot be accessed!\n"; exit(EXIT_FAILURE); } if (_printToScreen) { printf(" Matrix %s - sparse type\n", matrixName); printf(" domain: rows %s, columns %s\n", mapTypeName[smtx.TypeRows()], mapTypeName[smtx.TypeColumns()]); printf(" size: rows %i, columns %i, entries %i", smtx.NumRows(), smtx.NumColumns(), smtx.NumEntries()); if (smtx.IsSymmetric()) printf("; symmetric"); else { std::cout << ";unsymmetric" << std::endl; exit(EXIT_FAILURE); } printf("\n"); } if (!smtx.IsSymmetric()){ std::cout << " Error: System not Symmetric" << std::endl; exit(EXIT_FAILURE); } uma_SparseIterator iter(smtx); int row, col; double val; int count = 0; uma_ArrayInt nodes; smtx.MapColumns(nodes, uma_Enum::NODES); // test array uma_ArrayInt ldofs; smtx.MapColumns(ldofs, uma_Enum::DOFS); // test vector if (std::string(matrixName) == std::string(stiffnessUMA_key)) { std::cout << " > Importing Ke ..." << std::endl; mySparseKReal = new MathLibrary::SparseMatrix<double>(totalDOFs, true, true); for (iter.First(); !iter.IsDone(); iter.Next(), count++) { iter.Entry(row, col, val); int fnode_row = nodes[row]; int fdof_row = ldofs[row]; int fnode_col = nodes[col]; int fdof_col = ldofs[col]; int globalrow = -1; int globalcol = -1; for (int i = 0; i < nodeToDofMap[fnode_row].size(); i++) { if(nodeToDofMap[fnode_row][i] == fdof_row) globalrow = nodeToGlobalMap[fnode_row][i]; } for (int i = 0; i < nodeToDofMap[fnode_col].size(); i++) { if (nodeToDofMap[fnode_col][i] == fdof_col) globalcol = nodeToGlobalMap[fnode_col][i]; } //std::cout << "Entry @ " << globalrow << " , " << globalcol << std::endl; if (globalrow > globalcol) { int temp = globalrow; globalrow = globalcol; globalcol = temp; } (*mySparseKReal)(globalrow, globalcol) = val; myK_row.push_back(globalrow); myK_col.push_back(globalcol); if (globalrow == globalcol) { if (val >= 1e36) { std::cout << "Error: DBC pivot found!"; exit(EXIT_FAILURE); } } } if (_printToFile) { std::cout << ">> Printing to file Staccato_Sparse_Stiffness.mtx..." << std::endl; (*mySparseKReal).writeSparseMatrixToFile("Staccato_Sparse_Stiffness", "mtx"); } } else if (std::string(matrixName) == std::string(massUMA_key)) { std::cout << " > Importing Me ..." << std::endl; mySparseMReal = new MathLibrary::SparseMatrix<double>(totalDOFs, true, true); for (iter.First(); !iter.IsDone(); iter.Next(), count++) { iter.Entry(row, col, val); int fnode_row = nodes[row]; int fdof_row = ldofs[row]; int fnode_col = nodes[col]; int fdof_col = ldofs[col]; int globalrow = -1; int globalcol = -1; for (int i = 0; i < nodeToDofMap[fnode_row].size(); i++) { if (nodeToDofMap[fnode_row][i] == fdof_row) globalrow = nodeToGlobalMap[fnode_row][i]; } for (int i = 0; i < nodeToDofMap[fnode_col].size(); i++) { if (nodeToDofMap[fnode_col][i] == fdof_col) globalcol = nodeToGlobalMap[fnode_col][i]; } //std::cout << "Entry @ " << globalrow << " , " << globalcol << std::endl; if (fnode_row >= 1e9 || fnode_col >= 1e9) { if (val != 0) { std::cout << ">> ERROR: Has entry." << std::endl; exit(EXIT_FAILURE); } } if (globalrow <= globalcol) (*mySparseMReal)(globalrow, globalcol) = val; else (*mySparseMReal)(globalcol, globalrow) = val; myM_row.push_back(globalrow); myM_col.push_back(globalcol); } if (_printToFile) { std::cout << ">> Printing to file Staccato_Sparse_Mass.mtx..." << std::endl; (*mySparseMReal).writeSparseMatrixToFile("Staccato_Sparse_Mass", "mtx"); } } else if (std::string(matrixName) == std::string(structuralDampingUMA_key)) { std::cout << " > Importing SDe ..." << std::endl; for (iter.First(); !iter.IsDone(); iter.Next(), count++) { iter.Entry(row, col, val); int fnode_row = nodes[row]; int fdof_row = ldofs[row]; int fnode_col = nodes[col]; int fdof_col = ldofs[col]; int globalrow = -1; int globalcol = -1; for (int i = 0; i < nodeToDofMap[fnode_row].size(); i++) { if (nodeToDofMap[fnode_row][i] == fdof_row) globalrow = nodeToGlobalMap[fnode_row][i]; } for (int i = 0; i < nodeToDofMap[fnode_col].size(); i++) { if (nodeToDofMap[fnode_col][i] == fdof_col) globalcol = nodeToGlobalMap[fnode_col][i]; } //std::cout << "Entry @ " << globalrow << " , " << globalcol << std::endl; if (globalrow > globalcol) { int temp = globalrow; globalrow = globalcol; globalcol = temp; } (*mySparseSDReal)(globalrow, globalcol) = val; mySD_row.push_back(globalrow); mySD_col.push_back(globalcol); if (globalrow == globalcol) { if (val >= 1e36) { std::cout << "Error: DBC pivot found!"; exit(EXIT_FAILURE); } } } if (_printToFile) { std::cout << ">> Printing to file Staccato_Sparse_StructuralDamping.mtx..." << std::endl; (*mySparseSDReal).writeSparseMatrixToFile("Staccato_Sparse_StructuralDamping", "mtx"); } }*/ } #endif
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_activation_u_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
//**************************************************************************************** // MIT License //**************************************************************************************** // Copyright (c) 2012-2020 University of Bremen, Germany. // Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany. // Copyright (c) 2020 Johannes Kepler University Linz, Austria. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //**************************************************************************************** #include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU16 : public rand_obj { randv<sc_bv<2> > op; randv<sc_uint<16> > a, b; ALU16(rand_obj* parent = 0) : rand_obj(parent), op(this), a(this), b(this) { constraint((op() != 0x0) || (65535 >= a() + b())); constraint((op() != 0x1) || ((65535 >= a() - b()) && (b() <= a()))); constraint((op() != 0x2) || (65535 >= a() * b())); constraint((op() != 0x3) || (b() != 0)); } friend std::ostream& operator<<(std::ostream& o, ALU16 const& alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b; return o; } }; int sc_main(int argc, char** argv) { crave::init("crave.cfg"); boost::timer timer; ALU16 c; CHECK(c.next()); std::cout << "first: " << timer.elapsed() << "\n"; for (int i = 0; i < 1000; ++i) { CHECK(c.next()); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
// ************************************************************************************** // User-defined memory manager, which maintains a pool of transactions // From TLM Duolos tutorials // ************************************************************************************** #ifndef TRANSACTION_MEMORY_MANAGER_CPP #define TRANSACTION_MEMORY_MANAGER_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> class mm: public tlm::tlm_mm_interface { typedef tlm::tlm_generic_payload gp_t; public: mm() : free_list(0), empties(0) #ifdef DEBUG , count(0) #endif // DEBUG {} gp_t* allocate() { #ifdef DEBUG cout << "----------------------------- Called allocate(), #trans = " << ++count << endl; #endif // DEBUG gp_t* ptr; if (free_list) { ptr = free_list->trans; empties = free_list; free_list = free_list->next; } else { ptr = new gp_t(this); } return ptr; } void free(gp_t* trans) { #ifdef DEBUG cout << "----------------------------- Called free(), #trans = " << --count << endl; #endif // DEBUG if (!empties) { empties = new access; empties->next = free_list; empties->prev = 0; if (free_list) free_list->prev = empties; } free_list = empties; free_list->trans = trans; empties = free_list->prev; } private: struct access { gp_t* trans; access* next; access* prev; }; access* free_list; access* empties; #ifdef DEBUG int count; #endif // DEBUG }; #endif // TRANSACTION_MEMORY_MANAGER_CPP
#include <systemc.h> #include "SYSTEM.h"
/******************************************************************************* * gpio_mf.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC model of a generic multi-function GPIO with * analog function. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "gpio_mf.h" #include "info.h" /********************* * Function: set_function() * inputs: new function * outputs: none * returns: none * globals: none * * Sets the function, can be GPIO or ANALOG. */ void gpio_mf::set_function(gpio_function_t newfunction) { /* We ignore unchanged function requests. */ if (newfunction == function) return; /* We also ignore illegal function requests. */ if (newfunction == GPIOMF_ANALOG) { PRINTF_WARN("GPIOMF", "%s cannot be set to ANALOG", name()) return; } /* To select a function there must be at least the fin or the fout * available. The fen is optional. Ideal would be to require all three * but there are some peripherals that need only one of these pins, * so to make life easier, we require at least a fin or a fout. */ if (newfunction >= GPIOMF_FUNCTION && (newfunction-1 >= fin.size() && newfunction-1 >= fout.size())) { PRINTF_WARN("GPIOMF", "%s cannot be set to FUNC%d", name(), newfunction) return; } /* When we change to the GPIO function, we set the driver high and set * the function accordingly. */ if (newfunction == GPIOMF_GPIO) { PRINTF_INFO("GPIOMF", "%s set to GPIO mode", name()) function = newfunction; driveok = true; /* set_val() handles the driver. */ gpio_base::set_val(pinval); } else { PRINTF_INFO("GPIOMF", "%s set to FUNC%d", name(), newfunction); function = newfunction; } /* And we set any notifications we need. */ updatefunc.notify(); updatereturn.notify(); } /********************* * Function: get_function() * inputs: none * outputs: none * returns: current function * globals: none * * Returns the current function. */ gpio_function_t gpio_mf::get_function() { return function; } /********************* * Function: set_val() * inputs: new value * outputs: none * returns: none * globals: none * * Changes the value to set onto the GPIO, if GPIO function is set. */ void gpio_mf::set_val(bool newval) { pinval = newval; if (function == GPIOMF_GPIO) gpio_base::set_val(newval); } /********************* * Thread: drive_return() * inputs: none * outputs: none * returns: none * globals: none * * Drives the return path from the pin onto the alternate functions. */ void gpio_mf::drive_return() { sc_logic pinsamp; bool retval; int func; /* We begin driving all returns to low. */ for (func = 0; func < fout.size(); func = func + 1) fout[func]->write(false); /* Now we go into the loop waiting for a return or a change in function. */ for(;;) { /* printf("<<%s>>: U:%d pin:%d:%c @%s\n", name(), updatereturn.triggered(), pin.event(), pin.read().to_char(), sc_time_stamp().to_string().c_str()); */ pinsamp = pin.read(); /* If the sampling value is Z or X and we have a function set, we * then issue a warning. We also do not warn at time 0s or we get some * dummy initialization warnings. */ if (sc_time_stamp() != sc_time(0, SC_NS) && (pinsamp == SC_LOGIC_X || pinsamp == SC_LOGIC_Z) && function != GPIOMF_ANALOG && function != GPIOMF_GPIO) { retval = false; PRINTF_WARN("GPIOMF", "can't return '%c' onto FUNC%d", pinsamp.to_char(), function) } else if (pinsamp == SC_LOGIC_1) retval = true; else retval = false; for (func = 0; func < fout.size(); func = func + 1) if (function == GPIOMF_ANALOG) fout[func]->write(false); else if (function == GPIOMF_GPIO) fout[func]->write(false); else if (func != function-1) fout[func]->write(false); else fout[func]->write(retval); wait(); } } /********************* * Thread: drive_func() * inputs: none * outputs: none * returns: none * globals: none * * Drives the value from an alternate function onto the pins. This does not * actually drive the value, it just places it in the correct variables so that * the drive() thread handles it. */ void gpio_mf::drive_func() { for(;;) { /* We only use this thread if we have an alternate function selected. */ if (function != GPIOMF_GPIO && function-1 < fin.size()) { /* We check if the fen is ok. If this function has no fen we default * it to enabled. */ if (function-1 < fen.size() || fen[function-1]->read() == true) driveok = true; else driveok = false; /* Note that we do not set the pin val, just call set_val to handle * the pin drive. */ gpio_base::set_val(fin[function-1]->read()); } /* We now wait for a change. If the function is no selected or if we * have an illegal function selected, we have to wait for a change * in the function selection. */ if (function == GPIOMF_GPIO || function-1 >= fin.size()) wait(updatefunc); /* If we have a valid function selected, we wait for either the * function or the fen to change. We also have to wait for a * function change. */ else if (fen.size() >= function-1) wait(updatefunc | fin[function-1]->value_changed_event()); else wait(updatefunc | fin[function-1]->value_changed_event() | fen[function-1]->value_changed_event()); } }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_divider_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_divider vector_divider("VECTOR_DIVIDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_divider.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_divider.data_a_in[i](data_a_in[i]); vector_divider.data_b_in[i](data_b_in[i]); vector_divider.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** stimulus.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "stimulus.h" void stimulus::entry() { cycle++; // sending some reset values if (cycle<4) { reset.write(true); input_valid.write(false); } else { reset.write(false); input_valid.write( false ); // sending normal mode values if (cycle%10==0) { input_valid.write(true); sample.write( (int)send_value1 ); cout << "Stimuli : " << (int)send_value1 << " at time " /* << sc_time_stamp() << endl; */ << sc_time_stamp().to_double() << endl; send_value1++; }; } }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** stimulus.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "stimulus.h" void stimulus::entry() { cycle++; // sending some reset values if (cycle<4) { reset.write(true); input_valid.write(false); } else { reset.write(false); input_valid.write( false ); // sending normal mode values if (cycle%10==0) { input_valid.write(true); sample.write( (int)send_value1 ); cout << "Stimuli : " << (int)send_value1 << " at time " /* << sc_time_stamp() << endl; */ << sc_time_stamp().to_double() << endl; send_value1++; }; } }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #include "systemc.h" #include "tlm.h" #include <vector> #include <iomanip> using namespace sc_core; using namespace tlm; using std::vector; //------------------------------------------------------------------------------ // Title: UVMC Converter Example - SC Adapter Class // // This example demonstrates how to define a custom converter for a transaction // class whose members differ in number, type, and size from the corresponding // transaction definition in SV. This situation can arise in cases where the // transaction types are pre-existing in both SC and SV yet have compatible // content. // // (see UVMC_Converters_SC_UserDefinedAdapter.png) // // Because most SC transactions do not implement the pack and unpack member // functions required by the default converter, a template specialization // definition is required. A template specialization can be defined by hand or // via a <UVMC_UTILS> macro, which defines the same converter specialization // plus the operator<< for the default output stream (cout). This allows you // to print your packet contents using cout << my_packet; // // Template specializations are chosen automatically by the C+ compiler, so // you will not need to specify the converter type explicitly when connecting // via <The Connect Function>. // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Group: User Library // // This section defines a transaction class and generic consumer model. We will // define a converter for this packet, then connect an instance of the consumer // with an SV-side producer using a blocking put interface conveying that // transaction. //------------------------------------------------------------------------------ // (begin inline source) namespace user_lib { class packet { public: short addr_hi; short addr_lo; unsigned int payload[4]; char len; bool write; // 1=write, 0=read }; } // (end inline source) //------------------------------------------------------------------------------ // Group: Conversion code // // This section defines a converter specialization for our 'packet' transaction // type. We can not use the default converter because it delegates to ~pack~ and // ~unpack~ methods of the transaction, which our packet class doesn't have. // // So, we define a converter template specialization for our packet type. Your // transaction converters would implement the same template. // // The definition of a SC-side converter specialization is so regular that a // set of convenient macros have been developed to produce a converter class // definition for you. You would invoke one of the macros from the set, // depending on the number of fields in your transaction class and whether it // inherits from a base class. // See <UVMC Converter Example - SC Converter Class, Macro-Generated> for // for an example of using the <UVMC_UTILS> macros. // // // The corresponding transaction in SV declares the following fields, split // across two classes (one inheriting from the other), in the given order. // //| class packet_base extends uvm_sequence_item: //| typedef enum {WRITE, READ, NOOP} cmd_t; //| cmd_t cmd; //| int addr; //| byte data[$]; //| endclass //| //| class packet: //| int extra_int; //| endclass // // If we could define our SC-side transaction to suit this definition, we'd // mirror the types, declaration order, and even the inheritance hierarchy. // In this example, however, we are faced with having to adapt to a // pre-existing transaction type. // // When writing the converters on the SV and SC side, we can choose three // different ways: // // 1: Let the SC converter pack/unpack normally; implement a custom SV // converter to convert according to how the SC side expects to receive // the bits. // // 2: Let the SV converter pack/unpack normally; implement a SC converter // specialization of the default SC converter to convert according to // how the SV side expects to receive the bits. // // 3: Let the SV converter pack/unpack normally; implement a subtype to // the SC converter specialization to convert according to how the SV // side expects to receive the bits. Specify the custom converter type // when calling uvmc_connect. // // A converter specialization, e.g. ~template <> class uvmc_converter<packet>~, // should be reserved for converting the SC transaction as it is defined, // streaming each field in order and without adaptation. It should not // be used to adapt to a custom mapping on the SV side, as in this example. // For this reason, option 3 is the best. // // The ~packet~ transaction in SV will be packed normally: ~cmd~, ~addr~, // ~data~, and ~extra_int~. The SV packetized bits, assuming 3 bytes in // the data array, looks like this: // //| ____________________________________ //| | cmd | addr |d0|d1|d2|extra_int| //| |________|________|__|__|__|_________| //| 0 32 64 72 80 88 // // In SC, we shall adapt as follows // // - map the 32-bit ~cmd~ from SV to a single ~bool~ in SV // // - map the 32-bit ~addr~ from SV to two ~addr_lo~ and ~addr_hi~ 16-bit // values in SC // // - map the ~data~ byte array data from SV to an integer array in SV // // When dealing with built-in types, you should account for the endianess // of your machine's architecture. This example assumes a little-endian // architecture. // //------------------------------------------------------------------------------ // (begin inline source) #include <vector> #include <iomanip> using std::vector; #include "uvmc.h" using namespace uvmc; using namespace user_lib; struct packet_converter : public uvmc_converter<packet> { static void do_pack(const packet &t, uvmc_packer &packer) { int cmd_tmp; if (t.write) cmd_tmp = 0; else cmd_tmp = 1; packer << cmd_tmp << t.addr_lo << t.addr_hi << (int)(t.len) << t.payload; } static void do_unpack(packet &t, uvmc_packer &packer) { int cmd_tmp; vector<unsigned char> data_tmp; packer >> cmd_tmp >> t.addr_lo >> t.addr_hi >> data_tmp; t.len = data_tmp.size(); if (cmd_tmp == 0) t.write = 1; else if (cmd_tmp == 1) t.write = 0; else cout << "packet cmd from SV side has unsupported value " << cmd_tmp << endl; for (int i=0;i<4;i++) t.payload[i]=0; for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { if ((i*4+j)<t.len) { int b; b = data_tmp[i*4+j] << (8*j); t.payload[i] = t.payload[i] | b; } else { break; } } } } }; UVMC_PRINT_4(packet,addr_hi,addr_lo,len,write) // (end inline source) //------------------------------------------------------------------------------ // Group: Testbench code // // This section defines our testbench environment. In the top-level module, we // instantiate the generic consumer model. We also register the consumer's 'in' // export to have a UVMC connection with a lookup string 'stimulus'. The // SV-side will register its producer's 'out' port with the same 'stimulus' // lookup string. UVMC will match these two strings to complete the cross- // language connection, i.e. the SV producer's ~out~ port will be bound to the // SC consumer's ~in~ export. //------------------------------------------------------------------------------ // (begin inline source) #include "systemc.h" #include "tlm.h" using namespace sc_core; using namespace tlm; // a generic target with a TLM1 put export #include "consumer.cpp" class sc_env : public sc_module { public: consumer<packet> cons; sc_env(sc_module_name nm) : cons("cons") { uvmc_connect<packet_converter>(cons.in,"stimulus"); uvmc_connect<packet_converter>(cons.ap,"checker"); } }; // Define sc_main, the vendor-independent means of starting a // SystemC simulation. int sc_main(int argc, char* argv[]) { sc_env env("env"); sc_start(); return 0; } // (end inline source)
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_memory_matrix_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_memory_matrix_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_memory_matrix_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_memory_matrix_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/******************************************************************************* * esp_wifi.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file ports the esp_wifi functions for the ESP32 to the ESPMOD SystemC * model. It was based off the functions from Espressif Systems. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was based off the work covered by the license below: * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <systemc.h> #include "WiFi.h" #include "info.h" #include <IPAddress.h> #include "esp_system.h" #include "esp_err.h" #include "WiFiType.h" #include "esp_wifi_types.h" #include "wifistat.h" #include "esp_wifi.h" #include "lwip/sockets.h" #include <string.h> wifistat_t wifistat; /** * @brief Init WiFi * Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer, * WiFi NVS structure etc, this WiFi also start WiFi task * * @attention 1. This API must be called before all other WiFi API can be called * @attention 2. Always use WIFI_INIT_CONFIG_DEFAULT macro to init the config to default values, this can * guarantee all the fields got correct value when more fields are added into wifi_init_config_t * in future release. If you want to set your owner initial values, overwrite the default values * which are set by WIFI_INIT_CONFIG_DEFAULT, please be notified that the field 'magic' of * wifi_init_config_t should always be WIFI_INIT_CONFIG_MAGIC! * * @param config pointer to WiFi init configuration structure; can point to a temporary variable. * * @return * - ESP_OK: succeed * - ESP_ERR_NO_MEM: out of memory * - others: refer to error code esp_err.h */ esp_err_t esp_wifi_init(const wifi_init_config_t *config) { PRINTF_INFO("WIFI", "Initializing"); wifistat.initialized = true; wifistat.started = false; wifistat.stat = WL_IDLE_STATUS; return ESP_OK; } /** * @brief Deinit WiFi * Free all resource allocated in esp_wifi_init and stop WiFi task * * @attention 1. This API should be called if you want to remove WiFi driver from the system * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_deinit(void) { SC_REPORT_INFO("WIFI", "De-Init"); if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; wifistat.initialized = false; wifistat.started = false; wifistat.connected = false; return ESP_OK; } /** * @brief Set the WiFi operating mode * * Set the WiFi operating mode as station, soft-AP or station+soft-AP, * The default mode is soft-AP mode. * * @param mode WiFi operating mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_set_mode(wifi_mode_t mode) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else switch(mode) { case WIFI_MODE_STA: SC_REPORT_INFO("WIFI", "Setting WiFi to Station Mode"); wifistat.mode = mode; return ESP_OK; case WIFI_MODE_NULL: SC_REPORT_INFO("WIFI", "Switching WiFi Off"); wifistat.mode = mode; return ESP_OK; case WIFI_MODE_AP: SC_REPORT_INFO("WIFI", "Setting WiFi to AP Mode"); wifistat.mode = mode; return ESP_OK; case WIFI_MODE_APSTA: SC_REPORT_INFO("WIFI", "Setting WiFi to AP/STA Mode"); wifistat.mode = mode; return ESP_OK; default: return ESP_ERR_INVALID_ARG; } } /** * @brief Get current operating mode of WiFi * * @param[out] mode store current WiFi mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_mode(wifi_mode_t *mode) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else if (mode == NULL) return ESP_ERR_INVALID_ARG; else *mode = wifistat.mode; return ESP_OK; } /** * @brief Start WiFi according to current configuration * If mode is WIFI_MODE_STA, it create station control block and start station * If mode is WIFI_MODE_AP, it create soft-AP control block and start soft-AP * If mode is WIFI_MODE_APSTA, it create soft-AP and station control block and start soft-AP and station * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_NO_MEM: out of memory * - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong * - ESP_FAIL: other WiFi internal errors */ esp_err_t esp_wifi_start(void) { system_event_t ev; /* This is actually done by the init before the firmware loads, but we do * it here for lack of a better place. */ if (!wifistat.initialized) esp_wifi_init(NULL); /* Now we start the interface. */ if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; wifistat.started = true; wifistat.connected = false; if (wifistat.mode == WIFI_MODE_STA || wifistat.mode == WIFI_MODE_APSTA) { ev.event_id = SYSTEM_EVENT_STA_START; WiFiClass::_eventCallback(NULL, &ev); } if (wifistat.mode == WIFI_MODE_AP || wifistat.mode == WIFI_MODE_APSTA) { ev.event_id = SYSTEM_EVENT_AP_START; WiFiClass::_eventCallback(NULL, &ev); } return ESP_OK; } /** * @brief Stop WiFi * If mode is WIFI_MODE_STA, it stop station and free station control block * If mode is WIFI_MODE_AP, it stop soft-AP and free soft-AP control block * If mode is WIFI_MODE_APSTA, it stop station/soft-AP and free station/soft-AP control block * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_stop(void) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else return ESP_OK; } /** * @brief Restore WiFi stack persistent settings to default values * * This function will reset settings made using the following APIs: * - esp_wifi_get_auto_connect, * - esp_wifi_set_protocol, * - esp_wifi_set_config related * - esp_wifi_set_mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_restore(void) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; /* Set default settings. */ return ESP_OK; } /** * @brief Connect the ESP32 WiFi station to the AP. * * @attention 1. This API only impact WIFI_MODE_STA or WIFI_MODE_APSTA mode * @attention 2. If the ESP32 is connected to an AP, call esp_wifi_disconnect to disconnect. * @attention 3. The scanning triggered by esp_wifi_start_scan() will not be effective until connection between ESP32 and the AP is established. * If ESP32 is scanning and connecting at the same time, ESP32 will abort scanning and return a warning message and error * number ESP_ERR_WIFI_STATE. * If you want to do reconnection after ESP32 received disconnect event, remember to add the maximum retry time, otherwise the called * scan will not work. This is especially true when the AP doesn't exist, and you still try reconnection after ESP32 received disconnect * event with the reason code WIFI_REASON_NO_AP_FOUND. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start * - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong * - ESP_ERR_WIFI_SSID: SSID of AP which station connects is invalid */ esp_err_t esp_wifi_connect(void) { system_event_t ev; if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; if (wifistat.conf.sta.ssid[0] == '\0' || strlen((const char *)wifistat.conf.sta.ssid)>31) return ESP_ERR_WIFI_SSID; if (strchr((const char *)wifistat.conf.sta.ssid, ' ') != NULL) PRINTF_WARN("WIFI", "Found a space in the SSID, what is legal but often not supported."); /* If we are running a DHCP, we need to set the IP addresses. We then * pick something as we do not actually have a server. */ if (wifistat.dhcp_c) { wifistat.ip_info.ip.addr = IPAddress(192, 76, 0, 100); wifistat.ip_info.gw.addr = IPAddress(192, 76, 0, 1); wifistat.ip_info.netmask.addr = IPAddress(255, 255, 255, 0); } /* We call the callback */ ev.event_id = SYSTEM_EVENT_STA_GOT_IP; ev.event_info.got_ip.ip_info.ip = wifistat.ip_info.ip; ev.event_info.got_ip.ip_info.gw = wifistat.ip_info.gw; ev.event_info.got_ip.ip_info.netmask = wifistat.ip_info.netmask; /* If the IP changed we note tag it. */ if (wifistat.current_ip != wifistat.ip_info.ip.addr) ev.event_info.got_ip.ip_changed = true; else ev.event_info.got_ip.ip_changed = false; WiFiClass::_eventCallback(NULL, &ev); /* And we do the connection. */ wifistat.connected = true; wifistat.current_ip = wifistat.ip_info.ip.addr; return ESP_OK; } /** * @brief Disconnect the ESP32 WiFi station from the AP. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi was not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_FAIL: other WiFi internal errors */ esp_err_t esp_wifi_disconnect(void) { system_event_t ev; if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; /* We call the callback */ ev.event_id = SYSTEM_EVENT_STA_DISCONNECTED; /* For now it is the only one */ ev.event_info.disconnected.reason = WIFI_REASON_UNSPECIFIED; WiFiClass::_eventCallback(NULL, &ev); /* And we do the connection. */ wifistat.connected = false; return ESP_OK; } /** * @brief Currently this API is just an stub API * * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_wifi_clear_fast_connect(void); /** * @brief deauthenticate all stations or associated id equals to aid * * @param aid when aid is 0, deauthenticate all stations, otherwise deauthenticate station whose associated id is aid * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_MODE: WiFi mode is wrong */ esp_err_t esp_wifi_deauth_sta(uint16_t aid); /** * @brief Scan all available APs. * * @attention If this API is called, the found APs are stored in WiFi driver dynamic allocated memory and the * will be freed in esp_wifi_scan_get_ap_records, so generally, call esp_wifi_scan_get_ap_records to cause * the memory to be freed once the scan is done * @attention The values of maximum active scan time and passive scan time per channel are limited to 1500 milliseconds. * Values above 1500ms may cause station to disconnect from AP and are not recommended. * * @param config configuration of scanning * @param block if block is true, this API will block the caller until the scan is done, otherwise * it will return immediately * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_ERR_WIFI_TIMEOUT: blocking scan is timeout * - ESP_ERR_WIFI_STATE: wifi still connecting when invoke esp_wifi_scan_start * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block); /** * @brief Stop the scan in process * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start */ esp_err_t esp_wifi_scan_stop(void); /** * @brief Get number of APs found in last scan * * @param[out] number store number of APIs found in last scan * * @attention This API can only be called when the scan is completed, otherwise it may get wrong value. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_scan_get_ap_num(uint16_t *number); /** * @brief Get AP list found in last scan * * @param[inout] number As input param, it stores max AP number ap_records can hold. * As output param, it receives the actual AP number this API returns. * @param ap_records wifi_ap_record_t array to hold the found APs * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_NO_MEM: out of memory */ esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_records); /** * @brief Get information of AP which the ESP32 station is associated with * * @param ap_info the wifi_ap_record_t to hold AP information * sta can get the connected ap's phy mode info through the struct member * phy_11b,phy_11g,phy_11n,phy_lr in the wifi_ap_record_t struct. * For example, phy_11b = 1 imply that ap support 802.11b mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_CONN: The station interface don't initialized * - ESP_ERR_WIFI_NOT_CONNECT: The station is in disconnect status */ esp_err_t esp_wifi_sta_get_ap_info(wifi_ap_record_t *ap_info) { if (!wifistat.initialized) return ESP_ERR_WIFI_CONN; if (!wifistat.started) return ESP_ERR_WIFI_CONN; if (!wifistat.connected) return ESP_ERR_WIFI_NOT_CONNECT; if (ap_info == NULL) return ESP_ERR_INVALID_ARG; /* NOT IN THE LIST */ memcpy((void *)ap_info, (void *)&wifistat.ap_info, sizeof(wifi_ap_record_t)); return ESP_OK; } /** * @brief Set current WiFi power save type * * @attention Default power save type is WIFI_PS_MIN_MODEM. * * @param type power save type * * @return ESP_OK: succeed */ esp_err_t esp_wifi_set_ps(wifi_ps_type_t type) { wifistat.pstype = type; return ESP_OK; } /** * @brief Get current WiFi power save type * * @attention Default power save type is WIFI_PS_MIN_MODEM. * * @param[out] type: store current power save type * * @return ESP_OK: succeed */ esp_err_t esp_wifi_get_ps(wifi_ps_type_t *type) { if (type == NULL) return ESP_ERR_INVALID_ARG; /* NOT IN THE LIST */ *type = wifistat.pstype; return ESP_OK; } /** * @brief Set protocol type of specified interface * The default protocol is (WIFI_PROTOCOL_11B|WIFI_PROTOCOL_11G|WIFI_PROTOCOL_11N) * * @attention Currently we only support 802.11b or 802.11bg or 802.11bgn mode * * @param ifx interfaces * @param protocol_bitmap WiFi protocol bitmap * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_set_protocol(wifi_interface_t ifx, uint8_t protocol_bitmap); /** * @brief Get the current protocol bitmap of the specified interface * * @param ifx interface * @param[out] protocol_bitmap store current WiFi protocol bitmap of interface ifx * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_get_protocol(wifi_interface_t ifx, uint8_t *protocol_bitmap); /** * @brief Set the bandwidth of ESP32 specified interface * * @attention 1. API return false if try to configure an interface that is not enabled * @attention 2. WIFI_BW_HT40 is supported only when the interface support 11N * * @param ifx interface to be configured * @param bw bandwidth * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_set_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t bw); /** * @brief Get the bandwidth of ESP32 specified interface * * @attention 1. API return false if try to get a interface that is not enable * * @param ifx interface to be configured * @param[out] bw store bandwidth of interface ifx * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t *bw); /** * @brief Set primary/secondary channel of ESP32 * * @attention 1. This is a special API for sniffer * @attention 2. This API should be called after esp_wifi_start() or esp_wifi_set_promiscuous() * * @param primary for HT20, primary is the channel number, for HT40, primary is the primary channel * @param second for HT20, second is ignored, for HT40, second is the second channel * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_channel(uint8_t primary, wifi_second_chan_t second) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_CONN; if (primary > 13) return ESP_ERR_INVALID_ARG; wifistat.conf.sta.channel = primary; return ESP_OK; } /** * @brief Get the primary/secondary channel of ESP32 * * @attention 1. API return false if try to get a interface that is not enable * *
@param primary store current primary channel * @param[out] second store current second channel * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else if (primary == NULL || second == NULL) return ESP_ERR_INVALID_ARG; *primary = wifistat.conf.sta.channel; *second = WIFI_SECOND_CHAN_NONE; return ESP_OK; } /** * @brief configure country info * * @attention 1. The default country is {.cc="CN", .schan=1, .nchan=13, policy=WIFI_COUNTRY_POLICY_AUTO} * @attention 2. When the country policy is WIFI_COUNTRY_POLICY_AUTO, the country info of the AP to which * the station is connected is used. E.g. if the configured country info is {.cc="USA", .schan=1, .nchan=11} * and the country info of the AP to which the station is connected is {.cc="JP", .schan=1, .nchan=14} * then the country info that will be used is {.cc="JP", .schan=1, .nchan=14}. If the station disconnected * from the AP the country info is set back back to the country info of the station automatically, * {.cc="USA", .schan=1, .nchan=11} in the example. * @attention 3. When the country policy is WIFI_COUNTRY_POLICY_MANUAL, always use the configured country info. * @attention 4. When the country info is changed because of configuration or because the station connects to a different * external AP, the country IE in probe response/beacon of the soft-AP is changed also. * @attention 5. The country configuration is not stored into flash * @attention 6. This API doesn't validate the per-country rules, it's up to the user to fill in all fields according to * local regulations. * * @param country the configured country info * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_country(const wifi_country_t *country); /** * @brief get the current country info * * @param country country info * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_country(wifi_country_t *country); /** * @brief Set MAC address of the ESP32 WiFi station or the soft-AP interface. * * @attention 1. This API can only be called when the interface is disabled * @attention 2. ESP32 soft-AP and station have different MAC addresses, do not set them to be the same. * @attention 3. The bit 0 of the first byte of ESP32 MAC address can not be 1. For example, the MAC address * can set to be "1a:XX:XX:XX:XX:XX", but can not be "15:XX:XX:XX:XX:XX". * * @param ifx interface * @param mac the MAC address * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_WIFI_MAC: invalid mac address * - ESP_ERR_WIFI_MODE: WiFi mode is wrong * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_set_mac(wifi_interface_t ifx, const uint8_t mac[6]) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (ifx != WIFI_IF_STA && ifx != WIFI_IF_AP) return ESP_ERR_INVALID_ARG; PRINTF_WARN("WIFI", "esp_wifi_set_mac currently is unsupported."); return ESP_OK; } /** * @brief Get mac of specified interface * * @param ifx interface * @param[out] mac store mac of the interface ifx * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface */ esp_err_t esp_wifi_get_mac(wifi_interface_t ifx, uint8_t mac[6]) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (ifx != WIFI_IF_STA && ifx != WIFI_IF_AP) return ESP_ERR_INVALID_ARG; switch(ifx) { case WIFI_IF_STA: mac[0] = 0x55; mac[1] = 0x37; mac[2] = 0xce; mac[3] = 0x99; mac[4] = 0x75; mac[5] = 0x1E; return ESP_OK; case WIFI_IF_AP: mac[0] = 0x55; mac[1] = 0x37; mac[2] = 0xce; mac[3] = 0x99; mac[4] = 0x75; mac[5] = 0x39; return ESP_OK; default: return ESP_ERR_INVALID_ARG; } } /** * @brief The RX callback function in the promiscuous mode. * Each time a packet is received, the callback function will be called. * * @param buf Data received. Type of data in buffer (wifi_promiscuous_pkt_t or wifi_pkt_rx_ctrl_t) indicated by 'type' parameter. * @param type promiscuous packet type. * */ typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type); /** * @brief Register the RX callback function in the promiscuous mode. * * Each time a packet is received, the registered callback function will be called. * * @param cb callback * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb); /** * @brief Enable the promiscuous mode. * * @param en false - disable, true - enable * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous(bool en); /** * @brief Get the promiscuous mode. * * @param[out] en store the current status of promiscuous mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_promiscuous(bool *en); /** * @brief Enable the promiscuous mode packet type filter. * * @note The default filter is to filter all packets except WIFI_PKT_MISC * * @param filter the packet type filtered in promiscuous mode. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous_filter(const wifi_promiscuous_filter_t *filter); /** * @brief Get the promiscuous filter. * * @param[out] filter store the current status of promiscuous filter * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_promiscuous_filter(wifi_promiscuous_filter_t *filter); /** * @brief Enable subtype filter of the control packet in promiscuous mode. * * @note The default filter is to filter none control packet. * * @param filter the subtype of the control packet filtered in promiscuous mode. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous_ctrl_filter(const wifi_promiscuous_filter_t *filter); /** * @brief Get the subtype filter of the control packet in promiscuous mode. * * @param[out] filter store the current status of subtype filter of the control packet in promiscuous mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_promiscuous_ctrl_filter(wifi_promiscuous_filter_t *filter); /** * @brief Set the configuration of the ESP32 STA or AP * * @attention 1. This API can be called only when specified interface is enabled, otherwise, API fail * @attention 2. For station configuration, bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP. * @attention 3. ESP32 is limited to only one channel, so when in the soft-AP+station mode, the soft-AP will adjust its channel automatically to be the same as * the channel of the ESP32 station. * * @param interface interface * @param conf station or soft-AP configuration * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_WIFI_MODE: invalid mode * - ESP_ERR_WIFI_PASSWORD: invalid password * - ESP_ERR_WIFI_NVS: WiFi internal NVS error * - others: refer to the erro code in esp_err.h */ esp_err_t esp_wifi_set_config(wifi_interface_t interface, wifi_config_t *conf) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (conf == NULL) return ESP_ERR_INVALID_ARG; if (interface == WIFI_IF_STA) { if (strlen((const char *)(conf->sta.password)) > 64) { return ESP_ERR_WIFI_PASSWORD; } } else if (interface == WIFI_IF_AP) { if (strlen((char *)conf->ap.password) > 0 && strlen((char *)conf->ap.password) < 8 || strlen((char *)conf->ap.password) > 64) return ESP_ERR_WIFI_PASSWORD; /* We have no DHCP server, so for lack of a better place, we also set the * IP here. */ if (!wifistat.dhcp_s) { wifistat.ip_info.ip.addr = IPAddress(192, 76, 0, 1); wifistat.ip_info.gw.addr = IPAddress(192, 76, 0, 1); wifistat.ip_info.netmask.addr = IPAddress(255, 255, 255, 0); } } else return ESP_ERR_INVALID_ARG; memcpy((void *)&wifistat.conf, (void *)conf, sizeof(wifi_config_t)); return ESP_OK; } /** * @brief Get configuration of specified interface * * @param interface interface * @param[out] conf station or soft-AP configuration * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface */ esp_err_t esp_wifi_get_config(wifi_interface_t interface, wifi_config_t *conf) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (conf == NULL) return ESP_ERR_INVALID_ARG; if (interface != WIFI_IF_STA && interface != WIFI_IF_AP) return ESP_ERR_INVALID_ARG; if (interface == WIFI_IF_STA) { if (wifistat.mode != WIFI_MODE_STA && wifistat.mode != WIFI_MODE_APSTA) { return ESP_ERR_WIFI_IF; } } else if (interface == WIFI_IF_AP) { if (wifistat.mode != WIFI_MODE_AP && wifistat.mode != WIFI_MODE_APSTA) { return ESP_ERR_WIFI_IF; } } else return ESP_ERR_INVALID_ARG; memcpy((void *)conf, (void *)&wifistat.conf, sizeof(wifi_config_t)); return ESP_OK; } /** * @brief Get STAs associated with soft-AP * * @attention SSC only API * * @param[out] sta station list * ap can get the connected sta's phy mode info through the struct member * phy_11b,phy_11g,phy_11n,phy_lr in the wifi_sta_info_t struct. * For example, phy_11b = 1 imply that sta support 802.11b mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_MODE: WiFi mode is wrong * - ESP_ERR_WIFI_CONN: WiFi internal error, the station/soft-AP control block is invalid */ esp_err_t esp_wifi_ap_get_sta_list(wifi_sta_list_t *sta) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (sta == NULL) return ESP_ERR_INVALID_ARG; if (wifistat.mode == WIFI_MODE_STA) return ESP_ERR_WIFI_MODE; memcpy((void *)sta, (void *)&wifistat.sta_list, sizeof(wifi_sta_list_t)); return ESP_OK; } /** * @brief Set the WiFi API configuration storage type * * @attention 1. The default value is WIFI_STORAGE_FLASH * * @param storage : storage type * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_storage(wifi_storage_t storage); /** * @brief Set auto connect * The default value is true * * @param en : true - enable auto connect / false - disable auto connect * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_MODE: WiFi internal error, the station/soft-AP control block is invalid * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_set_auto_connect(bool en) { return ESP_OK; } /** * @brief Get the auto connect flag * * @param[out] en store current auto connect configuration * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_auto_connect(bool *en) { return ESP_OK; } /** * @brief Set 802.11 Vendor-Specific Information Element * * @param enable If true, specified IE is enabled. If false, specified IE is removed. * @param type Information Element type. Determines the frame type to associate with the IE. * @param idx Index to set or clear. Each IE type can be associated with up to two elements (indices 0 & 1). * @param vnd_ie Pointer to vendor specific element data. First 6 bytes should be a header with fields matching vendor_ie_data_t. * If enable is false, this argument is ignored and can be NULL. Data does not need to remain valid after the function returns. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init() * - ESP_ERR_INVALID_ARG: Invalid argument, including if first byte of vnd_ie is not WIFI_VENDOR_IE_ELEMENT_ID (0xDD) * or second byte is an invalid length. * - ESP_ERR_NO_MEM: Out of memory */ esp_err_t esp_wifi_set_vendor_ie(bool enable, wifi_vendor_ie_type_t type, wifi_vendor_ie_id_t idx, const void *vnd_ie); /** * @brief Function signature for received Vendor-Specific Information Element callback. * @param ctx Context argument, as passed to esp_wifi_set_vendor_ie_cb() when registering callback. * @param type Information element type, based on frame type received. * @param sa Source 802.11 address. * @param vnd_ie Pointer to the vendor specific element data received. * @param rssi Received signal strength indication. */ typedef void (*esp_vendor_ie_cb_t) (void *ctx, wifi_vendor_ie_type_t type, const uint8_t sa[6], const vendor_ie_data_t *vnd_ie, int rssi); /** * @brief Register Vendor-Specific Information Element monitoring callback. * * @param cb Callback function * @param ctx Context argument, passed to callback function. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_vendor_ie_cb(esp_vendor_ie_cb_t cb, void *ctx); /** * @brief Set maximum WiFi transmiting power * * @attention WiFi transmiting power is divided to six levels in phy init data. * Level0 represents highest transmiting power and level5 represents lowest * transmiting power. Packets of different rates are transmitted in * different powers according to the configuration in phy init data. * This API only sets maximum WiFi transmiting power. If this API is called, * the transmiting power of every packet will be less than or equal to the * value set by this API. If this API is not called, the value of maximum * transmitting power set in phy_init_data.bin or menuconfig (depend on * whether to use phy init data in partition or not) will be used. Default * value is level0. Values passed in power are mapped to transmit power * levels as follows: * - [78, 127]: level0 * - [76, 77]: level1 * - [74, 75]: level2 * - [68, 73]: level3 * - [60, 67]: level4 * - [52, 59]: level5 * - [44, 51]: level5 - 2dBm * - [34, 43]: level5 - 4.5dBm * - [28, 33]: level5 - 6dBm * - [20, 27]: level5 - 8dBm * - [8, 19]: level5 - 11dBm * - [-128, 7]: level5 - 14dBm * * @param power Maximum WiFi transmiting power. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start */ esp_err_t esp_wifi_set_max_tx_power(int8_t power) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; wifistat.power = power; return ESP_OK; } /** * @brief Get maximum WiFi transmiting power * * @attention This API gets maximum WiFi transmiting power. Values got * from power are mapped to transmit power levels as follows: * - 78: 19.5dBm * - 76: 19dBm * - 74: 18.5dBm * - 68: 17dBm * - 60: 15dBm * - 52: 13dBm * - 44: 11dBm * - 34: 8.5dBm * - 28: 7dBm * - 20: 5dBm * - 8: 2dBm * - -4: -1dBm * * @param power Maximum WiFi transmiting power. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_max_tx_power(int8_t *power) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; if (power == NULL) return ESP_ERR_INVALID_ARG; *power = wifistat.power; return ESP_OK; } /** * @brief Set mask to enable or disable some WiFi events * * @attention 1. Mask can be created by logical OR of various WIFI_EVENT_MASK_ constants. * Events which have corresponding bit set in the mask will not be delivered to the system event handler. * @attention 2. Default WiFi event mask is WIFI_EVENT_MASK_AP_PROBEREQRECVED. * @attention 3. There may be lots of stations sending probe request data around. * Don't unmask this event unless you need to receive probe request data. * * @param mask WiFi event mask. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_event_mask(uint32_t mask) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; wifistat.mask = mask; return ESP_OK; } /** * @brief Get mask of WiFi events * * @param mask WiFi event mask. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_event_mask(uint32_t *mask) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (mask == NULL) return ESP_ERR_INVALID_ARG; *mask = wifistat.mask; return ESP_OK; } /** * @brief Send raw ieee80211 data * * @attention Currently only support for sending beacon/probe request/probe response/action and non-QoS * data frame * * @param ifx interface if the Wi-Fi mode is Station, the ifx should be WIFI_IF_STA. If the Wi-Fi * mode is SoftAP, the ifx should be WIFI_IF_AP. If the Wi-Fi mode is Station+SoftAP, the * ifx should be W
IFI_IF_STA or WIFI_IF_AP. If the ifx is wrong, the API returns ESP_ERR_WIFI_IF. * @param buffer raw ieee80211 buffer * @param len the length of raw buffer, the len must be <= 1500 Bytes and >= 24 Bytes * @param en_sys_seq indicate whether use the internal sequence number. If en_sys_seq is false, the * sequence in raw buffer is unchanged, otherwise it will be overwritten by WiFi driver with * the system sequence number. * Generally, if esp_wifi_80211_tx is called before the Wi-Fi connection has been set up, both * en_sys_seq==true and en_sys_seq==false are fine. However, if the API is called after the Wi-Fi * connection has been set up, en_sys_seq must be true, otherwise ESP_ERR_INVALID_ARG is returned. * * @return * - ESP_OK: success * - ESP_ERR_WIFI_IF: Invalid interface * - ESP_ERR_INVALID_ARG: Invalid parameter * - ESP_ERR_WIFI_NO_MEM: out of memory */ esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq); /** * @brief The RX callback function of Channel State Information(CSI) data. * * Each time a CSI data is received, the callback function will be called. * * @param ctx context argument, passed to esp_wifi_set_csi_rx_cb() when registering callback function. * @param data CSI data received. The memory that it points to will be deallocated after callback function returns. * */ typedef void (* wifi_csi_cb_t)(void *ctx, wifi_csi_info_t *data); /** * @brief Register the RX callback function of CSI data. * * Each time a CSI data is received, the callback function will be called. * * @param cb callback * @param ctx context argument, passed to callback function * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_csi_rx_cb(wifi_csi_cb_t cb, void *ctx); /** * @brief Set CSI data configuration * * @param config configuration * * return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_csi_config(const wifi_csi_config_t *config); /** * @brief Enable or disable CSI * * @param en true - enable, false - disable * * return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_csi(bool en); /** * @brief Set antenna GPIO configuration * * @param config Antenna GPIO configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: Invalid argument, e.g. parameter is NULL, invalid GPIO number etc */ esp_err_t esp_wifi_set_ant_gpio(const wifi_ant_gpio_config_t *config); /** * @brief Get current antenna GPIO configuration * * @param config Antenna GPIO configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument, e.g. parameter is NULL */ esp_err_t esp_wifi_get_ant_gpio(wifi_ant_gpio_config_t *config); /** * @brief Set antenna configuration * * @param config Antenna configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: Invalid argument, e.g. parameter is NULL, invalid antenna mode or invalid GPIO number */ esp_err_t esp_wifi_set_ant(const wifi_ant_config_t *config); /** * @brief Get current antenna configuration * * @param config Antenna configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument, e.g. parameter is NULL */ esp_err_t esp_wifi_get_ant(wifi_ant_config_t *config);
/******************************************************************************* * cd4097_channel.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a simple model for a single channel of a CD4079 dual analog Mux. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "info.h" #include "cd4097_channel.h" int cd4097_channel::get_selector() { return (((c.read())?1:0) << 2) | (((b.read())?1:0) << 1) | ((a.read())?1:0); } void cd4097_channel::process_th() { int line; bool channel_is_driver = false; x.write(GN_LOGIC_Z); for(line = 0; line < channel.size(); line = line + 1) channel[line]->write(GN_LOGIC_Z); sel = get_selector(); bool recheck = false; while(true) { /* If the recheck is high, this means the selector changed and we need * to refigure out who is driving. */ if (recheck) { /* We wait a time stamp and redo the driving. */ wait(1, SC_NS); recheck = false; /* In these cases, we just keep everyone at Z. */ if (inh.read() || sel >= channel.size()) continue; /* We check who is the driver and drive the other. If they are both * being driven, we drive X everywhere. */ if (x.read() == GN_LOGIC_Z) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (channel[sel]->read()==GN_LOGIC_Z) { channel_is_driver = false; channel[sel]->write(x.read()); } else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } continue; } /* We wait for one either a change in the selector or a change in * either side of the mux. If the selector is pointing to an illegal * value, we then just wait for a change in the selector. */ if (sel >= channel.size()) wait(a->default_event() | b->default_event() | c->default_event() | inh->default_event()); else wait(channel[sel]->default_event() | a->default_event() | b->default_event() | c->default_event() | inh->default_event() | x->default_event()); bool sel_triggered = a->value_changed_event().triggered() || b->value_changed_event().triggered() || c->value_changed_event().triggered(); if (debug) { /* If the sel is illegal, we only can process the selector. */ if (sel >= channel.size()) printf("%s: sel = %d, triggers: sel %c, inh %c, x %c\n", name(), sel, (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); else printf( "%s: sel = %d, triggers: channel %c, sel %c, inh %c, x %c\n", name(), sel, (channel[sel]->value_changed_event().triggered())?'t':'f', (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); } /* If inh went high we shut it all off, it does not matter who triggered * what. */ if (inh.read() == GN_LOGIC_1) { x.write(GN_LOGIC_Z); if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); channel_is_driver = false; } /* If inh came back, we then need to resolve. */ else if (inh.value_changed_event().triggered()) { /* No need to drive Z if it is already. */ recheck = true; channel_is_driver = false; } /* Now we check the selector. If it changed, we need to drive Z and * recheck. This is because it is difficult to check every single * driver in a signal to find out what is going on. */ else if (sel_triggered) { int newsel = get_selector(); /* We now drive Z everywhere. */ if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); x.write(GN_LOGIC_Z); channel_is_driver = false; /* And we update the selector variable. */ sel = newsel; /* And if the new selector is valid, we do a recheck. */ if (sel < channel.size()) recheck = true; } /* If the selector is not valid, we just ignore any activity on either * side as there can't be any change. We simply drive Z everywhere. * Note: this path is a safety one, it is probably never called. */ else if (sel >= channel.size()) { channel_is_driver = false; x.write(GN_LOGIC_Z); } /* When we update a output pin, there is always a reflection. If both * sides have the same value, this probably was a reflection, so we * can dump it. */ else if (x.read() == channel[sel]->read()) continue; /* We have an analog mux. In a real mux system, we would do a fight * between the sides and eventually settle to something. This is a * digital simulator though, so we need a simplification. If I get a * driver on one side, we drive that value on the other. */ else if (channel[sel]->value_changed_event().triggered() && (channel_is_driver || x.read() == GN_LOGIC_Z)) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (x.default_event().triggered() && (!channel_is_driver || channel[sel]->read() == GN_LOGIC_Z)) { channel_is_driver = false; channel[sel]->write(x.read()); } /* If there are drivers on both sides, we need to put X on both sides. * Note: the current model will not leave this state unless there is * an inh or sel change. */ else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } } } void cd4097_channel::trace(sc_trace_file *tf) { sc_trace(tf, x, x.name()); sc_trace(tf, a, a.name()); sc_trace(tf, b, b.name()); sc_trace(tf, c, c.name()); sc_trace(tf, inh, inh.name()); }
/******************************************************************************* * pcntmod.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for the ESP32 Pulse Counter ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include <string.h> #include "pcntmod.h" #include "setfield.h" #include "soc/pcnt_struct.h" #include "soc/pcnt_reg.h" #include "clockpacer.h" void pcntmod::updateth() { int un; while(true) { wait(); for(un = 0; un < 8; un = un + 1) { conf0[un].write(PCNT.conf_unit[un].conf0.val); conf1[un].write(PCNT.conf_unit[un].conf1.val); conf2[un].write(PCNT.conf_unit[un].conf2.val); } int_ena.write(PCNT.int_ena.val); ctrl.write(PCNT.ctrl.val); /* We need to apply any reset bits. We can't set the values directly * as they are signals and they are driven by another thread, so we * just raise the notices. */ if ((PCNT_PLUS_CNT_RST_U0_M & PCNT.ctrl.val)>0) reset_un[0].notify(); if ((PCNT_PLUS_CNT_RST_U1_M & PCNT.ctrl.val)>0) reset_un[1].notify(); if ((PCNT_PLUS_CNT_RST_U2_M & PCNT.ctrl.val)>0) reset_un[2].notify(); if ((PCNT_PLUS_CNT_RST_U3_M & PCNT.ctrl.val)>0) reset_un[3].notify(); if ((PCNT_PLUS_CNT_RST_U4_M & PCNT.ctrl.val)>0) reset_un[4].notify(); if ((PCNT_PLUS_CNT_RST_U5_M & PCNT.ctrl.val)>0) reset_un[5].notify(); if ((PCNT_PLUS_CNT_RST_U6_M & PCNT.ctrl.val)>0) reset_un[6].notify(); if ((PCNT_PLUS_CNT_RST_U7_M & PCNT.ctrl.val)>0) reset_un[7].notify(); } } void pcntmod::returnth() { int un; while(true) { /* We wait for one of the counters to change. When that happens we copy * the values to the correct fields in the PCNT struct. This is not the * ideal way to do this, but it should work for now. */ wait( cnt_unit[0].value_changed_event() | cnt_unit[1].value_changed_event() | cnt_unit[2].value_changed_event() | cnt_unit[3].value_changed_event() | cnt_unit[4].value_changed_event() | cnt_unit[5].value_changed_event() | cnt_unit[6].value_changed_event() | cnt_unit[7].value_changed_event() | int_raw[0].value_changed_event() | int_raw[1].value_changed_event() | int_raw[2].value_changed_event() | int_raw[3].value_changed_event() | int_raw[4].value_changed_event() | int_raw[5].value_changed_event() | int_raw[6].value_changed_event() | int_raw[7].value_changed_event()); PCNT.int_raw.val = ((int_raw[7].read())?0x80:0x0) | ((int_raw[6].read())?0x40:0x0) | ((int_raw[5].read())?0x20:0x0) | ((int_raw[4].read())?0x10:0x0) | ((int_raw[3].read())?0x08:0x0) | ((int_raw[2].read())?0x04:0x0) | ((int_raw[1].read())?0x02:0x0) | ((int_raw[0].read())?0x01:0x0); PCNT.int_st.val = PCNT.int_raw.val & int_ena.read(); for(un = 0; un < 8; un = un + 1) { PCNT.cnt_unit[un].val = cnt_unit[un].read(); PCNT.status_unit[un].thres0_lat = PCNT.cnt_unit[un].val == RDFIELD(conf1[un], PCNT_CNT_THRES0_U0_M, PCNT_CNT_THRES0_U0_S); PCNT.status_unit[un].thres1_lat = PCNT.cnt_unit[un].val == RDFIELD(conf1[un], PCNT_CNT_THRES1_U0_M, PCNT_CNT_THRES1_U0_S); PCNT.status_unit[un].l_lim_lat = PCNT.cnt_unit[un].val <= RDFIELD(conf2[un], PCNT_CNT_L_LIM_U0_M, PCNT_CNT_L_LIM_U0_S); PCNT.status_unit[un].h_lim_lat = PCNT.cnt_unit[un].val >= RDFIELD(conf2[un], PCNT_CNT_H_LIM_U0_M, PCNT_CNT_H_LIM_U0_S); PCNT.status_unit[un].zero_lat = PCNT.cnt_unit[un].val == 0; } } } void pcntmod::update() { update_ev.notify(); clockpacer.wait_next_apb_clk(); } void pcntmod::initstruct() { memset(&PCNT, 0, sizeof(pcnt_dev_t)); } void pcntmod::start_of_simulation() { /* We spawn a thread for each channel. */ int un; for(un = 0; un < pcntbus_i.size(); un = un + 1) { sc_spawn(sc_bind(&pcntmod::capture, this, un)); sc_spawn(sc_bind(&pcntmod::count, this, un)); } } void pcntmod::capture(int un) { pcntbus_t lvl; pcntbus_t lastlvl; unsigned int filter_thres; lastlvl.sig_ch0 = false; lastlvl.sig_ch1 = false; lastlvl.ctrl_ch0 = false; lastlvl.ctrl_ch1 = false; fctrl0[un] = sc_time(0, SC_NS); fctrl1[un] = sc_time(0, SC_NS); while(true) { /* We wait until an input changed. */ wait(pcntbus_i[un]->default_event()); /* We wait until the next clock edge. */ clockpacer.wait_next_apb_clk(); /* Now we sample the inputs. Note that we might have lost some thing * but that is expected as this is a sampled protocol. */ lvl = pcntbus_i[un]->read(); /* We get the filter enable and value. */ if (RDFIELD(conf0[un], PCNT_FILTER_EN_U0_M, PCNT_FILTER_EN_U0_S)>0) filter_thres = RDFIELD(conf0[un], PCNT_FILTER_THRES_U0_M, PCNT_FILTER_THRES_U0_S); else filter_thres = 0; /* Now we need to look at each signal and find out if it should go high * now or if it should go high only when filtered. */ if (lvl.ctrl_ch0 != lastlvl.ctrl_ch0) { /* If the next transition is in the future, all we do is cancel the * transition. It has been filtered out. */ if (fctrl0[un] >= sc_time_stamp()) fctrl0[un] = sc_time(0, SC_NS); /* If it is in the past, then we record it. We then check the * filtering. If it is positive, we set it X clock cycles later. */ else if (filter_thres > 0) { fctrl0[un] = sc_time_stamp() + sc_time(filter_thres * clockpacer.get_apb_period()); } /* If no filtering was specified, we toggle the signal now. */ else fctrl0[un] = sc_time_stamp(); } /* And we redo it for the other channel. */ if (lvl.ctrl_ch1 != lastlvl.ctrl_ch1) { if (fctrl0[un] >= sc_time_stamp()) fctrl0[un] = sc_time(0, SC_NS); else if (filter_thres > 0) { fctrl1[un] = sc_time_stamp() + sc_time(filter_thres * clockpacer.get_apb_period()); } else fctrl1[un] = sc_time_stamp(); } /* Now we can do the signals. We also look at the signal to see when it * should be triggered. For this one, we raise a notification when the * signal should go high or low. */ /* First we check, if we are in reset, we do nothing. */ if (!((ctrl.read() & (PCNT_PLUS_CNT_RST_U0_M<<un*2))>0)) { /* If it is ok, we can check the filtering. */ if (lvl.sig_ch0 != lastlvl.sig_ch0) { /* If filtering is enabled so we notify the doit function when * the signal should change value. If filterig is off, we notify * it immediatedly. */ if (filter_thres > 0) filtered_sig0[un].notify( clockpacer.get_apb_period() * filter_thres); else filtered_sig0[un].notify(); } /* And we repeat for the other signal. */ if (lvl.sig_ch1 != lastlvl.sig_ch1) { if (filter_thres > 0) filtered_sig1[un].notify( clockpacer.get_apb_period() * filter_thres); else filtered_sig1[un].notify(); } } /* Once we are done, we need to copy the current lvl into the lastlvl * so that we can do edge detections. */ lastlvl = lvl; } } void pcntmod::count(int un) { pcntbus_t p; while(true) { wait(filtered_sig0[un] | filtered_sig1[un] | reset_un[un]); p = pcntbus_i[un]->read(); /* If there was a reset notice, we reset the block and do nothing else.*/ if (reset_un[un].triggered()) { cnt_unit[un].write(0); } /* Assuming it was not in reset, we can look at the other triggers. */ else { if (filtered_sig0[un].triggered()) { if (sc_time_stamp() < fctrl0[un]) docnt(un, p.sig_ch0, !p.ctrl_ch0, 0); else docnt(un, p.sig_ch0, p.ctrl_ch0, 0); } else { if (sc_time_stamp() < fctrl1[un]) docnt(un, p.sig_ch1, !p.ctrl_ch1, 1); else docnt(un, p.sig_ch1, p.ctrl_ch1, 1); } } } } void pcntmod::docnt(int un, bool siglvl, bool ctrllvl, int ch) { int mode, lctrl, hctrl; int16_t nc; /* If it is paused or in reset, we do nothing. */ if ((ctrl.read() & ((PCNT_PLUS_CNT_RST_U0_M|PCNT_CNT_PAUSE_U0_M)<<un*2))!=0) return; if (ch == 0) { if (siglvl) mode = RDFIELD(conf0[un], PCNT_CH0_POS_MODE_U0_M, PCNT_CH0_POS_MODE_U0_S); else mode = RDFIELD(conf0[un], PCNT_CH0_NEG_MODE_U0_M, PCNT_CH0_NEG_MODE_U0_S); lctrl = RDFIELD(conf0[un], PCNT_CH0_LCTRL_MODE_U0_M, PCNT_CH0_LCTRL_MODE_U0_S); hctrl = RDFIELD(conf0[un], PCNT_CH0_HCTRL_MODE_U0_M, PCNT_CH0_HCTRL_MODE_U0_S); } else { if (siglvl) mode = RDFIELD(conf0[un], PCNT_CH1_POS_MODE_U0_M, PCNT_CH1_POS_MODE_U0_S); else mode = RDFIELD(conf0[un], PCNT_CH1_NEG_MODE_U0_M, PCNT_CH1_NEG_MODE_U0_S); lctrl = RDFIELD(conf0[un], PCNT_CH1_LCTRL_MODE_U0_M, PCNT_CH1_LCTRL_MODE_U0_S); hctrl = RDFIELD(conf0[un], PCNT_CH1_HCTRL_MODE_U0_M, PCNT_CH1_HCTRL_MODE_U0_S); } /* If not we keep going. */ if (ctrllvl == true) { if (hctrl == 0 && mode == 1) nc = cnt_unit[un].read() + 1; else if (hctrl == 1 && mode == 2) nc = cnt_unit[un].read() + 1; else if (hctrl == 0 && mode == 2) nc = cnt_unit[un].read() - 1; else if (hctrl == 1 && mode == 1) nc = cnt_unit[un].read() - 1; /* disable and mode 0 we ignore */ else nc = cnt_unit[un].read(); } else { if (lctrl == 0 && mode == 1) nc = cnt_unit[un].read() + 1; else if (lctrl == 1 && mode == 2) nc = cnt_unit[un].read() + 1; else if (lctrl == 0 && mode == 2) nc = cnt_unit[un].read() - 1; else if (lctrl == 1 && mode == 1) nc = cnt_unit[un].read() - 1; /* disable and mode 0 we ignore */ else nc = cnt_unit[un].read(); } /* We now check the thresholds, limits and zero comparator. */ /* First we look at the limit comparators. */ if (RDFIELD(conf0[un], PCNT_THR_L_LIM_EN_U0_M, PCNT_THR_L_LIM_EN_U0_S) && nc <= (int16_t)RDFIELD(conf2[un], PCNT_CNT_L_LIM_U0_M, PCNT_CNT_L_LIM_U0_S) || RDFIELD(conf0[un], PCNT_THR_H_LIM_EN_U0_M, PCNT_THR_H_LIM_EN_U0_S) && nc >= (int16_t)RDFIELD(conf2[un], PCNT_CNT_H_LIM_U0_M, PCNT_CNT_H_LIM_U0_S)) { nc = 0; int_raw[un].write(true); } /* Now the thresholds. */ if (RDFIELD(conf0[un], PCNT_THR_THRES0_EN_U0_M, PCNT_THR_THRES0_EN_U0_S) && nc == (int16_t)RDFIELD(conf1[un], PCNT_CNT_THRES0_U0_M, PCNT_CNT_THRES0_U0_S)) { int_raw[un].write(true); } if (RDFIELD(conf0[un], PCNT_THR_THRES1_EN_U0_M, PCNT_THR_THRES1_EN_U0_S) && nc == (int16_t)RDFIELD(conf1[un], PCNT_CNT_THRES1_U0_M, PCNT_CNT_THRES1_U0_S)) { int_raw[un].write(true); } /* And finally the zero. */ if (nc == 0 && RDFIELD(conf0[un], PCNT_THR_ZERO_EN_U0_M, PCNT_THR_ZERO_EN_U0_S)) { int_raw[un].write(true); } /* And we commit the new value. */ cnt_unit[un].write(nc); } void pcntmod::trace(sc_trace_file *tf) { int un; std::string sigb = name(); std::string sign = sigb + ".conf0_0"; int digit; digit = sign.length() - 1; for(un = 0; un < 8; un = un + 1) { sign[digit] = '0' + un; sc_trace(tf, conf0[un], sign.c_str()); } sign[digit-2] = '1'; for(un = 0; un < 8; un = un + 1) { sign[digit] = '0' + un; sc_trace(tf, conf1[un], sign.c_str()); } sign[digit-2] = '2'; for(un = 0; un < 8; un = un + 1) { sign[digit] = '0' + un; sc_trace(tf, conf2[un], sign.c_str()); } sign = sigb + ".cntun_0"; digit = sign.length() - 1; for(un = 0; un < 8; un = un + 1) { sign[digit] = '0' + un; sc_trace(tf, cnt_unit[un], sign.c_str()); } sign = sigb + ".status_0"; digit = sign.length() - 1; for(un = 0; un < 8; un = un + 1) { sign[digit] = '0' + un; sc_trace(tf, status_unit[un], sign.c_str()); } sign = sigb + ".int_raw_0"; digit = sign.length() - 1; for(un = 0; un < 8; un = un + 1) { sign[digit] = '0' + un; sc_trace(tf, int_raw[un], sign.c_str()); } sc_trace(tf, ctrl, ctrl.name()); }
/******************************************************************************* * ledcmod.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for the ESP32 PWM LEDC module. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "ledcmod.h" #include "setfield.h" #include "soc/ledc_struct.h" #include "soc/ledc_reg.h" #include "clockpacer.h" #include "info.h" #define LEDC_OVF_TIMER_INTR 0 #define LEDC_DUTYEND_TIMER_INTR 8 void ledcmod::updateth() { int ch; int tim; sc_time base_period; while(true) { wait(); for(ch = 0; ch < (LEDC_CHANNELS/2); ch = ch + 1) { conf0[ch].write(LEDC.channel_group[0].channel[ch].conf0.val); conf1[ch].write(LEDC.channel_group[0].channel[ch].conf1.val); hpoint[ch].write(LEDC.channel_group[0].channel[ch].hpoint.val); duty[ch].write(LEDC.channel_group[0].channel[ch].duty.val); conf0[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].conf0.val); conf1[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].conf1.val); hpoint[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].hpoint.val); duty[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].duty.val); } /* we do not actually build the timers, so we need to do some * precalculations for the channels. */ for(tim = 0; tim < (LEDC_TIMERS/2); tim = tim + 1) { /* HSTIMER */ timer_conf[tim].write(LEDC.timer_group[0].timer[tim].conf.val); if (LEDC.timer_group[0].timer[tim].conf.tick_sel == 0) base_period = clockpacer.get_ref_period(); else base_period = clockpacer.get_apb_period(); /* TODO -- do the decimal part */ timerinc[tim].write( sc_time(base_period * (LEDC.timer_group[0].timer[tim].conf.clock_divider>>8))); /* LSTIMER */ timer_conf[tim+LEDC_TIMERS/2].write( LEDC.timer_group[1].timer[tim].conf.val); if (LEDC.timer_group[1].timer[tim].conf.tick_sel == 0) base_period = clockpacer.get_ref_period(); else base_period = clockpacer.get_rtc8m_period(); /* TODO -- do the decimal part */ /* TODO -- do the pause */ if (LEDC.timer_group[1].timer[tim].conf.low_speed_update) { timerinc[tim+LEDC_TIMERS/2].write(sc_time(base_period * (LEDC.timer_group[1].timer[tim].conf.clock_divider>>8))); } } /* int_ena we simply copy. */ int_ena.write(LEDC.int_ena.val); /* If we got a clear command, we trigger the event for the returnth to * handle it. */ if (LEDC.int_clr.val != 0x0) int_clr_ev.notify(); } } void ledcmod::returnth() { int un; /* We wait for one of the responses to get triggered, and then we copy the * R/O register back to the struct. */ while (true) { wait( timer_cnt[0].value_changed_event()| timer_cnt[1].value_changed_event() | timer_cnt[2].value_changed_event()| timer_cnt[3].value_changed_event() | timer_cnt[4].value_changed_event()| timer_cnt[5].value_changed_event() | timer_cnt[6].value_changed_event()| timer_cnt[7].value_changed_event() | duty_r[0].value_changed_event()| duty_r[1].value_changed_event() | duty_r[2].value_changed_event()| duty_r[3].value_changed_event() | duty_r[4].value_changed_event()| duty_r[5].value_changed_event() | duty_r[6].value_changed_event()| duty_r[7].value_changed_event() | duty_r[8].value_changed_event()| duty_r[9].value_changed_event() | duty_r[10].value_changed_event()| duty_r[11].value_changed_event() | duty_r[12].value_changed_event()| duty_r[13].value_changed_event() | duty_r[14].value_changed_event()| duty_r[15].value_changed_event() | int_clr_ev | int_ev[0] | int_ev[1] | int_ev[2] | int_ev[3] | int_ev[4] | int_ev[5] | int_ev[6] | int_ev[7] | int_ev[8] | int_ev[9] | int_ev[10]| int_ev[11]| int_ev[12]| int_ev[13]| int_ev[14]| int_ev[15]| int_ev[16]| int_ev[17]| int_ev[18]| int_ev[19]| int_ev[20]| int_ev[21]| int_ev[22]| int_ev[23]); for (un = 0; un < LEDC_CHANNELS; un = un + 1) { LEDC.int_raw.val = 0x0; /* If we hit the maximum dither times, we have an interrupt and * clear the duty_start. */ if (int_ev[un+LEDC_DUTYEND_TIMER_INTR].triggered()) { LEDC.int_raw.val = LEDC.int_raw.val | (1<<un); if (un < LEDC_CHANNELS/2) LEDC.channel_group[0].channel[un].conf1.duty_start = false; else LEDC.channel_group[1].channel[un-8].conf1.duty_start = false; } /* We copy the duty values */ if (un < LEDC_CHANNELS/2) LEDC.channel_group[0].channel[un].duty_rd.duty_read = duty_r[un].read(); else LEDC.channel_group[1].channel[un-8].duty_rd.duty_read = duty_r[un-8].read(); } /* We also copy over the timer values and interrupts. */ for(un = 0; un < (LEDC_TIMERS/2); un = un + 1) { if (int_ev[un+LEDC_OVF_TIMER_INTR].triggered()) LEDC.int_raw.val = LEDC.int_raw.val | (1<<un); LEDC.timer_group[0].timer[un].value.timer_cnt = timer_cnt[un].read(); if (int_ev[un+LEDC_OVF_TIMER_INTR+LEDC_TIMERS/2].triggered()) LEDC.int_raw.val = LEDC.int_raw.val | (1<<un+LEDC_TIMERS/2); LEDC.timer_group[1].timer[un].value.timer_cnt = timer_cnt[un].read(); } /* If we have a clear event we take it too. */ if (int_clr_ev.triggered()) { LEDC.int_raw.val = LEDC.int_raw.val & ~LEDC.int_clr.val; LEDC.int_clr.val = 0; } /* We update the raw. */ LEDC.int_st.val = LEDC.int_raw.val & int_ena.read(); /* We also drive the interrupt line */ intr_o.write(LEDC.int_st.val != 0); } } void ledcmod::update() { update_ev.notify(); clockpacer.wait_next_apb_clk(); } void ledcmod::initstruct() { memset(&LEDC, 0, sizeof(ledc_dev_t)); /* The reset bits begin all on. */ LEDC.timer_group[0].timer[0].conf.rst = 1; LEDC.timer_group[0].timer[1].conf.rst = 1; LEDC.timer_group[0].timer[2].conf.rst = 1; LEDC.timer_group[0].timer[3].conf.rst = 1; LEDC.timer_group[1].timer[0].conf.rst = 1; LEDC.timer_group[1].timer[1].conf.rst = 1; LEDC.timer_group[1].timer[2].conf.rst = 1; LEDC.timer_group[1].timer[3].conf.rst = 1; } void ledcmod::start_of_simulation() { /* We spawn a thread for each channel and timer. */ int un; for(un = 0; un < LEDC_CHANNELS; un = un + 1) { conf0[un].write(0); conf1[un].write(0); hpoint[un].write(0); duty[un].write(0); } for(un = 0; un < sig_out_hs_o.size(); un = un + 1) { sc_spawn(sc_bind(&ledcmod::channel, this, un)); sig_out_hs_o[un]->write(false); } for(un = LEDC_CHANNELS/2; un < sig_out_ls_o.size(); un = un + 1) { sc_spawn(sc_bind(&ledcmod::channel, this, un)); sig_out_ls_o[un-LEDC_CHANNELS/2]->write(false); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sc_spawn(sc_bind(&ledcmod::timer, this, un)); /* The RST bit starts off high, the other bits all start off low. */ timer_conf[un].write(LEDC_HSTIMER0_RST_M); timer_cnt[un].write(0); timer_lim[un].write(0); timerinc[un].write(sc_time(0, SC_NS)); } int_ena.write(0); } void ledcmod::calc_points(int un, bool start_dither) { int lp; int lpoint_frac; bool duty_start; int duty_num; int duty_cycle; bool duty_inc; int duty_scale; /* We first take the values into local registers to not have to keep * placing these lines in the middle of the code. */ if (un < LEDC_CHANNELS/2) { duty_start = (RDFIELD(conf1[un],LEDC_DUTY_START_HSCH0_M,LEDC_DUTY_START_HSCH0_S)>0); duty_num = RDFIELD(conf1[un],LEDC_DUTY_NUM_HSCH0_M,LEDC_DUTY_NUM_HSCH0_S); duty_cycle = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_CYCLE_HSCH0_S); duty_inc = (RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_INC_HSCH0_S)>0); duty_scale = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_SCALE_HSCH0_S); } else { duty_start = (RDFIELD(conf1[un],LEDC_DUTY_START_LSCH0_M,LEDC_DUTY_START_LSCH0_S)>0); duty_num = RDFIELD(conf1[un],LEDC_DUTY_NUM_LSCH0_M,LEDC_DUTY_NUM_LSCH0_S); duty_cycle = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_CYCLE_LSCH0_S); duty_inc = (RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_INC_LSCH0_S)>0); duty_scale = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_SCALE_LSCH0_S); } /* We get the lpoint and frac. */ lp = (duty[un].read() >> 4); lpoint_frac = duty[un].read() & 0x0f; /* We adjust the lpoint according to the fraction */ if (lpoint_frac > thiscyc[un]) lp = lp + 1; /* And we adjust the lpoint according to the dither. */ if (duty_start) { if (start_dither) { /* If this is the first time, dithcycles will be zero. We then * start by loading the settings of the dither and go on. */ dithtimes[un] = duty_num; dithcycles[un] = duty_cycle; } else { /* Other times we count the cycles and process it. */ dithcycles[un] = dithcycles[un] - 1; /* If we hit the target, we are done. */ if (dithcycles == 0 && duty_inc) { lp = lp + duty_scale; dithcycles[un] = duty_cycle; dithtimes[un] = dithtimes[un] - 1; } else if (dithcycles[un] == 0) { lp = lp - duty_scale; dithcycles[un] = duty_cycle; dithtimes[un] = dithtimes[un] - 1; } int_ev[un+LEDC_DUTYEND_TIMER_INTR].notify(); } } /* We put the lp value in the read/only register. */ duty_r[un].write(lp & LEDC_DUTY_HSCH0); thislp[un] = lp & LEDC_DUTY_HSCH0; } void ledcmod::channel(int ch) { bool outen; bool recheckpoints; /* Sel begins with -1 and it then is switched to the correct value. */ int sel = -1; while(1) { /* If there is no selected timer, all we do is wait for a configuration * change. If there is a timer specified, we wait for a timer trigger * or a configuration change. */ if (sel < 0) wait(conf0[ch].value_changed_event()); else wait(conf0[ch].value_changed_event() | conf1[ch].value_changed_event() | hpoint[ch].value_changed_event() | duty[ch].value_changed_event() | timer_cnt[sel].value_changed_event()); /* We go ahead and grab the output enable as we use it quite often. */ if (ch < LEDC_CHANNELS/2) { outen = RDFIELD(conf0[ch], LEDC_SIG_OUT_EN_HSCH0_M, LEDC_SIG_OUT_EN_HSCH0_S); sel= RDFIELD(conf0[ch], LEDC_TIMER_SEL_HSCH0_M, LEDC_TIMER_SEL_HSCH0_S); } else { outen = RDFIELD(conf0[ch], LEDC_SIG_OUT_EN_LSCH0_M, LEDC_SIG_OUT_EN_LSCH0_S); sel= RDFIELD(conf0[ch], LEDC_TIMER_SEL_LSCH0_M, LEDC_TIMER_SEL_LSCH0_S) + LEDC_TIMERS/2; } /* First we process changes in the PWM. These can affect the rest. */ /* If we got a trigger on the output and the channel is stopped, we * update the value. * The timer we ignore as the timer mux is done outside the channel. */ if (conf0[ch].event() && !outen) { if (ch < LEDC_CHANNELS/2) sig_out_hs_o[ch]->write( RDFIELD(conf0[ch], LEDC_IDLE_LV_HSCH0_M, LEDC_IDLE_LV_HSCH0_S)); else sig_out_ls_o[ch-LEDC_CHANNELS/2]->write( RDFIELD(conf0[ch], LEDC_IDLE_LV_LSCH0_M, LEDC_IDLE_LV_LSCH0_S)); } /* If we see a change in the hpoint or the duty we need to recalculate * the lpoint. We also need to do this when the timer is switched or when * we start a new cycle. */ if (duty[ch].event() || conf0[ch].event()) { calc_points(ch, true); /* We restart the cycle calculation. */ thiscyc[ch] = 0; /* And we will need to recheck the hpoint and lpoint. */ recheckpoints = true; } /* Anytime the cycle restarts (timer returns to zero) we need to * increment the cycle counter and adjust the jitter, if any. */ else if (timer_cnt[sel].read() == 0) { /* We start adjusting the cycle number for the dither. */ thiscyc[ch] = thiscyc[ch] + 1; if (thiscyc[ch] == LEDC_CYCLES) thiscyc[ch] = 0; /* We also calculate the lpoint. */ calc_points(ch, false); /* And we will need to recheck the hpoint and lpoint. */ recheckpoints = true; } else recheckpoints = false; /* If it was a timer tick, we need to see if it affects us. */ if (outen && (timer_cnt[sel].event() || recheckpoints)) { /* And we check where we are in the flow. */ bool nv; if (timer_cnt[sel].read() >= thislp[ch] + hpoint[ch].read()) nv = false; else if (timer_cnt[sel].read() >= hpoint[ch]) nv = true; else nv = false; if (ch < LEDC_CHANNELS/2) sig_out_hs_o[ch]->write(nv); else sig_out_ls_o[ch-LEDC_CHANNELS/2]->write(nv); } } } void ledcmod::timer(int tim) { bool rst; bool pause; bool wasstoped = true; while(1) { /* We wait for a timer tick or a change to the configuration register. */ wait(timer_ev[tim] | timer_conf[tim].value_changed_event() | timerinc[tim].value_changed_event()); /* We get the parameters first. */ if (tim < LEDC_TIMERS/2) { rst = RDFIELD(timer_conf[tim], LEDC_HSTIMER0_RST_M, LEDC_HSTIMER0_RST_S)>0; pause = RDFIELD(timer_conf[tim], LEDC_HSTIMER0_PAUSE_M, LEDC_HSTIMER0_PAUSE_S)>0; } else { rst = RDFIELD(timer_conf[tim], LEDC_LSTIMER0_RST_M, LEDC_LSTIMER0_RST_S)>0; pause = RDFIELD(timer_conf[tim], LEDC_LSTIMER0_PAUSE_M, LEDC_LSTIMER0_PAUSE_S)>0; } /* If we are in reset, we clear any future time events and wait. The next * event should be then a configuration change. */ if (rst) { timer_cnt[tim].write(0); timer_ev[tim].cancel(); wasstoped = true; } /* If we are paused, we just cancel any future events, but we do not * touch the counter value. */ else if (pause) { timer_ev[tim].cancel(); wasstoped = true; } /* If the timer increment is zero, we do the same. */ else if (timerinc[tim].read() == sc_time(0, SC_NS)) { timer_ev[tim].cancel(); } /* If we are comming out of reset or pause, we need to get the counter * going. */ else if (wasstoped) { timer_ev[tim].notify(timerinc[tim]); wasstoped = false; } /* We only count on timer event triggers. Configuration events should * not change the timer value. */ else if (timer_ev[tim].triggered()) { /* We calculate the next value, whichever it is. */ if (timer_cnt[tim].read() < timer_lim[tim].read() - 1) timer_cnt[tim].write(timer_cnt[tim].read() + 1); else { /* We hit the end we write a zero and raise the interrupt. */ timer_cnt[tim].write(0); int_ev[tim+LEDC_OVF_TIMER_INTR].notify(); } /* And we sleep until the next event. */ timer_ev[tim].notify(timerinc[tim]); } } } void ledcmod::trace(sc_trace_file *tf) { int un; std::string sigb = name(); std::string sign; for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".conf0_") + std::to_string(un); sc_trace(tf, conf0[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".conf1_") + std::to_string(un); sc_trace(tf, conf1[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".hpoint_") + std::to_string(un); sc_trace(tf, hpoint[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".duty_") + std::to_string(un); sc_trace(tf, duty[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".duty_r") + std::to_string(un); sc_trace(tf, duty_r[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_conf_") + std::to_string(un); sc_trace(tf, timer_conf[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_cnt_") + std::to_string(un); sc_trace(tf, timer_cnt[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_lim_") + std::to_string(un); sc_trace(tf, timer_lim[un], sign.c_str()); } }
/* * @ASCK */ #include <systemc.h> SC_MODULE (WB) { sc_in_clk clk; sc_in <sc_int<8>> prev_alu_result; sc_in <sc_int<8>> prev_mem_result; sc_in <bool> prev_WbMux; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_alu_result; sc_out <sc_int<8>> next_mem_result; sc_out <bool> next_WbMux; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (WB){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_alu_result.write(prev_alu_result.read()); next_mem_result.write(prev_mem_result.read()); next_WbMux.write(prev_WbMux.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
#include <systemc.h> #include "HammingRegister.h" #include "testbench.h" #include "SYSTEM.h" SYSTEMH *sysh=NULL; int sc_main(int argc, char *argv[]) { cout << " The Simulation Started"<< endl; sysh=new SYSTEMH("sysh"); sc_start(); //start the simulation cout <<" The Simulation Ended "<<endl; return 0; }
/******************************************************************************* * pcnttest.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is the main testbench for the pcnt.ino test. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "pcnttest.h" #include <string> #include <vector> #include "info.h" /********************** * Function: trace() * inputs: trace file * outputs: none * return: none * globals: none * * Traces all signals in the design. For a signal to be traced it must be listed * here. This function should also call tracing in any subblocks, if desired. */ void pcnttest::trace(sc_trace_file *tf) { sc_trace(tf, led, led.name()); sc_trace(tf, rx, rx.name()); sc_trace(tf, tx, tx.name()); sc_trace(tf, pwm0, pwm0.name()); sc_trace(tf, pwm1, pwm1.name()); sc_trace(tf, pwm2, pwm2.name()); sc_trace(tf, pwm3, pwm3.name()); sc_trace(tf, ctrl0, ctrl0.name()); sc_trace(tf, ctrl1, ctrl1.name()); sc_trace(tf, ctrl2, ctrl2.name()); i_esp.trace(tf); } /********************** * Task: serflush(): * inputs: none * outputs: none * return: none * globals: none * * Dumps everything comming from the serial interface. */ void pcnttest::serflush() { i_uartclient.dump(); } /********************** * Task: drivewave(): * inputs: none * outputs: none * return: none * globals: none * * Drives a waveform onto the pwm0 pin. */ void pcnttest::drivewave() { int c; pwm0.write(false); pwm1.write(false); pwm2.write(false); pwm3.write(false); while(true) { ctrl1.write(false); for(c = 0; c < 20; c = c + 1) { wait(1, SC_MS); pwm0.write(true); wait(300, SC_NS); pwm1.write(true); pwm2.write(true); wait(200, SC_NS); pwm0.write(false); wait(300, SC_NS); pwm1.write(false); pwm2.write(false); } ctrl1.write(true); for(c = 0; c < 20; c = c + 1) { wait(1, SC_MS); pwm0.write(true); wait(300, SC_NS); pwm1.write(true); pwm3.write(true); wait(200, SC_NS); pwm0.write(false); wait(300, SC_NS); pwm1.write(false); pwm3.write(false); } } } /******************************************************************************* ** Testbenches ***************************************************************** *******************************************************************************/ void pcnttest::t0(void) { SC_REPORT_INFO("TEST", "Running Test T0."); PRINTF_INFO("TEST", "Waiting for power-up"); ctrl0.write(false); ctrl2.write(false); wait(500, SC_MS); } void pcnttest::testbench(void) { /* Now we check the test case and run the correct TB. */ printf("Starting Testbench Test%d @%s\n", tn, sc_time_stamp().to_string().c_str()); if (tn == 0) t0(); else SC_REPORT_ERROR("TEST", "Test number too large."); sc_stop(); }
/******************************************************************************* * gn_mixed.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a derivative of the sc_signal_resolved class from SystemC * which was extended to support a third, analog level, data state. It should * be noted that this is not a real AMS style signal, for that we need * SystemC-AMS. This is just a shortcut to make it possible to express * a signal which can be either analog or 4-state without having to * use a AMS style simulator. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This was based off the work licensed as: * * Licensed to Accellera Systems Initiative Inc. (Accellera) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Accellera licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * Original Author: Martin Janssen, Synopsys, Inc., 2001-05-21 ******************************************************************************* */ #include <systemc.h> #include "gn_mixed.h" /* The table for resolving GN_LOGIC. * Some notes: * -weak always looses from strong, * -there is no weak undefined as we do not know if a weak undefined would * loose. * -Analog only wins from Z as a short between analog requires us to know * the currents. * -Conflicts with Undefined always produce an Undefined. */ gn_mixed::gn_logic_t gn_logic_resolution_tbl[7][7] = /* 0 */ /* 1 */ /* W0 */ /* W1 */ /* Z */ /* A */ /* X */ /* 0 */{{GN_LOGIC_0,GN_LOGIC_X,GN_LOGIC_0 ,GN_LOGIC_0 ,GN_LOGIC_0 ,GN_LOGIC_X,GN_LOGIC_X}, /* 1 */ {GN_LOGIC_X,GN_LOGIC_1,GN_LOGIC_1 ,GN_LOGIC_1 ,GN_LOGIC_1 ,GN_LOGIC_X,GN_LOGIC_X}, /*W0 */ {GN_LOGIC_0,GN_LOGIC_1,GN_LOGIC_W0,GN_LOGIC_X ,GN_LOGIC_W0,GN_LOGIC_X,GN_LOGIC_X}, /*W1 */ {GN_LOGIC_0,GN_LOGIC_1,GN_LOGIC_X ,GN_LOGIC_W1,GN_LOGIC_W1,GN_LOGIC_X,GN_LOGIC_X}, /* Z */ {GN_LOGIC_0,GN_LOGIC_1,GN_LOGIC_W0,GN_LOGIC_W1,GN_LOGIC_Z ,GN_LOGIC_A,GN_LOGIC_X}, /* A */ {GN_LOGIC_X,GN_LOGIC_X,GN_LOGIC_X ,GN_LOGIC_X ,GN_LOGIC_A ,GN_LOGIC_X,GN_LOGIC_X}, /* X */ {GN_LOGIC_X,GN_LOGIC_X,GN_LOGIC_X ,GN_LOGIC_X ,GN_LOGIC_X ,GN_LOGIC_X,GN_LOGIC_X}}; /* These are globals that set the analog levels to be used for the different * digital levels. There is no resolution or feedback calculated in them. * It is just a convention to make it more easily vieable in a digital * waveform viewer. vdd_lvl is the level for logic 1, vss_lvl is for logic 0 * and undef_lvl is for Z or X. */ float gn_mixed::vdd_lvl = 3.3f; float gn_mixed::vss_lvl = 0.0f; float gn_mixed::undef_lvl = 1.5f; sc_logic gn_to_sc_logic(gn_mixed::gn_logic_t g) { switch(g) { case GN_LOGIC_0: case GN_LOGIC_W0: return SC_LOGIC_0; case GN_LOGIC_1: case GN_LOGIC_W1: return SC_LOGIC_1; case GN_LOGIC_Z: return SC_LOGIC_Z; default: return SC_LOGIC_X; } } float gn_mixed::guess_lvl(sc_logic &l) { if (l == SC_LOGIC_0) return vss_lvl; else if (l == SC_LOGIC_1) return vdd_lvl; else return undef_lvl; } gn_mixed::gn_param_t gn_mixed::guess_param(gn_logic_t g) { switch(g) { case GN_LOGIC_W0: return GN_TYPE_WEAK; case GN_LOGIC_W1: return GN_TYPE_WEAK; case GN_LOGIC_A: return GN_TYPE_ANALOG; case GN_LOGIC_Z: return GN_TYPE_Z; default: return GN_TYPE_STRONG; } } gn_mixed::gn_logic_t char_to_gn(const char c_) { switch(c_) { case '0': return GN_LOGIC_0; case '1': return GN_LOGIC_1; case 'l': return GN_LOGIC_W0; case 'h': return GN_LOGIC_W1; case 'Z': return GN_LOGIC_Z; case 'A': return GN_LOGIC_A; default: return GN_LOGIC_X; } } gn_mixed::gn_mixed() { logic = SC_LOGIC_X; lvl = undef_lvl; param = GN_TYPE_STRONG; } gn_mixed::gn_mixed(const gn_mixed &n) { logic = n.logic; lvl = n.lvl; param = n.param; } gn_mixed::gn_mixed(const gn_logic_t n_) { logic = gn_to_sc_logic(n_); lvl = guess_lvl(logic); param = guess_param(n_); } gn_mixed::gn_mixed(const sc_logic &n) { logic = n; lvl = guess_lvl(logic); param = (n == SC_LOGIC_Z)?GN_TYPE_Z:GN_TYPE_STRONG; } gn_mixed::gn_mixed(const float &n) { logic = SC_LOGIC_X; lvl = n; param = GN_TYPE_ANALOG; } gn_mixed::gn_mixed(const char c_) { gn_logic_t g = char_to_gn(c_); logic = gn_to_sc_logic(g); lvl = guess_lvl(logic); param = guess_param(g); } gn_mixed::gn_mixed(const bool b_) { logic = sc_logic(b_); lvl = guess_lvl(logic); param = GN_TYPE_STRONG; } gn_mixed &gn_mixed::operator=(const gn_mixed &n) { logic = n.logic; lvl = n.lvl; param = n.param; return *this; } gn_mixed &gn_mixed::operator=(const gn_logic_t n_) { logic = gn_to_sc_logic(n_); lvl = guess_lvl(logic); param = guess_param(n_); return *this; } gn_mixed &gn_mixed::operator=(const sc_logic &n) { logic = n; lvl = guess_lvl(logic); param = (n == SC_LOGIC_Z)?GN_TYPE_Z:GN_TYPE_STRONG; return *this; } gn_mixed &gn_mixed::operator=(const float &n) { logic = LOGIC_A; lvl = n; param = GN_TYPE_ANALOG; return *this; } gn_mixed &gn_mixed::operator=(const char c_) { gn_logic_t g = char_to_gn(c_); logic = gn_to_sc_logic(g); lvl = guess_lvl(logic); param = guess_param(g); return *this; } gn_mixed &gn_mixed::operator=(const bool b_) { logic = sc_logic(b_); lvl = guess_lvl(logic); param = GN_TYPE_STRONG; return *this; } /* When comparing GN_MIXED, we compare all fields. When comparing GN_MIXED to * SC_LOGIC we have to treat the weak and strong signals as the same. We also * have to treat analog signals as simply undefined. */ bool operator==(const gn_mixed &a, const gn_mixed &b) { if (a.logic != b.logic) return false; if (a.param != b.param) return false; if (a.param != gn_mixed::GN_TYPE_ANALOG) return true; return (a.lvl > b.lvl - 0.01 && a.lvl < b.lvl + 0.01); } bool operator==(const gn_mixed &a, const sc_logic &b) { return a.logic == b; } char gn_mixed::to_char() const { if (param == GN_TYPE_ANALOG) return 'A'; else if (logic == SC_LOGIC_X) return 'X'; else if (logic == SC_LOGIC_Z) return 'Z'; else if (logic == SC_LOGIC_0) return (param == GN_TYPE_WEAK)?'l':'0'; else if (logic == SC_LOGIC_1) return (param == GN_TYPE_WEAK)?'h':'1'; else return GN_LOGIC_X; } gn_mixed::gn_logic_t gn_mixed::value() { if (param == GN_TYPE_ANALOG) return GN_LOGIC_A; else if (logic == SC_LOGIC_X) return GN_LOGIC_X; else if (logic == SC_LOGIC_Z) return GN_LOGIC_Z; else if (logic == SC_LOGIC_0) return (param == GN_TYPE_WEAK)?GN_LOGIC_W0:GN_LOGIC_0; else if (logic == SC_LOGIC_1) return (param == GN_TYPE_WEAK)?GN_LOGIC_W1:GN_LOGIC_1; else return GN_LOGIC_X; } static void gn_mixed_resolve(gn_mixed& result_, const std::vector<gn_mixed>& values_ ) { int sz = values_.size(); sc_assert( sz != 0 ); if( sz == 1 ) { result_ = values_[0]; return; } gn_mixed current; gn_mixed res = values_[0]; int i; /* We now scan the list of driven values so we can resolve it. If we find * a X it all goes X, so we can stop looking. */ for(i = sz - 1; i>0 && res.logic != SC_LOGIC_X; --i) { /* If the resolved is high-Z, we resolve to the next one. */ if (res.value() == GN_LOGIC_Z) { res = values_[i]; continue; } /* In other cases we use the resolution table. */ current = values_[i]; /* This case is simple. */ if (current.value() == GN_LOGIC_Z) continue; /* We let the resolution table handle the rest. */ res = gn_logic_resolution_tbl[res.value()][current.value()]; } result_ = res; } void gn_signal_mix::write(const value_type& value_) { sc_process_b* cur_proc = sc_get_current_process_b(); bool value_changed = false; bool found = false; for( int i = m_proc_vec.size() - 1; i >= 0; -- i ) { if( cur_proc == m_proc_vec[i] ) { if( value_ != m_val_vec[i] ) { m_val_vec[i] = value_; value_changed = true; } found = true; break; } } if( ! found ) { m_proc_vec.push_back( cur_proc ); m_val_vec.push_back( value_ ); value_changed = true; } if( value_changed ) { request_update(); } } void gn_signal_mix::write( const gn_mixed::gn_logic_t value_ ) { write(gn_mixed(value_));} void gn_signal_mix::write( const sc_logic& value_ ) { write(gn_mixed(value_)); } void gn_signal_mix::write( const float& value_ ) { write(gn_mixed(value_)); } void gn_signal_mix::write( const char value_ ) { write(gn_mixed(value_)); } void gn_signal_mix::write( const bool value_ ) { write(gn_mixed(value_)); } sc_logic gn_signal_mix::read_logic( ) { return read().logic; } float gn_signal_mix::read_lvl( ) { return read().lvl; } void gn_signal_mix::update() { gn_mixed_resolve( m_new_val, m_val_vec ); base_type::update(); } void gn_tie_mix::update() { base_type::update(); }
/* * @ASCK */ #include <systemc.h> SC_MODULE (Memory) { sc_in <bool> r_nw; sc_in <sc_uint<13>> addr; sc_in <sc_int<8>> data; sc_out <sc_int<8>> out; /* ** module global variables */ sc_int<8> mem[8192] = {0}; // 2^13 rows bool done = false; SC_CTOR (Memory){ SC_METHOD (process); sensitive << r_nw << addr << data; } void process () { if(done){ return; } if(addr.read() < 8192){ if(r_nw.read()){ out.write(mem[addr.read()]); } else{ mem[addr.read()] = data.read(); out.write(mem[addr.read()]); } } else{ out.write(0); } } };
// Copyright 2020 Glenn Ramalho - RFIDo Design // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This code was based off the work from Espressif Systems covered by the // License: // // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <systemc.h> #include "esp32-hal.h" #include "clockpacer.h" //Undocumented!!! Get chip temperature in Farenheit //Source: https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_int_temp_sensor/ESP32_int_temp_sensor.ino uint8_t temprature_sens_read(); float temperatureRead() { return (temprature_sens_read() - 32) / 1.8; } /* We need to use the C prototype style so that the weak alias will work. */ extern "C" { void __yield(); } void __yield() { /* We do a wait, as that hands the control back to the SystemC Scheduler, * which is also handling our FreeRTOS scheduler. */ wait(clockpacer.get_cpu_period()); } void yield() __attribute__ ((weak, alias("__yield"))); /* This is something often used inside the model and drivers for the model. */ void del1cycle() { if (clockpacer.is_thread()) clockpacer.wait_next_cpu_clk(); } #if CONFIG_AUTOSTART_ARDUINO /* extern TaskHandle_t loopTaskHandle; extern bool loopTaskWDTEnabled; void enableLoopWDT(){ if(loopTaskHandle != NULL){ if(esp_task_wdt_add(loopTaskHandle) != ESP_OK){ log_e("Failed to add loop task to WDT"); } else { loopTaskWDTEnabled = true; } } } void disableLoopWDT(){ if(loopTaskHandle != NULL && loopTaskWDTEnabled){ loopTaskWDTEnabled = false; if(esp_task_wdt_delete(loopTaskHandle) != ESP_OK){ log_e("Failed to remove loop task from WDT"); } } } void feedLoopWDT(){ esp_err_t err = esp_task_wdt_reset(); if(err != ESP_OK){ log_e("Failed to feed WDT! Error: %d", err); } } */ #endif /* void enableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_add(idle_0) != ESP_OK){ log_e("Failed to add Core 0 IDLE task to WDT"); } } void disableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_delete(idle_0) != ESP_OK){ log_e("Failed to remove Core 0 IDLE task from WDT"); } } #ifndef CONFIG_FREERTOS_UNICORE void enableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_add(idle_1) != ESP_OK){ log_e("Failed to add Core 1 IDLE task to WDT"); } } void disableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_delete(idle_1) != ESP_OK){ log_e("Failed to remove Core 1 IDLE task from WDT"); } } #endif */ /* BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, const BaseType_t xCoreID ){ #ifndef CONFIG_FREERTOS_UNICORE if(xCoreID >= 0 && xCoreID < 2) { return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); } else { #endif return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); #ifndef CONFIG_FREERTOS_UNICORE } #endif } */ /* micros and millis get the current time from the SystemC simulation time * instead of the CPU. */ unsigned long int micros() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000000); } unsigned long int millis() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000); } /* Delay does a SystemC wait. */ void delay(uint32_t del) { wait(del, SC_MS); } /* For the delayMicroseconds we do the same thing. We definitely do not want * the busy-wait loop that the original code uses. It bogs down too much the * simulation. */ void delayMicroseconds(uint32_t del) { wait(del, SC_US); } /* Not sure why these are here, but they do nothing, so they can remain here. */ void initVariant() __attribute__((weak)); void initVariant() {} void init() __attribute__((weak)); void init() {} bool verifyOta() __attribute__((weak)); bool verifyOta() { return true; } #ifdef CONFIG_BT_ENABLED //overwritten in esp32-hal-bt.c bool btInUse() __attribute__((weak)); bool btInUse(){ return false; } #endif /* void initArduino() { #ifdef CONFIG_APP_ROLLBACK_ENABLE const esp_partition_t *running = esp_ota_get_running_partition(); esp_ota_img_states_t ota_state; if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) { if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) { if (verifyOta()) { esp_ota_mark_app_valid_cancel_rollback(); } else { log_e("OTA verification failed! Start rollback to the previous version ..."); esp_ota_mark_app_invalid_rollback_and_reboot(); } } } #endif //init proper ref tick value for PLL (uncomment if REF_TICK is different than 1MHz) //ESP_REG(APB_CTRL_PLL_TICK_CONF_REG) = APB_CLK_FREQ / REF_CLK_FREQ - 1; #ifdef F_CPU setCpuFrequencyMhz(F_CPU/1000000); #endif #if CONFIG_SPIRAM_SUPPORT psramInit(); #endif esp_log_level_set("*", CONFIG_LOG_DEFAULT_LEVEL); esp_err_t err = nvs_flash_init(); if(err == ESP_ERR_NVS_NO_FREE_PAGES){ const esp_partition_t* partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL); if (partition != NULL) { err = esp_partition_erase_range(partition, 0, partition->size); if(!err){ err = nvs_flash_init(); } else { log_e("Failed to format the broken NVS partition!"); } } } if(err) { log_e("Failed to initialize NVS! Error: %u", err); } #ifdef CONFIG_BT_ENABLED if(!btInUse()){ esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); } #endif init(); initVariant(); } */ //used by hal log const char *pathToFileName(const char * path) { size_t i = 0; size_t pos = 0; char * p = (char *)path; while(*p){ i++; if(*p == '/' || *p == '\\'){ pos = i; } p++; } return path+pos; }
/******************************************************************************* * esp_wifi.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file ports the esp_wifi functions for the ESP32 to the ESPMOD SystemC * model. It was based off the functions from Espressif Systems. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was based off the work covered by the license below: * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <systemc.h> #include "WiFi.h" #include "info.h" #include <IPAddress.h> #include "esp_system.h" #include "esp_err.h" #include "WiFiType.h" #include "esp_wifi_types.h" #include "wifistat.h" #include "esp_wifi.h" #include "lwip/sockets.h" #include <string.h> wifistat_t wifistat; /** * @brief Init WiFi * Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer, * WiFi NVS structure etc, this WiFi also start WiFi task * * @attention 1. This API must be called before all other WiFi API can be called * @attention 2. Always use WIFI_INIT_CONFIG_DEFAULT macro to init the config to default values, this can * guarantee all the fields got correct value when more fields are added into wifi_init_config_t * in future release. If you want to set your owner initial values, overwrite the default values * which are set by WIFI_INIT_CONFIG_DEFAULT, please be notified that the field 'magic' of * wifi_init_config_t should always be WIFI_INIT_CONFIG_MAGIC! * * @param config pointer to WiFi init configuration structure; can point to a temporary variable. * * @return * - ESP_OK: succeed * - ESP_ERR_NO_MEM: out of memory * - others: refer to error code esp_err.h */ esp_err_t esp_wifi_init(const wifi_init_config_t *config) { PRINTF_INFO("WIFI", "Initializing"); wifistat.initialized = true; wifistat.started = false; wifistat.stat = WL_IDLE_STATUS; return ESP_OK; } /** * @brief Deinit WiFi * Free all resource allocated in esp_wifi_init and stop WiFi task * * @attention 1. This API should be called if you want to remove WiFi driver from the system * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_deinit(void) { SC_REPORT_INFO("WIFI", "De-Init"); if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; wifistat.initialized = false; wifistat.started = false; wifistat.connected = false; return ESP_OK; } /** * @brief Set the WiFi operating mode * * Set the WiFi operating mode as station, soft-AP or station+soft-AP, * The default mode is soft-AP mode. * * @param mode WiFi operating mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_set_mode(wifi_mode_t mode) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else switch(mode) { case WIFI_MODE_STA: SC_REPORT_INFO("WIFI", "Setting WiFi to Station Mode"); wifistat.mode = mode; return ESP_OK; case WIFI_MODE_NULL: SC_REPORT_INFO("WIFI", "Switching WiFi Off"); wifistat.mode = mode; return ESP_OK; case WIFI_MODE_AP: SC_REPORT_INFO("WIFI", "Setting WiFi to AP Mode"); wifistat.mode = mode; return ESP_OK; case WIFI_MODE_APSTA: SC_REPORT_INFO("WIFI", "Setting WiFi to AP/STA Mode"); wifistat.mode = mode; return ESP_OK; default: return ESP_ERR_INVALID_ARG; } } /** * @brief Get current operating mode of WiFi * * @param[out] mode store current WiFi mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_mode(wifi_mode_t *mode) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else if (mode == NULL) return ESP_ERR_INVALID_ARG; else *mode = wifistat.mode; return ESP_OK; } /** * @brief Start WiFi according to current configuration * If mode is WIFI_MODE_STA, it create station control block and start station * If mode is WIFI_MODE_AP, it create soft-AP control block and start soft-AP * If mode is WIFI_MODE_APSTA, it create soft-AP and station control block and start soft-AP and station * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_NO_MEM: out of memory * - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong * - ESP_FAIL: other WiFi internal errors */ esp_err_t esp_wifi_start(void) { system_event_t ev; /* This is actually done by the init before the firmware loads, but we do * it here for lack of a better place. */ if (!wifistat.initialized) esp_wifi_init(NULL); /* Now we start the interface. */ if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; wifistat.started = true; wifistat.connected = false; if (wifistat.mode == WIFI_MODE_STA || wifistat.mode == WIFI_MODE_APSTA) { ev.event_id = SYSTEM_EVENT_STA_START; WiFiClass::_eventCallback(NULL, &ev); } if (wifistat.mode == WIFI_MODE_AP || wifistat.mode == WIFI_MODE_APSTA) { ev.event_id = SYSTEM_EVENT_AP_START; WiFiClass::_eventCallback(NULL, &ev); } return ESP_OK; } /** * @brief Stop WiFi * If mode is WIFI_MODE_STA, it stop station and free station control block * If mode is WIFI_MODE_AP, it stop soft-AP and free soft-AP control block * If mode is WIFI_MODE_APSTA, it stop station/soft-AP and free station/soft-AP control block * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_stop(void) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else return ESP_OK; } /** * @brief Restore WiFi stack persistent settings to default values * * This function will reset settings made using the following APIs: * - esp_wifi_get_auto_connect, * - esp_wifi_set_protocol, * - esp_wifi_set_config related * - esp_wifi_set_mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_restore(void) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; /* Set default settings. */ return ESP_OK; } /** * @brief Connect the ESP32 WiFi station to the AP. * * @attention 1. This API only impact WIFI_MODE_STA or WIFI_MODE_APSTA mode * @attention 2. If the ESP32 is connected to an AP, call esp_wifi_disconnect to disconnect. * @attention 3. The scanning triggered by esp_wifi_start_scan() will not be effective until connection between ESP32 and the AP is established. * If ESP32 is scanning and connecting at the same time, ESP32 will abort scanning and return a warning message and error * number ESP_ERR_WIFI_STATE. * If you want to do reconnection after ESP32 received disconnect event, remember to add the maximum retry time, otherwise the called * scan will not work. This is especially true when the AP doesn't exist, and you still try reconnection after ESP32 received disconnect * event with the reason code WIFI_REASON_NO_AP_FOUND. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start * - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong * - ESP_ERR_WIFI_SSID: SSID of AP which station connects is invalid */ esp_err_t esp_wifi_connect(void) { system_event_t ev; if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; if (wifistat.conf.sta.ssid[0] == '\0' || strlen((const char *)wifistat.conf.sta.ssid)>31) return ESP_ERR_WIFI_SSID; if (strchr((const char *)wifistat.conf.sta.ssid, ' ') != NULL) PRINTF_WARN("WIFI", "Found a space in the SSID, what is legal but often not supported."); /* If we are running a DHCP, we need to set the IP addresses. We then * pick something as we do not actually have a server. */ if (wifistat.dhcp_c) { wifistat.ip_info.ip.addr = IPAddress(192, 76, 0, 100); wifistat.ip_info.gw.addr = IPAddress(192, 76, 0, 1); wifistat.ip_info.netmask.addr = IPAddress(255, 255, 255, 0); } /* We call the callback */ ev.event_id = SYSTEM_EVENT_STA_GOT_IP; ev.event_info.got_ip.ip_info.ip = wifistat.ip_info.ip; ev.event_info.got_ip.ip_info.gw = wifistat.ip_info.gw; ev.event_info.got_ip.ip_info.netmask = wifistat.ip_info.netmask; /* If the IP changed we note tag it. */ if (wifistat.current_ip != wifistat.ip_info.ip.addr) ev.event_info.got_ip.ip_changed = true; else ev.event_info.got_ip.ip_changed = false; WiFiClass::_eventCallback(NULL, &ev); /* And we do the connection. */ wifistat.connected = true; wifistat.current_ip = wifistat.ip_info.ip.addr; return ESP_OK; } /** * @brief Disconnect the ESP32 WiFi station from the AP. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi was not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_FAIL: other WiFi internal errors */ esp_err_t esp_wifi_disconnect(void) { system_event_t ev; if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; /* We call the callback */ ev.event_id = SYSTEM_EVENT_STA_DISCONNECTED; /* For now it is the only one */ ev.event_info.disconnected.reason = WIFI_REASON_UNSPECIFIED; WiFiClass::_eventCallback(NULL, &ev); /* And we do the connection. */ wifistat.connected = false; return ESP_OK; } /** * @brief Currently this API is just an stub API * * @return * - ESP_OK: succeed * - others: fail */ esp_err_t esp_wifi_clear_fast_connect(void); /** * @brief deauthenticate all stations or associated id equals to aid * * @param aid when aid is 0, deauthenticate all stations, otherwise deauthenticate station whose associated id is aid * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_MODE: WiFi mode is wrong */ esp_err_t esp_wifi_deauth_sta(uint16_t aid); /** * @brief Scan all available APs. * * @attention If this API is called, the found APs are stored in WiFi driver dynamic allocated memory and the * will be freed in esp_wifi_scan_get_ap_records, so generally, call esp_wifi_scan_get_ap_records to cause * the memory to be freed once the scan is done * @attention The values of maximum active scan time and passive scan time per channel are limited to 1500 milliseconds. * Values above 1500ms may cause station to disconnect from AP and are not recommended. * * @param config configuration of scanning * @param block if block is true, this API will block the caller until the scan is done, otherwise * it will return immediately * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_ERR_WIFI_TIMEOUT: blocking scan is timeout * - ESP_ERR_WIFI_STATE: wifi still connecting when invoke esp_wifi_scan_start * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block); /** * @brief Stop the scan in process * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start */ esp_err_t esp_wifi_scan_stop(void); /** * @brief Get number of APs found in last scan * * @param[out] number store number of APIs found in last scan * * @attention This API can only be called when the scan is completed, otherwise it may get wrong value. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_scan_get_ap_num(uint16_t *number); /** * @brief Get AP list found in last scan * * @param[inout] number As input param, it stores max AP number ap_records can hold. * As output param, it receives the actual AP number this API returns. * @param ap_records wifi_ap_record_t array to hold the found APs * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_NO_MEM: out of memory */ esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_records); /** * @brief Get information of AP which the ESP32 station is associated with * * @param ap_info the wifi_ap_record_t to hold AP information * sta can get the connected ap's phy mode info through the struct member * phy_11b,phy_11g,phy_11n,phy_lr in the wifi_ap_record_t struct. * For example, phy_11b = 1 imply that ap support 802.11b mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_CONN: The station interface don't initialized * - ESP_ERR_WIFI_NOT_CONNECT: The station is in disconnect status */ esp_err_t esp_wifi_sta_get_ap_info(wifi_ap_record_t *ap_info) { if (!wifistat.initialized) return ESP_ERR_WIFI_CONN; if (!wifistat.started) return ESP_ERR_WIFI_CONN; if (!wifistat.connected) return ESP_ERR_WIFI_NOT_CONNECT; if (ap_info == NULL) return ESP_ERR_INVALID_ARG; /* NOT IN THE LIST */ memcpy((void *)ap_info, (void *)&wifistat.ap_info, sizeof(wifi_ap_record_t)); return ESP_OK; } /** * @brief Set current WiFi power save type * * @attention Default power save type is WIFI_PS_MIN_MODEM. * * @param type power save type * * @return ESP_OK: succeed */ esp_err_t esp_wifi_set_ps(wifi_ps_type_t type) { wifistat.pstype = type; return ESP_OK; } /** * @brief Get current WiFi power save type * * @attention Default power save type is WIFI_PS_MIN_MODEM. * * @param[out] type: store current power save type * * @return ESP_OK: succeed */ esp_err_t esp_wifi_get_ps(wifi_ps_type_t *type) { if (type == NULL) return ESP_ERR_INVALID_ARG; /* NOT IN THE LIST */ *type = wifistat.pstype; return ESP_OK; } /** * @brief Set protocol type of specified interface * The default protocol is (WIFI_PROTOCOL_11B|WIFI_PROTOCOL_11G|WIFI_PROTOCOL_11N) * * @attention Currently we only support 802.11b or 802.11bg or 802.11bgn mode * * @param ifx interfaces * @param protocol_bitmap WiFi protocol bitmap * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_set_protocol(wifi_interface_t ifx, uint8_t protocol_bitmap); /** * @brief Get the current protocol bitmap of the specified interface * * @param ifx interface * @param[out] protocol_bitmap store current WiFi protocol bitmap of interface ifx * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_get_protocol(wifi_interface_t ifx, uint8_t *protocol_bitmap); /** * @brief Set the bandwidth of ESP32 specified interface * * @attention 1. API return false if try to configure an interface that is not enabled * @attention 2. WIFI_BW_HT40 is supported only when the interface support 11N * * @param ifx interface to be configured * @param bw bandwidth * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_set_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t bw); /** * @brief Get the bandwidth of ESP32 specified interface * * @attention 1. API return false if try to get a interface that is not enable * * @param ifx interface to be configured * @param[out] bw store bandwidth of interface ifx * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t *bw); /** * @brief Set primary/secondary channel of ESP32 * * @attention 1. This is a special API for sniffer * @attention 2. This API should be called after esp_wifi_start() or esp_wifi_set_promiscuous() * * @param primary for HT20, primary is the channel number, for HT40, primary is the primary channel * @param second for HT20, second is ignored, for HT40, second is the second channel * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_channel(uint8_t primary, wifi_second_chan_t second) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_CONN; if (primary > 13) return ESP_ERR_INVALID_ARG; wifistat.conf.sta.channel = primary; return ESP_OK; } /** * @brief Get the primary/secondary channel of ESP32 * * @attention 1. API return false if try to get a interface that is not enable * *
@param primary store current primary channel * @param[out] second store current second channel * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; else if (primary == NULL || second == NULL) return ESP_ERR_INVALID_ARG; *primary = wifistat.conf.sta.channel; *second = WIFI_SECOND_CHAN_NONE; return ESP_OK; } /** * @brief configure country info * * @attention 1. The default country is {.cc="CN", .schan=1, .nchan=13, policy=WIFI_COUNTRY_POLICY_AUTO} * @attention 2. When the country policy is WIFI_COUNTRY_POLICY_AUTO, the country info of the AP to which * the station is connected is used. E.g. if the configured country info is {.cc="USA", .schan=1, .nchan=11} * and the country info of the AP to which the station is connected is {.cc="JP", .schan=1, .nchan=14} * then the country info that will be used is {.cc="JP", .schan=1, .nchan=14}. If the station disconnected * from the AP the country info is set back back to the country info of the station automatically, * {.cc="USA", .schan=1, .nchan=11} in the example. * @attention 3. When the country policy is WIFI_COUNTRY_POLICY_MANUAL, always use the configured country info. * @attention 4. When the country info is changed because of configuration or because the station connects to a different * external AP, the country IE in probe response/beacon of the soft-AP is changed also. * @attention 5. The country configuration is not stored into flash * @attention 6. This API doesn't validate the per-country rules, it's up to the user to fill in all fields according to * local regulations. * * @param country the configured country info * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_country(const wifi_country_t *country); /** * @brief get the current country info * * @param country country info * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_country(wifi_country_t *country); /** * @brief Set MAC address of the ESP32 WiFi station or the soft-AP interface. * * @attention 1. This API can only be called when the interface is disabled * @attention 2. ESP32 soft-AP and station have different MAC addresses, do not set them to be the same. * @attention 3. The bit 0 of the first byte of ESP32 MAC address can not be 1. For example, the MAC address * can set to be "1a:XX:XX:XX:XX:XX", but can not be "15:XX:XX:XX:XX:XX". * * @param ifx interface * @param mac the MAC address * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_WIFI_MAC: invalid mac address * - ESP_ERR_WIFI_MODE: WiFi mode is wrong * - others: refer to error codes in esp_err.h */ esp_err_t esp_wifi_set_mac(wifi_interface_t ifx, const uint8_t mac[6]) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (ifx != WIFI_IF_STA && ifx != WIFI_IF_AP) return ESP_ERR_INVALID_ARG; PRINTF_WARN("WIFI", "esp_wifi_set_mac currently is unsupported."); return ESP_OK; } /** * @brief Get mac of specified interface * * @param ifx interface * @param[out] mac store mac of the interface ifx * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface */ esp_err_t esp_wifi_get_mac(wifi_interface_t ifx, uint8_t mac[6]) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (ifx != WIFI_IF_STA && ifx != WIFI_IF_AP) return ESP_ERR_INVALID_ARG; switch(ifx) { case WIFI_IF_STA: mac[0] = 0x55; mac[1] = 0x37; mac[2] = 0xce; mac[3] = 0x99; mac[4] = 0x75; mac[5] = 0x1E; return ESP_OK; case WIFI_IF_AP: mac[0] = 0x55; mac[1] = 0x37; mac[2] = 0xce; mac[3] = 0x99; mac[4] = 0x75; mac[5] = 0x39; return ESP_OK; default: return ESP_ERR_INVALID_ARG; } } /** * @brief The RX callback function in the promiscuous mode. * Each time a packet is received, the callback function will be called. * * @param buf Data received. Type of data in buffer (wifi_promiscuous_pkt_t or wifi_pkt_rx_ctrl_t) indicated by 'type' parameter. * @param type promiscuous packet type. * */ typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type); /** * @brief Register the RX callback function in the promiscuous mode. * * Each time a packet is received, the registered callback function will be called. * * @param cb callback * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb); /** * @brief Enable the promiscuous mode. * * @param en false - disable, true - enable * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous(bool en); /** * @brief Get the promiscuous mode. * * @param[out] en store the current status of promiscuous mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_promiscuous(bool *en); /** * @brief Enable the promiscuous mode packet type filter. * * @note The default filter is to filter all packets except WIFI_PKT_MISC * * @param filter the packet type filtered in promiscuous mode. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous_filter(const wifi_promiscuous_filter_t *filter); /** * @brief Get the promiscuous filter. * * @param[out] filter store the current status of promiscuous filter * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_promiscuous_filter(wifi_promiscuous_filter_t *filter); /** * @brief Enable subtype filter of the control packet in promiscuous mode. * * @note The default filter is to filter none control packet. * * @param filter the subtype of the control packet filtered in promiscuous mode. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_promiscuous_ctrl_filter(const wifi_promiscuous_filter_t *filter); /** * @brief Get the subtype filter of the control packet in promiscuous mode. * * @param[out] filter store the current status of subtype filter of the control packet in promiscuous mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_promiscuous_ctrl_filter(wifi_promiscuous_filter_t *filter); /** * @brief Set the configuration of the ESP32 STA or AP * * @attention 1. This API can be called only when specified interface is enabled, otherwise, API fail * @attention 2. For station configuration, bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP. * @attention 3. ESP32 is limited to only one channel, so when in the soft-AP+station mode, the soft-AP will adjust its channel automatically to be the same as * the channel of the ESP32 station. * * @param interface interface * @param conf station or soft-AP configuration * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface * - ESP_ERR_WIFI_MODE: invalid mode * - ESP_ERR_WIFI_PASSWORD: invalid password * - ESP_ERR_WIFI_NVS: WiFi internal NVS error * - others: refer to the erro code in esp_err.h */ esp_err_t esp_wifi_set_config(wifi_interface_t interface, wifi_config_t *conf) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (conf == NULL) return ESP_ERR_INVALID_ARG; if (interface == WIFI_IF_STA) { if (strlen((const char *)(conf->sta.password)) > 64) { return ESP_ERR_WIFI_PASSWORD; } } else if (interface == WIFI_IF_AP) { if (strlen((char *)conf->ap.password) > 0 && strlen((char *)conf->ap.password) < 8 || strlen((char *)conf->ap.password) > 64) return ESP_ERR_WIFI_PASSWORD; /* We have no DHCP server, so for lack of a better place, we also set the * IP here. */ if (!wifistat.dhcp_s) { wifistat.ip_info.ip.addr = IPAddress(192, 76, 0, 1); wifistat.ip_info.gw.addr = IPAddress(192, 76, 0, 1); wifistat.ip_info.netmask.addr = IPAddress(255, 255, 255, 0); } } else return ESP_ERR_INVALID_ARG; memcpy((void *)&wifistat.conf, (void *)conf, sizeof(wifi_config_t)); return ESP_OK; } /** * @brief Get configuration of specified interface * * @param interface interface * @param[out] conf station or soft-AP configuration * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_IF: invalid interface */ esp_err_t esp_wifi_get_config(wifi_interface_t interface, wifi_config_t *conf) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (conf == NULL) return ESP_ERR_INVALID_ARG; if (interface != WIFI_IF_STA && interface != WIFI_IF_AP) return ESP_ERR_INVALID_ARG; if (interface == WIFI_IF_STA) { if (wifistat.mode != WIFI_MODE_STA && wifistat.mode != WIFI_MODE_APSTA) { return ESP_ERR_WIFI_IF; } } else if (interface == WIFI_IF_AP) { if (wifistat.mode != WIFI_MODE_AP && wifistat.mode != WIFI_MODE_APSTA) { return ESP_ERR_WIFI_IF; } } else return ESP_ERR_INVALID_ARG; memcpy((void *)conf, (void *)&wifistat.conf, sizeof(wifi_config_t)); return ESP_OK; } /** * @brief Get STAs associated with soft-AP * * @attention SSC only API * * @param[out] sta station list * ap can get the connected sta's phy mode info through the struct member * phy_11b,phy_11g,phy_11n,phy_lr in the wifi_sta_info_t struct. * For example, phy_11b = 1 imply that sta support 802.11b mode * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument * - ESP_ERR_WIFI_MODE: WiFi mode is wrong * - ESP_ERR_WIFI_CONN: WiFi internal error, the station/soft-AP control block is invalid */ esp_err_t esp_wifi_ap_get_sta_list(wifi_sta_list_t *sta) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (sta == NULL) return ESP_ERR_INVALID_ARG; if (wifistat.mode == WIFI_MODE_STA) return ESP_ERR_WIFI_MODE; memcpy((void *)sta, (void *)&wifistat.sta_list, sizeof(wifi_sta_list_t)); return ESP_OK; } /** * @brief Set the WiFi API configuration storage type * * @attention 1. The default value is WIFI_STORAGE_FLASH * * @param storage : storage type * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_storage(wifi_storage_t storage); /** * @brief Set auto connect * The default value is true * * @param en : true - enable auto connect / false - disable auto connect * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_MODE: WiFi internal error, the station/soft-AP control block is invalid * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_set_auto_connect(bool en) { return ESP_OK; } /** * @brief Get the auto connect flag * * @param[out] en store current auto connect configuration * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_auto_connect(bool *en) { return ESP_OK; } /** * @brief Set 802.11 Vendor-Specific Information Element * * @param enable If true, specified IE is enabled. If false, specified IE is removed. * @param type Information Element type. Determines the frame type to associate with the IE. * @param idx Index to set or clear. Each IE type can be associated with up to two elements (indices 0 & 1). * @param vnd_ie Pointer to vendor specific element data. First 6 bytes should be a header with fields matching vendor_ie_data_t. * If enable is false, this argument is ignored and can be NULL. Data does not need to remain valid after the function returns. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init() * - ESP_ERR_INVALID_ARG: Invalid argument, including if first byte of vnd_ie is not WIFI_VENDOR_IE_ELEMENT_ID (0xDD) * or second byte is an invalid length. * - ESP_ERR_NO_MEM: Out of memory */ esp_err_t esp_wifi_set_vendor_ie(bool enable, wifi_vendor_ie_type_t type, wifi_vendor_ie_id_t idx, const void *vnd_ie); /** * @brief Function signature for received Vendor-Specific Information Element callback. * @param ctx Context argument, as passed to esp_wifi_set_vendor_ie_cb() when registering callback. * @param type Information element type, based on frame type received. * @param sa Source 802.11 address. * @param vnd_ie Pointer to the vendor specific element data received. * @param rssi Received signal strength indication. */ typedef void (*esp_vendor_ie_cb_t) (void *ctx, wifi_vendor_ie_type_t type, const uint8_t sa[6], const vendor_ie_data_t *vnd_ie, int rssi); /** * @brief Register Vendor-Specific Information Element monitoring callback. * * @param cb Callback function * @param ctx Context argument, passed to callback function. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_vendor_ie_cb(esp_vendor_ie_cb_t cb, void *ctx); /** * @brief Set maximum WiFi transmiting power * * @attention WiFi transmiting power is divided to six levels in phy init data. * Level0 represents highest transmiting power and level5 represents lowest * transmiting power. Packets of different rates are transmitted in * different powers according to the configuration in phy init data. * This API only sets maximum WiFi transmiting power. If this API is called, * the transmiting power of every packet will be less than or equal to the * value set by this API. If this API is not called, the value of maximum * transmitting power set in phy_init_data.bin or menuconfig (depend on * whether to use phy init data in partition or not) will be used. Default * value is level0. Values passed in power are mapped to transmit power * levels as follows: * - [78, 127]: level0 * - [76, 77]: level1 * - [74, 75]: level2 * - [68, 73]: level3 * - [60, 67]: level4 * - [52, 59]: level5 * - [44, 51]: level5 - 2dBm * - [34, 43]: level5 - 4.5dBm * - [28, 33]: level5 - 6dBm * - [20, 27]: level5 - 8dBm * - [8, 19]: level5 - 11dBm * - [-128, 7]: level5 - 14dBm * * @param power Maximum WiFi transmiting power. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start */ esp_err_t esp_wifi_set_max_tx_power(int8_t power) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; wifistat.power = power; return ESP_OK; } /** * @brief Get maximum WiFi transmiting power * * @attention This API gets maximum WiFi transmiting power. Values got * from power are mapped to transmit power levels as follows: * - 78: 19.5dBm * - 76: 19dBm * - 74: 18.5dBm * - 68: 17dBm * - 60: 15dBm * - 52: 13dBm * - 44: 11dBm * - 34: 8.5dBm * - 28: 7dBm * - 20: 5dBm * - 8: 2dBm * - -4: -1dBm * * @param power Maximum WiFi transmiting power. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_max_tx_power(int8_t *power) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED; if (power == NULL) return ESP_ERR_INVALID_ARG; *power = wifistat.power; return ESP_OK; } /** * @brief Set mask to enable or disable some WiFi events * * @attention 1. Mask can be created by logical OR of various WIFI_EVENT_MASK_ constants. * Events which have corresponding bit set in the mask will not be delivered to the system event handler. * @attention 2. Default WiFi event mask is WIFI_EVENT_MASK_AP_PROBEREQRECVED. * @attention 3. There may be lots of stations sending probe request data around. * Don't unmask this event unless you need to receive probe request data. * * @param mask WiFi event mask. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_event_mask(uint32_t mask) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; wifistat.mask = mask; return ESP_OK; } /** * @brief Get mask of WiFi events * * @param mask WiFi event mask. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_get_event_mask(uint32_t *mask) { if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT; if (mask == NULL) return ESP_ERR_INVALID_ARG; *mask = wifistat.mask; return ESP_OK; } /** * @brief Send raw ieee80211 data * * @attention Currently only support for sending beacon/probe request/probe response/action and non-QoS * data frame * * @param ifx interface if the Wi-Fi mode is Station, the ifx should be WIFI_IF_STA. If the Wi-Fi * mode is SoftAP, the ifx should be WIFI_IF_AP. If the Wi-Fi mode is Station+SoftAP, the * ifx should be W
IFI_IF_STA or WIFI_IF_AP. If the ifx is wrong, the API returns ESP_ERR_WIFI_IF. * @param buffer raw ieee80211 buffer * @param len the length of raw buffer, the len must be <= 1500 Bytes and >= 24 Bytes * @param en_sys_seq indicate whether use the internal sequence number. If en_sys_seq is false, the * sequence in raw buffer is unchanged, otherwise it will be overwritten by WiFi driver with * the system sequence number. * Generally, if esp_wifi_80211_tx is called before the Wi-Fi connection has been set up, both * en_sys_seq==true and en_sys_seq==false are fine. However, if the API is called after the Wi-Fi * connection has been set up, en_sys_seq must be true, otherwise ESP_ERR_INVALID_ARG is returned. * * @return * - ESP_OK: success * - ESP_ERR_WIFI_IF: Invalid interface * - ESP_ERR_INVALID_ARG: Invalid parameter * - ESP_ERR_WIFI_NO_MEM: out of memory */ esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq); /** * @brief The RX callback function of Channel State Information(CSI) data. * * Each time a CSI data is received, the callback function will be called. * * @param ctx context argument, passed to esp_wifi_set_csi_rx_cb() when registering callback function. * @param data CSI data received. The memory that it points to will be deallocated after callback function returns. * */ typedef void (* wifi_csi_cb_t)(void *ctx, wifi_csi_info_t *data); /** * @brief Register the RX callback function of CSI data. * * Each time a CSI data is received, the callback function will be called. * * @param cb callback * @param ctx context argument, passed to callback function * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_set_csi_rx_cb(wifi_csi_cb_t cb, void *ctx); /** * @brief Set CSI data configuration * * @param config configuration * * return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_csi_config(const wifi_csi_config_t *config); /** * @brief Enable or disable CSI * * @param en true - enable, false - disable * * return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled * - ESP_ERR_INVALID_ARG: invalid argument */ esp_err_t esp_wifi_set_csi(bool en); /** * @brief Set antenna GPIO configuration * * @param config Antenna GPIO configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: Invalid argument, e.g. parameter is NULL, invalid GPIO number etc */ esp_err_t esp_wifi_set_ant_gpio(const wifi_ant_gpio_config_t *config); /** * @brief Get current antenna GPIO configuration * * @param config Antenna GPIO configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument, e.g. parameter is NULL */ esp_err_t esp_wifi_get_ant_gpio(wifi_ant_gpio_config_t *config); /** * @brief Set antenna configuration * * @param config Antenna configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: Invalid argument, e.g. parameter is NULL, invalid antenna mode or invalid GPIO number */ esp_err_t esp_wifi_set_ant(const wifi_ant_config_t *config); /** * @brief Get current antenna configuration * * @param config Antenna configuration. * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_INVALID_ARG: invalid argument, e.g. parameter is NULL */ esp_err_t esp_wifi_get_ant(wifi_ant_config_t *config);
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019 Cadence Design Systems, Inc. All rights reserved worldwide. // // The code contained herein is the proprietary and confidential information // of Cadence or its licensors, and is supplied subject to a previously // executed license and maintenance agreement between Cadence and customer. // This code is intended for use with Cadence high-level synthesis tools and // may not be used with other high-level synthesis tools. Permission is only // granted to distribute the code as indicated. Cadence grants permission for // customer to distribute a copy of this code to any partner to aid in designing // or verifying the customer's intellectual property, as long as such // distribution includes a restriction of no additional distributions from the // partner, unless the partner receives permission directly from Cadence. // // ALL CODE FURNISHED BY CADENCE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, AND CADENCE SPECIFICALLY DISCLAIMS ANY WARRANTY OF NONINFRINGEMENT, // FITNESS FOR A PARTICULAR PURPOSE OR MERCHANTABILITY. CADENCE SHALL NOT BE // LIABLE FOR ANY COSTS OF PROCUREMENT OF SUBSTITUTES, LOSS OF PROFITS, // INTERRUPTION OF BUSINESS, OR FOR ANY OTHER SPECIAL, CONSEQUENTIAL OR // INCIDENTAL DAMAGES, HOWEVER CAUSED, WHETHER FOR BREACH OF WARRANTY, // CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE. // //////////////////////////////////////////////////////////////////////////////// #include <systemc.h> // SystemC definitions #include "system.h" // Top-level System module header file static System * m_system = NULL; // The pointer that holds the top-level System module instance. void esc_elaborate() // This function is required by Stratus to support { // SystemC-Verilog co-simulation. This is where an instance of the m_system = new System( "system" ); // top-level module should be created. } void esc_cleanup() // This function is called at the end of simulation by the { // Stratus co-simulation hub. It should delete the top-level delete m_system; // module instance. } int sc_main( int argc, char ** argv ) // This function is called by the SystemC kernel for pure SystemC simulations { esc_initialize( argc, argv ); // esc_initialize() passes in the cmd-line args. This initializes the Stratus simulation // environment (such as opening report files for later logging and analysis). esc_elaborate(); // esc_elaborate() (defined above) creates the top-level module instance. In a SystemC-Verilog // co-simulation, this is called during cosim initialization rather than from sc_main. sc_start(); // Starts the simulation. Returns when a module calls esc_stop(), which finishes the simulation. // esc_cleanup() (defined above) is automatically called before sc_start() returns. return 0; // Returns the status of the simulation. Required by most C compilers. }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** fir.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. ([email protected]) Date: 2018-Feb-20 Description of Modification: Added sampling of the covergroup created in the "fir.h" file. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "fir.h" void fir::entry() { sc_int<8> sample_tmp; sc_int<17> pro; sc_int<19> acc; sc_int<8> shift[16]; // reset watching /* this would be an unrolled loop */ for (int i=0; i<=15; i++) shift[i] = 0; result.write(0); output_data_ready.write(false); wait(); // main functionality while(1) { output_data_ready.write(false); do { wait(); } while ( !(input_valid == true) ); sample_tmp = sample.read(); acc = sample_tmp*coefs[0]; for(int i=14; i>=0; i--) { /* this would be an unrolled loop */ pro = shift[i]*coefs[i+1]; acc += pro; }; for(int i=14; i>=0; i--) { /* this would be an unrolled loop */ shift[i+1] = shift[i]; }; shift[0] = sample_tmp; // sample the shift value shift_cg.sample(shift[0]); // write output values result.write((int)acc); output_data_ready.write(true); wait(); }; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (Mux3) { sc_in <bool> sel; sc_in <sc_uint<3>> in0; sc_in <sc_uint<3>> in1; sc_out <sc_uint<3>> out; /* ** module global variables */ SC_CTOR (Mux3){ SC_METHOD (process); sensitive << in0 << in1 << sel; } void process () { if(!sel.read()){ out.write(in0.read()); } else{ out.write(in1.read()); } } };
/* * @ASCK */ #include <systemc.h> SC_MODULE (IR) { sc_in <sc_uint<14>> addr; sc_out <sc_uint<20>> inst; /* ** module global variables */ sc_uint<20> mem[819]; // 819 rows and 819*20=16380 bits = (16KB - 4bits) ~= 16KB int instNum = 50; sc_uint<20> instruction[50] = { // 0b01234567890123456789 0b00000000000000000000, 0b00100000000000000111, // transfer (r0 <- 7): 7 0b00010010010000000000, // inc (r1++): 1 //stall for achieving the correct register data - sub 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00000110000010000010, // sub (r3 <-r0 - r1): 6 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00011000110010000001, // addc (r4 <- r3 + r1 + 1): 8 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00001001000000101001, // shiftR (r4 >> 2): 2 0b01010000000000000101, // stroe (mem[5] <= r0) : 7 0b01001010000000000101, // load (r5 <= mem[5]) : 7 0b01100000000000000000, // do accelerator 0b01000100000000010100, // load (r2 <= mem[20]) : 17 => 0x11 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000 //nop }; SC_CTOR (IR){ SC_METHOD (process); sensitive << addr; for(int i=0; i<instNum; i++){ mem[i] = instruction[i]; } // filling out other rows with a nop opcode for(int i=instNum; i<819; i++){ mem[i] = 0b11110000000000000000; } } void process () { if(addr.read() < 819){ inst.write(mem[addr.read()]); } else{ inst.write(0); } } };
/******************************************************************************* * pn532.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a crude model for the PN532 with firmware v1.6. It will work for * basic work with a PN532 system. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "pn532.h" #include "info.h" const unsigned char PN532_ID = 0x24; void pn532::i2c_th(void) { int i; unsigned int devid, data; enum {IDLE, DEVID, ACKWR, ACKRD, RETZ, ACKWRD, WRDATA, READ, ACKNACK} i2cstate; enum {BUFFER_UNKNOWN, BUFFER_NOTUSED, BUFFER_VALID, BUFFER_INVALID} buffer_state; buffer_state = BUFFER_UNKNOWN; /* Then we begin waiting for the I2C commands. */ while(1) { wait(sda.default_event() | scl.default_event()); /* If we get Z or X, we ignore it. */ if (!scl.read().islogic()) { PRINTF_WARN("PN532", "SCL is not defined"); } else if (!sda.read().islogic()) { PRINTF_WARN("PN532", "SDA is not defined"); } /* At any time a start or stop bit can come in. */ else if (scl.read().ishigh() && sda.value_changed_event().triggered()) { if (sda.read().islow()) { /* START BIT */ i2cstate = DEVID; i = 7; devid = 0; buffer_state = BUFFER_UNKNOWN; } /* STOP BIT */ else { /* If we see a stop bit and we were giving the customer a buffer, * we flush it out. If we were not giving it a buffer, or it was * an invalid buffer, we do nothing. */ if (buffer_state == BUFFER_VALID) flush_to(); i2cstate = IDLE; } } /* The rest has to be data changes. For simplicity all data in and flow * control is here. The data returned is done on another branch. */ else if (scl.value_changed_event().triggered() && scl.read().ishigh()) switch(i2cstate) { case IDLE: break; case DEVID: /* We collect all bits of the device ID. The last bit is the R/W * bit. */ if (i > 0) devid = (devid << 1) + ((sda.read().ishigh())?1:0); /* If the ID matches, we can process it. First we handle reads. */ else if (devid == PN532_ID && sda.read().ishigh()) { /* We will go to ACKRD. */ i2cstate = ACKRD; /* We check the status of the buffer. If there is data to * be read out, it is valid. If not, it is invalid. */ if (to.num_available() == 0) buffer_state = BUFFER_INVALID; else buffer_state = BUFFER_VALID; } else if (devid == PN532_ID && sda.read().islow()) { i2cstate = ACKWR; buffer_state = BUFFER_NOTUSED; } /* If the devid does not match, we return Z. */ else i2cstate = RETZ; i = i - 1; break; /* If the address does not match, we return Z. */ case RETZ: i2cstate = IDLE; break; /* Once a code has been recognized as a write, so we return an ACK. * so that the master knows it was accepted. He can start sending * the data. We just store it in a buffer and let the FSM handle it. */ case ACKRD: case ACKWR: i = 7; /* If we are reading the buffer, and it is valid, we return 01 and * then the rest will be data. If it is invalid, we return 00 and * then we return garbage. For writes, we ignore this. */ if (buffer_state == BUFFER_INVALID) { data = 0x00; outtoken.write(data); /* We also update the debug outtoken. */ i2cstate = READ; } else if (buffer_state == BUFFER_VALID) { data = 0x01; outtoken.write(data); i2cstate = READ; } /* And for writes, the buffer is not used, we do the write. */ else { data = 0; i2cstate = WRDATA; /* Before we start, we dump anything that could be left over * from the previous command. */ while(from.num_available() != 0) (void)from.read(); } break; /* Each bit is taken. */ case WRDATA: data = (data << 1) + ((sda.read().ishigh())?1:0); if (i == 0) i2cstate = ACKWRD; else i = i - 1; break; /* Once a byte is in, we store it in the buffer and prepare for more.*/ case ACKWRD: from.write(data); data = 0; i = 7; i2cstate = WRDATA; break; /* Depending on the acknack we either return more data or not. */ case ACKNACK: /* If we got a NACK, we flush out the buffer and quit. */ if (sda.read().ishigh()) { i2cstate = IDLE; if (buffer_state == BUFFER_VALID) flush_to(); } /* If we got an ACK but the buffer was invalid, we return junk. */ else if (buffer_state == BUFFER_INVALID) { i2cstate = READ; i = 7; data = 0x7f; outtoken.write(data); } /* If we got an ACK and the buffer is valid, we return the data. */ else { i2cstate = READ; i = 7; /* If the buffer is empty, we return 0. */ if (to.num_available() == 0) data = 0; else data = to.read(); outtoken.write(data); } break; /* On reads, we send the data after each bit change. Note: the driving * is done on the other edge. */ case READ: if (i == 0) i2cstate = ACKNACK; else i = i - 1; break; } /* Anytime the clock drops, we return data. We only do the data return * to keep the FSM simpler. */ else if (scl.value_changed_event().triggered() && scl.read().islow()) switch (i2cstate) { /* If we get an illegal code, we return Z. We remain here until * we get. */ case RETZ: sda.write(GN_LOGIC_Z); break; /* ACKWRD, ACKWR and ACKRD we return a 0. */ case ACKRD: case ACKWR: case ACKWRD: sda.write(GN_LOGIC_0); break; /* For the WRITE state, all we do is release the SDA so that the * master can write. */ case WRDATA: case ACKNACK: sda.write(GN_LOGIC_Z); break; /* Each bit is returned. */ case READ: if (buffer_state == BUFFER_INVALID) sda.write(GN_LOGIC_0); else if ((data & (1 << i))>0) sda.write(GN_LOGIC_Z); else sda.write(GN_LOGIC_0); break; default: ; /* For the others we do nothing. */ } icstate.write(i2cstate); } } void pn532::trace(sc_trace_file *tf) { sc_trace(tf, icstate, icstate.name()); pn532_base::trace(tf); }