• Recent
  • Tags
  • Unsolved
  • Solved
  • MagicMirror² Repository
  • Documentation
  • 3rd-Party-Modules
  • Donate
  • Discord
  • Register
  • Login
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.

Error in using python with child_process

Scheduled Pinned Locked Moved Troubleshooting
3 Posts 2 Posters 157 Views 2 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.
  • D Offline
    doridol
    last edited by Jul 1, 2021, 2:29 PM

    node_helper.js

    const spawn = require('child_process').spawn;
    const NodeHelper = require("node_helper");
    
    var self;
    
    module.exports = NodeHelper.create({
    
        start: function () {
            self = this;
            console.log("Starting node_helper for: " + this.name);
        },
    
        getData: function () {
            const result = spawn('python', ['/home/pi/MagicMirror/modules/MMM-DustInfo/Naver_geo.py']);
    
    		result.stdout.on('data', function(data) {
    			console.log(data.toString());
    			recivedData = data.toString();
    			recivedData = JSON.parse(recivedData);
    		  });
    		  
    		  result.on('close', (code) => {
    			console.log(recivedData.station);
    
    			station = recivedData.station;
    			pm10 = recivedData.pm10;
    
    			var recivedData = {
                    station,
                    pm10
                }
    
    			self.sendSocketNotification('TEXT_RESULT', recivedData);
    
    			
    		  });
    		  process.on('exit', function() {
    			if (x) {
    			  x.kill();
    			}
    		  });
        },
    
        socketNotificationReceived: function (notification, payload) {
    
            if (notification === 'GET_TEXT_DATA') {
                self.getData();
            }
        },
    });
    

    my python file code

    import requests
    
    import pandas as pd
    
    import json
    
    import urllib.request
    
    from bs4 import BeautifulSoup
    
    from haversine import haversine
    
    
    
    station_data = pd.read_excel("/home/pi/Desktop/Dust/station_list.xlsx")
    
    location_data = pd.read_excel("/home/pi/Desktop/Dust/location.xlsx")
    
    location_data = location_data.values.tolist()
    
    
    
    def search_map(search_text):
    
        client_id = 'vo9k89s848' #클라이언트 ID값
    
        client_secret = 'MPooQfaCMH9eSMnT50RvNEYjChshVRHwq3qiBoQi' #클라이언트 Secret값
    
        encText = urllib.parse.quote(search_text) 
    
        url = 'https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query='+encText
    
        request = urllib.request.Request(url)
    
        request.add_header('X-NCP-APIGW-API-KEY-ID', client_id)
    
        request.add_header('X-NCP-APIGW-API-KEY', client_secret)
    
        response = urllib.request.urlopen(request)
    
        rescode = response.getcode()
    
        if(rescode==200):
    
            response_body = response.read()
    
            return response_body.decode('utf-8')
    
    
    
    def station_info():
    
        station_info = []
    
        for i in range(489):
    
            info = search_map(station_data.loc[i]['측정소 주소'])
    
            info = json.loads(info)
    
            station_info.append([float(info['addresses'][0]['y']),float(info['addresses'][0]['x'])])
    
        return station_info
    
    
    
    def curr_LocInfo():
    
        curr_LocInfo = []
    
        info = search_map("서울특별시 노원구 공릉로 232")
    
        info = json.loads(info)
    
        curr_LocInfo.append([float(info['addresses'][0]['y']),float(info['addresses'][0]['x'])])
    
        return curr_LocInfo
    
    
    
    def Loc_to_xlsx():
    
        station_x = station_info()
    
        station_x = pd.DataFrame(station_x)
    
        station_x.to_excel("C:/Users/sks12/Desktop/PythonWorkspace/Dust_Window/location.xlsx")
    
    
    
    def search_station():
    
        station_Loc = location_data
    
        curr_Loc = curr_LocInfo()
    
        
    
        min = 10000
    
        for i in range(489):
    
            distance = haversine((station_Loc[i][1], station_Loc[i][2]), curr_Loc[0], unit = 'km')
    
            if distance < min:
    
                min = distance
    
                globals()['station_index'] = i
    
    
    
    def Dust_info():
    
        search_station()
    
        city = station_data.loc[station_index]['측정소명']
    
        key = "mr81qR0Ed0RG4%2FUFpmXXLO0c7AO3HI6PC%2BVFgy%2BMO1yZ%2F7ciBAJejaPZ%2FmHi%2F30D4CYg7DKkGwpxHXTgHQDTSQ%3D%3D"
    
        url = "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?stationName={}&dataTerm=month&pageNo=1&numOfRows=100&returnType=xml&serviceKey={}".format(city, key)
    
        res = requests.get(url)
    
        res.raise_for_status()
    
        content = BeautifulSoup(res.text, "lxml")
    
    
    
        dust = content.item
    
        pm10 = dust.pm10value
    
        check = pm10.get_text()
    
    
    
        if check == '-':
    
            dust = dust.next_sibling
    
            dust = dust.next_sibling
    
    
    
        pm10 = dust.pm10value
    
        pm10 = int(pm10.get_text())
    
        # print("near station: {}".format(station_data.loc[station_index]['측정소명']))
    
        # print("dust info:{}".format(pm10))
    
    
    
        data = {
    
            "station" : station_data.loc[station_index]['측정소명'],
    
            "pm10" : pm10
    
            }
    
        data_json = json.dumps(data)
    
        print (data_json)
    
    
    
    Dust_info()
    

    my module code

    Module.register("MMM-DustInfo", {
    	defaults: {
    		updateInterval: 60000,
    
    	},
    
    	requiresVersion: "2.1.0", // Required version of MagicMirror
    
    	start: function () {
            // Log.info("Starting module: " + this.name);
            // requiresVersion: "2.1.0";
            // this.loaded = false;
            this.scheduleUpdate();
    
        },
    
        getStyles: function() {
            return["MMM-DustInfo.css"];
        },
    
    	scheduleUpdate: function () {
            setInterval(() => {
                this.getData();
            }, this.config.updateInterval);
            this.getData();
        },
    
    	
    	getData: function() {
    		console.log('GET_TEXT_DATA', this.config)
    		this.sendSocketNotification('GET_TEXT_DATA', this.config);
    	},
    
    	socketNotificationReceived: function (notification, payload) {
    		if (notification === "TEXT_RESULT") {
    			this.textDataRecived = payload;
    			this.loaded = true;
    	   } 
    	   this.updateDom();
    	},
    
    
    	getDom: function () {
            var wrapper = document.createElement("div");
    
            if (!this.loaded) {
                wrapper.innerHTML = "LOADING";
                return wrapper;
            }
            if (this.loaded) {
    
                var table = document.createElement('td');
    
                var space1 = document.createElement('tr');
                var space2 = document.createElement('tr');
                
                var pm10Icon = document.createElement("tr");
                if (this.textDataRecived.pm10 <= 30) {
                    Icon_pm10 = "fa fa-smile-o";
                    pm10Icon.id = 'smile'
                }
                else if (this.textDataRecived.pm10 > 30 && this.textDataRecived.pm10 <= 80) {
                    Icon_pm10 = "fa fa-meh-o"
                    pm10Icon.id = 'meh'
                }
                else {
                    Icon_pm10 = "fa fa-frown-o"
                    pm10Icon.id = 'frown'
                }
                pm10Icon.className = Icon_pm10;
                var pm10Data = document.createElement('span');
                pm10Data.className = "medium";
                pm10Data.innerHTML = "PM10: " + this.textDataRecived.pm10 +" ppm";
    
                var stationIcon = document.createElement("tr");
                stationIcon.className = "fa fa-home";
                var stationData = document.createElement("span");
                stationData.className = "medium";
                stationData.innerHTML = "내 위치: " + this.textDataRecived.station;
    
    
                table.appendChild(space1);
                table.appendChild(space2);
    
                space1.appendChild(pm10Icon);
                pm10Icon.appendChild(pm10Data);
                
                space2.appendChild(stationIcon);
                stationIcon.appendChild(stationData);
                
                wrapper.appendChild(table);
            }
            return wrapper;
        },
    	
    });
    
    

    and i got a error like this

    [01.07.2021 23:12.25.107] [LOG]   {"station": "\ub178\uc6d0\uad6c", "pm10": 31}
    
    [01.07.2021 23:12.25.342] [ERROR] Whoops! There was an uncaught exception...
    [01.07.2021 23:12.25.345] [ERROR] TypeError: Cannot read property 'station' of undefined
        at ChildProcess.<anonymous> (/home/pi/MagicMirror/modules/MMM-DustInfo/node_helper.js:23:28)
        at ChildProcess.emit (events.js:315:20)
        at maybeClose (internal/child_process.js:1021:16)
        at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
    
    

    I want to display pm10 value and nearest dustinfo station using airkorea API

    I’m really beginner please help me…

    S 1 Reply Last reply Jul 1, 2021, 3:21 PM Reply Quote 0
    • S Offline
      sdetweil @doridol
      last edited by sdetweil Jul 1, 2021, 3:56 PM Jul 1, 2021, 3:21 PM

      @doridol
      In node_helper

      receiveddata needs to be defined outside the on handlers. u could move the handling up to the on data, and remove the on close

      Sam

      How to add modules

      learning how to use browser developers window for css changes

      D 1 Reply Last reply Jul 1, 2021, 3:24 PM Reply Quote 0
      • D Offline
        doridol @sdetweil
        last edited by Jul 1, 2021, 3:24 PM

        @sdetweil Really really thanks!! I solved problem

        1 Reply Last reply Reply Quote 0
        • 1 / 1
        1 / 1
        • First post
          1/3
          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