MagicMirror Forum
    • Recent
    • Tags
    • Unsolved
    • Solved
    • MagicMirror² Repository
    • Documentation
    • 3rd-Party-Modules
    • Donate
    • Discord
    • Register
    • Login
    A New Chapter for MagicMirror: The Community Takes the Lead
    Read the statement by Michael Teeuw here.

    read csv-data and put it in an array

    Scheduled Pinned Locked Moved Utilities
    313 Posts 3 Posters 439.7k Views 4 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S Offline
      sdetweil @Perlchamp
      last edited by

      @Perlchamp ok, couple problems… in teh notification handler we write to active_birthdays,
      but it is a variable local to this routine… so, when this routine ends, it goes awau

      need to move its definition to the top

      
      	defaults: {
      		language: "de",
      		dimmEntries: true   // true: dims entries and the associated 
      							//       symbol when the date has expired.
      							// false: delete entries and the associated 
      							//        symbol when the date has expired.
      	},
          active_birthdays : {},
      

      then add ‘this.’ in front of it in the notification handler
      (and remove the var activebirthdays)

      now it is an instance variable (one per browser)

      also, I spelled substring wrong (I had it subString, its substring )

      gotta run to store, back in a little bit

      Sam

      How to add modules

      learning how to use browser developers window for css changes

      1 Reply Last reply Reply Quote 0
      • PerlchampP Offline
        Perlchamp
        last edited by Perlchamp

        ok, be carefully. keep corona away. use mouth and nose protection and wear disposable gloves !

        thanks, but doesn’t work. it seems, that i’m too stupid for this ?
        modified perlchamp.js:

        Module.register("perlchamp", {
        
        	defaults: {
        		language: "de",
        		dimmEntries: true   // true: dims entries and the associated 
        							//       symbol when the date has expired.
        							// false: delete entries and the associated 
        							//        symbol when the date has expired.
        	},
        	
        	active_birthdays: {
        		
        	},
        
        
        	init: function(){
        		Log.log(this.name + " is in init!");
        	},
        
        	start: function(){
        		Log.log("Starting module: " + this.name);
        
        		// Set locale
        		moment.locale(config.language);
        	},
        
        	loaded: function(callback) {
        		Log.log(this.name + " is loaded!");
        		callback();
        	},
        
        	// return list of other functional scripts to use, if any (like require in node_helper)
        	getScripts: function() {
        		return	["moment.js"];
        	}, 
        
        	// return list of stylesheet files to use if any
        	getStyles: function() {
        		return 	[this.data.path + "/css/perlchamp.css"];
        	},
        
        
        	// only called if the module header was configured in module config in config.js
        	getHeader: function() {
        		return this.data.header;
        	},
        
        	// messages received from other modules and the system (NOT from your node helper)
        	// payload is a notification dependent data structure
        	notificationReceived: function(notification, payload, sender) {
        		// once everybody is loaded up
        		if(notification==="ALL_MODULES_STARTED"){
        			// send our config to our node_helper
        			this.sendSocketNotification("CONFIG",this.config);
        		}
        		if (sender) {
        			Log.log(this.name + " received a module notification: " + notification + " from sender: " + sender.name);
        		} else {
        			Log.log(this.name + " received a system notification: " + notification);
        		}
        	},
        	
        	// messages received from from your node helper (NOT other modules or the system)
        	// payload is a notification dependent data structure, up to you to design between module and node_helper
        	socketNotificationReceived: function(notification, payload) {
        
        		if(notification === "have data"){
        			Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
        			
        			var now = moment();
        			for(var birthday of payload) {
        				// get 1st 5 chars of birthdate, thru month
        				// we will use this as the key in the hash
        				var birth_date = birthday.birth.substring(0,4);
        				
        				// get the birthday as a moment in this year, for comparing
        				var birth_date_moment = moment(birth_date + now.getYear(),"DD.MMYYYY");
        
        				// u can add days to a moment object and then compare 
        				//     if the birthdate is before that date (and after now)
        				//     so within the next xx days
        
        				// if the date is the same or later, don't use time of day
        				if(birth_date.startOf('day').isSame(now.startOf('day'))) {
        
        					// birthday is in this month
        					// check the hash if we've seen anything for today yet
        					// if we haven't see this date yet
        					if(this.active_birthdays[birth_date] == undefined){
                   
        						//  create the holder for its info (array of 
        						//		names) in the hash
        						this.active_birthdays[birth_date] = [];
        					}
        					// save the persons name on the list
        					this.active_birthdays[birth_date].push(birthday.name);
        				}
        			}
             
        			// tell MM to call and get our content
        			self.updateDom();
        		}     			
        	},
        
        	// system notification your module is being hidden
        	// typically you would stop doing UI updates (getDom/updateDom) if the module is hidden
        	suspend: function(){
        
        	},
        
        	// system notification your module is being unhidden/shown
        	// typically you would resume doing UI updates (getDom/updateDom) if the module is shown
        	resume: function(){
        
        	},
        
        	// this is the major worker of the module, it provides the displayable content for this module
        	getDom: function() {
        		var wrapper = document.createElement("div");
        
        		for(var birthday of Object.keys(this.active_birthdays)){
        			for(var name of this.active_birthdays[birthday]){
        				var m = document.createElement('div');
        				m.innerText = birthday + ' '+ name;
        				wrapper.appendChild(m);
        			}
        		}
        
        		// pass the created content back to MM to add to DOM.
        		return wrapper;
        	}
        })
        

        in node_helper.js was nothing to be changed. maybe I put a few semicolons where none have to go?

        1 Reply Last reply Reply Quote 0
        • S Offline
          sdetweil
          last edited by sdetweil

          sorry, forgot one thing i saw in node helper,… need to move everything in the start function to the socketNotification section… at start time the module is not up yet, so the message goes nowhere

          socketNotificationReceived(notification, payload) {		
          	var self = this		
          		// if config message from module
          		if (notification === "CONFIG") {
          			// save payload config info
          			this.config = payload;
          			var self = this;
          			console.log("Starting module helper: " + this.name);
          
          			// convert the csv-file into a JSON-String
          			const csvFilePath = this.path + '/birthdays.csv';
          			csv()
          			.fromFile(csvFilePath)
          			.then((jsonObj)=>{      
          				birthdaysArray = JSON.stringify(jsonObj);
          				
          				// for debugging only
          				console.log("birthdaysArray: ", JSON.stringify(birthdaysArray));
          				
          				// send data to [modulname].js
          				self.sendSocketNotification("have data", jsonObj);
          			})	
          		}
          		else if(notification === "????2") {
          		}
          	},
          

          also, by moving it here, all you have to do is fix the code, save and then refresh the page… don’t have to restart MM

          start is now empty

          	start() {
          	
          	},
          

          Sam

          How to add modules

          learning how to use browser developers window for css changes

          1 Reply Last reply Reply Quote 0
          • PerlchampP Offline
            Perlchamp
            last edited by

            ok, nothing changed and i don’t see any messages of “HAVEDATA” (changed it in both files to big letter without space). i only see the header “Geburtstage” … :-(
            node_helper.js:

            var NodeHelper = require("node_helper");
            var moment = require("moment");
            
            // add require of other javascripot components here
            // var xxx = require('yyy'); here
            const csv = require("csvtojson");
            var birthdaysArray = [];
            
            module.exports = NodeHelper.create({
            /*
            	init(){
            		console.log("init module helper perlchamp");
            	},
            */
            	start() {
            
            	},
            /*	
            	stop(){
            		console.log("Stopping module helper: " + this.name);
            	},
            */
            	// handle messages from our module// each notification indicates a different messages
            	// payload is a data structure that is different per message.. up to you to design this
            	socketNotificationReceived(notification, payload) {				
            
            		var self = this;
            		console.log("Starting module helper: " + this.name);
            
            		// convert the csv-file into a JSON-String
            		const csvFilePath = this.path + '/data/birthdays.csv';
            		csv()
            		.fromFile(csvFilePath)
            		.then((jsonObj)=>{      
            			birthdaysArray = JSON.stringify(jsonObj);
            			
            			// send data to [modulname].js
            			self.sendSocketNotification("HAVEDATA", jsonObj);
            		})		
            
            		// if config message from module
            		if (notification === "CONFIG") {
            			// save payload config info
            			this.config = payload;
            			// wait 15 seconds, send a message back to module
            			setTimeout(()=> {this.sendSocketNotification("message_from_helper"," this is a test_message")}, 15000);
            		}
            		else if(notification === "????2") {
            	
            		}
            	},
            });
            

            maye change this part, cause i never need this variable birthdaysArray:

            .then((jsonObj)=>{      
            			birthdaysArray = JSON.stringify(jsonObj);
            

            perlchamp.js:

            Module.register("perlchamp", {
            
            	defaults: {
            		language: "de",
            		dimmEntries: true   // true: dims entries and the associated 
            							//       symbol when the date has expired.
            							// false: delete entries and the associated 
            							//        symbol when the date has expired.
            	},
            	
            	active_birthdays: {
            		
            	},
            
            
            	init: function(){
            		Log.log(this.name + " is in init!");
            	},
            
            	start: function(){
            		Log.log("Starting module: " + this.name);
            
            		// Set locale
            		moment.locale(config.language);
            	},
            
            	loaded: function(callback) {
            		Log.log(this.name + " is loaded!");
            		callback();
            	},
            
            	// return list of other functional scripts to use, if any (like require in node_helper)
            	getScripts: function() {
            		return	["moment.js"];
            	}, 
            
            	// return list of stylesheet files to use if any
            	getStyles: function() {
            		return 	[this.data.path + "/css/perlchamp.css"];
            	},
            
            
            	// only called if the module header was configured in module config in config.js
            	getHeader: function() {
            		return this.data.header;
            	},
            
            	// messages received from other modules and the system (NOT from your node helper)
            	// payload is a notification dependent data structure
            	notificationReceived: function(notification, payload, sender) {
            		// once everybody is loaded up
            		if(notification==="ALL_MODULES_STARTED"){
            			// send our config to our node_helper
            			this.sendSocketNotification("CONFIG",this.config);
            		}
            		if (sender) {
            			Log.log(this.name + " received a module notification: " + notification + " from sender: " + sender.name);
            		} else {
            			Log.log(this.name + " received a system notification: " + notification);
            		}
            	},
            	
            	// messages received from from your node helper (NOT other modules or the system)
            	// payload is a notification dependent data structure, up to you to design between module and node_helper
            	socketNotificationReceived: function(notification, payload) {
            
            		if(notification === "HAVEDATE"){
            			Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
            			
            			var now = moment();
            			for(var birthday of payload) {
            				// get 1st 5 chars of birthdate, thru month
            				// we will use this as the key in the hash
            				var birth_date = birthday.birth.substring(0,4);
            				
            				// get the birthday as a moment in this year, for comparing
            				var birth_date_moment = moment(birth_date + now.getYear(),"DD.MMYYYY");
            
            				// u can add days to a moment object and then compare 
            				//     if the birthdate is before that date (and after now)
            				//     so within the next xx days
            
            				// if the date is the same or later, don't use time of day
            				if(birth_date.startOf('day').isSame(now.startOf('day'))) {
            
            					// birthday is in this month
            					// check the hash if we've seen anything for today yet
            					// if we haven't see this date yet
            					if(this.active_birthdays[birth_date] == undefined){
                       
            						//  create the holder for its info (array of 
            						//		names) in the hash
            						this.active_birthdays[birth_date] = [];
            					}
            					// save the persons name on the list
            					this.active_birthdays[birth_date].push(birthday.name);
            				}
            			}
                 
            			// tell MM to call and get our content
            			self.updateDom();
            		}     			
            	},
            
            	// system notification your module is being hidden
            	// typically you would stop doing UI updates (getDom/updateDom) if the module is hidden
            	suspend: function(){
            
            	},
            
            	// system notification your module is being unhidden/shown
            	// typically you would resume doing UI updates (getDom/updateDom) if the module is shown
            	resume: function(){
            
            	},
            
            	// this is the major worker of the module, it provides the displayable content for this module
            	getDom: function() {
            		var wrapper = document.createElement("div");
            
            		for(var birthday of Object.keys(this.active_birthdays)){
            			for(var name of this.active_birthdays[birthday]){
            				var m = document.createElement('div');
            				m.innerText = birthday + ' '+ name;
            				wrapper.appendChild(m);
            			}
            		}
            
            		// pass the created content back to MM to add to DOM.
            		return wrapper;
            	}
            })
            

            please have an eye on the getDom-sektion.

            S 1 Reply Last reply Reply Quote 0
            • S Offline
              sdetweil
              last edited by sdetweil

              no… it will do the thig every time a notifcation comes in, only want it when the module sends down a message (say it is alive)

              in node_help you are sending this “HAVEDATA”
              and in module you are looking for this if(notification === “HAVEDATE”){

              add a var self = this to start of socketNotificationReceived() and getDom()

              Sam

              How to add modules

              learning how to use browser developers window for css changes

              1 Reply Last reply Reply Quote 0
              • S Offline
                sdetweil @Perlchamp
                last edited by

                @Perlchamp said in read csv-data and put it in an array:

                if(birth_date.startOf(‘day’)

                also should be

                if(birth_date_moment.startOf('day')
                

                comparing moments, not strings! oops

                Sam

                How to add modules

                learning how to use browser developers window for css changes

                1 Reply Last reply Reply Quote 0
                • PerlchampP Offline
                  Perlchamp
                  last edited by

                  only the header i see, BUT now i see the terminal-message “HAVEDATA” but an error, too:
                  picture

                  S 1 Reply Last reply Reply Quote 0
                  • S Offline
                    sdetweil @Perlchamp
                    last edited by

                    @Perlchamp open the developers window, ctrl-shift-i on the mirror screen,
                    select console tab,
                    put perl in the filter field

                    select the sources tab, navigate the left nav tree,. to modules/perlchamp/perlcmap.js

                    find the socketnotificationreceived

                    click the number in the left column, hit f5 (refresh) on keyboard

                    code should stop at the line you clicked

                    in the right pane, top there is a blue arrow (resume executing) and a top half of a globe, stop on next )instruction)

                    Sam

                    How to add modules

                    learning how to use browser developers window for css changes

                    1 Reply Last reply Reply Quote 0
                    • PerlchampP Offline
                      Perlchamp
                      last edited by

                      before looking in dev: i saw the following:

                      var birth_date_moment = moment(birth_date + now.getYear(),"DD.MMYYYY");
                      

                      change to DD.MM.YYYY (point between MM and YYYY) ?

                      S 1 Reply Last reply Reply Quote 0
                      • S Offline
                        sdetweil @Perlchamp
                        last edited by sdetweil

                        @Perlchamp no, cause we extract dd.mm from the info provided in file…

                        oh, the substring should be 0,5, not 0,4

                        var birth_date = birthday.birth.substring(0,5);
                        

                        Sam

                        How to add modules

                        learning how to use browser developers window for css changes

                        1 Reply Last reply Reply Quote 0
                        • 1
                        • 2
                        • 10
                        • 11
                        • 12
                        • 13
                        • 14
                        • 31
                        • 32
                        • 12 / 32
                        • First post
                          Last post
                        Enjoying MagicMirror? Please consider a donation!
                        MagicMirror created by Michael Teeuw.
                        Forum managed by Sam, technical setup by Karsten.
                        This forum is using NodeBB as its core | Contributors
                        Contact | Privacy Policy